Spaces:
Running
Running
Update main.py
Browse files
main.py
CHANGED
@@ -7,8 +7,11 @@ from pydantic import BaseModel
|
|
7 |
from fastapi import Query
|
8 |
from transformers import pipeline
|
9 |
import os, logging, traceback
|
10 |
-
from model import
|
11 |
-
|
|
|
|
|
|
|
12 |
|
13 |
app = FastAPI(
|
14 |
title="\U0001f9e0 NeuroPulse AI",
|
@@ -51,7 +54,7 @@ class ReviewInput(BaseModel):
|
|
51 |
model: str = "distilbert-base-uncased-finetuned-sst-2-english"
|
52 |
industry: Optional[str] = None
|
53 |
aspects: bool = False
|
54 |
-
follow_up: Optional[str] = None
|
55 |
product_category: Optional[str] = None
|
56 |
device: Optional[str] = None
|
57 |
intelligence: Optional[bool] = False
|
@@ -65,8 +68,10 @@ class BulkReviewInput(BaseModel):
|
|
65 |
aspects: bool = False
|
66 |
product_category: Optional[List[str]] = None
|
67 |
device: Optional[List[str]] = None
|
|
|
|
|
68 |
intelligence: Optional[bool] = False
|
69 |
-
|
70 |
VALID_API_KEY = "my-secret-key"
|
71 |
logging.basicConfig(level=logging.INFO)
|
72 |
sentiment_pipeline = pipeline("sentiment-analysis")
|
@@ -80,22 +85,22 @@ def auto_fill(value: Optional[str], fallback: str) -> str:
|
|
80 |
async def analyze(data: ReviewInput, x_api_key: str = Header(None)):
|
81 |
if x_api_key and x_api_key != VALID_API_KEY:
|
82 |
raise HTTPException(status_code=401, detail="β Invalid API key")
|
83 |
-
|
84 |
if len(data.text.split()) < 20:
|
85 |
raise HTTPException(status_code=400, detail="β οΈ Review too short for analysis (min. 20 words).")
|
86 |
|
87 |
try:
|
88 |
response = {}
|
89 |
|
90 |
-
# Only perform core analysis if follow-up not present (or first-time analysis)
|
91 |
if not data.follow_up:
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
|
|
96 |
|
97 |
sentiment = sentiment_pipeline(data.text)[0]
|
98 |
-
emotion =
|
99 |
|
100 |
industry = detect_industry(data.text) if not data.industry or "auto" in data.industry.lower() else data.industry
|
101 |
product_category = detect_product_category(data.text) if not data.product_category or "auto" in data.product_category.lower() else data.product_category
|
@@ -110,10 +115,11 @@ async def analyze(data: ReviewInput, x_api_key: str = Header(None)):
|
|
110 |
"industry": industry
|
111 |
}
|
112 |
|
113 |
-
|
|
|
|
|
114 |
if data.follow_up:
|
115 |
-
|
116 |
-
response["follow_up"] = follow_up_response
|
117 |
|
118 |
return response
|
119 |
|
@@ -122,12 +128,10 @@ async def analyze(data: ReviewInput, x_api_key: str = Header(None)):
|
|
122 |
raise HTTPException(status_code=500, detail="Internal Server Error during analysis. Please contact support.")
|
123 |
|
124 |
@app.post("/bulk/")
|
125 |
-
async def bulk_analyze(
|
126 |
-
data: BulkReviewInput,
|
127 |
-
token: str = Query(None)
|
128 |
-
):
|
129 |
if token != VALID_API_KEY:
|
130 |
raise HTTPException(status_code=401, detail="β Unauthorized: Invalid API token")
|
|
|
131 |
try:
|
132 |
results = []
|
133 |
for i, review_text in enumerate(data.reviews):
|
@@ -140,13 +144,13 @@ async def bulk_analyze(
|
|
140 |
|
141 |
summary = smart_summarize(review_text, n_clusters=2 if data.intelligence else 1)
|
142 |
sentiment = sentiment_pipeline(review_text)[0]
|
143 |
-
emotion =
|
144 |
|
145 |
ind = auto_fill(data.industry[i] if data.industry else None, detect_industry(review_text))
|
146 |
prod = auto_fill(data.product_category[i] if data.product_category else None, detect_product_category(review_text))
|
147 |
dev = auto_fill(data.device[i] if data.device else None, "Web")
|
148 |
|
149 |
-
|
150 |
"review": review_text,
|
151 |
"summary": summary,
|
152 |
"sentiment": sentiment["label"],
|
@@ -155,9 +159,21 @@ async def bulk_analyze(
|
|
155 |
"industry": ind,
|
156 |
"product_category": prod,
|
157 |
"device": dev
|
158 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
159 |
return {"results": results}
|
160 |
-
|
161 |
except Exception as e:
|
162 |
logging.error(f"π₯ Bulk processing failed: {traceback.format_exc()}")
|
163 |
raise HTTPException(status_code=500, detail="Failed to analyze bulk reviews")
|
|
|
7 |
from fastapi import Query
|
8 |
from transformers import pipeline
|
9 |
import os, logging, traceback
|
10 |
+
from model import (
|
11 |
+
summarize_review, smart_summarize, detect_industry,
|
12 |
+
detect_product_category, answer_followup, detect_emotion, generate_explanation
|
13 |
+
)
|
14 |
+
from typing import Optional, List, Union
|
15 |
|
16 |
app = FastAPI(
|
17 |
title="\U0001f9e0 NeuroPulse AI",
|
|
|
54 |
model: str = "distilbert-base-uncased-finetuned-sst-2-english"
|
55 |
industry: Optional[str] = None
|
56 |
aspects: bool = False
|
57 |
+
follow_up: Optional[Union[str, List[str]]] = None
|
58 |
product_category: Optional[str] = None
|
59 |
device: Optional[str] = None
|
60 |
intelligence: Optional[bool] = False
|
|
|
68 |
aspects: bool = False
|
69 |
product_category: Optional[List[str]] = None
|
70 |
device: Optional[List[str]] = None
|
71 |
+
follow_up: Optional[List[Union[str, List[str]]]] = None
|
72 |
+
explain: Optional[bool] = False
|
73 |
intelligence: Optional[bool] = False
|
74 |
+
|
75 |
VALID_API_KEY = "my-secret-key"
|
76 |
logging.basicConfig(level=logging.INFO)
|
77 |
sentiment_pipeline = pipeline("sentiment-analysis")
|
|
|
85 |
async def analyze(data: ReviewInput, x_api_key: str = Header(None)):
|
86 |
if x_api_key and x_api_key != VALID_API_KEY:
|
87 |
raise HTTPException(status_code=401, detail="β Invalid API key")
|
88 |
+
|
89 |
if len(data.text.split()) < 20:
|
90 |
raise HTTPException(status_code=400, detail="β οΈ Review too short for analysis (min. 20 words).")
|
91 |
|
92 |
try:
|
93 |
response = {}
|
94 |
|
|
|
95 |
if not data.follow_up:
|
96 |
+
summary = (
|
97 |
+
summarize_review(data.text, max_len=40, min_len=8)
|
98 |
+
if data.verbosity.lower() == "brief"
|
99 |
+
else smart_summarize(data.text, n_clusters=2 if data.intelligence else 1)
|
100 |
+
)
|
101 |
|
102 |
sentiment = sentiment_pipeline(data.text)[0]
|
103 |
+
emotion = detect_emotion(data.text)
|
104 |
|
105 |
industry = detect_industry(data.text) if not data.industry or "auto" in data.industry.lower() else data.industry
|
106 |
product_category = detect_product_category(data.text) if not data.product_category or "auto" in data.product_category.lower() else data.product_category
|
|
|
115 |
"industry": industry
|
116 |
}
|
117 |
|
118 |
+
if data.explain:
|
119 |
+
response["explanation"] = generate_explanation(data.text)
|
120 |
+
|
121 |
if data.follow_up:
|
122 |
+
response["follow_up"] = answer_followup(data.text, data.follow_up, verbosity=data.verbosity)
|
|
|
123 |
|
124 |
return response
|
125 |
|
|
|
128 |
raise HTTPException(status_code=500, detail="Internal Server Error during analysis. Please contact support.")
|
129 |
|
130 |
@app.post("/bulk/")
|
131 |
+
async def bulk_analyze(data: BulkReviewInput, token: str = Query(None)):
|
|
|
|
|
|
|
132 |
if token != VALID_API_KEY:
|
133 |
raise HTTPException(status_code=401, detail="β Unauthorized: Invalid API token")
|
134 |
+
|
135 |
try:
|
136 |
results = []
|
137 |
for i, review_text in enumerate(data.reviews):
|
|
|
144 |
|
145 |
summary = smart_summarize(review_text, n_clusters=2 if data.intelligence else 1)
|
146 |
sentiment = sentiment_pipeline(review_text)[0]
|
147 |
+
emotion = detect_emotion(review_text)
|
148 |
|
149 |
ind = auto_fill(data.industry[i] if data.industry else None, detect_industry(review_text))
|
150 |
prod = auto_fill(data.product_category[i] if data.product_category else None, detect_product_category(review_text))
|
151 |
dev = auto_fill(data.device[i] if data.device else None, "Web")
|
152 |
|
153 |
+
result = {
|
154 |
"review": review_text,
|
155 |
"summary": summary,
|
156 |
"sentiment": sentiment["label"],
|
|
|
159 |
"industry": ind,
|
160 |
"product_category": prod,
|
161 |
"device": dev
|
162 |
+
}
|
163 |
+
|
164 |
+
# Optional follow-up
|
165 |
+
if data.follow_up and i < len(data.follow_up):
|
166 |
+
follow_q = data.follow_up[i]
|
167 |
+
result["follow_up"] = answer_followup(review_text, follow_q)
|
168 |
+
|
169 |
+
# Optional explanation
|
170 |
+
if data.explain:
|
171 |
+
result["explanation"] = generate_explanation(review_text)
|
172 |
+
|
173 |
+
results.append(result)
|
174 |
+
|
175 |
return {"results": results}
|
176 |
+
|
177 |
except Exception as e:
|
178 |
logging.error(f"π₯ Bulk processing failed: {traceback.format_exc()}")
|
179 |
raise HTTPException(status_code=500, detail="Failed to analyze bulk reviews")
|