Hasitha16 commited on
Commit
ac5d8ef
·
verified ·
1 Parent(s): 0017ff9

Upload main.py

Browse files
Files changed (1) hide show
  1. main.py +115 -0
main.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, Request, Header, HTTPException
2
+ from fastapi.responses import HTMLResponse, JSONResponse
3
+ from fastapi.openapi.utils import get_openapi
4
+ from fastapi.openapi.docs import get_swagger_ui_html
5
+ from fastapi.middleware.cors import CORSMiddleware
6
+ from pydantic import BaseModel
7
+ from transformers import pipeline
8
+ import os, logging, traceback
9
+ from model import summarize_review, smart_summarize, detect_industry, detect_product_category, answer_followup
10
+ from typing import Optional, List
11
+
12
+ app = FastAPI(
13
+ title="\U0001f9e0 NeuroPulse AI",
14
+ description="Multilingual GenAI for smarter feedback — summarization, sentiment, emotion, aspects, Q&A and tags.",
15
+ version="2025.1.0",
16
+ openapi_url="/openapi.json",
17
+ docs_url=None,
18
+ redoc_url="/redoc"
19
+ )
20
+
21
+ app.add_middleware(
22
+ CORSMiddleware,
23
+ allow_origins=["*"],
24
+ allow_credentials=True,
25
+ allow_methods=["*"],
26
+ allow_headers=["*"],
27
+ )
28
+
29
+ @app.exception_handler(Exception)
30
+ async def exception_handler(request: Request, exc: Exception):
31
+ logging.error(f"Unhandled Exception: {traceback.format_exc()}")
32
+ return JSONResponse(status_code=500, content={"detail": "Internal Server Error. Please contact support."})
33
+
34
+ @app.get("/docs", include_in_schema=False)
35
+ def custom_swagger_ui():
36
+ return get_swagger_ui_html(
37
+ openapi_url=app.openapi_url,
38
+ title="\U0001f9e0 Swagger UI - NeuroPulse AI",
39
+ swagger_favicon_url="https://cdn-icons-png.flaticon.com/512/3794/3794616.png",
40
+ swagger_js_url="https://cdn.jsdelivr.net/npm/[email protected]/swagger-ui-bundle.js",
41
+ swagger_css_url="https://cdn.jsdelivr.net/npm/[email protected]/swagger-ui.css",
42
+ )
43
+
44
+ @app.get("/", response_class=HTMLResponse)
45
+ def root():
46
+ return "<h1>NeuroPulse AI Backend is Running</h1>"
47
+
48
+ class ReviewInput(BaseModel):
49
+ text: str
50
+ model: str = "distilbert-base-uncased-finetuned-sst-2-english"
51
+ industry: Optional[str] = None
52
+ aspects: bool = False
53
+ follow_up: Optional[str] = None
54
+ product_category: Optional[str] = None
55
+ device: Optional[str] = None
56
+ intelligence: Optional[bool] = False
57
+ verbosity: Optional[str] = "detailed"
58
+ explain: Optional[bool] = False
59
+
60
+ class BulkReviewInput(BaseModel):
61
+ reviews: List[str]
62
+ model: str = "distilbert-base-uncased-finetuned-sst-2-english"
63
+ industry: Optional[List[str]] = None
64
+ aspects: bool = False
65
+ product_category: Optional[List[str]] = None
66
+ device: Optional[List[str]] = None
67
+
68
+ VALID_API_KEY = "my-secret-key"
69
+ logging.basicConfig(level=logging.INFO)
70
+ sentiment_pipeline = pipeline("sentiment-analysis")
71
+
72
+ def auto_fill(value: Optional[str], fallback: str) -> str:
73
+ if not value or value.lower() == "auto-detect":
74
+ return fallback
75
+ return value
76
+
77
+ @app.post("/analyze/")
78
+ async def analyze(data: ReviewInput, x_api_key: str = Header(None)):
79
+ if x_api_key != VALID_API_KEY:
80
+ raise HTTPException(status_code=401, detail="❌ Unauthorized: Invalid API key")
81
+ if len(data.text.split()) < 20:
82
+ raise HTTPException(status_code=400, detail="⚠️ Review too short for analysis (min. 20 words).")
83
+
84
+ try:
85
+ # Smart summary logic based on verbosity and intelligence
86
+ if data.verbosity.lower() == "brief":
87
+ summary = summarize_review(data.text, max_len=40, min_len=8)
88
+ else:
89
+ summary = smart_summarize(data.text, n_clusters=2 if data.intelligence else 1)
90
+
91
+ sentiment = sentiment_pipeline(data.text)[0]
92
+ emotion = "joy"
93
+
94
+ # Auto-detection logic
95
+ industry = detect_industry(data.text) if not data.industry or "auto" in data.industry.lower() else data.industry
96
+ product_category = detect_product_category(data.text) if not data.product_category or "auto" in data.product_category.lower() else data.product_category
97
+ device = "Web"
98
+
99
+ follow_up_response = None
100
+ if data.follow_up:
101
+ follow_up_response = answer_followup(data.text, data.follow_up, verbosity=data.verbosity)
102
+
103
+ return {
104
+ "summary": summary,
105
+ "sentiment": sentiment,
106
+ "emotion": emotion,
107
+ "product_category": product_category,
108
+ "device": device,
109
+ "industry": industry,
110
+ "follow_up": follow_up_response
111
+ }
112
+
113
+ except Exception as e:
114
+ logging.error(f"🔥 Unexpected analysis failure: {traceback.format_exc()}")
115
+ raise HTTPException(status_code=500, detail="Internal Server Error during analysis. Please contact support.")