Spaces:
Sleeping
Sleeping
from fastapi import FastAPI, Request, Header, HTTPException | |
from fastapi.responses import HTMLResponse, JSONResponse | |
from fastapi.openapi.utils import get_openapi | |
from fastapi.openapi.docs import get_swagger_ui_html | |
from fastapi.middleware.cors import CORSMiddleware | |
from pydantic import BaseModel | |
from transformers import pipeline | |
import os, logging, traceback | |
from model import summarize_review, smart_summarize | |
from typing import Optional, List | |
app = FastAPI( | |
title="π§ NeuroPulse AI", | |
description="Multilingual GenAI for smarter feedback β summarization, sentiment, emotion, aspects, Q&A and tags.", | |
version="2025.1.0", | |
openapi_url="/openapi.json", | |
docs_url=None, | |
redoc_url="/redoc" | |
) | |
app.add_middleware( | |
CORSMiddleware, | |
allow_origins=["*"], | |
allow_credentials=True, | |
allow_methods=["*"], | |
allow_headers=["*"], | |
) | |
async def exception_handler(request: Request, exc: Exception): | |
logging.error(f"Unhandled Exception: {traceback.format_exc()}") | |
return JSONResponse(status_code=500, content={"detail": "Internal Server Error. Please contact support."}) | |
def custom_swagger_ui(): | |
return get_swagger_ui_html( | |
openapi_url=app.openapi_url, | |
title="π§ Swagger UI - NeuroPulse AI", | |
swagger_favicon_url="https://cdn-icons-png.flaticon.com/512/3794/3794616.png", | |
swagger_js_url="https://cdn.jsdelivr.net/npm/[email protected]/swagger-ui-bundle.js", | |
swagger_css_url="https://cdn.jsdelivr.net/npm/[email protected]/swagger-ui.css", | |
) | |
def root(): | |
return "<h1>NeuroPulse AI Backend is Running</h1>" | |
class ReviewInput(BaseModel): | |
text: str | |
model: str = "distilbert-base-uncased-finetuned-sst-2-english" | |
industry: Optional[str] = None | |
aspects: bool = False | |
follow_up: Optional[str] = None | |
product_category: Optional[str] = None | |
device: Optional[str] = None | |
intelligence: Optional[bool] = False | |
verbosity: Optional[str] = "detailed" | |
explain: Optional[bool] = False | |
class BulkReviewInput(BaseModel): | |
reviews: List[str] | |
model: str = "distilbert-base-uncased-finetuned-sst-2-english" | |
industry: Optional[List[str]] = None | |
aspects: bool = False | |
product_category: Optional[List[str]] = None | |
device: Optional[List[str]] = None | |
VALID_API_KEY = "my-secret-key" | |
logging.basicConfig(level=logging.INFO) | |
sentiment_pipeline = pipeline("sentiment-analysis") | |
def auto_fill(value: Optional[str], default: str = "Generic") -> str: | |
if not value or value.lower() == "auto-detect": | |
return default | |
return value | |
async def analyze(data: ReviewInput, x_api_key: str = Header(None)): | |
if x_api_key != VALID_API_KEY: | |
raise HTTPException(status_code=401, detail="β Unauthorized: Invalid API key") | |
if len(data.text.split()) < 10: | |
raise HTTPException(status_code=400, detail="β οΈ Review too short for analysis (min. 10 words).") | |
try: | |
# Summary Generation | |
try: | |
summary = smart_summarize(data.text) if data.intelligence else summarize_review(data.text) | |
except Exception as e: | |
logging.error(f"π Summarization error: {traceback.format_exc()}") | |
raise HTTPException(status_code=500, detail="π§ Failed to generate summary. Please try again.") | |
# Sentiment Analysis | |
try: | |
sentiment = sentiment_pipeline(data.text)[0] | |
except Exception as e: | |
logging.error(f"π Sentiment analysis error: {traceback.format_exc()}") | |
raise HTTPException(status_code=500, detail="π Sentiment analysis failed. Please retry.") | |
# (Optional future: plug in emotion model) | |
emotion = "joy" # hardcoded placeholder | |
return { | |
"summary": summary, | |
"sentiment": sentiment, | |
"emotion": emotion, | |
"product_category": auto_fill(data.product_category), | |
"device": auto_fill(data.device, "Web"), | |
"industry": auto_fill(data.industry) | |
} | |
except Exception as e: | |
logging.error(f"π₯ Unexpected analysis failure: {traceback.format_exc()}") | |
raise HTTPException(status_code=500, detail="Internal Server Error during analysis. Please contact support.") | |