-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
69 lines (51 loc) · 1.71 KB
/
app.py
File metadata and controls
69 lines (51 loc) · 1.71 KB
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
import mlflow
import pandas as pd
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
mlflow.set_tracking_uri("sqlite:////mlflow-data/mlflow.db")
app = FastAPI(title="Wine Quality Classifier")
model = None
WINE_CLASS_NAMES = {0: "class_0", 1: "class_1", 2: "class_2"}
class WineFeatures(BaseModel):
model_config = {"populate_by_name": True}
alcohol: float
malic_acid: float
ash: float
alcalinity_of_ash: float
magnesium: float
total_phenols: float
flavanoids: float
nonflavanoid_phenols: float
proanthocyanins: float
color_intensity: float
hue: float
od280_od315_of_diluted_wines: float = Field(alias="od280/od315_of_diluted_wines")
proline: float
class PredictionResponse(BaseModel):
prediction: int
class_name: str
@app.on_event("startup")
def load_model():
global model
try:
model = mlflow.pyfunc.load_model("models:/wine_model_from_nb/1")
except Exception as e:
print(f"Failed to load model: {e}")
@app.get("/")
def root():
return {"message": "Welcome to the Wine Quality Classifier API"}
@app.get("/health")
def health():
if model is None:
raise HTTPException(status_code=503, detail="Model not loaded")
return {"status": "healthy", "model_loaded": True}
@app.post("/predict", response_model=PredictionResponse)
def predict(features: WineFeatures):
if model is None:
raise HTTPException(status_code=503, detail="Model not loaded")
df = pd.DataFrame([features.model_dump(by_alias=True)])
prediction = int(model.predict(df)[0])
return PredictionResponse(
prediction=prediction,
class_name=WINE_CLASS_NAMES.get(prediction, f"unknown_{prediction}"),
)