Spaces:
Sleeping
Sleeping
| from fastapi import APIRouter, Depends, HTTPException, Header, status | |
| from sqlalchemy.orm import Session | |
| from app.core.database import get_db | |
| from app.models.schemas import InputSchema, PredictionOutput | |
| from app.models.models import PredictionLog | |
| from app.services.ml_service import ml_service | |
| from app.core.config import settings | |
| router = APIRouter() | |
| def verify_api_key(x_api_key: str = Header(...)): | |
| if x_api_key != settings.API_KEY: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid API Key", | |
| ) | |
| return x_api_key | |
| def predict(input_data: InputSchema, db: Session = Depends(get_db), api_key: str = Depends(verify_api_key)): | |
| # Convert Pydantic model to dict | |
| data_dict = input_data.dict() | |
| try: | |
| # Make prediction | |
| prediction, probability = ml_service.predict(data_dict) | |
| # Log to Database | |
| db_log = PredictionLog( | |
| **data_dict, | |
| prediction=prediction, | |
| probability=probability | |
| ) | |
| db.add(db_log) | |
| db.commit() | |
| db.refresh(db_log) | |
| return PredictionOutput(prediction=prediction, probability=probability) | |
| except Exception as e: | |
| print(f"Error during prediction: {e}") | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| def health_check(): | |
| return {"status": "healthy"} | |
| def model_info(api_key: str = Depends(verify_api_key)): | |
| model = ml_service.model | |
| if not model: | |
| return {"status": "Model not loaded"} | |
| return { | |
| "type": str(type(model)), | |
| "params": model.get_params() if hasattr(model, "get_params") else "Unknown" | |
| } | |