vineelagampa commited on
Commit
a1e2229
·
verified ·
1 Parent(s): e9537a4

Update backend.py

Browse files
Files changed (1) hide show
  1. backend.py +38 -72
backend.py CHANGED
@@ -1,4 +1,4 @@
1
- from fastapi import FastAPI, UploadFile, File, Form, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from pydantic import BaseModel
4
  from typing import Optional
@@ -12,6 +12,13 @@ import re
12
  import os
13
  import google.generativeai as genai
14
  from dotenv import load_dotenv
 
 
 
 
 
 
 
15
 
16
  load_dotenv()
17
  def extract_non_negated_keywords(text: str) -> list:
@@ -27,6 +34,25 @@ disease_home_care = {"cholesterol": ["Maintain a healthy diet."]}
27
 
28
  app = FastAPI()
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  app.add_middleware(
31
  CORSMiddleware,
32
  allow_origins=["*"],
@@ -35,8 +61,18 @@ app.add_middleware(
35
  allow_headers=["*"],
36
  )
37
 
 
 
 
 
38
  EXTRACTED_TEXT_CACHE: str = ""
39
 
 
 
 
 
 
 
40
  try:
41
  gemini_api_key = os.environ.get("GEMINI_API_KEY")
42
  if not gemini_api_key:
@@ -114,56 +150,6 @@ def ocr_text_from_image(image_bytes: bytes) -> str:
114
  except Exception as e:
115
  raise HTTPException(status_code=500, detail=f"OCR error: {e}")
116
 
117
- @app.post("/analyze/")
118
- async def analyze(
119
- file: UploadFile = File(...),
120
- model: Optional[str] = Form("bert")
121
- ):
122
- global EXTRACTED_TEXT_CACHE
123
- if not file.filename:
124
- raise HTTPException(status_code=400, detail="No file uploaded.")
125
-
126
- filename = file.filename.lower()
127
- ocr_full = ""
128
-
129
- try:
130
- if filename.endswith(".pdf"):
131
- pdf_bytes = await file.read()
132
- image_bytes_list = extract_images_from_pdf_bytes(pdf_bytes)
133
- else:
134
- content = await file.read()
135
- image_bytes_list = [content]
136
-
137
- for img_bytes in image_bytes_list:
138
- ocr_text = ocr_text_from_image(img_bytes)
139
- ocr_full += ocr_text + "\n\n"
140
- except Exception as e:
141
- raise HTTPException(status_code=500, detail=f"File processing error: {e}")
142
-
143
- EXTRACTED_TEXT_CACHE = ocr_full.strip()
144
-
145
- found_diseases = extract_non_negated_keywords(EXTRACTED_TEXT_CACHE)
146
- resolutions = []
147
- for disease in found_diseases:
148
- severity, _ = classify_disease_and_severity(EXTRACTED_TEXT_CACHE)
149
- link = disease_links.get(disease.lower(), "https://www.webmd.com/")
150
- next_steps = disease_next_steps.get(disease.lower(), ["Consult a doctor."])
151
- specialist = disease_doctor_specialty.get(disease.lower(), "General Practitioner")
152
- home_care = disease_home_care.get(disease.lower(), [])
153
-
154
- resolutions.append({
155
- "findings": disease,
156
- "severity": severity,
157
- "recommendations": next_steps,
158
- "treatment_suggestions": f"Consult a specialist: {specialist}",
159
- "home_care_guidance": home_care,
160
- "info_link": link
161
- })
162
-
163
- return {
164
- "ocr_text": EXTRACTED_TEXT_CACHE,
165
- "resolutions": resolutions
166
- }
167
 
168
  @app.post("/chat/", response_model=ChatResponse)
169
  async def chat_endpoint(request: ChatRequest):
@@ -188,28 +174,7 @@ async def chat_endpoint(request: ChatRequest):
188
  print(f"Gemini API error: {traceback.format_exc()}")
189
  raise HTTPException(status_code=500, detail=f"An error occurred during chat response generation: {e}")
190
 
191
- from bert import analyze_with_clinicalBert, classify_disease_and_severity, extract_non_negated_keywords, analyze_measurements, detect_past_diseases
192
- from disease_links import diseases as disease_links
193
- from disease_steps import disease_next_steps
194
- from disease_support import disease_doctor_specialty, disease_home_care
195
 
196
- df = pd.read_csv("measurement.csv")
197
- df.columns = df.columns.str.lower()
198
- df['measurement'] = df['measurement'].str.lower()
199
-
200
- app = FastAPI()
201
-
202
- app.add_middleware(
203
- CORSMiddleware,
204
- allow_origins=[
205
- "http://localhost:8002"
206
- "http://localhost:9000"
207
- "http://localhost:5501"
208
- ],
209
- allow_credentials=True,
210
- allow_methods=["*"],
211
- allow_headers=["*"],
212
- )
213
 
214
 
215
  def extract_images_from_pdf_bytes(pdf_bytes: bytes) -> list:
@@ -329,6 +294,7 @@ def analyze_text(text):
329
  def health():
330
  return {"response": "ok"}
331
 
 
332
  @app.on_event("startup")
333
  def _log_routes():
334
  from fastapi.routing import APIRoute
 
1
+ from fastapi import FastAPI, UploadFile, File, Form, HTTPException,APIRouter
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from pydantic import BaseModel
4
  from typing import Optional
 
12
  import os
13
  import google.generativeai as genai
14
  from dotenv import load_dotenv
15
+ from fastapi.responses import RedirectResponse
16
+ from fastapi.staticfiles import StaticFiles
17
+ from bert import analyze_with_clinicalBert, classify_disease_and_severity, extract_non_negated_keywords, analyze_measurements, detect_past_diseases
18
+ from disease_links import diseases as disease_links
19
+ from disease_steps import disease_next_steps
20
+ from disease_support import disease_doctor_specialty, disease_home_care
21
+
22
 
23
  load_dotenv()
24
  def extract_non_negated_keywords(text: str) -> list:
 
34
 
35
  app = FastAPI()
36
 
37
+ api = APIRouter(prefix="/api")
38
+ app.include_router(api)
39
+
40
+
41
+ '''app.add_middleware(
42
+ CORSMiddleware,
43
+ allow_origins=[
44
+ "http://localhost:8002"
45
+ "http://localhost:9000"
46
+ "http://localhost:5501"
47
+ ],
48
+ allow_credentials=True,
49
+ allow_methods=["*"],
50
+ allow_headers=["*"],
51
+ )'''
52
+
53
+
54
+ app.mount("/app", StaticFiles(directory="web", html=True), name="web")
55
+
56
  app.add_middleware(
57
  CORSMiddleware,
58
  allow_origins=["*"],
 
61
  allow_headers=["*"],
62
  )
63
 
64
+ @app.get("/")
65
+ def root():
66
+ return RedirectResponse(url="/app/")
67
+
68
  EXTRACTED_TEXT_CACHE: str = ""
69
 
70
+
71
+ df = pd.read_csv("measurement.csv")
72
+ df.columns = df.columns.str.lower()
73
+ df['measurement'] = df['measurement'].str.lower()
74
+
75
+
76
  try:
77
  gemini_api_key = os.environ.get("GEMINI_API_KEY")
78
  if not gemini_api_key:
 
150
  except Exception as e:
151
  raise HTTPException(status_code=500, detail=f"OCR error: {e}")
152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
 
154
  @app.post("/chat/", response_model=ChatResponse)
155
  async def chat_endpoint(request: ChatRequest):
 
174
  print(f"Gemini API error: {traceback.format_exc()}")
175
  raise HTTPException(status_code=500, detail=f"An error occurred during chat response generation: {e}")
176
 
 
 
 
 
177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
 
179
 
180
  def extract_images_from_pdf_bytes(pdf_bytes: bytes) -> list:
 
294
  def health():
295
  return {"response": "ok"}
296
 
297
+
298
  @app.on_event("startup")
299
  def _log_routes():
300
  from fastapi.routing import APIRoute