from fastapi import FastAPI, HTTPException, UploadFile, File from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles from pydantic import BaseModel from setfit import AbsaModel import logging from typing import List, Dict, Any import uvicorn import os # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # Initialize FastAPI app app = FastAPI(title="ABSA Web Application", description="Aspect-Based Sentiment Analysis using SetFit models") # Add CORS middleware app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Global variable to store the model absa_model = None class TextInput(BaseModel): text: str class ABSAResponse(BaseModel): text: str predictions: List[Dict[str, Any]] success: bool message: str async def load_model(): """Load the ABSA model on startup""" global absa_model try: logger.info("Loading ABSA models...") absa_model = AbsaModel.from_pretrained( "ronalhung/setfit-absa-restaurants-aspect", "ronalhung/setfit-absa-restaurants-polarity", ) logger.info("Models loaded successfully!") except Exception as e: logger.error(f"Failed to load models: {str(e)}") raise e @app.on_event("startup") async def startup_event(): """Load model when the application starts""" await load_model() @app.get("/", response_class=HTMLResponse) async def get_home(): """Serve the main HTML page""" html_content = """