#!/usr/bin/env python3 """ FastAPI server for EagleViz maintenance prediction API Serves the trained sklearn model for real-time inference """ import os import logging from typing import Dict, List, Optional, Any from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel import joblib import numpy as np from datetime import datetime # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) app = FastAPI(title="EagleViz Maintenance Prediction API", version="1.0.0") # CORS middleware for frontend integration app.add_middleware( CORSMiddleware, allow_origins=["*"], # Configure for production allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Load the trained model MODEL_PATH = "./models/maintenance-predictor/sklearn_pipeline.joblib" model = None def load_model(): """Load the trained sklearn model""" global model try: print(f"DEBUG: Loading model from {MODEL_PATH}") if os.path.exists(MODEL_PATH): model = joblib.load(MODEL_PATH) print(f"DEBUG: Model loaded, type: {type(model)}") logger.info("✅ Sklearn model loaded successfully") return True else: print(f"DEBUG: Model file not found at {MODEL_PATH}") logger.warning(f"⚠️ Model not found at {MODEL_PATH}") return False except Exception as e: print(f"DEBUG: Error loading model: {e}") logger.error(f"❌ Failed to load model: {e}") return False # Load model on startup model_loaded = load_model() class MaintenanceAnalysisRequest(BaseModel): text: str vehicle_id: Optional[str] = None additional_features: Optional[Dict[str, Any]] = None class MaintenanceAnalysisResponse(BaseModel): category: str confidence: float top_predictions: List[Dict[str, Any]] model_version: str = "sklearn-v1.0" timestamp: datetime class HealthResponse(BaseModel): status: str model_loaded: bool timestamp: datetime @app.get("/health", response_model=HealthResponse) async def health_check(): """Health check endpoint""" return HealthResponse( status="healthy" if model_loaded else "degraded", model_loaded=model_loaded, timestamp=datetime.now() ) @app.post("/api/maintenance/analyze") async def analyze_maintenance(request: MaintenanceAnalysisRequest): """ Analyze maintenance text and predict issue category This endpoint is called by the frontend HuggingFaceIntegration service """ print(f"DEBUG: Received request with text: {request.text}") # Simple response for testing return { "category": "brake_issue", "confidence": 0.85, "top_predictions": [ {"category": 0, "confidence": 0.6}, {"category": 1, "confidence": 0.4} ], "timestamp": datetime.now().isoformat() } @app.get("/api/maintenance/categories") async def get_categories(): """Get available maintenance categories""" return { "categories": [ "no_issue", "brake_issue", "engine_problem", "transmission", "electrical", "tire_wear", "other" ] } if __name__ == "__main__": import uvicorn port = int(os.getenv("PORT", 8000)) logger.info(f"🚀 Starting EagleViz Maintenance API on port {port}") uvicorn.run(app, host="0.0.0.0", port=port)