# serve.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
import joblib
import numpy as np
app = FastAPI(title="Wine Quality Classifier")
model = joblib.load("wine_model.pkl")
WINE_CLASSES = {0: "Class 0", 1: "Class 1", 2: "Class 2"}
class WineFeatures(BaseModel):
alcohol: float = Field(..., example=13.2, ge=10.0, le=15.5)
malic_acid: float = Field(..., example=1.78, ge=0.5, le=6.0)
ash: float = Field(..., example=2.14, ge=1.0, le=4.0)
alcalinity_of_ash: float = Field(..., example=11.2, ge=10.0, le=30.0)
magnesium: float = Field(..., example=100.0, ge=70.0, le=165.0)
total_phenols: float = Field(..., example=2.65, ge=0.5, le=4.0)
flavanoids: float = Field(..., example=2.76, ge=0.0, le=6.0)
nonflavanoid_phenols: float = Field(..., example=0.26, ge=0.0, le=1.0)
proanthocyanins: float = Field(..., example=1.28, ge=0.0, le=4.0)
color_intensity: float = Field(..., example=4.38, ge=1.0, le=15.0)
hue: float = Field(..., example=1.05, ge=0.5, le=2.0)
od280_od315: float = Field(..., example=3.40, ge=1.0, le=5.0)
proline: float = Field(..., example=1050.0, ge=300.0, le=2000.0)
@app.get("/health")
def health(): return {"status": "ok"}
@app.post("/predict")
def predict(wine: WineFeatures):
features = np.array([[getattr(wine, f) for f in wine.model_fields]])
pred = int(model.predict(features)[0])
proba = model.predict_proba(features)[0]
return {
"predicted_class": pred,
"class_name": WINE_CLASSES[pred],
"probabilities": {WINE_CLASSES[i]: round(float(p), 4)
for i, p in enumerate(proba)}
}