Ali2206 commited on
Commit
9095ee0
·
verified ·
1 Parent(s): 3069ccd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -50
app.py CHANGED
@@ -542,61 +542,89 @@ async def voice_chat_endpoint(
542
  logger.error(f"Error in voice chat: {e}")
543
  raise HTTPException(status_code=500, detail="Error processing voice chat")
544
 
545
- @app.post("/patient/upload-report")
546
- async def upload_patient_report(
547
- patient_id: Optional[str] = Form(None),
548
- file: UploadFile = File(...)
 
 
549
  ):
550
- """Upload and analyze a patient report (text, PDF, or audio)."""
 
 
 
 
 
 
 
 
 
 
551
  try:
552
- # Validate patient_id if provided
553
- if patient_id:
554
- patient = await patients_collection.find_one({"fhir_id": patient_id})
555
- if not patient:
556
- raise HTTPException(status_code=404, detail=f"Patient {patient_id} not found")
557
- logger.info(f"Uploading report for patient: {patient_id}")
558
- else:
559
- logger.info("Uploading report without patient ID")
560
-
561
- # Determine file type from extension or MIME type
562
- file_extension = file.filename.lower().split('.')[-1] if file.filename else ''
563
- mime_type = file.content_type or mimetypes.guess_type(file.filename)[0] or 'application/octet-stream'
564
- logger.info(f"Detected file extension: {file_extension}, MIME type: {mime_type}")
565
-
566
- if file_extension in ['txt'] or mime_type.startswith('text'):
567
- file_type = 'text'
568
- elif file_extension == 'pdf' or mime_type == 'application/pdf':
569
- file_type = 'pdf'
570
- elif file_extension in ['wav', 'mp3', 'ogg', 'flac'] or mime_type.startswith('audio'):
571
- file_type = 'audio'
572
- else:
573
- raise HTTPException(
574
- status_code=400,
575
- detail=f"Unsupported file type: {file_extension}. Supported: text (.txt), PDF (.pdf), audio (.wav, .mp3, .ogg, .flac)"
576
- )
577
-
578
- # Read and process file
579
- file_content = await file.read()
580
-
581
- if file_type == "text":
582
- report_content = file_content.decode('utf-8')
583
- elif file_type == "pdf":
584
- report_content = extract_text_from_pdf(file_content)
585
- elif file_type == "audio":
586
- report_content = recognize_speech(file_content, language="en-US")
587
- else:
588
- raise HTTPException(status_code=400, detail="Error processing file type")
589
-
590
- # Analyze the report
591
- analysis = await analyze_patient_report(patient_id, report_content, file_type, file_content)
592
- return JSONResponse(content=analysis)
593
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
594
  except HTTPException:
595
  raise
596
  except Exception as e:
597
- logger.error(f"Error processing patient report upload: {e}")
598
- raise HTTPException(status_code=500, detail="Error processing patient report")
599
-
600
  if __name__ == "__main__":
601
  import uvicorn
602
  uvicorn.run(app, host="0.0.0.0", port=8000)
 
542
  logger.error(f"Error in voice chat: {e}")
543
  raise HTTPException(status_code=500, detail="Error processing voice chat")
544
 
545
+ @app.post("/analyze-report")
546
+ async def analyze_clinical_report(
547
+ file: Optional[UploadFile] = File(None),
548
+ text: Optional[str] = Form(None),
549
+ temperature: float = Form(0.5),
550
+ max_new_tokens: int = Form(1024)
551
  ):
552
+ """
553
+ Analyze a clinical patient report either from uploaded file or direct text input.
554
+
555
+ Parameters:
556
+ - file: Uploaded clinical report file (PDF, TXT, DOCX)
557
+ - text: Direct text input of the clinical report
558
+ - temperature: Controls randomness of response (0.1-1.0)
559
+ - max_new_tokens: Maximum length of response
560
+
561
+ Returns structured analysis of the patient report.
562
+ """
563
  try:
564
+ # Validate input
565
+ if not (file or text):
566
+ raise HTTPException(status_code=400, detail="Either file or text input is required")
567
+
568
+ # Extract text from file if provided
569
+ report_text = text
570
+ if file:
571
+ if file.filename.lower().endswith('.pdf'):
572
+ # PDF processing
573
+ import PyPDF2
574
+ pdf_reader = PyPDF2.PdfReader(file.file)
575
+ report_text = "\n".join([page.extract_text() for page in pdf_reader.pages])
576
+ elif file.filename.lower().endswith(('.txt', '.md')):
577
+ # Plain text
578
+ report_text = (await file.read()).decode('utf-8')
579
+ elif file.filename.lower().endswith(('.docx', '.doc')):
580
+ # Word document
581
+ from docx import Document
582
+ doc = Document(io.BytesIO(await file.read()))
583
+ report_text = "\n".join([para.text for para in doc.paragraphs])
584
+ else:
585
+ raise HTTPException(status_code=400, detail="Unsupported file format")
586
+
587
+ # Clean and validate the extracted text
588
+ if not report_text or len(report_text.strip()) < 50:
589
+ raise HTTPException(status_code=400, detail="Report text is too short or empty")
590
+
591
+ # Create analysis prompt
592
+ prompt = (
593
+ "You are a senior clinical analyst. Analyze this patient report and provide:\n"
594
+ "1. SUMMARY: Concise summary of key findings\n"
595
+ "2. DIAGNOSES: List of confirmed or suspected diagnoses\n"
596
+ "3. RISK FACTORS: Important risk factors identified\n"
597
+ "4. RED FLAGS: Any urgent concerns that need attention\n"
598
+ "5. RECOMMENDATIONS: Suggested next steps for care\n\n"
599
+ f"PATIENT REPORT:\n{report_text[:15000]}" # Limit input size
600
+ )
601
+
602
+ # Get AI analysis
603
+ raw_response = agent.chat(
604
+ message=prompt,
605
+ history=[],
606
+ temperature=temperature,
607
+ max_new_tokens=max_new_tokens
608
+ )
609
+
610
+ # Structure the response
611
+ structured_response = structure_medical_response(raw_response)
612
+
613
+ # Add suicide risk assessment
614
+ risk_level, risk_score, risk_factors = detect_suicide_risk(raw_response)
615
+ structured_response["suicide_risk"] = {
616
+ "level": risk_level.value,
617
+ "score": risk_score,
618
+ "factors": risk_factors
619
+ }
620
+
621
+ return JSONResponse(content=structured_response)
622
+
623
  except HTTPException:
624
  raise
625
  except Exception as e:
626
+ logger.error(f"Error analyzing clinical report: {e}")
627
+ raise HTTPException(status_code=500, detail="Error processing clinical report")
 
628
  if __name__ == "__main__":
629
  import uvicorn
630
  uvicorn.run(app, host="0.0.0.0", port=8000)