ANL2001 commited on
Commit
222b972
·
1 Parent(s): 917c2df

feat: add FastAPI application

Browse files

Three endpoints: GET /health, POST /predict, GET /predictions.
Pydantic v2 schemas with field aliases for digit-prefixed column names.
SQLAlchemy ORM with PostgreSQL (prod) and SQLite (local dev) support.
Predictions logged to database on every inference.

Files changed (4) hide show
  1. app/database.py +49 -0
  2. app/main.py +54 -0
  3. app/model.py +29 -0
  4. app/schemas.py +143 -0
app/database.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from datetime import datetime, timezone
3
+ from sqlalchemy import create_engine, Column, Integer, Float, JSON, DateTime
4
+ from sqlalchemy.orm import DeclarativeBase, sessionmaker, Session
5
+
6
+ DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./predictions.db")
7
+
8
+ # SQLite needs a special connect arg for multithreading
9
+ connect_args = {"check_same_thread": False} if DATABASE_URL.startswith("sqlite") else {}
10
+
11
+ engine = create_engine(DATABASE_URL, connect_args=connect_args)
12
+ SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
13
+
14
+
15
+ class Base(DeclarativeBase):
16
+ pass
17
+
18
+
19
+ class Prediction(Base):
20
+ __tablename__ = "predictions"
21
+
22
+ id = Column(Integer, primary_key=True, index=True)
23
+ input_features = Column(JSON, nullable=False)
24
+ predicted_price = Column(Float, nullable=False)
25
+ created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
26
+
27
+
28
+ def create_tables():
29
+ Base.metadata.create_all(bind=engine)
30
+
31
+
32
+ def get_db():
33
+ db = SessionLocal()
34
+ try:
35
+ yield db
36
+ finally:
37
+ db.close()
38
+
39
+
40
+ def save_prediction(db: Session, input_features: dict, predicted_price: float) -> Prediction:
41
+ record = Prediction(input_features=input_features, predicted_price=predicted_price)
42
+ db.add(record)
43
+ db.commit()
44
+ db.refresh(record)
45
+ return record
46
+
47
+
48
+ def get_predictions(db: Session, limit: int = 50) -> list[Prediction]:
49
+ return db.query(Prediction).order_by(Prediction.created_at.desc()).limit(limit).all()
app/main.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import asynccontextmanager
2
+ from typing import List
3
+ from fastapi import FastAPI, Depends, HTTPException
4
+ from sqlalchemy.orm import Session
5
+
6
+ from app import model as ml
7
+ from app.database import create_tables, get_db, save_prediction, get_predictions
8
+ from app.schemas import HouseFeatures, PredictionResponse, PredictionRecord
9
+
10
+
11
+ @asynccontextmanager
12
+ async def lifespan(app: FastAPI):
13
+ create_tables()
14
+ ml.load_artifacts()
15
+ yield
16
+
17
+
18
+ app = FastAPI(
19
+ title="House Price Prediction API",
20
+ description="Predicts house sale prices using a GBR + CatBoost + KernelRidge stacking ensemble trained on the Kaggle Housing Prices dataset (Top 16 / 4,000+ participants).",
21
+ version="1.0.0",
22
+ lifespan=lifespan,
23
+ )
24
+
25
+
26
+ @app.get("/health", tags=["Health"])
27
+ def health():
28
+ return {"status": "ok", "model": "loaded" if ml._stack is not None else "not loaded"}
29
+
30
+
31
+ @app.post("/predict", response_model=PredictionResponse, tags=["Prediction"])
32
+ def predict(features: HouseFeatures, db: Session = Depends(get_db)):
33
+ try:
34
+ input_df = features.to_dataframe()
35
+ price = ml.predict(input_df)
36
+ except Exception as e:
37
+ raise HTTPException(status_code=500, detail=f"Prediction failed: {str(e)}")
38
+
39
+ record = save_prediction(
40
+ db=db,
41
+ input_features=features.model_dump(by_alias=True),
42
+ predicted_price=price,
43
+ )
44
+
45
+ return PredictionResponse(
46
+ prediction_id=record.id,
47
+ predicted_price=round(price, 2),
48
+ predicted_price_formatted=f"${price:,.0f}",
49
+ )
50
+
51
+
52
+ @app.get("/predictions", response_model=List[PredictionRecord], tags=["Prediction"])
53
+ def list_predictions(limit: int = 50, db: Session = Depends(get_db)):
54
+ return get_predictions(db, limit=limit)
app/model.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ import joblib
4
+ import pandas as pd
5
+
6
+ ARTIFACTS_DIR = os.path.join(os.path.dirname(__file__), "..", "ml", "artifacts")
7
+
8
+ _manual_processor = None
9
+ _stack = None
10
+ _core_features = None
11
+
12
+
13
+ def load_artifacts():
14
+ global _manual_processor, _stack, _core_features
15
+ _manual_processor = joblib.load(os.path.join(ARTIFACTS_DIR, "manual_processor.joblib"))
16
+ _stack = joblib.load(os.path.join(ARTIFACTS_DIR, "stack.joblib"))
17
+ _core_features = joblib.load(os.path.join(ARTIFACTS_DIR, "core_features.joblib"))
18
+ print("Model artifacts loaded.")
19
+
20
+
21
+ def predict(input_df: pd.DataFrame) -> float:
22
+ if _stack is None:
23
+ raise RuntimeError("Model not loaded. Call load_artifacts() first.")
24
+
25
+ X = input_df[_core_features].copy()
26
+ X_processed = _manual_processor.transform(X)
27
+
28
+ log_pred = _stack.predict(X_processed)
29
+ return float(np.expm1(log_pred)[0])
app/schemas.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ from typing import Optional
3
+ from pydantic import BaseModel, Field, ConfigDict
4
+ import pandas as pd
5
+
6
+
7
+ class HouseFeatures(BaseModel):
8
+ """Input features for house price prediction.
9
+ Fields starting with digits use snake_case aliases."""
10
+
11
+ model_config = ConfigDict(populate_by_name=True)
12
+
13
+ # Numerical area features
14
+ GrLivArea: float = Field(default=0.0, description="Above grade living area (sq ft)")
15
+ TotalBsmtSF: float = Field(default=0.0, description="Total basement area (sq ft)")
16
+ LotArea: float = Field(default=0.0, description="Lot size (sq ft)")
17
+ GarageArea: float = Field(default=0.0, description="Garage size (sq ft)")
18
+ PoolArea: float = Field(default=0.0, description="Pool area (sq ft)")
19
+ LotFrontage: Optional[float] = Field(default=None, description="Street frontage (ft)")
20
+ floor_2nd_sf: float = Field(default=0.0, alias="2ndFlrSF", description="2nd floor sq ft")
21
+ LowQualFinSF: float = Field(default=0.0, description="Low quality finished area (sq ft)")
22
+ BsmtUnfSF: float = Field(default=0.0, description="Unfinished basement area (sq ft)")
23
+ floor_1st_sf: float = Field(default=0.0, alias="1stFlrSF", description="1st floor sq ft")
24
+ WoodDeckSF: float = Field(default=0.0, description="Wood deck area (sq ft)")
25
+ OpenPorchSF: float = Field(default=0.0, description="Open porch area (sq ft)")
26
+ EnclosedPorch: float = Field(default=0.0, description="Enclosed porch area (sq ft)")
27
+ porch_3ssn_sf: float = Field(default=0.0, alias="3SsnPorch", description="3-season porch (sq ft)")
28
+ ScreenPorch: float = Field(default=0.0, description="Screen porch area (sq ft)")
29
+
30
+ # Counts
31
+ FullBath: int = Field(default=0, description="Full bathrooms above grade")
32
+ HalfBath: int = Field(default=0, description="Half baths above grade")
33
+ BsmtFullBath: int = Field(default=0, description="Basement full bathrooms")
34
+ BsmtHalfBath: int = Field(default=0, description="Basement half bathrooms")
35
+ TotRmsAbvGrd: int = Field(default=6, description="Total rooms above grade")
36
+ Fireplaces: int = Field(default=0, description="Number of fireplaces")
37
+
38
+ # Temporal
39
+ YearBuilt: int = Field(default=2000, description="Original construction year")
40
+ YrSold: int = Field(default=2010, description="Year sold")
41
+ YearRemodAdd: int = Field(default=2000, description="Remodel date")
42
+
43
+ # Quality / Condition (ordinal)
44
+ OverallQual: int = Field(default=5, ge=1, le=10, description="Overall material quality (1-10)")
45
+ OverallCond: int = Field(default=5, ge=1, le=9, description="Overall condition (1-9)")
46
+ HeatingQC: Optional[str] = Field(default="TA", description="Heating quality: Ex/Gd/TA/Fa/Po")
47
+ BsmtQual: Optional[str] = Field(default="TA", description="Basement height quality")
48
+ PoolQC: Optional[str] = Field(default=None, description="Pool quality")
49
+ ExterQual: Optional[str] = Field(default="TA", description="Exterior material quality")
50
+ KitchenQual: Optional[str] = Field(default="TA", description="Kitchen quality")
51
+ Functional: Optional[str] = Field(default="Typ", description="Home functionality")
52
+ FireplaceQu: Optional[str] = Field(default=None, description="Fireplace quality")
53
+ BsmtCond: Optional[str] = Field(default="TA", description="Basement condition")
54
+ ExterCond: Optional[str] = Field(default="TA", description="Exterior condition")
55
+
56
+ # Categorical (one-hot encoded)
57
+ Neighborhood: Optional[str] = Field(default="NAmes", description="Physical location")
58
+ MSZoning: Optional[str] = Field(default="RL", description="General zoning classification")
59
+ MSSubClass: Optional[int] = Field(default=20, description="Building class")
60
+ LandSlope: Optional[str] = Field(default="Gtl", description="Slope of property")
61
+ Alley: Optional[str] = Field(default=None, description="Alley access type")
62
+ LandContour: Optional[str] = Field(default="Lvl", description="Flatness of property")
63
+ BldgType: Optional[str] = Field(default="1Fam", description="Type of dwelling")
64
+ Condition1: Optional[str] = Field(default="Norm", description="Proximity to main road/railroad")
65
+ RoofStyle: Optional[str] = Field(default="Gable", description="Type of roof")
66
+ Foundation: Optional[str] = Field(default="PConc", description="Type of foundation")
67
+ SaleCondition: Optional[str] = Field(default="Normal", description="Condition of sale")
68
+ Exterior1st: Optional[str] = Field(default="VinylSd", description="Exterior covering on house")
69
+ Utilities: Optional[str] = Field(default="AllPub", description="Type of utilities available")
70
+ Electrical: Optional[str] = Field(default="SBrkr", description="Electrical system")
71
+ GarageQual: Optional[str] = Field(default="TA", description="Garage quality")
72
+ GarageCond: Optional[str] = Field(default="TA", description="Garage condition")
73
+
74
+ def to_dataframe(self) -> "pd.DataFrame":
75
+ import pandas as pd
76
+ row = {
77
+ "GrLivArea": self.GrLivArea,
78
+ "TotalBsmtSF": self.TotalBsmtSF,
79
+ "LotArea": self.LotArea,
80
+ "GarageArea": self.GarageArea,
81
+ "PoolArea": self.PoolArea,
82
+ "LotFrontage": self.LotFrontage,
83
+ "2ndFlrSF": self.floor_2nd_sf,
84
+ "LowQualFinSF": self.LowQualFinSF,
85
+ "BsmtUnfSF": self.BsmtUnfSF,
86
+ "1stFlrSF": self.floor_1st_sf,
87
+ "WoodDeckSF": self.WoodDeckSF,
88
+ "OpenPorchSF": self.OpenPorchSF,
89
+ "EnclosedPorch": self.EnclosedPorch,
90
+ "3SsnPorch": self.porch_3ssn_sf,
91
+ "ScreenPorch": self.ScreenPorch,
92
+ "FullBath": self.FullBath,
93
+ "HalfBath": self.HalfBath,
94
+ "BsmtFullBath": self.BsmtFullBath,
95
+ "BsmtHalfBath": self.BsmtHalfBath,
96
+ "TotRmsAbvGrd": self.TotRmsAbvGrd,
97
+ "Fireplaces": self.Fireplaces,
98
+ "YearBuilt": self.YearBuilt,
99
+ "YrSold": self.YrSold,
100
+ "YearRemodAdd": self.YearRemodAdd,
101
+ "OverallQual": self.OverallQual,
102
+ "OverallCond": self.OverallCond,
103
+ "HeatingQC": self.HeatingQC,
104
+ "BsmtQual": self.BsmtQual,
105
+ "PoolQC": self.PoolQC,
106
+ "ExterQual": self.ExterQual,
107
+ "KitchenQual": self.KitchenQual,
108
+ "Functional": self.Functional,
109
+ "FireplaceQu": self.FireplaceQu,
110
+ "BsmtCond": self.BsmtCond,
111
+ "ExterCond": self.ExterCond,
112
+ "Neighborhood": self.Neighborhood,
113
+ "MSZoning": self.MSZoning,
114
+ "MSSubClass": self.MSSubClass,
115
+ "LandSlope": self.LandSlope,
116
+ "Alley": self.Alley,
117
+ "LandContour": self.LandContour,
118
+ "BldgType": self.BldgType,
119
+ "Condition1": self.Condition1,
120
+ "RoofStyle": self.RoofStyle,
121
+ "Foundation": self.Foundation,
122
+ "SaleCondition": self.SaleCondition,
123
+ "Exterior1st": self.Exterior1st,
124
+ "Utilities": self.Utilities,
125
+ "Electrical": self.Electrical,
126
+ "GarageQual": self.GarageQual,
127
+ "GarageCond": self.GarageCond,
128
+ }
129
+ return pd.DataFrame([row])
130
+
131
+
132
+ class PredictionResponse(BaseModel):
133
+ prediction_id: int
134
+ predicted_price: float
135
+ predicted_price_formatted: str
136
+
137
+
138
+ class PredictionRecord(BaseModel):
139
+ id: int
140
+ predicted_price: float
141
+ created_at: datetime
142
+
143
+ model_config = ConfigDict(from_attributes=True)