File size: 8,919 Bytes
f9ce179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edd091c
 
 
 
 
36a0796
f9ce179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d22171
 
 
 
 
f9ce179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72d7cd5
 
 
f9ce179
72d7cd5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# from fastapi import FastAPI, HTTPException, status, Depends
# from fastapi.responses import RedirectResponse
# from pydantic import BaseModel, conlist
# import pandas as pd
# from pycaret.classification import load_model, predict_model
# import logging
# from typing import Optional
# import numpy as np
# import os

# # Constants
# MODEL_PATH = "./api/model/saved_tuned_model"  # os.getenv("MODEL_PATH", "saved_tuned_model")  # Load model path from environment variable
# EMBEDDING_DIMENSION = 1024  # Update this to match your model's expected input dimension
# LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO")  # Logging level from environment variable

# # Configure logging
# logging.basicConfig(level=LOG_LEVEL)
# logger = logging.getLogger(__name__)


# # Load the saved model
# def load_tuned_model(model_path: str):
#     """Load the pre-trained model from the specified path."""
#     try:
#         logger.info(f"Loading model from {model_path}...")
#         model = load_model(model_path)
#         logger.info("Model loaded successfully.")
#         return model
#     except Exception as e:
#         logger.error(f"Failed to load the model: {str(e)}")
#         raise RuntimeError(f"Model loading failed: {str(e)}")


# tuned_model = load_tuned_model(MODEL_PATH)


# # Define the input data model using Pydantic
# class EmbeddingRequest(BaseModel):
#     embedding: conlist(
#         float, min_length=EMBEDDING_DIMENSION, max_length=EMBEDDING_DIMENSION
#     )


# # Define the response model
# class PredictionResponse(BaseModel):
#     predicted_label: int
#     predicted_score: float


# # Initialize FastAPI app
# app = FastAPI(
#     title="Embedding Prediction API",
#     description="API for predicting labels and scores from embeddings using a pre-trained model.",
#     version="1.0.0",
# )


# # Dependency for model access
# def get_model():
#     """Dependency to provide the loaded model to endpoints."""
#     return tuned_model


# # Define the prediction endpoint
# @app.post("/predict", response_model=PredictionResponse)
# async def predict(
#     request: EmbeddingRequest,
#     model=Depends(get_model),
# ):
#     """
#     Predicts the label and score for a given embedding.

#     Args:
#         request (EmbeddingRequest): A request containing the embedding as a list of floats.
#         model: The pre-trained model injected via dependency.

#     Returns:
#         PredictionResponse: A response containing the predicted label and score.
#     """
#     try:
#         logger.info("Received prediction request.")

#         # Convert the input embedding to a DataFrame
#         input_data = pd.DataFrame(
#             [request.embedding],
#             columns=[f"embedding_{i}" for i in range(EMBEDDING_DIMENSION)],
#         )

#         # Make a prediction using the loaded model
#         logger.info("Making prediction...")
#         prediction = predict_model(model, data=input_data)

#         # Extract the predicted label and score
#         predicted_label = prediction["prediction_label"].iloc[0]
#         predicted_score = prediction["prediction_score"].iloc[0]

#         logger.info(
#             f"Prediction successful: label={predicted_label}, score={predicted_score}"
#         )

#         return PredictionResponse(
#             predicted_label=int(predicted_label),
#             predicted_score=float(predicted_score),
#         )

#     except Exception as e:
#         logger.error(f"Prediction failed: {str(e)}")
#         raise HTTPException(
#             status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
#             detail=f"An error occurred during prediction: {str(e)}",
#         )


# # Health check endpoint
# @app.get("/health", status_code=status.HTTP_200_OK)
# async def health_check():
#     """Health check endpoint to verify the API is running."""
#     return {"status": "healthy"}


# # Run the FastAPI app
# if __name__ == "__main__":
#     import uvicorn

#     uvicorn.run(app, host="0.0.0.0", port=8000)


from fastapi import FastAPI, HTTPException, status, Depends
from fastapi.responses import RedirectResponse
from pydantic import BaseModel, conlist, ValidationError
from pydantic_settings import BaseSettings
import pandas as pd
from pycaret.classification import load_model, predict_model
import logging
from typing import Optional, List
import numpy as np
import os

# Configure structured logging
logging.basicConfig(
    level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)


# Define settings using Pydantic BaseSettings
class Settings(BaseSettings):
    model_path: str = "./api/model/saved_tuned_model"
    embedding_dimension: int = 1024
    log_level: str = "INFO"

    class Config:
        env_file = ".env"
        env_file_encoding = "utf-8"


settings = Settings()


# Load the saved model
def load_tuned_model(model_path: str):
    """Load the pre-trained model from the specified path."""
    try:
        logger.info(f"Loading model from {model_path}...")
        model = load_model(model_path)
        logger.info("Model loaded successfully.")
        return model
    except Exception as e:
        logger.error(f"Failed to load the model: {str(e)}")
        raise RuntimeError(f"Model loading failed: {str(e)}")


tuned_model = load_tuned_model(settings.model_path)


# Define the input data model using Pydantic
class EmbeddingRequest(BaseModel):
    # embedding: conlist(
    #     float,
    #     min_length=settings.embedding_dimension,
    #     max_length=settings.embedding_dimension,
    # )
    embedding: List[float]


# Define the response model
class PredictionResponse(BaseModel):
    predicted_label: int
    predicted_score: float


# Initialize FastAPI app
app = FastAPI(
    title="Embedding Prediction API",
    description="API for predicting labels and scores from embeddings using a pre-trained model.",
    version="1.0.0",
)


# Dependency for model access
def get_model():
    """Dependency to provide the loaded model to endpoints."""
    return tuned_model


@app.get("/")
async def root():
    return RedirectResponse(url="/docs")


# Define the prediction endpoint
@app.post("/predict", response_model=PredictionResponse)
async def predict(
    request: EmbeddingRequest,
    model=Depends(get_model),
):
    """
    Predicts the label and score for a given embedding.

    Args:
        request (EmbeddingRequest): A request containing the embedding as a list of floats.
        model: The pre-trained model injected via dependency.

    Returns:
        PredictionResponse: A response containing the predicted label and score.
    """
    try:
        logger.info("Received prediction request.")

        # Convert the input embedding to a DataFrame
        input_data = pd.DataFrame(
            [request.embedding],
            columns=[f"embedding_{i}" for i in range(settings.embedding_dimension)],
        )

        # Make a prediction using the loaded model
        logger.info("Making prediction...")
        prediction = predict_model(model, data=input_data)

        # Validate the prediction output
        if (
            "prediction_label" not in prediction.columns
            or "prediction_score" not in prediction.columns
        ):
            raise ValueError("Model prediction output is missing required columns.")

        # Extract the predicted label and score
        predicted_label = prediction["prediction_label"].iloc[0]
        predicted_score = prediction["prediction_score"].iloc[0]

        if predicted_label == 3:
            predicted_label = 4

        logger.info(
            f"Prediction successful: label={predicted_label}, score={predicted_score}"
        )

        return PredictionResponse(
            predicted_label=int(predicted_label),
            predicted_score=float(predicted_score),
        )

    except ValidationError as e:
        logger.error(f"Validation error: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Invalid input data: {str(e)}",
        )
    except ValueError as e:
        logger.error(f"Value error: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Model output validation failed: {str(e)}",
        )
    except Exception as e:
        logger.error(f"Prediction failed: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"An error occurred during prediction: {str(e)}",
        )


# Health check endpoint
@app.get("/health", status_code=status.HTTP_200_OK)
async def health_check():
    """Health check endpoint to verify the API is running."""
    return {"status": "healthy"}


# # Run the FastAPI app
# if __name__ == "__main__":
#     import uvicorn

#     uvicorn.run(app, host="0.0.0.0", port=8000)