File size: 1,049 Bytes
9e03a51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

from pathlib import Path

from fastapi import FastAPI

from src.data import load_training_data
from src.modeling import DEFAULT_MODEL_PATH, HousePriceModel
from src.modeling import train_model
from src.schemas import HouseFeatures, PredictionResponse


def create_app(model_path: str | Path = DEFAULT_MODEL_PATH) -> FastAPI:
    app = FastAPI(title="House Price Prediction API", version="1.0.0")
    model_path = Path(model_path)
    if not model_path.exists():
        train_model(load_training_data(), artifact_path=model_path)
    model = HousePriceModel.load(model_path)

    @app.get("/health")
    def health() -> dict[str, str]:
        return {"status": "ok"}

    @app.get("/metrics")
    def metrics() -> dict[str, float]:
        return model.metrics

    @app.post("/predict", response_model=PredictionResponse)
    def predict(features: HouseFeatures) -> PredictionResponse:
        return PredictionResponse(predicted_price=model.predict(features.model_dump()))

    return app


app = create_app()