File size: 9,474 Bytes
d12790d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# """
# FastAPI REST API for Product Classification
# """
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse, JSONResponse
from starlette.requests import Request

from fastapi import FastAPI, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from typing import List, Optional
import logging
import time

# from classifier import ProductClassifier
# from config import API_TITLE, API_VERSION, API_DESCRIPTION, validate_files
from .classifier import ProductClassifier
from .config import API_TITLE, API_VERSION, API_DESCRIPTION, validate_files

# Set up logging
logging.basicConfig(
    level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)

# Validate files exist before starting
try:
    validate_files()
    logger.info("βœ… All required model files found")
except FileNotFoundError as e:
    logger.error(f"❌ Missing files: {e}")
    raise

# Create FastAPI app
app = FastAPI(title=API_TITLE, version=API_VERSION, description=API_DESCRIPTION)
templates = Jinja2Templates(directory="templates")
# Add CORS middleware (allows frontend to access API)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # In production, specify actual origins
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Initialize classifier (loaded once at startup)
classifier = None


# Pydantic models for request/response validation
class ProductInput(BaseModel):
    """Input model for single product classification"""

    id: Optional[str] = Field(default="unknown", description="Product ID")
    title: str = Field(..., description="Product title", min_length=1)
    product_type: Optional[str] = Field(default="", description="Product type/category")
    vendor: Optional[str] = Field(default="", description="Brand or vendor name")
    tags: Optional[List[str]] = Field(default=[], description="Product tags")
    description: Optional[str] = Field(default="", description="Product description")

    class Config:
        json_schema_extra = {
            "example": {
                "id": "prod_123",
                "title": "Apple iPhone 15 Pro",
                "product_type": "Smartphone",
                "vendor": "Apple Inc",
                "tags": ["electronics", "phone", "mobile"],
                "description": "Latest flagship smartphone",
            }
        }


class CategoryResult(BaseModel):
    """Result for a single category match"""

    rank: int
    category_id: str
    category_path: str
    confidence_percentage: float
    semantic_score: Optional[float] = None
    boost_applied: Optional[float] = None


class ClassificationResponse(BaseModel):
    """Response model for classification"""

    product_id: str
    action: str
    reason: str
    top_category: str
    top_confidence: float
    product_text: str
    alternatives: List[CategoryResult]
    processing_time_ms: Optional[float] = None


class BatchProductInput(BaseModel):
    """Input model for batch classification"""

    products: List[ProductInput] = Field(
        ..., description="List of products to classify"
    )
    top_k: int = Field(
        default=5, ge=1, le=20, description="Number of top matches to return"
    )


class HealthResponse(BaseModel):
    """Health check response"""

    status: str
    model: str
    categories_loaded: int
    embedding_dimension: int


# Startup event - load classifier
@app.on_event("startup")
async def startup_event():
    """Load the classifier when API starts"""
    global classifier
    logger.info("πŸš€ Starting API server...")
    logger.info("Loading Product Classifier...")

    try:
        classifier = ProductClassifier()
        logger.info("βœ… Classifier loaded successfully!")
    except Exception as e:
        logger.error(f"❌ Failed to load classifier: {e}")
        raise


# Root endpoint
# @app.get("/", tags=["General"])
# async def root():
#     """Root endpoint - API information"""
#     return {
#         "message": "Insurance Product Classification API",
#         "version": API_VERSION,
#         "status": "running",
#         "docs": "/docs",
#         "health": "/health",
#     }
@app.get("/", response_class=HTMLResponse, tags=["General"])
async def root(request: Request):
    """Serve the web UI"""
    return templates.TemplateResponse("index.html", {"request": request})


# Health check endpoint
@app.get("/health", response_model=HealthResponse, tags=["General"])
async def health_check():
    """
    Health check endpoint
    Returns system status and model information
    """
    if classifier is None:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="Classifier not initialized",
        )

    return {
        "status": "healthy",
        "model": "all-mpnet-base-v2",
        "categories_loaded": len(classifier.embeddings),
        "embedding_dimension": classifier.embeddings.shape[1],
    }


# Single product classification
@app.post("/classify", response_model=ClassificationResponse, tags=["Classification"])
async def classify_product(product: ProductInput):
    """
    Classify a single product into insurance categories

    Returns:
    - action: AUTO_APPROVE, QUICK_REVIEW, or MANUAL_CATEGORIZATION
    - top_category: Best matching category
    - confidence: Confidence score (0-100%)
    - alternatives: Top alternative categories
    """
    if classifier is None:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="Classifier not initialized",
        )

    try:
        # Start timer
        start_time = time.time()

        # Classify
        result = classifier.classify(product.dict())

        # Calculate processing time
        processing_time = (time.time() - start_time) * 1000  # Convert to ms
        result["processing_time_ms"] = round(processing_time, 2)

        logger.info(
            f"Classified product '{product.title}' β†’ "
            f"{result['action']} ({result['top_confidence']}%)"
        )

        return result

    except Exception as e:
        logger.error(f"Classification error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Classification failed: {str(e)}",
        )


# Batch product classification
@app.post("/classify-batch", tags=["Classification"])
async def classify_batch(batch: BatchProductInput):
    """
    Classify multiple products at once

    Useful for bulk processing of product catalogs
    """
    if classifier is None:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="Classifier not initialized",
        )

    try:
        start_time = time.time()

        # Convert to list of dicts
        products_data = [p.dict() for p in batch.products]

        # Classify batch
        results = classifier.classify_batch(products_data, top_k=batch.top_k)

        # Calculate stats
        processing_time = (time.time() - start_time) * 1000

        # Count actions
        action_counts = {}
        for result in results:
            action = result.get("action", "UNKNOWN")
            action_counts[action] = action_counts.get(action, 0) + 1

        logger.info(
            f"Batch classified {len(products_data)} products in {processing_time:.0f}ms"
        )

        return {
            "total_products": len(products_data),
            "processing_time_ms": round(processing_time, 2),
            "action_counts": action_counts,
            "results": results,
        }

    except Exception as e:
        logger.error(f"Batch classification error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Batch classification failed: {str(e)}",
        )


# Get statistics
@app.get("/stats", tags=["General"])
async def get_statistics():
    """
    Get system statistics
    """
    if classifier is None:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="Classifier not initialized",
        )

    return {
        "total_categories": len(classifier.embeddings),
        "embedding_dimension": classifier.embeddings.shape[1],
        "model_name": "all-mpnet-base-v2",
        "thresholds": {
            "auto_approve": "β‰₯75%",
            "quick_review": "60-75%",
            "manual": "<60%",
        },
    }


# Error handlers
from fastapi.responses import JSONResponse


@app.exception_handler(404)
async def not_found_handler(request, exc):
    """Handle 404 errors"""
    return JSONResponse(
        status_code=404,
        content={
            "error": "Endpoint not found",
            "message": "Check /docs for available endpoints",
        },
    )


@app.exception_handler(500)
async def internal_error_handler(request, exc):
    """Handle 500 errors"""
    logger.error(f"Internal server error: {exc}")
    return JSONResponse(
        status_code=500,
        content={
            "error": "Internal server error",
            "message": "Something went wrong. Check logs for details.",
        },
    )


# Run with: uvicorn api:app --reload
if __name__ == "__main__":
    import uvicorn

    uvicorn.run("api:app", host="0.0.0.0", port=8000, reload=True, log_level="info")