File size: 3,550 Bytes
ce09f09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#!/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)