AyushSankar13 commited on
Commit
ce51ce4
·
verified ·
1 Parent(s): ee41b72

Update backend.py

Browse files
Files changed (1) hide show
  1. backend.py +372 -77
backend.py CHANGED
@@ -3,16 +3,17 @@ from ast import List
3
  from fastapi.middleware.cors import CORSMiddleware
4
  from pydantic import BaseModel
5
  import io
6
- #import fitz
7
  import traceback
8
  import pandas as pd
9
-
10
  import base64
11
  import json
12
  import re
13
  import asyncio
14
  import functools
15
  from typing import Any, Optional
 
 
16
 
17
  import google.generativeai as genai
18
  from fastapi import FastAPI, UploadFile, File, Form, HTTPException, APIRouter, Request
@@ -22,9 +23,15 @@ import firebase_admin
22
  from firebase_admin import credentials, firestore
23
  from google.generativeai import generative_models
24
  from pydantic import BaseModel
25
- from past_reports import router as reports_router, db_fetch_reports
 
 
 
 
 
26
 
27
- from api_key import GEMINI_API_KEY
 
28
 
29
  app = FastAPI()
30
  api = APIRouter(prefix="/api")
@@ -51,8 +58,6 @@ class AnalyzeRequest(BaseModel):
51
  image_base64: str
52
  prompt: Optional[str] = None
53
 
54
- GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", GEMINI_API_KEY)
55
-
56
  if not GEMINI_API_KEY:
57
  raise RuntimeError(
58
  "No Gemini API key found. Put it in api_key.py as `GEMINI_API_KEY = '...'` or set env var GEMINI_API_KEY."
@@ -61,10 +66,10 @@ if not GEMINI_API_KEY:
61
  genai.configure(api_key=GEMINI_API_KEY)
62
 
63
  generation_config = {
64
- "temperature": 0.2,
65
- "top_p": 0.95,
66
- "top_k": 40,
67
- "max_output_tokens": 2048,
68
  }
69
 
70
  safety_settings = [
@@ -84,45 +89,65 @@ class ChatResponse(BaseModel):
84
  class TextRequest(BaseModel):
85
  text: str
86
 
87
- system_prompt = """ You are a highly skilled medical practitioner specializing in medical image and document analysis. You will be given either a medical image or a PDF.
 
88
  Your responsibilities are:
 
89
  1. **Extract Text**: If the input is a PDF or image, first extract all the text content (lab values, notes, measurements, etc.). Do not summarize — keep the extracted text verbatim.
 
90
  2. **Detailed Analysis**: Use both the extracted text and the visual features of the image to identify any anomalies, diseases, or health issues.
91
- 3. **Finding Report**: Document all observed anomalies or signs of disease.
92
- - Include any measurements (e.g., triglycerides, HBa1c, HDL) in the format:
93
- `{"findings": "Condition only if risky: measurement type -- value with unit(current range)"}`
94
- - Simplify the finding in **3 words** at the beginning when helpful.
95
- 4. **Checking for Past**: If a disease is family history or previously recovered, mark severity as:
96
- `"severity": "severity of anomaly (Past Anomaly but Still Under Risk)"`
97
- 5. **Recommendations and Next Steps**: Provide detailed recommendations (tests, follow-ups, consultations).
98
- 6. **Treatment Suggestions**: Offer preliminary treatments or interventions.
99
- 7. **Output Format**: Always return a JSON object containing both the raw extracted text and the structured analysis, like this:
100
- ```json
101
  {
102
  "ocr_text": "<<<FULL VERBATIM TEXT FROM THE PDF/IMAGE>>>",
103
- "analysis": [
104
  {
105
- "findings": "UPPERCASE MAIN CONCERN. Description of the first disease or condition.",
106
- "severity": "MILD/SEVERE/CRITICAL",
107
- "recommendations": ["Follow-up test 1", "Follow-up test 2"],
108
- "treatment_suggestions": ["Treatment 1", "Treatment 2"],
109
- "home_care_guidance": ["Care tip 1", "Care tip 2"]
 
 
110
  },
111
  {
112
- "findings": "UPPERCASE MAIN CONCERN. Description of the second disease or condition.",
113
- "severity": "MILD/SEVERE/CRITICAL",
114
- "recommendations": ["Follow-up test A", "Follow-up test B"],
115
- "treatment_suggestions": ["Treatment A", "Treatment B"],
116
- "home_care_guidance": ["Care tip A", "Care tip B"]
 
 
 
 
 
 
 
 
 
 
 
117
  }
118
  ]
119
  }
120
- Important Notes:
121
- 1. Scope of Response: Only respond if the image pertains to a human health issue.
122
- 2. Clarity of Image: Ensure the image is clear and suitable for accurate analysis.
123
- 3. As an AI, don't produce any output than doesn't follow this format and also remember that we need your input on the medical report for a team of renowned doctors to recheck your readings and determine AI's role in the medical industry.
124
- 4. Your Insights are Invaluable: Your insights play a crucial role in guiding clinical decisions. Please proceed with your analysis, adhering to the structured approach outlined above.
125
- 5. Completely UPPERCASE the main concern in the finding """
 
 
 
 
 
 
 
 
 
 
 
126
 
127
  system_prompt_chat = """
128
  *** Role: Medical Chat Assistant ***
@@ -133,7 +158,6 @@ Rules:
133
  - Give top 2 actionable steps if needed.
134
  - If condition is serious, suggest consulting a doctor immediately.
135
  - Always end with: "Check with your physician before acting."
136
-
137
  Input:
138
  Report Text: {document_text}
139
  User Question: {user_question}
@@ -152,7 +176,45 @@ async def _call_model_blocking(request_inputs, generation_cfg, safety_cfg):
152
  loop = asyncio.get_event_loop()
153
  return await loop.run_in_executor(None, fn)
154
 
155
- async def analyze_image(image_bytes: bytes, mime_type: str, prompt: Optional[str] = None) -> Any:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  base64_img = base64.b64encode(image_bytes).decode("utf-8")
157
  text_prompt = (prompt or system_prompt).strip()
158
 
@@ -164,7 +226,9 @@ async def analyze_image(image_bytes: bytes, mime_type: str, prompt: Optional[str
164
  try:
165
  response = await _call_model_blocking(request_inputs, generation_config, safety_settings)
166
  except Exception as e:
 
167
  raise RuntimeError(f"Model call failed: {e}")
 
168
  text = getattr(response, "text", None)
169
  if not text and isinstance(response, dict):
170
  candidates = response.get("candidates") or []
@@ -173,25 +237,93 @@ async def analyze_image(image_bytes: bytes, mime_type: str, prompt: Optional[str
173
  if not text:
174
  text = str(response)
175
 
176
- clean = re.sub(r"```(?:json)?", "", text).strip()
177
- print(f"Cleaned text: {clean}")
 
 
 
 
 
178
  try:
179
  parsed = json.loads(clean)
180
- ocr_text = parsed["ocr_text"]
181
- analysis = parsed["analysis"]
182
- print(f"Parsed JSON: {parsed}")
183
- return analysis,ocr_text
184
- except json.JSONDecodeError:
185
- match = re.search(r"(\[.*\]|\{.*\})", clean, re.DOTALL)
186
- if match:
187
- try:
188
- parsed = json.loads(match.group(1)), None
189
- ocr_text = parsed["ocr_text"]
190
- analysis = parsed["analysis"]
191
- return analysis, ocr_text
192
- except json.JSONDecodeError:
193
- return {"raw_found_json": match.group(1)}, None
194
- return {"raw_output": clean}, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
 
196
  def get_past_reports_from_sqllite(user_id: str):
197
  try:
@@ -200,19 +332,23 @@ def get_past_reports_from_sqllite(user_id: str):
200
  history_text = ""
201
  for report in reports:
202
  history_text += f"Report from {report.get('report_date', 'N/A')}:\n{report.get('ocr_text', 'No OCR text found')}\n\n"
 
 
 
203
  except Exception as e:
204
- history_text = "No past reports found for this user."
205
- return history_text
206
 
207
  @app.post("/chat/", response_model=ChatResponse)
208
  async def chat_endpoint(request: ChatRequest):
209
  global result
210
- print(f"Received chat request for user: {request.user_id}")
 
211
  full_document_text = get_past_reports_from_sqllite(request.user_id.strip())
 
 
212
 
213
- full_document_text = EXTRACTED_TEXT_CACHE+"\n\n" + "PAST REPORTS:\n" + full_document_text
214
- print(f"Full document text: {full_document_text}")
215
- if not full_document_text:
216
  raise HTTPException(status_code=400, detail="No past reports or current data exists for this user")
217
 
218
  try:
@@ -220,38 +356,197 @@ async def chat_endpoint(request: ChatRequest):
220
  document_text=full_document_text,
221
  user_question=request.question
222
  )
223
- print(f"Full prompt: {full_prompt}")
224
 
225
  response = model.generate_content(full_prompt)
226
  return ChatResponse(answer=response.text)
227
  except Exception as e:
 
228
  raise HTTPException(status_code=500, detail=f"Chat error: {e}")
229
 
230
  @app.post("/analyze")
231
- async def analyze_endpoint(file: UploadFile = File(...), prompt: str = Form(None)):
232
- global result,EXTRACTED_TEXT_CACHE
 
 
 
 
233
 
234
  filename = file.filename.lower()
235
- print(f"Received analyze request for file {filename}")
236
  contents = await file.read()
237
  mime = file.content_type or "image/png"
238
 
239
  try:
240
- result, ocr_text = await analyze_image(contents, mime, prompt)
241
  EXTRACTED_TEXT_CACHE = ocr_text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
  except Exception as e:
 
 
243
  raise HTTPException(status_code=500, detail=str(e))
244
- return JSONResponse(content={
245
- "ocr_text": ocr_text,
246
- "Detected_Anomolies": result
247
- })
248
 
249
  @app.post("/analyze_json")
250
  async def analyze_json(req: AnalyzeRequest):
251
  import base64
252
  image_bytes = base64.b64decode(req.image_base64)
253
- result = await analyze_image(image_bytes, "image/png", req.prompt)
254
- return {"result": result}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
255
 
256
  @app.get("/health/")
257
  def health():
@@ -274,7 +569,7 @@ def main():
274
  uvicorn.run(
275
  "main:app",
276
  host="localhost",
277
- port="8000",
278
  reload=True,
279
  log_level="debug"
280
  )
@@ -282,7 +577,7 @@ def main():
282
  uvicorn.run(
283
  app,
284
  host="localhost",
285
- port="8000",
286
  reload=False,
287
  log_level="info"
288
  )
@@ -292,4 +587,4 @@ def main():
292
  raise
293
 
294
  if __name__ == "__main__":
295
- main()
 
3
  from fastapi.middleware.cors import CORSMiddleware
4
  from pydantic import BaseModel
5
  import io
 
6
  import traceback
7
  import pandas as pd
8
+ import logging
9
  import base64
10
  import json
11
  import re
12
  import asyncio
13
  import functools
14
  from typing import Any, Optional
15
+ from datetime import datetime
16
+ import uvicorn
17
 
18
  import google.generativeai as genai
19
  from fastapi import FastAPI, UploadFile, File, Form, HTTPException, APIRouter, Request
 
23
  from firebase_admin import credentials, firestore
24
  from google.generativeai import generative_models
25
  from pydantic import BaseModel
26
+ from past_reports import router as reports_router, db_fetch_reports, db_insert_report, db_get_report
27
+
28
+ GEMINI_API_KEY="AIzaSyAK0HJWN-WLuG5BxkHawu6_qFpcXU71cT0"
29
+
30
+ logger = logging.getLogger(__name__)
31
+ logging.basicConfig(level=logging.INFO)
32
 
33
+ class Config:
34
+ DEBUG = True
35
 
36
  app = FastAPI()
37
  api = APIRouter(prefix="/api")
 
58
  image_base64: str
59
  prompt: Optional[str] = None
60
 
 
 
61
  if not GEMINI_API_KEY:
62
  raise RuntimeError(
63
  "No Gemini API key found. Put it in api_key.py as `GEMINI_API_KEY = '...'` or set env var GEMINI_API_KEY."
 
66
  genai.configure(api_key=GEMINI_API_KEY)
67
 
68
  generation_config = {
69
+ "temperature": 0.1,
70
+ "top_p": 0.8,
71
+ "top_k": 20,
72
+ "max_output_tokens": 4096,
73
  }
74
 
75
  safety_settings = [
 
89
  class TextRequest(BaseModel):
90
  text: str
91
 
92
+ system_prompt = """You are a highly skilled medical practitioner specializing in medical image and document analysis. You will be given either a medical image or a PDF.
93
+
94
  Your responsibilities are:
95
+
96
  1. **Extract Text**: If the input is a PDF or image, first extract all the text content (lab values, notes, measurements, etc.). Do not summarize — keep the extracted text verbatim.
97
+
98
  2. **Detailed Analysis**: Use both the extracted text and the visual features of the image to identify any anomalies, diseases, or health issues.
99
+
100
+ 3. **Output Format**: You MUST return ONLY a valid JSON object with this EXACT structure (no additional text, no markdown, no code blocks):
101
+
 
 
 
 
 
 
 
102
  {
103
  "ocr_text": "<<<FULL VERBATIM TEXT FROM THE PDF/IMAGE>>>",
104
+ "measurements": [
105
  {
106
+ "type": "HbA1c",
107
+ "value": 8.5,
108
+ "unit": "%",
109
+ "min": "4.0",
110
+ "max": "5.6",
111
+ "status": "HIGH",
112
+ "severity": "SEVERE"
113
  },
114
  {
115
+ "type": "Total Cholesterol",
116
+ "value": 280,
117
+ "unit": "mg/dL",
118
+ "min": "0",
119
+ "max": "200",
120
+ "status": "HIGH",
121
+ "severity": "SEVERE"
122
+ }
123
+ ],
124
+ "analysis": [
125
+ {
126
+ "findings": "DIABETES. Elevated HbA1c indicates poor glucose control over past 2-3 months.",
127
+ "severity": "SEVERE",
128
+ "recommendations": ["Consult endocrinologist immediately", "Review medication regimen"],
129
+ "treatment_suggestions": ["Adjust insulin dosage", "Consider metformin"],
130
+ "home_care_guidance": ["Monitor blood sugar 4x daily", "Follow diabetic diet"]
131
  }
132
  ]
133
  }
134
+
135
+ 4. **Measurement Extraction Rules**:
136
+ - Extract EVERY numerical health measurement found in the document
137
+ - Include lab values, vital signs, body measurements, test results
138
+ - For each measurement provide: type, value, unit, min, max, status, severity
139
+ - To provide the min and max, first check the document for a provided min or max, if not just use your AI knowledge to provide the min and max for that specific measurement type
140
+ - Status should be LOW, NORMAL, BORDER-LINE HIGH, and HIGH based on min and max.
141
+
142
+ 5. **Finding Analysis**:
143
+ - Document all observed anomalies or diseases in the analysis section
144
+ - UPPERCASE the main concern in each finding
145
+ - Link findings to relevant measurements when applicable
146
+ - If a disease is family history or previously recovered, mark severity as: "severity of anomaly (Past Anomaly but Still Under Risk)"
147
+ - Provide actionable recommendations and treatment suggestions
148
+
149
+ CRITICAL: Return ONLY the JSON object. No explanatory text, no markdown formatting, no code blocks. Also make sure to check all your information twice before sending.
150
+ """
151
 
152
  system_prompt_chat = """
153
  *** Role: Medical Chat Assistant ***
 
158
  - Give top 2 actionable steps if needed.
159
  - If condition is serious, suggest consulting a doctor immediately.
160
  - Always end with: "Check with your physician before acting."
 
161
  Input:
162
  Report Text: {document_text}
163
  User Question: {user_question}
 
176
  loop = asyncio.get_event_loop()
177
  return await loop.run_in_executor(None, fn)
178
 
179
+ def extract_measurements_from_gemini_structured(measurements_data):
180
+ measurements = []
181
+
182
+ if not measurements_data:
183
+ logger.warning("No measurements data provided")
184
+ return measurements
185
+
186
+ for measurement in measurements_data:
187
+ try:
188
+ measurement_type = measurement.get("type") or measurement.get("measurement_type", "Unknown")
189
+ value = measurement.get("value", 0)
190
+ unit = measurement.get("unit", "")
191
+
192
+ ref_range = ""
193
+ if measurement.get("reference_range"):
194
+ ref_range = measurement.get("reference_range")
195
+ elif measurement.get("min") and measurement.get("max"):
196
+ ref_range = f"{measurement.get('min')}-{measurement.get('max')}"
197
+ elif measurement.get("min"):
198
+ ref_range = f">{measurement.get('min')}"
199
+ elif measurement.get("max"):
200
+ ref_range = f"<{measurement.get('max')}"
201
+
202
+ measurements.append({
203
+ "measurement_type": measurement_type,
204
+ "value": float(value) if value else 0.0,
205
+ "unit": unit,
206
+ "min": measurement.get('min'),
207
+ "max": measurement.get('max'),
208
+ "status": measurement.get("status", "UNKNOWN"),
209
+ "severity": measurement.get("severity", "UNKNOWN"),
210
+ })
211
+ except Exception as e:
212
+ logger.error(f"Error processing measurement: {measurement}, error: {e}")
213
+ continue
214
+
215
+ return measurements
216
+
217
+ async def analyze_image(image_bytes: bytes, mime_type: str, prompt: Optional[str] = None) -> tuple:
218
  base64_img = base64.b64encode(image_bytes).decode("utf-8")
219
  text_prompt = (prompt or system_prompt).strip()
220
 
 
226
  try:
227
  response = await _call_model_blocking(request_inputs, generation_config, safety_settings)
228
  except Exception as e:
229
+ logger.error(f"Model call failed: {e}")
230
  raise RuntimeError(f"Model call failed: {e}")
231
+
232
  text = getattr(response, "text", None)
233
  if not text and isinstance(response, dict):
234
  candidates = response.get("candidates") or []
 
237
  if not text:
238
  text = str(response)
239
 
240
+ logger.info(f"Raw Gemini response: {text[:500]}...")
241
+
242
+ clean = re.sub(r'```(?:json)?\s*', '', text).strip()
243
+ clean = re.sub(r'```\s*$', '', clean).strip()
244
+
245
+ logger.info(f"Cleaned response: {clean[:500]}...")
246
+
247
  try:
248
  parsed = json.loads(clean)
249
+
250
+ if "ocr_text" in parsed and "measurements" in parsed and "analysis" in parsed:
251
+ ocr_text = parsed.get("ocr_text", "")
252
+ measurements = parsed.get("measurements", [])
253
+ analysis = parsed.get("analysis", [])
254
+
255
+ logger.info(f"Successfully parsed structured response with {len(measurements)} measurements and {len(analysis)} analyses")
256
+ return analysis, ocr_text, measurements
257
+
258
+ logger.warning("Response not in expected format, attempting to extract...")
259
+
260
+ except json.JSONDecodeError as e:
261
+ logger.error(f"Initial JSON decode error: {e}")
262
+
263
+ json_match = re.search(r'\{[\s\S]*"ocr_text"[\s\S]*"measurements"[\s\S]*"analysis"[\s\S]*\}', clean)
264
+ if json_match:
265
+ try:
266
+ logger.info("Found structured JSON in response, attempting to parse...")
267
+ parsed = json.loads(json_match.group(0))
268
+
269
+ ocr_text = parsed.get("ocr_text", "")
270
+ measurements = parsed.get("measurements", [])
271
+ analysis = parsed.get("analysis", [])
272
+
273
+ logger.info(f"Successfully extracted structured data with {len(measurements)} measurements and {len(analysis)} analyses")
274
+ return analysis, ocr_text, measurements
275
+
276
+ except json.JSONDecodeError as e:
277
+ logger.error(f"Failed to parse extracted JSON: {e}")
278
+
279
+ if "raw_found_json" in clean:
280
+ try:
281
+ temp_parsed = json.loads(clean)
282
+ if "raw_found_json" in temp_parsed:
283
+ inner_json = temp_parsed["raw_found_json"]
284
+ if isinstance(inner_json, str):
285
+ inner_parsed = json.loads(inner_json)
286
+ else:
287
+ inner_parsed = inner_json
288
+
289
+ ocr_text = inner_parsed.get("ocr_text", "")
290
+ measurements = inner_parsed.get("measurements", [])
291
+ analysis = inner_parsed.get("analysis", [])
292
+
293
+ logger.info(f"Successfully unwrapped raw_found_json with {len(measurements)} measurements")
294
+ return analysis, ocr_text, measurements
295
+
296
+ except (json.JSONDecodeError, KeyError) as e:
297
+ logger.error(f"Failed to unwrap raw_found_json: {e}")
298
+
299
+ logger.warning("Using fallback parsing - structured data extraction failed")
300
+ return [{"findings": "Failed to parse structured response", "raw_output": clean[:1000]}], "", []
301
+
302
+ def save_analysis_with_measurements(user_id, ocr_text, analysis_data, measurements_data, report_date=None):
303
+ measurements = extract_measurements_from_gemini_structured(measurements_data)
304
+
305
+ report_data = {
306
+ "user_id": user_id,
307
+ "report_date": report_date or datetime.now().strftime("%Y-%m-%d"),
308
+ "ocr_text": ocr_text,
309
+ "anomalies": json.dumps(analysis_data) if analysis_data else None,
310
+ "measurements": json.dumps(measurements)
311
+ }
312
+
313
+ try:
314
+ logger.info(f"Saving report for user {user_id} with {len(measurements)} measurements")
315
+ report_id = db_insert_report(report_data)
316
+ logger.info(f"Report saved with ID: {report_id}")
317
+
318
+ for measurement in measurements:
319
+ status_indicator = "WARNING" if measurement['status'] in ['HIGH', 'LOW', 'CRITICAL'] else "OK"
320
+ logger.info(f" {status_indicator} {measurement['measurement_type']}: {measurement['value']} {measurement['unit']} ({measurement['status']})")
321
+
322
+ return report_id, measurements
323
+ except Exception as e:
324
+ logger.error(f"Failed to save report: {e}")
325
+ logger.error(f"Report data: {report_data}")
326
+ return None, measurements
327
 
328
  def get_past_reports_from_sqllite(user_id: str):
329
  try:
 
332
  history_text = ""
333
  for report in reports:
334
  history_text += f"Report from {report.get('report_date', 'N/A')}:\n{report.get('ocr_text', 'No OCR text found')}\n\n"
335
+
336
+ logger.info(f"Retrieved {len(reports)} past reports for user {user_id}")
337
+ return history_text
338
  except Exception as e:
339
+ logger.error(f"Error fetching past reports: {e}")
340
+ return "No past reports found for this user."
341
 
342
  @app.post("/chat/", response_model=ChatResponse)
343
  async def chat_endpoint(request: ChatRequest):
344
  global result
345
+ logger.info(f"Received chat request for user: {request.user_id}")
346
+
347
  full_document_text = get_past_reports_from_sqllite(request.user_id.strip())
348
+ full_document_text = EXTRACTED_TEXT_CACHE + "\n\n" + "PAST REPORTS:\n" + full_document_text
349
+ logger.info(f"Full document text length: {len(full_document_text)}")
350
 
351
+ if not full_document_text.strip():
 
 
352
  raise HTTPException(status_code=400, detail="No past reports or current data exists for this user")
353
 
354
  try:
 
356
  document_text=full_document_text,
357
  user_question=request.question
358
  )
359
+ logger.info(f"Generated chat prompt length: {len(full_prompt)}")
360
 
361
  response = model.generate_content(full_prompt)
362
  return ChatResponse(answer=response.text)
363
  except Exception as e:
364
+ logger.error(f"Chat error: {e}")
365
  raise HTTPException(status_code=500, detail=f"Chat error: {e}")
366
 
367
  @app.post("/analyze")
368
+ async def analyze_endpoint(
369
+ file: UploadFile = File(...),
370
+ prompt: str = Form(None),
371
+ user_id: str = Form("anonymous")
372
+ ):
373
+ global result, EXTRACTED_TEXT_CACHE
374
 
375
  filename = file.filename.lower()
376
+ logger.info(f"Received analyze request for file {filename} from user {user_id}")
377
  contents = await file.read()
378
  mime = file.content_type or "image/png"
379
 
380
  try:
381
+ analysis_result, ocr_text, measurements_data = await analyze_image(contents, mime, prompt)
382
  EXTRACTED_TEXT_CACHE = ocr_text
383
+ result = analysis_result
384
+
385
+ report_id, measurements = save_analysis_with_measurements(
386
+ user_id=user_id,
387
+ ocr_text=ocr_text,
388
+ analysis_data=analysis_result,
389
+ measurements_data=measurements_data
390
+ )
391
+
392
+ response_data = {
393
+ "report_id": report_id,
394
+ "ocr_text": ocr_text,
395
+ "Detected_Anomolies": analysis_result,
396
+ "measurements": measurements,
397
+ "measurement_count": len(measurements)
398
+ }
399
+
400
+ logger.info(f"Analysis complete. Report ID: {report_id}, Measurements: {len(measurements)}")
401
+ return JSONResponse(content=response_data)
402
+
403
  except Exception as e:
404
+ logger.error(f"Analysis error: {e}")
405
+ logger.error(f"Traceback: {traceback.format_exc()}")
406
  raise HTTPException(status_code=500, detail=str(e))
 
 
 
 
407
 
408
  @app.post("/analyze_json")
409
  async def analyze_json(req: AnalyzeRequest):
410
  import base64
411
  image_bytes = base64.b64decode(req.image_base64)
412
+ result, ocr_text, measurements = await analyze_image(image_bytes, "image/png", req.prompt)
413
+ return {
414
+ "result": result,
415
+ "ocr_text": ocr_text,
416
+ "measurements": measurements
417
+ }
418
+
419
+ @app.get("/measurements/{report_id}")
420
+ async def get_report_measurements(report_id: int):
421
+ try:
422
+ report = db_get_report(report_id)
423
+ if not report:
424
+ raise HTTPException(status_code=404, detail="Report not found")
425
+
426
+ measurements_json = report.get('measurements', '[]')
427
+ if isinstance(measurements_json, str):
428
+ measurements = json.loads(measurements_json)
429
+ else:
430
+ measurements = measurements_json or []
431
+
432
+ logger.info(f"Retrieved {len(measurements)} measurements for report {report_id}")
433
+
434
+ return JSONResponse(content={
435
+ "report_id": report_id,
436
+ "measurements": measurements,
437
+ "measurement_count": len(measurements)
438
+ })
439
+ except Exception as e:
440
+ logger.error(f"Error getting measurements for report {report_id}: {e}")
441
+ raise HTTPException(status_code=500, detail=str(e))
442
+
443
+ @app.get("/user_measurements/")
444
+ async def get_user_measurements(user_id: str):
445
+ try:
446
+ reports = db_fetch_reports(user_id=user_id, limit=100, offset=0)
447
+ all_measurements = []
448
+
449
+ for report in reports:
450
+ measurements_json = report.get('measurements', '[]')
451
+ if isinstance(measurements_json, str):
452
+ measurements = json.loads(measurements_json)
453
+ else:
454
+ measurements = measurements_json or []
455
+
456
+ if measurements:
457
+ for measurement in measurements:
458
+ measurement['report_id'] = report['id']
459
+ measurement['report_date'] = report['report_date']
460
+ measurement['created_at'] = report['created_at']
461
+ all_measurements.append(measurement)
462
+
463
+ all_measurements.sort(key=lambda x: x.get('created_at', ''), reverse=True)
464
+
465
+ logger.info(f"Retrieved {len(all_measurements)} total measurements for user {user_id}")
466
+
467
+ return JSONResponse(content={
468
+ "user_id": user_id,
469
+ "total_measurements": len(all_measurements),
470
+ "measurements": all_measurements
471
+ })
472
+ except Exception as e:
473
+ logger.error(f"Error getting user measurements for {user_id}: {e}")
474
+ raise HTTPException(status_code=500, detail=str(e))
475
+
476
+ @app.get("/measurement_trends/")
477
+ async def get_measurement_trends(user_id: str, measurement_type: str = None):
478
+ try:
479
+ reports = db_fetch_reports(user_id=user_id, limit=100, offset=0)
480
+ trends = {}
481
+
482
+ for report in reports:
483
+ measurements_json = report.get('measurements', '[]')
484
+ if isinstance(measurements_json, str):
485
+ measurements = json.loads(measurements_json)
486
+ else:
487
+ measurements = measurements_json or []
488
+
489
+ if measurements:
490
+ for measurement in measurements:
491
+ m_type = measurement['measurement_type']
492
+
493
+ if measurement_type and m_type.lower() != measurement_type.lower():
494
+ continue
495
+
496
+ if m_type not in trends:
497
+ trends[m_type] = []
498
+
499
+ trends[m_type].append({
500
+ "date": report['report_date'] or report['created_at'],
501
+ "value": measurement['value'],
502
+ "unit": measurement['unit'],
503
+ "status": measurement['status'],
504
+ "severity": measurement['severity'],
505
+ "report_id": report['id']
506
+ })
507
+
508
+ for m_type in trends:
509
+ trends[m_type].sort(key=lambda x: x['date'])
510
+
511
+ logger.info(f"Retrieved trends for {len(trends)} measurement types for user {user_id}")
512
+
513
+ return JSONResponse(content={
514
+ "user_id": user_id,
515
+ "measurement_type_filter": measurement_type,
516
+ "trends": trends
517
+ })
518
+ except Exception as e:
519
+ logger.error(f"Error getting measurement trends for {user_id}: {e}")
520
+ raise HTTPException(status_code=500, detail=str(e))
521
+
522
+ @app.get("/test_db")
523
+ async def test_database():
524
+ try:
525
+ test_reports = db_fetch_reports(user_id="test_user", limit=5, offset=0)
526
+
527
+ test_data = {
528
+ "user_id": "test_user",
529
+ "report_date": datetime.now().strftime("%Y-%m-%d"),
530
+ "ocr_text": "Test OCR text",
531
+ "anomalies": json.dumps([{"test": "data"}]),
532
+ "measurements": json.dumps([{"measurement_type": "Test", "value": 100, "unit": "mg/dL", "status": "NORMAL"}])
533
+ }
534
+
535
+ test_report_id = db_insert_report(test_data)
536
+
537
+ return JSONResponse(content={
538
+ "database_status": "connected",
539
+ "existing_reports": len(test_reports),
540
+ "test_report_id": test_report_id,
541
+ "test_successful": True
542
+ })
543
+ except Exception as e:
544
+ logger.error(f"Database test failed: {e}")
545
+ return JSONResponse(content={
546
+ "database_status": "error",
547
+ "error": str(e),
548
+ "test_successful": False
549
+ }, status_code=500)
550
 
551
  @app.get("/health/")
552
  def health():
 
569
  uvicorn.run(
570
  "main:app",
571
  host="localhost",
572
+ port=8000,
573
  reload=True,
574
  log_level="debug"
575
  )
 
577
  uvicorn.run(
578
  app,
579
  host="localhost",
580
+ port=8000,
581
  reload=False,
582
  log_level="info"
583
  )
 
587
  raise
588
 
589
  if __name__ == "__main__":
590
+ main()