Spaces:
Running
Running
Delete main.py
Browse files
main.py
DELETED
@@ -1,195 +0,0 @@
|
|
1 |
-
from fastapi import FastAPI, Request, Header, HTTPException, Query
|
2 |
-
from fastapi.responses import HTMLResponse, JSONResponse
|
3 |
-
from fastapi.openapi.docs import get_swagger_ui_html
|
4 |
-
from fastapi.middleware.cors import CORSMiddleware
|
5 |
-
from pydantic import BaseModel
|
6 |
-
from transformers import pipeline
|
7 |
-
import logging, traceback
|
8 |
-
from typing import Optional, List, Union
|
9 |
-
|
10 |
-
from model import (
|
11 |
-
summarize_review, smart_summarize, detect_industry,
|
12 |
-
detect_product_category, detect_emotion, answer_followup, answer_only
|
13 |
-
)
|
14 |
-
|
15 |
-
app = FastAPI(
|
16 |
-
title="🧠 NeuroPulse AI",
|
17 |
-
description="Multilingual GenAI for smarter feedback — summarization, sentiment, emotion, aspects, Q&A and tags.",
|
18 |
-
version="2025.1.0",
|
19 |
-
openapi_url="/openapi.json",
|
20 |
-
docs_url=None,
|
21 |
-
redoc_url="/redoc"
|
22 |
-
)
|
23 |
-
|
24 |
-
app.add_middleware(
|
25 |
-
CORSMiddleware,
|
26 |
-
allow_origins=["*"],
|
27 |
-
allow_credentials=True,
|
28 |
-
allow_methods=["*"],
|
29 |
-
allow_headers=["*"],
|
30 |
-
)
|
31 |
-
|
32 |
-
logging.basicConfig(level=logging.INFO)
|
33 |
-
VALID_API_KEY = "my-secret-key"
|
34 |
-
|
35 |
-
@app.get("/", response_class=HTMLResponse)
|
36 |
-
def root():
|
37 |
-
return "<h1>NeuroPulse AI Backend is Running</h1>"
|
38 |
-
|
39 |
-
@app.get("/docs", include_in_schema=False)
|
40 |
-
def custom_swagger_ui():
|
41 |
-
return get_swagger_ui_html(
|
42 |
-
openapi_url=app.openapi_url,
|
43 |
-
title="🧠 Swagger UI - NeuroPulse AI",
|
44 |
-
swagger_favicon_url="https://cdn-icons-png.flaticon.com/512/3794/3794616.png",
|
45 |
-
swagger_js_url="https://cdn.jsdelivr.net/npm/[email protected]/swagger-ui-bundle.js",
|
46 |
-
swagger_css_url="https://cdn.jsdelivr.net/npm/[email protected]/swagger-ui.css",
|
47 |
-
)
|
48 |
-
|
49 |
-
@app.exception_handler(Exception)
|
50 |
-
async def exception_handler(request: Request, exc: Exception):
|
51 |
-
logging.error(f"Unhandled Exception: {traceback.format_exc()}")
|
52 |
-
return JSONResponse(status_code=500, content={"detail": "Internal Server Error. Please contact support."})
|
53 |
-
|
54 |
-
# ==== SCHEMAS ====
|
55 |
-
|
56 |
-
class ReviewInput(BaseModel):
|
57 |
-
text: str
|
58 |
-
model: str = "distilbert-base-uncased-finetuned-sst-2-english"
|
59 |
-
industry: Optional[str] = None
|
60 |
-
aspects: bool = False
|
61 |
-
follow_up: Optional[Union[str, List[str]]] = None
|
62 |
-
product_category: Optional[str] = None
|
63 |
-
device: Optional[str] = None
|
64 |
-
intelligence: Optional[bool] = False
|
65 |
-
verbosity: Optional[str] = "detailed"
|
66 |
-
|
67 |
-
class BulkReviewInput(BaseModel):
|
68 |
-
reviews: List[str]
|
69 |
-
model: str = "distilbert-base-uncased-finetuned-sst-2-english"
|
70 |
-
industry: Optional[List[str]] = None
|
71 |
-
aspects: bool = False
|
72 |
-
product_category: Optional[List[str]] = None
|
73 |
-
device: Optional[List[str]] = None
|
74 |
-
follow_up: Optional[List[Union[str, List[str]]]] = None
|
75 |
-
intelligence: Optional[bool] = False
|
76 |
-
|
77 |
-
class FollowUpRequest(BaseModel):
|
78 |
-
text: str
|
79 |
-
question: str
|
80 |
-
verbosity: Optional[str] = "brief"
|
81 |
-
|
82 |
-
# ==== HELPERS ====
|
83 |
-
|
84 |
-
def auto_fill(value: Optional[str], fallback: str) -> str:
|
85 |
-
if not value or value.lower() == "auto-detect":
|
86 |
-
return fallback
|
87 |
-
return value
|
88 |
-
|
89 |
-
# ==== ENDPOINTS ====
|
90 |
-
|
91 |
-
@app.post("/analyze/")
|
92 |
-
async def analyze(data: ReviewInput, x_api_key: str = Header(None)):
|
93 |
-
if x_api_key and x_api_key != VALID_API_KEY:
|
94 |
-
raise HTTPException(status_code=401, detail="❌ Invalid API key")
|
95 |
-
|
96 |
-
if len(data.text.split()) < 20:
|
97 |
-
raise HTTPException(status_code=400, detail="⚠️ Review too short for analysis (min. 20 words).")
|
98 |
-
|
99 |
-
try:
|
100 |
-
response = {}
|
101 |
-
|
102 |
-
if not data.follow_up:
|
103 |
-
summary = (
|
104 |
-
summarize_review(data.text, max_len=40, min_len=8)
|
105 |
-
if data.verbosity.lower() == "brief"
|
106 |
-
else smart_summarize(data.text, n_clusters=2 if data.intelligence else 1)
|
107 |
-
)
|
108 |
-
|
109 |
-
sentiment_pipeline = pipeline("sentiment-analysis", model=data.model)
|
110 |
-
sentiment = sentiment_pipeline(data.text)[0]
|
111 |
-
emotion = detect_emotion(data.text)
|
112 |
-
|
113 |
-
industry = detect_industry(data.text) if not data.industry or "auto" in data.industry.lower() else data.industry
|
114 |
-
product_category = detect_product_category(data.text) if not data.product_category or "auto" in data.product_category.lower() else data.product_category
|
115 |
-
|
116 |
-
response = {
|
117 |
-
"summary": summary,
|
118 |
-
"sentiment": sentiment,
|
119 |
-
"emotion": emotion,
|
120 |
-
"product_category": product_category,
|
121 |
-
"device": "Web",
|
122 |
-
"industry": industry
|
123 |
-
}
|
124 |
-
|
125 |
-
if data.follow_up:
|
126 |
-
response["follow_up"] = answer_followup(data.text, data.follow_up, verbosity=data.verbosity)
|
127 |
-
|
128 |
-
return response
|
129 |
-
|
130 |
-
except Exception as e:
|
131 |
-
logging.error(f"🔥 Unexpected analysis failure: {traceback.format_exc()}")
|
132 |
-
raise HTTPException(status_code=500, detail="Internal Server Error during analysis. Please contact support.")
|
133 |
-
|
134 |
-
@app.post("/followup/")
|
135 |
-
async def followup(request: FollowUpRequest, x_api_key: str = Header(None)):
|
136 |
-
if x_api_key and x_api_key != VALID_API_KEY:
|
137 |
-
raise HTTPException(status_code=401, detail="Invalid API key")
|
138 |
-
|
139 |
-
if not request.question or len(request.text.split()) < 10:
|
140 |
-
raise HTTPException(status_code=400, detail="Question or text is too short.")
|
141 |
-
|
142 |
-
try:
|
143 |
-
answer = answer_only(request.text, request.question)
|
144 |
-
return {"answer": answer}
|
145 |
-
except Exception as e:
|
146 |
-
logging.error(f"❌ Follow-up failed: {traceback.format_exc()}")
|
147 |
-
raise HTTPException(status_code=500, detail="Internal Server Error during follow-up.")
|
148 |
-
|
149 |
-
@app.post("/bulk/")
|
150 |
-
async def bulk_analyze(data: BulkReviewInput, token: str = Query(None)):
|
151 |
-
if token != VALID_API_KEY:
|
152 |
-
raise HTTPException(status_code=401, detail="❌ Unauthorized: Invalid API token")
|
153 |
-
|
154 |
-
try:
|
155 |
-
results = []
|
156 |
-
sentiment_pipeline = pipeline("sentiment-analysis", model=data.model)
|
157 |
-
|
158 |
-
for i, review_text in enumerate(data.reviews):
|
159 |
-
if len(review_text.split()) < 20:
|
160 |
-
results.append({
|
161 |
-
"review": review_text,
|
162 |
-
"error": "Too short to analyze"
|
163 |
-
})
|
164 |
-
continue
|
165 |
-
|
166 |
-
summary = smart_summarize(review_text, n_clusters=2 if data.intelligence else 1)
|
167 |
-
sentiment = sentiment_pipeline(review_text)[0]
|
168 |
-
emotion = detect_emotion(review_text)
|
169 |
-
|
170 |
-
ind = auto_fill(data.industry[i] if data.industry else None, detect_industry(review_text))
|
171 |
-
prod = auto_fill(data.product_category[i] if data.product_category else None, detect_product_category(review_text))
|
172 |
-
dev = auto_fill(data.device[i] if data.device else None, "Web")
|
173 |
-
|
174 |
-
result = {
|
175 |
-
"review": review_text,
|
176 |
-
"summary": summary,
|
177 |
-
"sentiment": sentiment["label"],
|
178 |
-
"score": sentiment["score"],
|
179 |
-
"emotion": emotion,
|
180 |
-
"industry": ind,
|
181 |
-
"product_category": prod,
|
182 |
-
"device": dev
|
183 |
-
}
|
184 |
-
|
185 |
-
if data.follow_up and i < len(data.follow_up):
|
186 |
-
follow_q = data.follow_up[i]
|
187 |
-
result["follow_up"] = answer_followup(review_text, follow_q)
|
188 |
-
|
189 |
-
results.append(result)
|
190 |
-
|
191 |
-
return {"results": results}
|
192 |
-
|
193 |
-
except Exception as e:
|
194 |
-
logging.error(f"🔥 Bulk processing failed: {traceback.format_exc()}")
|
195 |
-
raise HTTPException(status_code=500, detail="Failed to analyze bulk reviews")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|