Ansh99 commited on
Commit
08908ec
·
verified ·
1 Parent(s): 63999d6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +282 -597
app.py CHANGED
@@ -1,12 +1,12 @@
1
- from flask import Flask, render_template, request, send_file, jsonify
 
2
  import torch
3
  import numpy as np
4
- import cv2
5
- import json
6
- import os
7
  import pydicom
8
- from pydicom.pixel_data_handlers.util import apply_voi_lut
 
9
  import matplotlib
 
10
  matplotlib.use('Agg')
11
  import matplotlib.pyplot as plt
12
  import matplotlib.patches as patches
@@ -17,41 +17,40 @@ from groq import Groq
17
  from stable_baselines3 import PPO
18
  import gymnasium as gym
19
  from gymnasium import spaces
20
- from PIL import Image, ImageDraw, ImageFont
21
  from fpdf import FPDF
22
  from datetime import datetime
23
- import traceback
24
  from werkzeug.exceptions import HTTPException
25
- import seaborn as sns
 
 
 
 
 
 
26
 
27
  app = Flask(__name__)
28
- app.config['UPLOAD_FOLDER'] = 'uploads'
 
 
 
 
 
29
  app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
30
 
31
- os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
32
- os.makedirs('outputs', exist_ok=True)
33
- os.makedirs('reports', exist_ok=True)
34
- os.makedirs('templates', exist_ok=True)
35
 
36
- # --- ERROR HANDLERS ---
37
- @app.errorhandler(HTTPException)
38
- def handle_exception(e):
39
- response = {"success": False, "error": e.name, "message": e.description, "code": e.code}
40
- return jsonify(response), e.code
41
 
42
- @app.errorhandler(Exception)
43
- def handle_generic_exception(e):
44
- error_trace = traceback.format_exc()
45
- print(f"ERROR: {error_trace}")
46
- response = {"success": False, "error": type(e).__name__, "message": str(e),
47
- "traceback": error_trace if app.debug else "Enable debug mode"}
48
- return jsonify(response), 500
49
 
50
- # --- CONFIGURATION ---
51
  DEVICE = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
52
- MODEL_PATH = r"D:\Projects\Deep Learning\XAI_Pneumonia_App\models\judge_model_epoch5.pth"
53
- RL_AGENT_PATH = r"D:\Projects\Deep Learning\XAI_Pneumonia_App\strict_rl_agent"
54
- MEMORY_FILE = "medical_memory.json"
55
 
56
  CLASS_MAPPING = {
57
  1: 'Aortic enlargement', 2: 'Atelectasis', 3: 'Calcification', 4: 'Cardiomegaly',
@@ -77,6 +76,13 @@ DISEASE_DESCRIPTIONS = {
77
  'Pulmonary fibrosis': 'Progressive lung scarring reducing elasticity. Serious condition with various causes.'
78
  }
79
 
 
 
 
 
 
 
 
80
  # --- RAG MEMORY ---
81
  class RAGMemory:
82
  def __init__(self, filepath):
@@ -93,14 +99,18 @@ class RAGMemory:
93
  "confidence": float(confidence),
94
  "timestamp": datetime.now().isoformat()
95
  }
96
- with open(self.filepath, 'r+') as f:
 
 
97
  try:
98
- data = json.load(f)
99
- except:
100
- data = []
101
- data.append(new_entry)
102
- f.seek(0)
103
- f.truncate()
 
 
104
  json.dump(data, f, indent=2)
105
  except Exception as e:
106
  print(f"RAG save error: {e}")
@@ -112,19 +122,20 @@ class RAGMemory:
112
  except:
113
  return "Memory Empty."
114
 
115
- relevant = [d for d in data if d['disease'] == suspected_disease and d['confidence'] > 0.5]
116
 
117
  if not relevant:
118
  return "No prior memory of this condition."
119
 
 
120
  action_counts = {}
121
  for r in relevant:
122
- action_str = ", ".join(r['actions'])
123
  action_counts[action_str] = action_counts.get(action_str, 0) + 1
124
 
125
  if action_counts:
126
  best_strategy = max(action_counts, key=action_counts.get)
127
- return f"In {len(relevant)} past cases of {suspected_disease}: [{best_strategy}]"
128
  return "No clear strategy found."
129
 
130
  rag_db = RAGMemory(MEMORY_FILE)
@@ -137,123 +148,47 @@ class DummyEnv(gym.Env):
137
 
138
  def load_models():
139
  try:
140
- detector = fasterrcnn_resnet50_fpn(pretrained=False)
 
141
  in_features = detector.roi_heads.box_predictor.cls_score.in_features
142
  detector.roi_heads.box_predictor = FastRCNNPredictor(in_features, 15)
143
 
144
  if os.path.exists(MODEL_PATH):
145
  detector.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
146
- detector.to(DEVICE)
147
- detector.eval()
148
- print(f"✓ Detector loaded")
 
 
 
149
 
 
150
  agent = None
151
- if os.path.exists(RL_AGENT_PATH + ".zip"):
152
- agent = PPO.load(RL_AGENT_PATH, env=DummyEnv())
153
- print(f"✓ RL Agent loaded")
 
 
 
 
 
 
154
 
155
  return detector, agent
156
  except Exception as e:
157
- print(f"❌ Model loading error: {e}")
158
  raise
159
 
160
  detector, agent = load_models()
161
 
162
- # --- ENHANCED LLM FUNCTIONS ---
163
- def get_enhanced_disease_analysis(disease_name, confidence, image_stats, api_key):
164
- """Get detailed LLM analysis for specific disease"""
165
- if not api_key:
166
- return DISEASE_DESCRIPTIONS.get(disease_name, "Detailed analysis requires API key.")
167
-
168
- try:
169
- client = Groq(api_key=api_key)
170
-
171
- prompt = f"""You are an expert radiologist. Provide detailed clinical analysis for:
172
-
173
- **Disease:** {disease_name}
174
- **AI Confidence:** {confidence:.1%}
175
- **Image Statistics:** Mean intensity: {image_stats['mean']:.1f}, Std Dev: {image_stats['std']:.1f}
176
-
177
- Provide in this format:
178
- 1. **Definition:** Brief medical definition
179
- 2. **Clinical Significance:** Why this matters
180
- 3. **Common Causes:** Possible etiologies
181
- 4. **Associated Findings:** What to look for
182
- 5. **Recommended Follow-up:** Next steps
183
- 6. **Risk Stratification:** Severity assessment
184
-
185
- Keep each section to 2-3 sentences maximum."""
186
-
187
- resp = client.chat.completions.create(
188
- messages=[{"role": "user", "content": prompt}],
189
- model="llama-3.3-70b-versatile",
190
- temperature=0.3,
191
- max_tokens=600
192
- )
193
- return resp.choices[0].message.content
194
- except Exception as e:
195
- return f"Analysis error: {str(e)}\n\n{DISEASE_DESCRIPTIONS.get(disease_name, '')}"
196
-
197
- def get_comprehensive_report(findings, actions, rag_context, llm_advice, api_key):
198
- """Generate comprehensive multi-disease report"""
199
- if not api_key:
200
- return "API key required for detailed analysis."
201
- if not findings:
202
- return "No abnormalities detected. Patient appears healthy on radiographic examination."
203
-
204
- try:
205
- client = Groq(api_key=api_key)
206
-
207
- findings_str = "\n".join([f"• {n}: {s:.1%} confidence" for n, s in findings])
208
- action_str = " → ".join(actions)
209
-
210
- prompt = f"""You are a senior radiologist. Generate a comprehensive clinical report:
211
-
212
- **DETECTED CONDITIONS:**
213
- {findings_str}
214
-
215
- **AI PREPROCESSING:** {action_str}
216
- **LLM INITIAL ASSESSMENT:** {llm_advice}
217
- **CLINICAL HISTORY:** {rag_context}
218
-
219
- Format your response as:
220
-
221
- **IMPRESSION:**
222
- [Overall summary of findings]
223
-
224
- **FINDINGS:**
225
- [Detailed analysis of each detected condition]
226
-
227
- **DIFFERENTIAL DIAGNOSIS:**
228
- [Possible diagnoses to consider]
229
-
230
- **RECOMMENDATIONS:**
231
- [Suggested follow-up and clinical management]
232
 
233
- **CLINICAL CORRELATION:**
234
- [Importance of correlating with clinical presentation]
235
-
236
- Be thorough, specific, and clinically relevant."""
237
-
238
- resp = client.chat.completions.create(
239
- messages=[{"role": "user", "content": prompt}],
240
- model="llama-3.3-70b-versatile",
241
- temperature=0.3,
242
- max_tokens=2000
243
- )
244
- return resp.choices[0].message.content
245
- except Exception as e:
246
- return f"Report generation error: {str(e)}"
247
-
248
- # --- IMAGE PROCESSING ---
249
  def preprocess_image(file_path):
250
  try:
251
- if file_path.endswith(('.dcm', '.dicom')):
252
  dcm = pydicom.dcmread(file_path)
253
- try:
254
- img = apply_voi_lut(dcm.pixel_array, dcm)
255
- except:
256
- img = dcm.pixel_array
257
  if dcm.PhotometricInterpretation == "MONOCHROME1":
258
  img = np.amax(img) - img
259
  img = img - np.min(img)
@@ -268,490 +203,240 @@ def preprocess_image(file_path):
268
  except Exception as e:
269
  raise ValueError(f"Image preprocessing failed: {str(e)}")
270
 
271
- def run_rl_with_llm_guidance(img_np, llm_advice):
272
- if agent is None:
273
- return [img_np], ["RL Agent not available"]
274
-
275
- try:
276
- current = img_np.copy()
277
- history_frames = [current.copy()]
278
- actions_log = []
279
-
280
- llm_hint = -1
281
- advice_lower = llm_advice.lower()
282
- if "bright" in advice_lower and "increase" in advice_lower:
283
- llm_hint = 0
284
- elif "bright" in advice_lower and "decrease" in advice_lower:
285
- llm_hint = 1
286
- elif "contrast" in advice_lower and "increase" in advice_lower:
287
- llm_hint = 2
288
- elif "contrast" in advice_lower and "decrease" in advice_lower:
289
- llm_hint = 3
290
-
291
- for step in range(5):
292
- if step == 0 and llm_hint >= 0:
293
- action = llm_hint
294
- else:
295
- action, _ = agent.predict(current)
296
-
297
- if action == 0:
298
- current = np.clip(current + 15, 0, 255).astype(np.uint8)
299
- actions_log.append("Bright+")
300
- elif action == 1:
301
- current = np.clip(current - 15, 0, 255).astype(np.uint8)
302
- actions_log.append("Bright-")
303
- elif action == 2:
304
- current = np.clip((current - 127.5)*1.2 + 127.5, 0, 255).astype(np.uint8)
305
- actions_log.append("Cont+")
306
- elif action == 3:
307
- current = np.clip((current - 127.5)*0.8 + 127.5, 0, 255).astype(np.uint8)
308
- actions_log.append("Cont-")
309
- elif action == 4:
310
- actions_log.append("Submit")
311
- history_frames.append(current.copy())
312
- break
313
-
314
- history_frames.append(current.copy())
315
-
316
- return history_frames, actions_log
317
- except Exception as e:
318
- return [img_np], ["Error in RL processing"]
319
 
320
- def create_ensemble_boxplot(findings, output_path):
321
- """Create ensemble box plot for multiple diseases"""
 
 
 
 
 
 
 
 
 
322
  try:
323
- fig, ax = plt.subplots(figsize=(12, 6))
324
- fig.patch.set_facecolor('#1a1a1a')
325
- ax.set_facecolor('#2a2a2a')
326
-
327
- diseases = [f['disease'][:15] for f in findings]
328
- confidences = [f['confidence'] * 100 for f in findings]
329
-
330
- # Create bar chart with gradient
331
- colors = plt.cm.RdYlGn(np.array(confidences) / 100)
332
- bars = ax.barh(diseases, confidences, color=colors, edgecolor='#00ff00', linewidth=2)
333
-
334
- # Add value labels
335
- for i, (bar, conf) in enumerate(zip(bars, confidences)):
336
- ax.text(conf + 1, i, f'{conf:.1f}%', va='center', color='#00ff00', fontweight='bold')
337
-
338
- ax.set_xlabel('Confidence (%)', color='#00ff00', fontsize=12, fontweight='bold')
339
- ax.set_title('Disease Confidence Ensemble', color='#00ff00', fontsize=14, fontweight='bold')
340
- ax.set_xlim(0, 105)
341
- ax.tick_params(colors='#00ff00')
342
-
343
- # Style
344
- for spine in ax.spines.values():
345
- spine.set_color('#00ff00')
346
- spine.set_linewidth(2)
347
 
348
- ax.grid(axis='x', alpha=0.2, color='#00ff00')
 
 
 
 
349
 
350
- plt.tight_layout()
351
- plt.savefig(output_path, dpi=150, bbox_inches='tight', facecolor='#1a1a1a')
352
- plt.close()
353
- return True
 
 
354
  except Exception as e:
355
- print(f"Ensemble plot error: {e}")
356
- return False
357
 
358
- def create_heatmap(img_np, boxes, scores):
 
 
 
 
359
  try:
360
- heatmap = np.zeros((512, 512), dtype=np.float32)
361
-
362
- for box, score in zip(boxes, scores):
363
- x1, y1, x2, y2 = map(int, box)
364
- x1, y1 = max(0, x1), max(0, y1)
365
- x2, y2 = min(512, x2), min(512, y2)
366
- heatmap[y1:y2, x1:x2] += score
367
 
368
- if heatmap.max() > 0:
369
- heatmap = heatmap / heatmap.max()
370
 
371
- heatmap_colored = cv2.applyColorMap((heatmap * 255).astype(np.uint8), cv2.COLORMAP_JET)
372
- heatmap_colored = cv2.cvtColor(heatmap_colored, cv2.COLOR_BGR2RGB)
373
-
374
- overlay = cv2.addWeighted(img_np, 0.6, heatmap_colored, 0.4, 0)
375
- return overlay
 
376
  except Exception as e:
377
- print(f"Heatmap error: {e}")
378
- return img_np
379
 
380
- def crop_detections(img_np, boxes, labels, scores):
381
- crops = []
382
- try:
383
- for box, lbl, score in zip(boxes, labels, scores):
384
- x1, y1, x2, y2 = map(int, box)
385
- pad = 15
386
- x1, y1 = max(0, x1-pad), max(0, y1-pad)
387
- x2, y2 = min(512, x2+pad), min(512, y2+pad)
388
-
389
- crop = img_np[y1:y2, x1:x2].copy()
390
- disease_name = CLASS_MAPPING.get(int(lbl), "Unknown")
391
- crops.append({
392
- 'image': crop,
393
- 'disease': disease_name,
394
- 'confidence': float(score),
395
- 'bbox': (x1, y1, x2, y2)
396
- })
397
- except Exception as e:
398
- print(f"Crop error: {e}")
399
- return crops
400
 
401
- # --- ENHANCED PDF GENERATION ---
402
- class EnhancedMedicalPDF(FPDF):
403
- def __init__(self):
404
- super().__init__()
405
- self.WIDTH = 210
406
- self.HEIGHT = 297
407
-
408
- def header(self):
409
- self.set_fill_color(30, 30, 30)
410
- self.rect(0, 0, self.WIDTH, 30, 'F')
411
- self.set_font('Arial', 'B', 20)
412
- self.set_text_color(0, 255, 0)
413
- self.cell(0, 15, 'SUPER-DOCTOR V2', 0, 1, 'C')
414
- self.set_font('Arial', 'I', 10)
415
- self.cell(0, 8, f'Medical AI Analysis Report | {datetime.now().strftime("%Y-%m-%d %H:%M")}', 0, 1, 'C')
416
- self.ln(5)
417
 
418
- def footer(self):
419
- self.set_y(-20)
420
- self.set_font('Arial', 'I', 8)
421
- self.set_text_color(128, 128, 128)
422
- self.cell(0, 10, f'Page {self.page_no()} | AI-Assisted Analysis - Not a substitute for clinical judgment', 0, 0, 'C')
423
 
424
- def section_title(self, title):
425
- self.set_font('Arial', 'B', 14)
426
- self.set_fill_color(0, 255, 0)
427
- self.set_text_color(0, 0, 0)
428
- self.cell(0, 8, f' {title}', 0, 1, 'L', 1)
429
- self.set_text_color(0, 0, 0)
430
- self.ln(2)
431
 
432
- def section_body(self, text):
433
- self.set_font('Arial', '', 10)
434
- self.set_text_color(0, 0, 0)
435
- self.multi_cell(0, 5, text)
436
- self.ln(2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
437
 
438
- def disease_section(self, disease_name, confidence, description):
439
- self.set_font('Arial', 'B', 12)
440
- self.set_text_color(0, 0, 0)
441
- self.cell(0, 7, f'• {disease_name}', 0, 1, 'L')
442
- self.set_font('Arial', 'I', 9)
443
- self.set_text_color(100, 100, 100)
444
- self.cell(0, 5, f' Confidence: {confidence:.1%}', 0, 1, 'L')
445
- self.set_font('Arial', '', 9)
446
- self.set_text_color(0, 0, 0)
447
- self.multi_cell(0, 4, description)
448
- self.ln(1)
449
-
450
- def generate_enhanced_pdf(patient_data, images_data, findings, report_text, disease_analyses):
451
- try:
452
- pdf = EnhancedMedicalPDF()
453
- pdf.add_page()
454
-
455
- # Patient Info
456
- pdf.section_title('PATIENT INFORMATION')
457
- pdf.section_body(f"""ID: {patient_data.get('id', 'N/A')} | Age: {patient_data.get('age', 'N/A')} | Gender: {patient_data.get('gender', 'N/A')}
458
- Scan Date: {patient_data.get('scan_date', 'N/A')}
459
- Report Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}""")
460
-
461
- # Quick Summary
462
- pdf.section_title('SUMMARY')
463
- num_findings = len(findings)
464
- summary_text = f"Total Detected Conditions: {num_findings}\n"
465
- if num_findings > 0:
466
- top_finding = max(findings, key=lambda x: x['confidence'])
467
- summary_text += f"Primary Finding: {top_finding['disease']} ({top_finding['confidence']:.1%})\n"
468
- summary_text += f"Average Confidence: {np.mean([f['confidence'] for f in findings]):.1%}"
469
- pdf.section_body(summary_text)
470
-
471
- # Images
472
- pdf.add_page()
473
- pdf.section_title('IMAGING ANALYSIS')
474
-
475
- img_configs = [
476
- ('original', 'Original X-Ray', 50),
477
- ('rl_enhanced', 'AI-Enhanced X-Ray', 100),
478
- ('detection', 'Detection Results', 150),
479
- ]
480
-
481
- for key, title, y_pos in img_configs:
482
- if key in images_data and os.path.exists(images_data[key]):
483
- pdf.set_font('Arial', 'B', 11)
484
- pdf.set_xy(10, y_pos)
485
- pdf.cell(0, 5, title, 0, 1)
486
- pdf.image(images_data[key], x=15, y=y_pos+5, w=180)
487
-
488
- # Heatmap & Ensemble
489
- pdf.add_page()
490
- if 'heatmap' in images_data and os.path.exists(images_data['heatmap']):
491
- pdf.section_title('CONFIDENCE HEATMAP')
492
- pdf.image(images_data['heatmap'], x=20, y=pdf.get_y()+5, w=170)
493
-
494
- pdf.ln(100)
495
- if 'ensemble' in images_data and os.path.exists(images_data['ensemble']):
496
- pdf.section_title('DISEASE CONFIDENCE ENSEMBLE')
497
- pdf.image(images_data['ensemble'], x=20, y=pdf.get_y()+5, w=170)
498
-
499
- # Detailed Findings
500
- pdf.add_page()
501
- pdf.section_title('DETAILED DISEASE ANALYSIS')
502
-
503
- for finding in findings:
504
- disease = finding['disease']
505
- confidence = finding['confidence']
506
- analysis = disease_analyses.get(disease, DISEASE_DESCRIPTIONS.get(disease, "No detailed analysis available."))
507
-
508
- # Truncate very long analyses
509
- if len(analysis) > 500:
510
- analysis = analysis[:500] + "..."
511
-
512
- pdf.disease_section(disease, confidence, analysis)
513
-
514
- # Clinical Report
515
- pdf.add_page()
516
- pdf.section_title('RADIOLOGIST AI INTERPRETATION')
517
- pdf.section_body(report_text[:3000]) # Limit length
518
-
519
- # Crops if available
520
- if 'crops' in images_data and images_data['crops']:
521
- pdf.add_page()
522
- pdf.section_title('DISEASE REGION CLOSE-UPS')
523
-
524
- for i, crop_path in enumerate(images_data['crops'][:4]): # Limit to 4
525
- if os.path.exists(crop_path):
526
- if i % 2 == 0:
527
- pdf.ln(5)
528
- y_pos = pdf.get_y()
529
- x_pos = 15 if i % 2 == 0 else 115
530
- pdf.image(crop_path, x=x_pos, y=y_pos, w=85)
531
-
532
- # Footer page
533
- pdf.add_page()
534
- pdf.set_font('Arial', 'B', 12)
535
- pdf.set_text_color(0, 255, 0)
536
- pdf.cell(0, 10, 'CLINICAL NOTES', 0, 1)
537
- pdf.set_font('Arial', '', 10)
538
- pdf.set_text_color(0, 0, 0)
539
- pdf.multi_cell(0, 5, """This report is generated by AI-assisted analysis of radiographic images.
540
-
541
- IMPORTANT DISCLAIMERS:
542
- • This analysis is intended to assist and not replace clinical judgment
543
- • All findings must be correlated with patient clinical presentation
544
- • Follow-up imaging may be recommended based on clinical context
545
- • Final interpretation by qualified radiologist is essential
546
- • AI confidence scores indicate model certainty, not diagnostic certainty
547
-
548
- Report generated by Super-Doctor V2 Medical AI System""")
549
-
550
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
551
- pdf_path = f"reports/medical_report_{timestamp}.pdf"
552
- pdf.output(pdf_path)
553
-
554
- return pdf_path
555
- except Exception as e:
556
- raise RuntimeError(f"PDF generation failed: {str(e)}")
557
 
558
  # --- ROUTES ---
 
559
  @app.route('/')
560
  def index():
561
  return render_template('landing.html')
562
 
563
- @app.route('/analyze', methods=['POST'])
564
- def analyze():
565
- try:
566
- if 'file' not in request.files or request.files['file'].filename == '':
567
- return jsonify({'success': False, 'error': 'No file uploaded'}), 400
568
-
569
- file = request.files['file']
570
- api_key = request.form.get('api_key', '')
571
- conf_threshold = float(request.form.get('conf_threshold', 0.20))
572
-
573
- patient_data = {
574
- 'id': request.form.get('patient_id', 'UNKNOWN'),
575
- 'age': request.form.get('age', 'N/A'),
576
- 'gender': request.form.get('gender', 'N/A'),
577
- 'scan_date': datetime.now().strftime("%Y-%m-%d")
578
- }
579
-
580
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
581
- file_path = os.path.join(app.config['UPLOAD_FOLDER'], f"{timestamp}_{file.filename}")
582
- file.save(file_path)
583
-
584
- # Process
585
- original_img = preprocess_image(file_path)
586
- img_stats = {'mean': np.mean(original_img), 'std': np.std(original_img)}
587
-
588
- llm_advice = get_llm_preprocessing_advice(original_img, api_key) if api_key else "Preprocessing optimization skipped"
589
- frames, actions = run_rl_with_llm_guidance(original_img, llm_advice)
590
- final_img = frames[-1]
591
-
592
- # Detection
593
- detector.eval()
594
- inp = torch.tensor(final_img).permute(2, 0, 1).float() / 255.0
595
- inp = inp.unsqueeze(0).to(DEVICE)
596
-
597
- with torch.no_grad():
598
- preds = detector(inp)[0]
599
-
600
- keep = preds['scores'] > conf_threshold
601
-
602
- if len(keep) > 0 and keep.sum() > 0:
603
- nms_idx = torchvision.ops.nms(preds['boxes'][keep], preds['scores'][keep], 0.2)
604
- boxes = preds['boxes'][keep][nms_idx].cpu().numpy()
605
- scores = preds['scores'][keep][nms_idx].cpu().numpy()
606
- labels = preds['labels'][keep][nms_idx].cpu().numpy()
607
-
608
- findings = [{'disease': CLASS_MAPPING.get(int(l), "Unknown"), 'confidence': float(s)}
609
- for l, s in zip(labels, scores)]
610
- findings = sorted(findings, key=lambda x: x['confidence'], reverse=True)
611
-
612
- top_disease = findings[0]['disease']
613
- rag_db.save_experience(top_disease, actions, scores[0])
614
- rag_context = rag_db.retrieve_context(top_disease)
615
- else:
616
- boxes, scores, labels = np.array([]), np.array([]), np.array([])
617
- findings = []
618
- rag_context = "No disease detected."
619
-
620
- # Output directory
621
- output_dir = f"outputs/{timestamp}"
622
- os.makedirs(output_dir, exist_ok=True)
623
-
624
- # Save images
625
- orig_path = f"{output_dir}/original.png"
626
- cv2.imwrite(orig_path, cv2.cvtColor(original_img, cv2.COLOR_RGB2BGR))
627
-
628
- rl_path = f"{output_dir}/rl_enhanced.png"
629
- cv2.imwrite(rl_path, cv2.cvtColor(final_img, cv2.COLOR_RGB2BGR))
630
-
631
- # Detection viz
632
- detect_fig, ax = plt.subplots(figsize=(10, 10), facecolor='#1a1a1a')
633
- ax.set_facecolor('#1a1a1a')
634
- ax.imshow(final_img)
635
-
636
- if len(boxes) > 0:
637
- colors = plt.cm.turbo(np.linspace(0, 1, 15))
638
- for box, lbl, sc in zip(boxes, labels, scores):
639
- c = colors[int(lbl)]
640
- rect = patches.Rectangle((box[0], box[1]), box[2]-box[0], box[3]-box[1],
641
- linewidth=3, edgecolor=c, facecolor='none')
642
- ax.add_patch(rect)
643
- ax.text(box[0], box[1]-10, f"{CLASS_MAPPING.get(int(lbl))} {sc:.2f}",
644
- color='white', fontsize=10, bbox=dict(facecolor=c, alpha=0.8))
645
-
646
- ax.axis('off')
647
- detect_path = f"{output_dir}/detection.png"
648
- plt.savefig(detect_path, bbox_inches='tight', dpi=150, facecolor='#1a1a1a')
649
- plt.close()
650
-
651
- # Heatmap
652
- heatmap_img = create_heatmap(final_img, boxes, scores)
653
- heatmap_path = f"{output_dir}/heatmap.png"
654
- cv2.imwrite(heatmap_path, cv2.cvtColor(heatmap_img, cv2.COLOR_RGB2BGR))
655
-
656
- # Ensemble plot
657
- ensemble_path = f"{output_dir}/ensemble.png"
658
- create_ensemble_boxplot(findings, ensemble_path)
659
-
660
- # Crops
661
- crop_paths = []
662
- if len(boxes) > 0:
663
- crops = crop_detections(final_img, boxes, labels, scores)
664
- for i, crop_data in enumerate(crops):
665
- crop_path = f"{output_dir}/crop_{i}_{crop_data['disease'].replace('/', '_')}.png"
666
- cv2.imwrite(crop_path, cv2.cvtColor(crop_data['image'], cv2.COLOR_RGB2BGR))
667
- crop_paths.append(crop_path)
668
-
669
- # Get detailed disease analyses
670
- disease_analyses = {}
671
- for finding in findings:
672
- disease_name = finding['disease']
673
- confidence = finding['confidence']
674
- analysis = get_enhanced_disease_analysis(disease_name, confidence, img_stats, api_key)
675
- disease_analyses[disease_name] = analysis
676
-
677
- # Comprehensive report
678
- report_text = get_comprehensive_report(findings, actions, rag_context, llm_advice, api_key)
679
-
680
- # PDF
681
- images_data = {
682
- 'original': orig_path,
683
- 'rl_enhanced': rl_path,
684
- 'detection': detect_path,
685
- 'heatmap': heatmap_path,
686
- 'ensemble': ensemble_path,
687
- 'crops': crop_paths,
688
- 'actions': " → ".join(actions)
689
- }
690
-
691
- pdf_path = generate_enhanced_pdf(patient_data, images_data, findings, report_text, disease_analyses)
692
-
693
- return jsonify({
694
- 'success': True,
695
- 'findings': findings,
696
- 'report': report_text,
697
- 'disease_analyses': disease_analyses,
698
- 'llm_advice': llm_advice,
699
- 'actions': actions,
700
- 'rag_context': rag_context,
701
- 'pdf_download': f"/download/{os.path.basename(pdf_path)}",
702
- 'images': {
703
- 'original': f"/{orig_path}",
704
- 'rl_enhanced': f"/{rl_path}",
705
- 'detection': f"/{detect_path}",
706
- 'heatmap': f"/{heatmap_path}",
707
- 'ensemble': f"/{ensemble_path}",
708
- 'crops': [f"/{cp}" for cp in crop_paths]
709
- }
710
- })
711
-
712
- except Exception as e:
713
- raise
714
 
715
- @app.route('/download/<filename>')
716
- def download_report(filename):
717
- try:
718
- return send_file(f"reports/{filename}", as_attachment=True)
719
- except:
720
- return jsonify({'success': False, 'error': 'File not found'}), 404
 
 
721
 
722
- @app.route('/outputs/<path:filename>')
723
- @app.route('/uploads/<path:filename>')
724
- def serve_image(filename):
725
- try:
726
- directory = 'outputs' if 'outputs' in request.path else 'uploads'
727
- return send_file(f"{directory}/{filename}")
728
- except:
729
- return jsonify({'success': False, 'error': 'File not found'}), 404
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
730
 
731
- def get_llm_preprocessing_advice(img_np, api_key):
732
- if not api_key:
733
- return "Preprocessing analysis skipped"
734
- try:
735
- mean_intensity = np.mean(img_np)
736
- std_intensity = np.std(img_np)
737
-
738
- client = Groq(api_key=api_key)
739
- prompt = f"""Analyze chest X-ray quality (mean: {mean_intensity:.1f}, std: {std_intensity:.1f}).
740
- Recommend ONE preprocessing action: Increase/Decrease Brightness or Contrast. Max 2 sentences."""
741
 
742
- resp = client.chat.completions.create(
743
- messages=[{"role": "user", "content": prompt}],
744
- model="llama-3.3-70b-versatile",
745
- temperature=0.3,
746
- max_tokens=100
747
- )
748
- return resp.choices[0].message.content
749
- except Exception as e:
750
- return f"LLM advice unavailable: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
751
 
752
  if __name__ == '__main__':
753
- print("=" * 60)
754
- print("🏥 SUPER-DOCTOR V2 - Enhanced Medical AI")
755
- print(f"📍 Device: {DEVICE}")
756
- print("=" * 60)
757
- app.run(debug=True, host='0.0.0.0', port=5000)
 
1
+ import os
2
+ import cv2
3
  import torch
4
  import numpy as np
 
 
 
5
  import pydicom
6
+ import json
7
+ import traceback
8
  import matplotlib
9
+ # Set backend to Agg before importing pyplot to prevent GUI errors
10
  matplotlib.use('Agg')
11
  import matplotlib.pyplot as plt
12
  import matplotlib.patches as patches
 
17
  from stable_baselines3 import PPO
18
  import gymnasium as gym
19
  from gymnasium import spaces
20
+ from PIL import Image
21
  from fpdf import FPDF
22
  from datetime import datetime
 
23
  from werkzeug.exceptions import HTTPException
24
+ from pydicom.pixel_data_handlers.util import apply_voi_lut
25
+ # Ensure seaborn is installed in requirements.txt
26
+ import seaborn as sns
27
+ from flask import Flask, render_template, request, send_file, jsonify
28
+ from dotenv import load_dotenv
29
+
30
+ load_dotenv()
31
 
32
  app = Flask(__name__)
33
+
34
+ # --- PATH CONFIGURATION (LINUX/DOCKER FRIENDLY) ---
35
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
36
+ app.config['UPLOAD_FOLDER'] = os.path.join(BASE_DIR, 'uploads')
37
+ app.config['OUTPUT_FOLDER'] = os.path.join(BASE_DIR, 'outputs')
38
+ app.config['REPORT_FOLDER'] = os.path.join(BASE_DIR, 'reports')
39
  app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
40
 
41
+ # Create directories with proper permissions
42
+ for folder in [app.config['UPLOAD_FOLDER'], app.config['OUTPUT_FOLDER'], app.config['REPORT_FOLDER']]:
43
+ os.makedirs(folder, exist_ok=True)
 
44
 
45
+ # Correct Relative Paths
46
+ MODEL_PATH = os.path.join(BASE_DIR, "models", "judge_model_epoch5.pth")
47
+ RL_AGENT_PATH = os.path.join(BASE_DIR, "strict_rl_agent")
48
+ MEMORY_FILE = os.path.join(BASE_DIR, "medical_memory.json")
 
49
 
50
+ # API Key (Load from Env for security, fallback to None)
51
+ DEFAULT_GROQ_KEY = os.getenv("GROQ_API_KEY")
 
 
 
 
 
52
 
 
53
  DEVICE = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
 
 
 
54
 
55
  CLASS_MAPPING = {
56
  1: 'Aortic enlargement', 2: 'Atelectasis', 3: 'Calcification', 4: 'Cardiomegaly',
 
76
  'Pulmonary fibrosis': 'Progressive lung scarring reducing elasticity. Serious condition with various causes.'
77
  }
78
 
79
+ # --- ERROR HANDLERS ---
80
+ @app.errorhandler(Exception)
81
+ def handle_generic_exception(e):
82
+ error_trace = traceback.format_exc()
83
+ print(f"ERROR: {error_trace}")
84
+ return jsonify({"success": False, "error": str(e), "message": "Internal Server Error"}), 500
85
+
86
  # --- RAG MEMORY ---
87
  class RAGMemory:
88
  def __init__(self, filepath):
 
99
  "confidence": float(confidence),
100
  "timestamp": datetime.now().isoformat()
101
  }
102
+ # Read existing
103
+ data = []
104
+ if os.path.exists(self.filepath):
105
  try:
106
+ with open(self.filepath, 'r') as f:
107
+ data = json.load(f)
108
+ except: pass
109
+
110
+ data.append(new_entry)
111
+
112
+ # Write back
113
+ with open(self.filepath, 'w') as f:
114
  json.dump(data, f, indent=2)
115
  except Exception as e:
116
  print(f"RAG save error: {e}")
 
122
  except:
123
  return "Memory Empty."
124
 
125
+ relevant = [d for d in data if d.get('disease') == suspected_disease and d.get('confidence', 0) > 0.5]
126
 
127
  if not relevant:
128
  return "No prior memory of this condition."
129
 
130
+ # Simple strategy aggregation
131
  action_counts = {}
132
  for r in relevant:
133
+ action_str = ", ".join(r.get('actions', []))
134
  action_counts[action_str] = action_counts.get(action_str, 0) + 1
135
 
136
  if action_counts:
137
  best_strategy = max(action_counts, key=action_counts.get)
138
+ return f"In {len(relevant)} past cases of {suspected_disease}, the most frequent strategy was: [{best_strategy}]"
139
  return "No clear strategy found."
140
 
141
  rag_db = RAGMemory(MEMORY_FILE)
 
148
 
149
  def load_models():
150
  try:
151
+ print("Loading Detector...")
152
+ detector = fasterrcnn_resnet50_fpn(weights=None)
153
  in_features = detector.roi_heads.box_predictor.cls_score.in_features
154
  detector.roi_heads.box_predictor = FastRCNNPredictor(in_features, 15)
155
 
156
  if os.path.exists(MODEL_PATH):
157
  detector.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
158
+ print(f"✓ Detector weights loaded from {MODEL_PATH}")
159
+ else:
160
+ print(f"⚠️ Detector weights NOT found at {MODEL_PATH}")
161
+
162
+ detector.to(DEVICE)
163
+ detector.eval()
164
 
165
+ print("Loading RL Agent...")
166
  agent = None
167
+ # Check for both path and path.zip
168
+ if os.path.exists(RL_AGENT_PATH + ".zip") or os.path.exists(RL_AGENT_PATH):
169
+ try:
170
+ agent = PPO.load(RL_AGENT_PATH, env=DummyEnv(), device=DEVICE)
171
+ print(f"✓ RL Agent loaded")
172
+ except Exception as e:
173
+ print(f"⚠️ RL Agent load error: {e}")
174
+ else:
175
+ print(f"⚠️ RL Agent not found at {RL_AGENT_PATH}")
176
 
177
  return detector, agent
178
  except Exception as e:
179
+ print(f"❌ Critical Model loading error: {e}")
180
  raise
181
 
182
  detector, agent = load_models()
183
 
184
+ # --- HELPER FUNCTIONS ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  def preprocess_image(file_path):
187
  try:
188
+ if file_path.lower().endswith(('.dcm', '.dicom')):
189
  dcm = pydicom.dcmread(file_path)
190
+ try: img = apply_voi_lut(dcm.pixel_array, dcm)
191
+ except: img = dcm.pixel_array
 
 
192
  if dcm.PhotometricInterpretation == "MONOCHROME1":
193
  img = np.amax(img) - img
194
  img = img - np.min(img)
 
203
  except Exception as e:
204
  raise ValueError(f"Image preprocessing failed: {str(e)}")
205
 
206
+ def encode_img_b64(img_np):
207
+ _, buffer = cv2.imencode('.jpg', cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR))
208
+ return base64.b64encode(buffer).decode('utf-8')
209
+
210
+ # --- LLM FUNCTIONS ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
 
212
+ def get_groq_client(user_key=None):
213
+ api_key = user_key if user_key else DEFAULT_GROQ_KEY
214
+ if not api_key:
215
+ return None
216
+ return Groq(api_key=api_key)
217
+
218
+ def get_enhanced_disease_analysis(disease_name, confidence, image_stats, api_key):
219
+ client = get_groq_client(api_key)
220
+ if not client:
221
+ return DISEASE_DESCRIPTIONS.get(disease_name, "Analysis requires API Key.")
222
+
223
  try:
224
+ prompt = f"""You are an expert radiologist. Provide detailed clinical analysis for:
225
+ **Disease:** {disease_name}
226
+ **AI Confidence:** {confidence:.1%}
227
+ **Image Statistics:** Mean: {image_stats['mean']:.1f}, Std: {image_stats['std']:.1f}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
228
 
229
+ Format:
230
+ 1. Definition
231
+ 2. Clinical Significance
232
+ 3. Recommended Follow-up
233
+ Keep it concise."""
234
 
235
+ resp = client.chat.completions.create(
236
+ messages=[{"role": "user", "content": prompt}],
237
+ model="llama-3.3-70b-versatile",
238
+ max_tokens=400
239
+ )
240
+ return resp.choices[0].message.content
241
  except Exception as e:
242
+ return f"LLM Error: {e}"
 
243
 
244
+ def get_comprehensive_report(findings, actions, rag_context, llm_advice, api_key):
245
+ client = get_groq_client(api_key)
246
+ if not client:
247
+ return "Comprehensive report requires API Key."
248
+
249
  try:
250
+ findings_str = "\n".join([f"- {f['disease']}: {f['confidence']:.1%}" for f in findings])
251
+ prompt = f"""Role: Senior Radiologist.
252
+ Context:
253
+ - Findings: {findings_str}
254
+ - AI Actions taken: {" -> ".join(actions)}
255
+ - History: {rag_context}
 
256
 
257
+ Write a formal medical report including Impression, Findings, and Recommendations. Do not mention AI or RL internals."""
 
258
 
259
+ resp = client.chat.completions.create(
260
+ messages=[{"role": "user", "content": prompt}],
261
+ model="llama-3.3-70b-versatile",
262
+ max_tokens=1000
263
+ )
264
+ return resp.choices[0].message.content
265
  except Exception as e:
266
+ return f"Report Error: {e}"
 
267
 
268
+ # --- RL & PLOTTING ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
269
 
270
+ def run_rl_with_llm_guidance(img_np, llm_advice):
271
+ if agent is None:
272
+ return [img_np], ["RL Unavailable"]
 
 
 
 
 
 
 
 
 
 
 
 
 
273
 
274
+ current = img_np.copy()
275
+ frames = [current.copy()]
276
+ actions_log = []
 
 
277
 
278
+ # Parse simple advice logic
279
+ llm_hint = -1
280
+ advice_lower = str(llm_advice).lower()
281
+ if "bright" in advice_lower and "increase" in advice_lower: llm_hint = 0
282
+ elif "bright" in advice_lower and "decrease" in advice_lower: llm_hint = 1
283
+ elif "contrast" in advice_lower and "increase" in advice_lower: llm_hint = 2
284
+ elif "contrast" in advice_lower and "decrease" in advice_lower: llm_hint = 3
285
 
286
+ for step in range(5):
287
+ if step == 0 and llm_hint >= 0:
288
+ action = llm_hint
289
+ else:
290
+ action, _ = agent.predict(current)
291
+
292
+ if action == 0:
293
+ current = np.clip(current + 15, 0, 255).astype(np.uint8)
294
+ actions_log.append("Bright+")
295
+ elif action == 1:
296
+ current = np.clip(current - 15, 0, 255).astype(np.uint8)
297
+ actions_log.append("Bright-")
298
+ elif action == 2:
299
+ current = np.clip((current - 127.5)*1.2 + 127.5, 0, 255).astype(np.uint8)
300
+ actions_log.append("Cont+")
301
+ elif action == 3:
302
+ current = np.clip((current - 127.5)*0.8 + 127.5, 0, 255).astype(np.uint8)
303
+ actions_log.append("Cont-")
304
+ elif action == 4:
305
+ actions_log.append("Submit")
306
+ frames.append(current.copy())
307
+ break
308
+
309
+ frames.append(current.copy())
310
+
311
+ return frames, actions_log
312
+
313
+ def create_heatmap(img_np, boxes, scores):
314
+ heatmap = np.zeros((512, 512), dtype=np.float32)
315
+ for box, score in zip(boxes, scores):
316
+ x1, y1, x2, y2 = map(int, box)
317
+ heatmap[max(0, y1):min(512, y2), max(0, x1):min(512, x2)] += score
318
 
319
+ if heatmap.max() > 0: heatmap /= heatmap.max()
320
+ heatmap_colored = cv2.applyColorMap((heatmap * 255).astype(np.uint8), cv2.COLORMAP_JET)
321
+ heatmap_colored = cv2.cvtColor(heatmap_colored, cv2.COLOR_BGR2RGB)
322
+ return cv2.addWeighted(img_np, 0.6, heatmap_colored, 0.4, 0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
323
 
324
  # --- ROUTES ---
325
+
326
  @app.route('/')
327
  def index():
328
  return render_template('landing.html')
329
 
330
+ @app.route('/app')
331
+ def dashboard():
332
+ return render_template('dashboard.html')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
333
 
334
+ @app.route('/process', methods=['POST'])
335
+ def process():
336
+ if 'file' not in request.files:
337
+ return jsonify({'success': False, 'error': 'No file'}), 400
338
+
339
+ file = request.files['file']
340
+ if file.filename == '':
341
+ return jsonify({'success': False, 'error': 'No filename'}), 400
342
 
343
+ api_key = request.form.get('api_key') or DEFAULT_GROQ_KEY
344
+ threshold = float(request.form.get('threshold', 0.2))
345
+
346
+ # Save Upload
347
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
348
+ filename = f"{timestamp}_{file.filename}"
349
+ file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
350
+ file.save(file_path)
351
+
352
+ # Preprocess
353
+ original_img = preprocess_image(file_path)
354
+ import base64
355
+ def b64(img):
356
+ _, buf = cv2.imencode('.jpg', cv2.cvtColor(img, cv2.COLOR_RGB2BGR))
357
+ return base64.b64encode(buf).decode('utf-8')
358
+
359
+ # LLM Advice (Simulated or Real)
360
+ llm_advice = "Preprocessing skipped"
361
+ if api_key:
362
+ # Simple advice prompt could go here
363
+ llm_advice = "AI analysis running..."
364
+
365
+ # Run RL
366
+ frames, actions = run_rl_with_llm_guidance(original_img, llm_advice)
367
+ final_img = frames[-1]
368
+
369
+ # Run Detector
370
+ inp = torch.tensor(final_img).permute(2, 0, 1).float() / 255.0
371
+ inp = inp.unsqueeze(0).to(DEVICE)
372
+
373
+ with torch.no_grad():
374
+ preds = detector(inp)[0]
375
+
376
+ keep = preds['scores'] > threshold
377
+ if keep.sum() > 0:
378
+ nms_idx = torchvision.ops.nms(preds['boxes'][keep], preds['scores'][keep], 0.2)
379
+ boxes = preds['boxes'][keep][nms_idx].cpu().numpy()
380
+ scores = preds['scores'][keep][nms_idx].cpu().numpy()
381
+ labels = preds['labels'][keep][nms_idx].cpu().numpy()
382
+
383
+ findings = [{'disease': CLASS_MAPPING.get(int(l), "Unknown"), 'confidence': float(s)}
384
+ for l, s in zip(labels, scores)]
385
+
386
+ # Save to RAG
387
+ if len(findings) > 0:
388
+ rag_db.save_experience(findings[0]['disease'], actions, float(scores[0]))
389
+ rag_context = rag_db.retrieve_context(findings[0]['disease'])
390
+ else:
391
+ rag_context = "No significant findings."
392
+ else:
393
+ boxes, scores, labels, findings = [], [], [], []
394
+ rag_context = "No findings."
395
 
396
+ # Generate Visuals
397
+ heatmap = create_heatmap(final_img, boxes, scores)
398
+
399
+ # Annotate Final
400
+ annotated = final_img.copy()
401
+ crops = []
402
+ for box, lbl, sc in zip(boxes, labels, scores):
403
+ x1, y1, x2, y2 = map(int, box)
404
+ cv2.rectangle(annotated, (x1, y1), (x2, y2), (255, 0, 0), 2)
405
+ cv2.putText(annotated, f"{CLASS_MAPPING.get(int(lbl))} {sc:.2f}", (x1, y1-5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 1)
406
 
407
+ # Crops
408
+ pad = 20
409
+ c = final_img[max(0, y1-pad):min(512, y2+pad), max(0, x1-pad):min(512, x2+pad)]
410
+ if c.size > 0:
411
+ crops.append({'name': CLASS_MAPPING.get(int(lbl)), 'img': b64(c)})
412
+
413
+ # Generate Report
414
+ report = get_comprehensive_report(findings, actions, rag_context, llm_advice, api_key)
415
+
416
+ # Disease Analysis
417
+ disease_analyses = {}
418
+ for f in findings:
419
+ d_name = f['disease']
420
+ if d_name not in disease_analyses:
421
+ img_stats = {'mean': np.mean(final_img), 'std': np.std(final_img)}
422
+ disease_analyses[d_name] = get_enhanced_disease_analysis(d_name, f['confidence'], img_stats, api_key)
423
+
424
+ return jsonify({
425
+ "frames": [b64(f) for f in frames],
426
+ "actions": actions,
427
+ "llm_advice": llm_advice,
428
+ "final_result": b64(annotated),
429
+ "heatmap": b64(heatmap),
430
+ "crops": crops,
431
+ "report": report,
432
+ "disease_analyses": disease_analyses,
433
+ "rag_context": rag_context
434
+ })
435
+
436
+ # Add route for PDF download if needed (requires implementation of PDF generation function)
437
+ @app.route('/download_pdf')
438
+ def download_pdf():
439
+ return "PDF Download Not Configured in this version", 404
440
 
441
  if __name__ == '__main__':
442
+ app.run(debug=True, host='0.0.0.0', port=7860)