Spaces:
Running
Running
Update main.py
Browse files
main.py
CHANGED
@@ -12,7 +12,7 @@ from typing import Optional, List, Union
|
|
12 |
from model import (
|
13 |
summarize_review, smart_summarize, detect_industry,
|
14 |
detect_product_category, detect_emotion, answer_followup, answer_only,
|
15 |
-
assess_churn_risk # β
|
16 |
)
|
17 |
|
18 |
app = FastAPI(
|
@@ -34,7 +34,7 @@ app.add_middleware(
|
|
34 |
|
35 |
logging.basicConfig(level=logging.INFO)
|
36 |
VALID_API_KEY = "my-secret-key"
|
37 |
-
log_store = []
|
38 |
|
39 |
@app.get("/", response_class=HTMLResponse)
|
40 |
def root():
|
@@ -100,52 +100,45 @@ async def analyze(data: ReviewInput, x_api_key: str = Header(None)):
|
|
100 |
if len(data.text.split()) < 20:
|
101 |
raise HTTPException(status_code=400, detail="β οΈ Review too short for analysis (min. 20 words).")
|
102 |
|
103 |
-
|
104 |
-
response = {}
|
105 |
-
|
106 |
-
if not data.follow_up:
|
107 |
-
summary = (
|
108 |
-
summarize_review(data.text, max_len=40, min_len=8)
|
109 |
-
if data.verbosity.lower() == "brief"
|
110 |
-
else smart_summarize(data.text, n_clusters=2 if data.intelligence else 1)
|
111 |
-
)
|
112 |
-
|
113 |
-
sentiment_pipeline = pipeline("sentiment-analysis", model=data.model)
|
114 |
-
sentiment = sentiment_pipeline(data.text)[0]
|
115 |
-
emotion_raw = detect_emotion(data.text)
|
116 |
-
emotion = emotion_raw["label"] if isinstance(emotion_raw, dict) and "label" in emotion_raw else str(emotion_raw)
|
117 |
-
churn_risk = assess_churn_risk(sentiment["label"], emotion)
|
118 |
-
|
119 |
-
# Log churn risk analysis
|
120 |
-
log_entry = {
|
121 |
-
"timestamp": datetime.now(),
|
122 |
-
"product": data.product_category or "Generic",
|
123 |
-
"churn_risk": churn_risk,
|
124 |
-
"user_id": str(uuid.uuid4()) # Optional
|
125 |
-
}
|
126 |
-
log_store.append(log_entry)
|
127 |
-
if len(log_store) > 1000:
|
128 |
-
log_store = log_store[-1000:] # keep latest 1000 entries
|
129 |
-
|
130 |
-
pain_points = []
|
131 |
-
if data.aspects:
|
132 |
-
from model import extract_pain_points # π Import inline if not already
|
133 |
-
pain_points = extract_pain_points(data.text)
|
134 |
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
"emotion": emotion,
|
142 |
-
"product_category": product_category,
|
143 |
-
"device": "Web",
|
144 |
-
"industry": industry,
|
145 |
-
"churn_risk": churn_risk,
|
146 |
-
"pain_points": pain_points
|
147 |
|
148 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
149 |
|
150 |
if data.follow_up:
|
151 |
response["follow_up"] = answer_followup(data.text, data.follow_up, verbosity=data.verbosity)
|
@@ -154,22 +147,19 @@ async def analyze(data: ReviewInput, x_api_key: str = Header(None)):
|
|
154 |
|
155 |
except Exception as e:
|
156 |
logging.error(f"π₯ Unexpected analysis failure: {traceback.format_exc()}")
|
157 |
-
raise HTTPException(status_code=500, detail="Internal Server Error during analysis.
|
158 |
|
159 |
@app.post("/followup/")
|
160 |
async def followup(request: FollowUpRequest, x_api_key: str = Header(None)):
|
161 |
if x_api_key and x_api_key != VALID_API_KEY:
|
162 |
raise HTTPException(status_code=401, detail="Invalid API key")
|
163 |
-
|
164 |
-
if not request.question or len(request.text.split()) < 10:
|
165 |
-
raise HTTPException(status_code=400, detail="Question or text is too short.")
|
166 |
-
|
167 |
try:
|
168 |
-
|
169 |
-
|
|
|
170 |
except Exception as e:
|
171 |
logging.error(f"β Follow-up failed: {traceback.format_exc()}")
|
172 |
-
raise HTTPException(status_code=500, detail="
|
173 |
|
174 |
@app.get("/log/")
|
175 |
async def get_churn_log(x_api_key: str = Header(None)):
|
@@ -177,12 +167,13 @@ async def get_churn_log(x_api_key: str = Header(None)):
|
|
177 |
raise HTTPException(status_code=401, detail="Unauthorized")
|
178 |
return {"log": log_store}
|
179 |
|
180 |
-
|
181 |
@app.post("/bulk/")
|
182 |
async def bulk_analyze(data: BulkReviewInput, token: str = Query(None)):
|
183 |
if token != VALID_API_KEY:
|
184 |
raise HTTPException(status_code=401, detail="β Unauthorized: Invalid API token")
|
185 |
|
|
|
|
|
186 |
try:
|
187 |
results = []
|
188 |
sentiment_pipeline = pipeline("sentiment-analysis", model=data.model)
|
@@ -198,22 +189,9 @@ async def bulk_analyze(data: BulkReviewInput, token: str = Query(None)):
|
|
198 |
summary = smart_summarize(review_text, n_clusters=2 if data.intelligence else 1)
|
199 |
sentiment = sentiment_pipeline(review_text)[0]
|
200 |
emotion = detect_emotion(review_text)
|
201 |
-
|
202 |
churn = assess_churn_risk(sentiment["label"], emotion)
|
203 |
pain = extract_pain_points(review_text) if data.aspects else []
|
204 |
|
205 |
-
# π Log churn data
|
206 |
-
log_entry = {
|
207 |
-
"timestamp": datetime.now(),
|
208 |
-
"product": prod,
|
209 |
-
"churn_risk": churn,
|
210 |
-
"user_id": str(uuid.uuid4())
|
211 |
-
}
|
212 |
-
log_store.append(log_entry)
|
213 |
-
if len(log_store) > 1000:
|
214 |
-
log_store = log_store[-1000:]
|
215 |
-
|
216 |
-
|
217 |
ind = auto_fill(data.industry[i] if data.industry else None, detect_industry(review_text))
|
218 |
prod = auto_fill(data.product_category[i] if data.product_category else None, detect_product_category(review_text))
|
219 |
dev = auto_fill(data.device[i] if data.device else None, "Web")
|
@@ -235,11 +213,21 @@ async def bulk_analyze(data: BulkReviewInput, token: str = Query(None)):
|
|
235 |
follow_q = data.follow_up[i]
|
236 |
result["follow_up"] = answer_followup(review_text, follow_q)
|
237 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
238 |
results.append(result)
|
239 |
|
|
|
|
|
|
|
240 |
return {"results": results}
|
241 |
|
242 |
except Exception as e:
|
243 |
logging.error(f"π₯ Bulk processing failed: {traceback.format_exc()}")
|
244 |
raise HTTPException(status_code=500, detail="Failed to analyze bulk reviews")
|
245 |
-
|
|
|
12 |
from model import (
|
13 |
summarize_review, smart_summarize, detect_industry,
|
14 |
detect_product_category, detect_emotion, answer_followup, answer_only,
|
15 |
+
assess_churn_risk, extract_pain_points # β
Added extract_pain_points
|
16 |
)
|
17 |
|
18 |
app = FastAPI(
|
|
|
34 |
|
35 |
logging.basicConfig(level=logging.INFO)
|
36 |
VALID_API_KEY = "my-secret-key"
|
37 |
+
log_store = [] # β
Shared in-memory churn log
|
38 |
|
39 |
@app.get("/", response_class=HTMLResponse)
|
40 |
def root():
|
|
|
100 |
if len(data.text.split()) < 20:
|
101 |
raise HTTPException(status_code=400, detail="β οΈ Review too short for analysis (min. 20 words).")
|
102 |
|
103 |
+
global log_store # β
Needed for logging
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
|
105 |
+
try:
|
106 |
+
summary = (
|
107 |
+
summarize_review(data.text, max_len=40, min_len=8)
|
108 |
+
if data.verbosity.lower() == "brief"
|
109 |
+
else smart_summarize(data.text, n_clusters=2 if data.intelligence else 1)
|
110 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
111 |
|
112 |
+
sentiment_pipeline = pipeline("sentiment-analysis", model=data.model)
|
113 |
+
sentiment = sentiment_pipeline(data.text)[0]
|
114 |
+
emotion_raw = detect_emotion(data.text)
|
115 |
+
emotion = emotion_raw["label"] if isinstance(emotion_raw, dict) and "label" in emotion_raw else str(emotion_raw)
|
116 |
+
churn_risk = assess_churn_risk(sentiment["label"], emotion)
|
117 |
+
industry = detect_industry(data.text) if not data.industry or "auto" in data.industry.lower() else data.industry
|
118 |
+
product_category = detect_product_category(data.text) if not data.product_category or "auto" in data.product_category.lower() else data.product_category
|
119 |
+
|
120 |
+
pain_points = extract_pain_points(data.text) if data.aspects else []
|
121 |
+
|
122 |
+
# β
Log churn entry
|
123 |
+
log_store.append({
|
124 |
+
"timestamp": datetime.now(),
|
125 |
+
"product": product_category,
|
126 |
+
"churn_risk": churn_risk,
|
127 |
+
"user_id": str(uuid.uuid4())
|
128 |
+
})
|
129 |
+
if len(log_store) > 1000:
|
130 |
+
log_store = log_store[-1000:]
|
131 |
+
|
132 |
+
response = {
|
133 |
+
"summary": summary,
|
134 |
+
"sentiment": sentiment,
|
135 |
+
"emotion": emotion,
|
136 |
+
"product_category": product_category,
|
137 |
+
"device": "Web",
|
138 |
+
"industry": industry,
|
139 |
+
"churn_risk": churn_risk,
|
140 |
+
"pain_points": pain_points
|
141 |
+
}
|
142 |
|
143 |
if data.follow_up:
|
144 |
response["follow_up"] = answer_followup(data.text, data.follow_up, verbosity=data.verbosity)
|
|
|
147 |
|
148 |
except Exception as e:
|
149 |
logging.error(f"π₯ Unexpected analysis failure: {traceback.format_exc()}")
|
150 |
+
raise HTTPException(status_code=500, detail="Internal Server Error during analysis.")
|
151 |
|
152 |
@app.post("/followup/")
|
153 |
async def followup(request: FollowUpRequest, x_api_key: str = Header(None)):
|
154 |
if x_api_key and x_api_key != VALID_API_KEY:
|
155 |
raise HTTPException(status_code=401, detail="Invalid API key")
|
|
|
|
|
|
|
|
|
156 |
try:
|
157 |
+
if not request.question or len(request.text.split()) < 10:
|
158 |
+
raise HTTPException(status_code=400, detail="Question or text is too short.")
|
159 |
+
return {"answer": answer_only(request.text, request.question)}
|
160 |
except Exception as e:
|
161 |
logging.error(f"β Follow-up failed: {traceback.format_exc()}")
|
162 |
+
raise HTTPException(status_code=500, detail="Follow-up generation failed.")
|
163 |
|
164 |
@app.get("/log/")
|
165 |
async def get_churn_log(x_api_key: str = Header(None)):
|
|
|
167 |
raise HTTPException(status_code=401, detail="Unauthorized")
|
168 |
return {"log": log_store}
|
169 |
|
|
|
170 |
@app.post("/bulk/")
|
171 |
async def bulk_analyze(data: BulkReviewInput, token: str = Query(None)):
|
172 |
if token != VALID_API_KEY:
|
173 |
raise HTTPException(status_code=401, detail="β Unauthorized: Invalid API token")
|
174 |
|
175 |
+
global log_store # β
Needed to log bulk churn
|
176 |
+
|
177 |
try:
|
178 |
results = []
|
179 |
sentiment_pipeline = pipeline("sentiment-analysis", model=data.model)
|
|
|
189 |
summary = smart_summarize(review_text, n_clusters=2 if data.intelligence else 1)
|
190 |
sentiment = sentiment_pipeline(review_text)[0]
|
191 |
emotion = detect_emotion(review_text)
|
|
|
192 |
churn = assess_churn_risk(sentiment["label"], emotion)
|
193 |
pain = extract_pain_points(review_text) if data.aspects else []
|
194 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
195 |
ind = auto_fill(data.industry[i] if data.industry else None, detect_industry(review_text))
|
196 |
prod = auto_fill(data.product_category[i] if data.product_category else None, detect_product_category(review_text))
|
197 |
dev = auto_fill(data.device[i] if data.device else None, "Web")
|
|
|
213 |
follow_q = data.follow_up[i]
|
214 |
result["follow_up"] = answer_followup(review_text, follow_q)
|
215 |
|
216 |
+
# β
Log churn
|
217 |
+
log_store.append({
|
218 |
+
"timestamp": datetime.now(),
|
219 |
+
"product": prod,
|
220 |
+
"churn_risk": churn,
|
221 |
+
"user_id": str(uuid.uuid4())
|
222 |
+
})
|
223 |
+
|
224 |
results.append(result)
|
225 |
|
226 |
+
if len(log_store) > 1000:
|
227 |
+
log_store = log_store[-1000:]
|
228 |
+
|
229 |
return {"results": results}
|
230 |
|
231 |
except Exception as e:
|
232 |
logging.error(f"π₯ Bulk processing failed: {traceback.format_exc()}")
|
233 |
raise HTTPException(status_code=500, detail="Failed to analyze bulk reviews")
|
|