Hasitha16 commited on
Commit
db263fd
·
verified ·
1 Parent(s): 1c216da

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +45 -43
main.py CHANGED
@@ -1,21 +1,19 @@
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 model import answer_only
8
- from fastapi import Query
9
  from transformers import pipeline
10
- import os, logging, traceback
 
 
11
  from model import (
12
- summarize_review, smart_summarize, detect_industry,
13
- detect_product_category, answer_followup, detect_emotion
14
  )
15
- from typing import Optional, List, Union
16
 
17
  app = FastAPI(
18
- title="\U0001f9e0 NeuroPulse AI",
19
  description="Multilingual GenAI for smarter feedback — summarization, sentiment, emotion, aspects, Q&A and tags.",
20
  version="2025.1.0",
21
  openapi_url="/openapi.json",
@@ -31,24 +29,29 @@ app.add_middleware(
31
  allow_headers=["*"],
32
  )
33
 
34
- @app.exception_handler(Exception)
35
- async def exception_handler(request: Request, exc: Exception):
36
- logging.error(f"Unhandled Exception: {traceback.format_exc()}")
37
- return JSONResponse(status_code=500, content={"detail": "Internal Server Error. Please contact support."})
 
 
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="\U0001f9e0 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.get("/", response_class=HTMLResponse)
50
- def root():
51
- return "<h1>NeuroPulse AI Backend is Running</h1>"
 
 
 
52
 
53
  class ReviewInput(BaseModel):
54
  text: str
@@ -69,16 +72,22 @@ class BulkReviewInput(BaseModel):
69
  product_category: Optional[List[str]] = None
70
  device: Optional[List[str]] = None
71
  follow_up: Optional[List[Union[str, List[str]]]] = None
72
- intelligence: Optional[bool] = False
73
 
74
- VALID_API_KEY = "my-secret-key"
75
- logging.basicConfig(level=logging.INFO)
 
 
 
 
76
 
77
  def auto_fill(value: Optional[str], fallback: str) -> str:
78
  if not value or value.lower() == "auto-detect":
79
  return fallback
80
  return value
81
 
 
 
82
  @app.post("/analyze/")
83
  async def analyze(data: ReviewInput, x_api_key: str = Header(None)):
84
  if x_api_key and x_api_key != VALID_API_KEY:
@@ -103,14 +112,13 @@ async def analyze(data: ReviewInput, x_api_key: str = Header(None)):
103
 
104
  industry = detect_industry(data.text) if not data.industry or "auto" in data.industry.lower() else data.industry
105
  product_category = detect_product_category(data.text) if not data.product_category or "auto" in data.product_category.lower() else data.product_category
106
- device = "Web"
107
 
108
  response = {
109
  "summary": summary,
110
  "sentiment": sentiment,
111
  "emotion": emotion,
112
  "product_category": product_category,
113
- "device": device,
114
  "industry": industry
115
  }
116
 
@@ -123,6 +131,21 @@ async def analyze(data: ReviewInput, x_api_key: str = Header(None)):
123
  logging.error(f"🔥 Unexpected analysis failure: {traceback.format_exc()}")
124
  raise HTTPException(status_code=500, detail="Internal Server Error during analysis. Please contact support.")
125
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  @app.post("/bulk/")
127
  async def bulk_analyze(data: BulkReviewInput, token: str = Query(None)):
128
  if token != VALID_API_KEY:
@@ -170,24 +193,3 @@ async def bulk_analyze(data: BulkReviewInput, token: str = Query(None)):
170
  except Exception as e:
171
  logging.error(f"🔥 Bulk processing failed: {traceback.format_exc()}")
172
  raise HTTPException(status_code=500, detail="Failed to analyze bulk reviews")
173
- from model import answer_only
174
-
175
- class FollowUpRequest(BaseModel):
176
- text: str
177
- question: str
178
- verbosity: Optional[str] = "brief"
179
-
180
- @app.post("/followup/")
181
- async def followup(request: FollowUpRequest, x_api_key: str = Header(None)):
182
- if x_api_key and x_api_key != VALID_API_KEY:
183
- raise HTTPException(status_code=401, detail="Invalid API key")
184
-
185
- if not request.question or len(request.text.split()) < 10:
186
- raise HTTPException(status_code=400, detail="Question or text is too short.")
187
-
188
- try:
189
- answer = answer_only(request.text, request.question)
190
- return {"answer": answer}
191
- except Exception as e:
192
- logging.error(f"❌ Follow-up failed: {traceback.format_exc()}")
193
- raise HTTPException(status_code=500, detail="Internal Server Error during follow-up.")
 
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",
 
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
 
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:
 
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
 
 
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:
 
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")