SmartHeal commited on
Commit
981c773
·
verified ·
1 Parent(s): 16d2812

Update src/ai_processor.py

Browse files
Files changed (1) hide show
  1. src/ai_processor.py +170 -405
src/ai_processor.py CHANGED
@@ -7,6 +7,7 @@ from datetime import datetime
7
  import gradio as gr
8
  import spaces
9
  import torch
 
10
 
11
  from huggingface_hub import HfApi, HfFolder
12
  from langchain_community.document_loaders import PyPDFLoader
@@ -28,7 +29,7 @@ YOLO_MODEL_PATH = "src/best.pt"
28
  SEG_MODEL_PATH = "src/segmentation_model.h5"
29
  GUIDELINE_PDFS = ["src/eHealth in Wound Care.pdf", "src/IWGDF Guideline.pdf", "src/evaluation.pdf"]
30
  DATASET_ID = "SmartHeal/wound-image-uploads"
31
- MAX_NEW_TOKENS = 2048
32
  PIXELS_PER_CM = 38
33
 
34
  # =============== GLOBAL CACHES ===============
@@ -131,115 +132,86 @@ def setup_knowledge_base():
131
  initialize_cpu_models()
132
  setup_knowledge_base()
133
 
134
- # =============== GPU-DECORATED MEDGEMMA FUNCTION ===============
135
- @spaces.GPU(enable_queue=True, duration=120)
136
- def generate_medgemma_report(
137
  patient_info,
138
  visual_results,
139
  guideline_context,
140
  image_pil,
141
  max_new_tokens=None,
142
  ):
143
- """GPU-only function for MedGemma report generation - EXACTLY like working reference."""
 
144
  from transformers import pipeline
 
 
 
 
 
 
 
 
 
145
 
146
- # Lazy-load MedGemma pipeline on GPU - EXACTLY like working reference
147
- if not hasattr(generate_medgemma_report, "_pipe"):
148
- try:
149
- generate_medgemma_report._pipe = pipeline(
150
- "image-text-to-text",
151
- model="google/medgemma-4b-it",
152
- torch_dtype=torch.bfloat16,
153
- device_map="auto",
154
- token=HF_TOKEN
155
- )
156
- logging.info("✅ MedGemma pipeline loaded on GPU")
157
- except Exception as e:
158
- logging.warning(f"MedGemma pipeline load failed: {e}")
159
- return None
160
 
161
- pipe = generate_medgemma_report._pipe
 
 
 
 
162
 
163
- # Use the EXACT prompt format from the working reference
164
- prompt = f"""
165
- 🩺 You are SmartHeal-AI Agent, a world-class wound care AI specialist trained in clinical wound assessment and guideline-based treatment planning.
166
- Your task is to process the following structured inputs (patient data, wound measurements, clinical guidelines, and image) and perform **clinical reasoning and decision-making** to generate a complete wound care report.
167
- ---
168
- 🔍 **YOUR PROCESS — FOLLOW STRICTLY:**
169
- ### Step 1: Clinical Reasoning (Chain-of-Thought)
170
- Use the provided information to think step-by-step about:
171
- - Patient's risk factors (e.g. diabetes, age, healing limitations)
172
- - Wound characteristics (size, tissue appearance, moisture, infection signs)
173
- - Visual clues from the image (location, granulation, maceration, inflammation, surrounding skin)
174
- - Clinical guidelines provided — selectively choose the ones most relevant to this case
175
- Do NOT list all guidelines verbatim. Use judgment: apply them where relevant. Explain why or why not.
176
- Also assess whether this wound appears:
177
- - Acute vs chronic
178
- - Surgical vs traumatic
179
- - Inflammatory vs proliferative healing phase
180
- ---
181
- ### Step 2: Structured Clinical Report
182
- Generate the following report sections using markdown and medical terminology:
183
- #### **1. Clinical Summary**
184
- - Describe wound appearance and tissue types (e.g., slough, necrotic, granulating, epithelializing)
185
- - Include size, wound bed condition, peri-wound skin, and signs of infection or biofilm
186
- - Mention inferred location (e.g., heel, forefoot) if image allows
187
- - Summarize patient's systemic risk profile
188
- #### **2. Medicinal & Dressing Recommendations**
189
- Based on your analysis:
190
- - Recommend specific **wound care dressings** (e.g., hydrocolloid, alginate, foam, antimicrobial silver, etc.) suitable to wound moisture level and infection risk
191
- - Propose **topical or systemic agents** ONLY if relevant — include name classes (e.g., antiseptic: povidone iodine, antibiotic ointments, enzymatic debriders)
192
- - Mention **techniques** (e.g., sharp debridement, NPWT, moisture balance, pressure offloading, dressing frequency)
193
- - Avoid repeating guidelines — **apply them**
194
- #### **3. Key Risk Factors**
195
- Explain how the patient's condition (e.g., diabetic, poor circulation, advanced age, poor hygiene) may affect wound healing
196
- #### **4. Prognosis & Monitoring Advice**
197
- - Mention how often wound should be reassessed
198
- - Indicate signs to monitor for deterioration or improvement
199
- - Include when escalation to specialist is necessary
200
- #### **5. Disclaimer**
201
- This is an AI-generated summary based on available data. It is not a substitute for clinical evaluation by a wound care professional.
202
- **Note:** Every dressing change is a chance for wound reassessment. Always perform a thorough wound evaluation at each dressing change.
203
- ---
204
- 🧾 **INPUT DATA**
205
- **Patient Info:**
206
- {patient_info}
207
- **Wound Details:**
208
- - Type: {visual_results['wound_type']}
209
- - Size: {visual_results['length_cm']} × {visual_results['breadth_cm']} cm
210
- - Area: {visual_results['surface_area_cm2']} cm²
211
- **Clinical Guideline Evidence:**
212
- {guideline_context}
213
- You may now begin your analysis and generate the two-part report.
214
  """
215
 
216
- # Use EXACT message format from working reference
217
- messages = [
218
- {
219
- "role": "system",
220
- "content": [{"type": "text", "text": "You are a world-class medical AI assistant. Follow the user's instructions precisely to perform a two-step analysis and generate a structured report."}],
221
- },
222
- {
223
- "role": "user",
224
- "content": [
225
- {"type": "image", "image": image_pil},
226
- {"type": "text", "text": prompt},
227
- ]
228
- }
229
- ]
230
-
231
- try:
 
 
 
 
 
 
232
  output = pipe(
233
  text=messages,
234
- max_new_tokens=max_new_tokens or MAX_NEW_TOKENS,
235
  do_sample=False,
 
 
236
  )
237
- result = output[0]["generated_text"][-1].get("content", "").strip()
238
- return result if result else "⚠️ No content generated. Try reducing max tokens or input size."
239
-
 
 
 
 
 
 
 
240
  except Exception as e:
241
- logging.error(f"Failed to generate MedGemma report: {e}", exc_info=True)
242
- return f"❌ An error occurred while generating the report: {e}"
 
 
 
 
243
 
244
  # =============== AI PROCESSOR CLASS ===============
245
  class AIProcessor:
@@ -252,12 +224,12 @@ class AIProcessor:
252
  self.hf_token = HF_TOKEN
253
 
254
  def perform_visual_analysis(self, image_pil: Image.Image) -> dict:
255
- """Performs the full visual analysis pipeline - EXACTLY like working reference."""
256
  try:
257
  # Convert PIL to OpenCV format
258
  image_cv = cv2.cvtColor(np.array(image_pil), cv2.COLOR_RGB2BGR)
259
 
260
- # YOLO Detection - EXACTLY like working reference
261
  results = self.models_cache["det"].predict(image_cv, verbose=False, device="cpu")
262
  if not results or not results[0].boxes:
263
  raise ValueError("No wound could be detected.")
@@ -265,13 +237,13 @@ class AIProcessor:
265
  box = results[0].boxes[0].xyxy[0].cpu().numpy().astype(int)
266
  detected_region_cv = image_cv[box[1]:box[3], box[0]:box[2]]
267
 
268
- # Segmentation - EXACTLY like working reference
269
  input_size = self.models_cache["seg"].input_shape[1:3]
270
  resized = cv2.resize(detected_region_cv, (input_size[1], input_size[0]))
271
  mask_pred = self.models_cache["seg"].predict(np.expand_dims(resized / 255.0, 0), verbose=0)[0]
272
  mask_np = (mask_pred[:, :, 0] > 0.5).astype(np.uint8)
273
 
274
- # Calculate measurements - EXACTLY like working reference
275
  contours, _ = cv2.findContours(mask_np, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
276
  length, breadth, area = (0, 0, 0)
277
  if contours:
@@ -279,23 +251,25 @@ class AIProcessor:
279
  x, y, w, h = cv2.boundingRect(cnt)
280
  length, breadth, area = round(h / self.px_per_cm, 2), round(w / self.px_per_cm, 2), round(cv2.contourArea(cnt) / (self.px_per_cm ** 2), 2)
281
 
282
- # Classification - EXACTLY like working reference
283
  detected_image_pil = Image.fromarray(cv2.cvtColor(detected_region_cv, cv2.COLOR_BGR2RGB))
284
  wound_type = max(self.models_cache["cls"](detected_image_pil), key=lambda x: x["score"])["label"]
285
 
286
- # Save detection visualization
287
- det_vis = image_cv.copy()
288
- cv2.rectangle(det_vis, (box[0], box[1]), (box[2], box[3]), (0, 255, 0), 2)
289
  os.makedirs(f"{self.uploads_dir}/analysis", exist_ok=True)
290
  ts = datetime.now().strftime("%Y%m%d_%H%M%S")
 
 
 
 
291
  det_path = f"{self.uploads_dir}/analysis/detection_{ts}.png"
292
  cv2.imwrite(det_path, det_vis)
293
 
294
- # Save original image for reference
295
  original_path = f"{self.uploads_dir}/analysis/original_{ts}.png"
296
  cv2.imwrite(original_path, image_cv)
297
 
298
- # Save segmentation visualization if available
299
  seg_path = None
300
  if contours:
301
  mask_resized = cv2.resize(mask_np * 255, (detected_region_cv.shape[1], detected_region_cv.shape[0]), interpolation=cv2.INTER_NEAREST)
@@ -328,9 +302,9 @@ class AIProcessor:
328
  if not vector_store:
329
  return "Knowledge base is not available."
330
 
331
- retriever = vector_store.as_retriever(search_kwargs={"k": 10})
332
  docs = retriever.invoke(query)
333
- return "\n\n".join([f"Source: {doc.metadata.get('source', 'N/A')}, Page: {doc.metadata.get('page', 'N/A')}\nContent: {doc.page_content}" for doc in docs])
334
 
335
  except Exception as e:
336
  logging.error(f"Guidelines query failed: {e}")
@@ -340,16 +314,18 @@ class AIProcessor:
340
  self, patient_info: str, visual_results: dict, guideline_context: str,
341
  image_pil: Image.Image, max_new_tokens: int = None
342
  ) -> str:
343
- """Generate final report using MedGemma GPU pipeline - EXACTLY like working reference."""
344
  try:
345
- report = generate_medgemma_report(
 
346
  patient_info, visual_results, guideline_context, image_pil, max_new_tokens
347
  )
348
 
 
349
  if report and report.strip() and not report.startswith("❌") and not report.startswith("⚠️"):
350
  return report
351
  else:
352
- logging.warning("MedGemma returned empty or error response, using fallback")
353
  return self._generate_fallback_report(patient_info, visual_results, guideline_context)
354
 
355
  except Exception as e:
@@ -359,9 +335,9 @@ class AIProcessor:
359
  def _generate_fallback_report(
360
  self, patient_info: str, visual_results: dict, guideline_context: str
361
  ) -> str:
362
- """Generate fallback report if MedGemma fails."""
363
 
364
- report = f"""# 🩺 SmartHeal AI - Wound Analysis Report
365
 
366
  ## 📋 Patient Information
367
  {patient_info}
@@ -370,47 +346,96 @@ class AIProcessor:
370
  - **Wound Type**: {visual_results.get('wound_type', 'Unknown')}
371
  - **Dimensions**: {visual_results.get('length_cm', 0)} cm × {visual_results.get('breadth_cm', 0)} cm
372
  - **Surface Area**: {visual_results.get('surface_area_cm2', 0)} cm²
373
- - **Detection Confidence**: {visual_results.get('detection_confidence', 0):.2f}
374
 
375
- ## 📊 Analysis Images
376
- - **Detection Image**: {visual_results.get('detection_image_path', 'N/A')}
377
- - **Segmentation Image**: {visual_results.get('segmentation_image_path', 'N/A')}
 
378
 
379
- ## 📚 Clinical Guidelines Context
380
- {guideline_context[:1000]}{'...' if len(guideline_context) > 1000 else ''}
381
 
382
- ## 🎯 Assessment Summary
383
- Based on the automated visual analysis, the wound has been classified as **{visual_results.get('wound_type', 'Unknown')}** with measurable dimensions. The detection confidence indicates the reliability of the automated assessment.
 
 
 
384
 
385
  ### Clinical Observations
386
- - **Wound Classification**: {visual_results.get('wound_type', 'Unspecified')}
387
- - **Approximate Size**: {visual_results.get('length_cm', 0)} × {visual_results.get('breadth_cm', 0)} cm
388
- - **Calculated Area**: {visual_results.get('surface_area_cm2', 0)} cm²
389
-
390
- ## 💊 General Recommendations
391
- 1. **Clinical Evaluation**: This automated analysis should be supplemented with professional clinical assessment
392
- 2. **Documentation**: Regular monitoring and documentation of wound progression is recommended
393
- 3. **Treatment Planning**: Develop appropriate treatment protocol based on wound characteristics and patient factors
394
- 4. **Follow-up**: Schedule appropriate follow-up intervals based on wound severity and healing progress
395
-
396
- ## ⚠️ Important Clinical Notes
397
- - This is an automated analysis and should not replace professional medical judgment
398
- - All measurements are estimates based on computer vision algorithms
399
- - Clinical correlation is essential for proper diagnosis and treatment planning
400
- - Consider patient-specific factors not captured in this automated assessment
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
401
 
402
  ## 🏥 Next Steps
403
- 1. **Professional Assessment**: Consult with a qualified wound care specialist
404
- 2. **Comprehensive Evaluation**: Consider patient's overall health status and comorbidities
405
- 3. **Treatment Protocol**: Develop individualized care plan based on clinical findings
406
- 4. **Monitoring Plan**: Establish regular assessment schedule
407
 
408
- ## ⚖️ Disclaimer
409
- This automated analysis is provided for informational purposes only and does not constitute medical advice. Always consult with qualified healthcare professionals for proper diagnosis and treatment. This AI-generated report should be used as a supplementary tool alongside professional clinical assessment.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
410
 
411
  ---
412
- *Generated by SmartHeal AI - Advanced Wound Care Analysis System*
413
- *Report Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*
 
414
  """
415
  return report
416
 
@@ -449,7 +474,7 @@ This automated analysis is provided for informational purposes only and does not
449
  return ""
450
 
451
  def full_analysis_pipeline(self, image_pil: Image.Image, questionnaire_data: dict) -> dict:
452
- """Run full analysis pipeline - EXACTLY like working reference."""
453
  try:
454
  # Save image first
455
  saved_path = self.save_and_commit_image(image_pil)
@@ -459,10 +484,10 @@ This automated analysis is provided for informational purposes only and does not
459
  visual_results = self.perform_visual_analysis(image_pil)
460
  logging.info(f"Visual analysis completed: {visual_results}")
461
 
462
- # Process questionnaire data - EXACTLY like working reference
463
  patient_info = f"Age: {questionnaire_data.get('age', 'N/A')}, Diabetic: {questionnaire_data.get('diabetic', 'N/A')}, Allergies: {questionnaire_data.get('allergies', 'N/A')}, Date of Wound Sustained: {questionnaire_data.get('date_of_injury', 'N/A')}, Professional Care: {questionnaire_data.get('professional_care', 'N/A')}, Oozing/Bleeding: {questionnaire_data.get('oozing_bleeding', 'N/A')}, Infection: {questionnaire_data.get('infection', 'N/A')}, Moisture: {questionnaire_data.get('moisture', 'N/A')}"
464
 
465
- # Query guidelines - EXACTLY like working reference
466
  query = f"best practices for managing a {visual_results['wound_type']} with moisture level '{questionnaire_data.get('moisture', 'unknown')}' and signs of infection '{questionnaire_data.get('infection', 'unknown')}' in a patient who is diabetic '{questionnaire_data.get('diabetic', 'unknown')}'"
467
  guideline_context = self.query_guidelines(query)
468
  logging.info("Guidelines queried successfully")
@@ -517,264 +542,4 @@ This automated analysis is provided for informational purposes only and does not
517
  'report': f"Analysis initialization failed: {str(e)}",
518
  'saved_image_path': None,
519
  'guideline_context': ""
520
- }
521
-
522
- def _assess_risk_legacy(self, questionnaire_data: dict) -> dict:
523
- """Legacy risk assessment function - maintains original function name."""
524
- risk_factors = []
525
- risk_score = 0
526
-
527
- try:
528
- # Age assessment
529
- age = questionnaire_data.get('age', 0)
530
- if isinstance(age, str):
531
- try:
532
- age = int(age)
533
- except ValueError:
534
- age = 0
535
-
536
- if age > 65:
537
- risk_factors.append("Advanced age (>65)")
538
- risk_score += 2
539
- elif age > 50:
540
- risk_factors.append("Older adult (50-65)")
541
- risk_score += 1
542
-
543
- # Wound duration assessment
544
- duration = str(questionnaire_data.get('wound_duration', '')).lower()
545
- if any(term in duration for term in ['month', 'months', 'year', 'years']):
546
- risk_factors.append("Chronic wound (>4 weeks)")
547
- risk_score += 3
548
- elif any(term in duration for term in ['week', 'weeks']):
549
- # Try to extract number of weeks
550
- import re
551
- weeks_match = re.search(r'(\d+)\s*week', duration)
552
- if weeks_match and int(weeks_match.group(1)) > 4:
553
- risk_factors.append("Chronic wound (>4 weeks)")
554
- risk_score += 3
555
-
556
- # Pain level assessment
557
- pain = questionnaire_data.get('pain_level', 0)
558
- if isinstance(pain, str):
559
- try:
560
- pain = float(pain)
561
- except ValueError:
562
- pain = 0
563
-
564
- if pain >= 7:
565
- risk_factors.append("High pain level (≥7/10)")
566
- risk_score += 2
567
- elif pain >= 5:
568
- risk_factors.append("Moderate pain level (5-6/10)")
569
- risk_score += 1
570
-
571
- # Medical history assessment
572
- medical_history = str(questionnaire_data.get('medical_history', '')).lower()
573
- diabetic_status = str(questionnaire_data.get('diabetic', '')).lower()
574
-
575
- if 'diabetes' in medical_history or 'yes' in diabetic_status:
576
- risk_factors.append("Diabetes mellitus")
577
- risk_score += 3
578
-
579
- if any(term in medical_history for term in ['vascular', 'circulation', 'arterial', 'venous']):
580
- risk_factors.append("Vascular disease")
581
- risk_score += 2
582
-
583
- if any(term in medical_history for term in ['immune', 'immunocompromised', 'steroid', 'chemotherapy']):
584
- risk_factors.append("Immune system compromise")
585
- risk_score += 2
586
-
587
- if any(term in medical_history for term in ['smoking', 'smoker', 'tobacco']):
588
- risk_factors.append("Smoking history")
589
- risk_score += 2
590
-
591
- # Infection signs
592
- infection_signs = str(questionnaire_data.get('infection', '')).lower()
593
- if 'yes' in infection_signs:
594
- risk_factors.append("Signs of infection present")
595
- risk_score += 3
596
-
597
- # Moisture level
598
- moisture = str(questionnaire_data.get('moisture', '')).lower()
599
- if any(term in moisture for term in ['wet', 'heavy', 'excessive']):
600
- risk_factors.append("Excessive wound exudate")
601
- risk_score += 1
602
-
603
- # Determine risk level
604
- if risk_score >= 8:
605
- risk_level = "Very High"
606
- elif risk_score >= 6:
607
- risk_level = "High"
608
- elif risk_score >= 3:
609
- risk_level = "Moderate"
610
- else:
611
- risk_level = "Low"
612
-
613
- return {
614
- 'risk_score': risk_score,
615
- 'risk_level': risk_level,
616
- 'risk_factors': risk_factors,
617
- 'recommendations': self._get_risk_recommendations(risk_level, risk_factors)
618
- }
619
-
620
- except Exception as e:
621
- logging.error(f"Risk assessment error: {e}")
622
- return {
623
- 'risk_score': 0,
624
- 'risk_level': 'Unknown',
625
- 'risk_factors': [],
626
- 'recommendations': ["Unable to assess risk due to data processing error"]
627
- }
628
-
629
- def _get_risk_recommendations(self, risk_level: str, risk_factors: list) -> list:
630
- """Generate risk-based recommendations."""
631
- recommendations = []
632
-
633
- if risk_level in ["High", "Very High"]:
634
- recommendations.append("Urgent referral to wound care specialist recommended")
635
- recommendations.append("Consider daily wound monitoring")
636
- recommendations.append("Implement aggressive wound care protocol")
637
- elif risk_level == "Moderate":
638
- recommendations.append("Regular wound care follow-up every 2-3 days")
639
- recommendations.append("Monitor for signs of deterioration")
640
- else:
641
- recommendations.append("Standard wound care monitoring")
642
- recommendations.append("Weekly assessment recommended")
643
-
644
- # Specific recommendations based on risk factors
645
- if "Diabetes mellitus" in risk_factors:
646
- recommendations.append("Strict glycemic control essential")
647
- recommendations.append("Monitor for diabetic complications")
648
-
649
- if "Signs of infection present" in risk_factors:
650
- recommendations.append("Consider antibiotic therapy")
651
- recommendations.append("Increase wound cleaning frequency")
652
-
653
- if "Excessive wound exudate" in risk_factors:
654
- recommendations.append("Use high-absorption dressings")
655
- recommendations.append("More frequent dressing changes may be needed")
656
-
657
- return recommendations
658
-
659
-
660
- # =============== STANDALONE SAVE AND COMMIT FUNCTION ===============
661
- def save_and_commit_image(image_to_save):
662
- """Saves an image locally and commits it to the separate HF Dataset repository - EXACTLY like working reference."""
663
- if not image_to_save:
664
- return
665
-
666
- timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
667
- filename = f"{timestamp}.png"
668
- local_save_path = os.path.join(UPLOADS_DIR, filename)
669
-
670
- image_to_save.convert("RGB").save(local_save_path)
671
- logging.info(f"✅ Image saved to temporary local storage: {local_save_path}")
672
-
673
- if DATASET_ID and HF_TOKEN:
674
- try:
675
- api = HfApi()
676
- repo_path = f"images/{filename}"
677
-
678
- logging.info(f"Attempting to commit {local_save_path} to DATASET {DATASET_ID}...")
679
-
680
- api.upload_file(
681
- path_or_fileobj=local_save_path,
682
- path_in_repo=repo_path,
683
- repo_id=DATASET_ID,
684
- repo_type="dataset",
685
- commit_message=f"Upload wound image: {filename}"
686
- )
687
- logging.info(f"✅ Image successfully committed to dataset.")
688
- except Exception as e:
689
- logging.error(f"❌ FAILED TO COMMIT IMAGE TO DATASET: {e}")
690
- else:
691
- logging.warning("DATASET_ID or HF_TOKEN not set. Skipping file commit.")
692
-
693
- # =============== MAIN ANALYSIS FUNCTION (with @spaces.GPU) - EXACTLY LIKE WORKING REFERENCE ===============
694
- @spaces.GPU(enable_queue=True, duration=120)
695
- def analyze(image, age, diabetic, allergies, date_of_injury, professional_care, oozing_bleeding, infection, moisture):
696
- """Main analysis function with GPU decorator - EXACTLY like working reference."""
697
- try:
698
- yield None, None, "⏳ Initializing... Loading AI models..."
699
-
700
- # Load all models - using global cache
701
- if "medgemma_pipe" not in models_cache:
702
- from transformers import pipeline
703
- models_cache["medgemma_pipe"] = pipeline(
704
- "image-text-to-text",
705
- model="google/medgemma-4b-it",
706
- torch_dtype=torch.bfloat16,
707
- device_map="auto",
708
- token=HF_TOKEN
709
- )
710
- logging.info("✅ All models loaded.")
711
-
712
- yield None, None, "⏳ Setting up knowledge base from guidelines..."
713
-
714
- # Save image
715
- save_and_commit_image(image)
716
-
717
- # Create processor instance
718
- processor = AIProcessor()
719
-
720
- yield None, None, "⏳ Performing visual analysis..."
721
-
722
- # Perform visual analysis - EXACTLY like working reference
723
- image_cv = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
724
- results = models_cache["det"].predict(image_cv, verbose=False, device="cpu")
725
- if not results or not results[0].boxes:
726
- raise ValueError("No wound could be detected.")
727
-
728
- box = results[0].boxes[0].xyxy[0].cpu().numpy().astype(int)
729
- detected_region_cv = image_cv[box[1]:box[3], box[0]:box[2]]
730
-
731
- input_size = models_cache["seg"].input_shape[1:3]
732
- resized = cv2.resize(detected_region_cv, (input_size[1], input_size[0]))
733
- mask_pred = models_cache["seg"].predict(np.expand_dims(resized / 255.0, 0), verbose=0)[0]
734
- mask_np = (mask_pred[:, :, 0] > 0.5).astype(np.uint8)
735
-
736
- contours, _ = cv2.findContours(mask_np, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
737
- length, breadth, area = (0, 0, 0)
738
- if contours:
739
- cnt = max(contours, key=cv2.contourArea)
740
- x, y, w, h = cv2.boundingRect(cnt)
741
- length, breadth, area = round(h / PIXELS_PER_CM, 2), round(w / PIXELS_PER_CM, 2), round(cv2.contourArea(cnt) / (PIXELS_PER_CM ** 2), 2)
742
-
743
- detected_image_pil = Image.fromarray(cv2.cvtColor(detected_region_cv, cv2.COLOR_BGR2RGB))
744
- wound_type = max(models_cache["cls"](detected_image_pil), key=lambda x: x["score"])["label"]
745
-
746
- visual_results = {"wound_type": wound_type, "length_cm": length, "breadth_cm": breadth, "surface_area_cm2": area}
747
-
748
- # Create visualization images
749
- segmented_mask = Image.fromarray(cv2.resize(mask_np * 255, (detected_region_cv.shape[1], detected_region_cv.shape[0]), interpolation=cv2.INTER_NEAREST))
750
-
751
- yield detected_image_pil, segmented_mask, f"✅ Visual analysis complete. Detected: {visual_results['wound_type']}. Querying guidelines..."
752
-
753
- # Query guidelines
754
- patient_info = f"Age: {age}, Diabetic: {diabetic}, Allergies: {allergies}, Date of Wound Sustained: {date_of_injury}, Professional Care: {professional_care}, Oozing/Bleeding: {oozing_bleeding}, Infection: {infection}, Moisture: {moisture}"
755
- query = f"best practices for managing a {visual_results['wound_type']} with moisture level '{moisture}' and signs of infection '{infection}' in a patient who is diabetic '{diabetic}'"
756
- guideline_context = processor.query_guidelines(query)
757
-
758
- yield detected_image_pil, segmented_mask, "✅ Guidelines queried. Generating final report..."
759
-
760
- # Generate final report using MedGemma
761
- final_report = generate_medgemma_report(
762
- patient_info,
763
- visual_results,
764
- guideline_context,
765
- image_pil=image
766
- )
767
-
768
- visual_summary = f"""## 📊 Programmatic Visual Analysis
769
- | Metric | Result |
770
- | :--- | :--- |
771
- | **Detected Wound Type** | {visual_results['wound_type']} |
772
- | **Estimated Dimensions** | {visual_results['length_cm']}cm x {visual_results['breadth_cm']}cm (Area: {visual_results['surface_area_cm2']}cm²) |
773
- ---
774
- """
775
- final_output_text = visual_summary + "## 🩺 MedHeal-AI Clinical Assessment\n" + final_report
776
- yield detected_image_pil, segmented_mask, final_output_text
777
-
778
- except Exception as e:
779
- logging.error(f"An error occurred during analysis: {e}", exc_info=True)
780
- yield None, None, f"❌ **An error occurred:** {e}"
 
7
  import gradio as gr
8
  import spaces
9
  import torch
10
+ import time
11
 
12
  from huggingface_hub import HfApi, HfFolder
13
  from langchain_community.document_loaders import PyPDFLoader
 
29
  SEG_MODEL_PATH = "src/segmentation_model.h5"
30
  GUIDELINE_PDFS = ["src/eHealth in Wound Care.pdf", "src/IWGDF Guideline.pdf", "src/evaluation.pdf"]
31
  DATASET_ID = "SmartHeal/wound-image-uploads"
32
+ MAX_NEW_TOKENS = 1024 # Reduced for stability
33
  PIXELS_PER_CM = 38
34
 
35
  # =============== GLOBAL CACHES ===============
 
132
  initialize_cpu_models()
133
  setup_knowledge_base()
134
 
135
+ # =============== GPU-DECORATED MEDGEMMA FUNCTION WITH TIMEOUT HANDLING ===============
136
+ @spaces.GPU(enable_queue=True, duration=90) # Reduced duration for stability
137
+ def generate_medgemma_report_with_timeout(
138
  patient_info,
139
  visual_results,
140
  guideline_context,
141
  image_pil,
142
  max_new_tokens=None,
143
  ):
144
+ """GPU-only function for MedGemma report generation with improved timeout handling."""
145
+ import torch
146
  from transformers import pipeline
147
+
148
+ try:
149
+ # Clear GPU cache first
150
+ if torch.cuda.is_available():
151
+ torch.cuda.empty_cache()
152
+
153
+ # Use a shorter, more focused prompt to reduce processing time
154
+ prompt = f"""
155
+ You are a medical AI assistant. Analyze this wound image and patient data to provide a clinical assessment.
156
 
157
+ Patient: {patient_info}
158
+ Wound: {visual_results.get('wound_type', 'Unknown')} - {visual_results.get('length_cm', 0)}×{visual_results.get('breadth_cm', 0)}cm
 
 
 
 
 
 
 
 
 
 
 
 
159
 
160
+ Provide a structured report with:
161
+ 1. Clinical Summary (wound appearance, size, location)
162
+ 2. Treatment Recommendations (dressings, care protocols)
163
+ 3. Risk Assessment (healing factors)
164
+ 4. Monitoring Plan (follow-up schedule)
165
 
166
+ Keep response concise but medically comprehensive.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  """
168
 
169
+ # Initialize pipeline with optimized settings
170
+ pipe = pipeline(
171
+ "image-text-to-text",
172
+ model="google/medgemma-4b-it",
173
+ torch_dtype=torch.bfloat16,
174
+ device_map="auto",
175
+ token=HF_TOKEN,
176
+ model_kwargs={"low_cpu_mem_usage": True, "use_cache": True}
177
+ )
178
+
179
+ messages = [
180
+ {
181
+ "role": "user",
182
+ "content": [
183
+ {"type": "image", "image": image_pil},
184
+ {"type": "text", "text": prompt},
185
+ ]
186
+ }
187
+ ]
188
+
189
+ # Generate with conservative settings
190
+ start_time = time.time()
191
  output = pipe(
192
  text=messages,
193
+ max_new_tokens=max_new_tokens or 800, # Reduced for stability
194
  do_sample=False,
195
+ temperature=0.7,
196
+ pad_token_id=pipe.tokenizer.eos_token_id
197
  )
198
+
199
+ processing_time = time.time() - start_time
200
+ logging.info(f"✅ MedGemma processing completed in {processing_time:.2f} seconds")
201
+
202
+ if output and len(output) > 0:
203
+ result = output[0]["generated_text"][-1].get("content", "").strip()
204
+ return result if result else "⚠️ Empty response generated"
205
+ else:
206
+ return "⚠️ No output generated"
207
+
208
  except Exception as e:
209
+ logging.error(f" MedGemma generation error: {e}")
210
+ return f"❌ Report generation failed: {str(e)}"
211
+ finally:
212
+ # Clear GPU memory
213
+ if torch.cuda.is_available():
214
+ torch.cuda.empty_cache()
215
 
216
  # =============== AI PROCESSOR CLASS ===============
217
  class AIProcessor:
 
224
  self.hf_token = HF_TOKEN
225
 
226
  def perform_visual_analysis(self, image_pil: Image.Image) -> dict:
227
+ """Performs the full visual analysis pipeline."""
228
  try:
229
  # Convert PIL to OpenCV format
230
  image_cv = cv2.cvtColor(np.array(image_pil), cv2.COLOR_RGB2BGR)
231
 
232
+ # YOLO Detection
233
  results = self.models_cache["det"].predict(image_cv, verbose=False, device="cpu")
234
  if not results or not results[0].boxes:
235
  raise ValueError("No wound could be detected.")
 
237
  box = results[0].boxes[0].xyxy[0].cpu().numpy().astype(int)
238
  detected_region_cv = image_cv[box[1]:box[3], box[0]:box[2]]
239
 
240
+ # Segmentation
241
  input_size = self.models_cache["seg"].input_shape[1:3]
242
  resized = cv2.resize(detected_region_cv, (input_size[1], input_size[0]))
243
  mask_pred = self.models_cache["seg"].predict(np.expand_dims(resized / 255.0, 0), verbose=0)[0]
244
  mask_np = (mask_pred[:, :, 0] > 0.5).astype(np.uint8)
245
 
246
+ # Calculate measurements
247
  contours, _ = cv2.findContours(mask_np, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
248
  length, breadth, area = (0, 0, 0)
249
  if contours:
 
251
  x, y, w, h = cv2.boundingRect(cnt)
252
  length, breadth, area = round(h / self.px_per_cm, 2), round(w / self.px_per_cm, 2), round(cv2.contourArea(cnt) / (self.px_per_cm ** 2), 2)
253
 
254
+ # Classification
255
  detected_image_pil = Image.fromarray(cv2.cvtColor(detected_region_cv, cv2.COLOR_BGR2RGB))
256
  wound_type = max(self.models_cache["cls"](detected_image_pil), key=lambda x: x["score"])["label"]
257
 
258
+ # Save visualization images
 
 
259
  os.makedirs(f"{self.uploads_dir}/analysis", exist_ok=True)
260
  ts = datetime.now().strftime("%Y%m%d_%H%M%S")
261
+
262
+ # Detection visualization
263
+ det_vis = image_cv.copy()
264
+ cv2.rectangle(det_vis, (box[0], box[1]), (box[2], box[3]), (0, 255, 0), 2)
265
  det_path = f"{self.uploads_dir}/analysis/detection_{ts}.png"
266
  cv2.imwrite(det_path, det_vis)
267
 
268
+ # Original image
269
  original_path = f"{self.uploads_dir}/analysis/original_{ts}.png"
270
  cv2.imwrite(original_path, image_cv)
271
 
272
+ # Segmentation visualization
273
  seg_path = None
274
  if contours:
275
  mask_resized = cv2.resize(mask_np * 255, (detected_region_cv.shape[1], detected_region_cv.shape[0]), interpolation=cv2.INTER_NEAREST)
 
302
  if not vector_store:
303
  return "Knowledge base is not available."
304
 
305
+ retriever = vector_store.as_retriever(search_kwargs={"k": 5}) # Reduced for efficiency
306
  docs = retriever.invoke(query)
307
+ return "\n\n".join([f"Source: {doc.metadata.get('source', 'N/A')}\nContent: {doc.page_content[:300]}..." for doc in docs])
308
 
309
  except Exception as e:
310
  logging.error(f"Guidelines query failed: {e}")
 
314
  self, patient_info: str, visual_results: dict, guideline_context: str,
315
  image_pil: Image.Image, max_new_tokens: int = None
316
  ) -> str:
317
+ """Generate final report using MedGemma with timeout handling."""
318
  try:
319
+ # Try MedGemma with timeout handling
320
+ report = generate_medgemma_report_with_timeout(
321
  patient_info, visual_results, guideline_context, image_pil, max_new_tokens
322
  )
323
 
324
+ # Check if report is valid
325
  if report and report.strip() and not report.startswith("❌") and not report.startswith("⚠️"):
326
  return report
327
  else:
328
+ logging.warning("MedGemma returned invalid response, using fallback")
329
  return self._generate_fallback_report(patient_info, visual_results, guideline_context)
330
 
331
  except Exception as e:
 
335
  def _generate_fallback_report(
336
  self, patient_info: str, visual_results: dict, guideline_context: str
337
  ) -> str:
338
+ """Generate comprehensive fallback report if MedGemma fails."""
339
 
340
+ report = f"""# 🩺 SmartHeal AI - Comprehensive Wound Analysis Report
341
 
342
  ## 📋 Patient Information
343
  {patient_info}
 
346
  - **Wound Type**: {visual_results.get('wound_type', 'Unknown')}
347
  - **Dimensions**: {visual_results.get('length_cm', 0)} cm × {visual_results.get('breadth_cm', 0)} cm
348
  - **Surface Area**: {visual_results.get('surface_area_cm2', 0)} cm²
349
+ - **Detection Confidence**: {visual_results.get('detection_confidence', 0):.1%}
350
 
351
+ ## 📊 Analysis Images Available
352
+ - **Original Image**: {visual_results.get('original_image_path', 'Available')}
353
+ - **Detection Visualization**: {visual_results.get('detection_image_path', 'Available')}
354
+ - **Segmentation Overlay**: {visual_results.get('segmentation_image_path', 'Available')}
355
 
356
+ ## 🎯 Clinical Assessment Summary
 
357
 
358
+ ### Wound Classification
359
+ Based on automated analysis, this wound has been classified as **{visual_results.get('wound_type', 'Unspecified')}** with the following characteristics:
360
+ - Size: {visual_results.get('length_cm', 0)} × {visual_results.get('breadth_cm', 0)} cm
361
+ - Total area: {visual_results.get('surface_area_cm2', 0)} cm²
362
+ - Detection confidence: {visual_results.get('detection_confidence', 0):.1%}
363
 
364
  ### Clinical Observations
365
+ The automated visual analysis provides quantitative measurements that should be verified through clinical examination. The wound type classification helps guide initial treatment considerations.
366
+
367
+ ## 💊 Treatment Recommendations
368
+
369
+ ### Wound Care Protocol
370
+ 1. **Assessment**: Comprehensive clinical evaluation by qualified healthcare professional
371
+ 2. **Cleaning**: Gentle wound cleansing with appropriate solution
372
+ 3. **Debridement**: Remove necrotic tissue if present (professional assessment required)
373
+ 4. **Dressing Selection**: Choose appropriate dressing based on wound characteristics:
374
+ - Moisture level assessment
375
+ - Infection risk evaluation
376
+ - Patient comfort and mobility
377
+
378
+ ### Monitoring Plan
379
+ - **Initial Phase**: Daily assessment for first week
380
+ - **Ongoing Care**: Reassessment every 2-3 days or as clinically indicated
381
+ - **Documentation**: Regular photo documentation and measurement tracking
382
+ - **Progress Evaluation**: Weekly review of healing progression
383
+
384
+ ## ⚠️ Risk Factors & Considerations
385
+
386
+ ### Patient-Specific Factors
387
+ Review patient history for factors that may impact healing:
388
+ - Age and general health status
389
+ - Diabetes or metabolic conditions
390
+ - Circulation and vascular health
391
+ - Nutritional status
392
+ - Mobility and pressure relief
393
+
394
+ ### Warning Signs
395
+ Monitor for signs requiring immediate attention:
396
+ - Increased pain, redness, or swelling
397
+ - Purulent drainage or odor
398
+ - Fever or systemic signs of infection
399
+ - Wound expansion or deterioration
400
+ - Delayed healing beyond expected timeframe
401
+
402
+ ## 📚 Clinical Guidelines Context
403
+ {guideline_context[:800]}{'...' if len(guideline_context) > 800 else ''}
404
 
405
  ## 🏥 Next Steps
 
 
 
 
406
 
407
+ ### Immediate Actions
408
+ 1. **Professional Consultation**: Schedule appointment with wound care specialist
409
+ 2. **Baseline Documentation**: Establish comprehensive baseline assessment
410
+ 3. **Treatment Plan**: Develop individualized care protocol
411
+ 4. **Patient Education**: Provide wound care instructions and warning signs
412
+
413
+ ### Follow-up Schedule
414
+ - **Week 1**: Daily monitoring and assessment
415
+ - **Week 2-4**: Every 2-3 days or as indicated
416
+ - **Monthly**: Comprehensive reassessment and plan review
417
+ - **As Needed**: Immediate evaluation for any concerning changes
418
+
419
+ ## ⚖️ Important Medical Disclaimer
420
+
421
+ **This automated analysis is provided for informational and educational purposes only.**
422
+
423
+ - This report does not constitute medical diagnosis or treatment advice
424
+ - All measurements are computer-generated estimates requiring clinical verification
425
+ - Professional medical evaluation is essential for proper diagnosis and treatment
426
+ - This AI tool should supplement, not replace, clinical judgment
427
+ - Always consult qualified healthcare professionals for medical decisions
428
+
429
+ ### Clinical Correlation Required
430
+ - Verify all measurements with standard clinical tools
431
+ - Correlate findings with patient symptoms and history
432
+ - Consider factors not captured in automated analysis
433
+ - Follow institutional protocols and guidelines
434
 
435
  ---
436
+ *Generated by SmartHeal AI - Advanced Wound Care Analysis System*
437
+ *Report Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*
438
+ *Version: AI-Processor v1.2 with Enhanced Fallback Reporting*
439
  """
440
  return report
441
 
 
474
  return ""
475
 
476
  def full_analysis_pipeline(self, image_pil: Image.Image, questionnaire_data: dict) -> dict:
477
+ """Run full analysis pipeline."""
478
  try:
479
  # Save image first
480
  saved_path = self.save_and_commit_image(image_pil)
 
484
  visual_results = self.perform_visual_analysis(image_pil)
485
  logging.info(f"Visual analysis completed: {visual_results}")
486
 
487
+ # Process questionnaire data
488
  patient_info = f"Age: {questionnaire_data.get('age', 'N/A')}, Diabetic: {questionnaire_data.get('diabetic', 'N/A')}, Allergies: {questionnaire_data.get('allergies', 'N/A')}, Date of Wound Sustained: {questionnaire_data.get('date_of_injury', 'N/A')}, Professional Care: {questionnaire_data.get('professional_care', 'N/A')}, Oozing/Bleeding: {questionnaire_data.get('oozing_bleeding', 'N/A')}, Infection: {questionnaire_data.get('infection', 'N/A')}, Moisture: {questionnaire_data.get('moisture', 'N/A')}"
489
 
490
+ # Query guidelines
491
  query = f"best practices for managing a {visual_results['wound_type']} with moisture level '{questionnaire_data.get('moisture', 'unknown')}' and signs of infection '{questionnaire_data.get('infection', 'unknown')}' in a patient who is diabetic '{questionnaire_data.get('diabetic', 'unknown')}'"
492
  guideline_context = self.query_guidelines(query)
493
  logging.info("Guidelines queried successfully")
 
542
  'report': f"Analysis initialization failed: {str(e)}",
543
  'saved_image_path': None,
544
  'guideline_context': ""
545
+ }