Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,7 +2,6 @@ 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
|
|
@@ -26,6 +25,8 @@ from pydicom.pixel_data_handlers.util import apply_voi_lut
|
|
| 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 |
|
|
@@ -265,6 +266,27 @@ def get_comprehensive_report(findings, actions, rag_context, llm_advice, api_key
|
|
| 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):
|
|
@@ -321,6 +343,217 @@ def create_heatmap(img_np, boxes, scores):
|
|
| 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('/')
|
|
@@ -341,8 +574,7 @@ def process():
|
|
| 341 |
return jsonify({'success': False, 'error': 'No filename'}), 400
|
| 342 |
|
| 343 |
api_key = request.form.get('api_key') or DEFAULT_GROQ_KEY
|
| 344 |
-
|
| 345 |
-
threshold = float(request.form.get('threshold', 0.4))
|
| 346 |
|
| 347 |
# Save Upload
|
| 348 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
@@ -352,16 +584,10 @@ def process():
|
|
| 352 |
|
| 353 |
# Preprocess
|
| 354 |
original_img = preprocess_image(file_path)
|
| 355 |
-
|
| 356 |
-
def b64(img):
|
| 357 |
-
_, buf = cv2.imencode('.jpg', cv2.cvtColor(img, cv2.COLOR_RGB2BGR))
|
| 358 |
-
return base64.b64encode(buf).decode('utf-8')
|
| 359 |
|
| 360 |
-
# LLM Advice
|
| 361 |
-
llm_advice = "Preprocessing skipped"
|
| 362 |
-
if api_key:
|
| 363 |
-
# Simple advice prompt could go here
|
| 364 |
-
llm_advice = "AI analysis running..."
|
| 365 |
|
| 366 |
# Run RL
|
| 367 |
frames, actions = run_rl_with_llm_guidance(original_img, llm_advice)
|
|
@@ -375,6 +601,12 @@ def process():
|
|
| 375 |
preds = detector(inp)[0]
|
| 376 |
|
| 377 |
keep = preds['scores'] > threshold
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 378 |
if keep.sum() > 0:
|
| 379 |
nms_idx = torchvision.ops.nms(preds['boxes'][keep], preds['scores'][keep], 0.2)
|
| 380 |
boxes = preds['boxes'][keep][nms_idx].cpu().numpy()
|
|
@@ -383,61 +615,115 @@ def process():
|
|
| 383 |
|
| 384 |
findings = [{'disease': CLASS_MAPPING.get(int(l), "Unknown"), 'confidence': float(s)}
|
| 385 |
for l, s in zip(labels, scores)]
|
|
|
|
| 386 |
|
| 387 |
-
# Save to RAG
|
| 388 |
if len(findings) > 0:
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
rag_context = "No significant findings."
|
| 393 |
-
else:
|
| 394 |
-
boxes, scores, labels, findings = [], [], [], []
|
| 395 |
-
rag_context = "No findings."
|
| 396 |
|
| 397 |
-
#
|
| 398 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 399 |
|
| 400 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 401 |
annotated = final_img.copy()
|
| 402 |
-
crops = []
|
| 403 |
for box, lbl, sc in zip(boxes, labels, scores):
|
| 404 |
x1, y1, x2, y2 = map(int, box)
|
| 405 |
cv2.rectangle(annotated, (x1, y1), (x2, y2), (255, 0, 0), 2)
|
| 406 |
cv2.putText(annotated, f"{CLASS_MAPPING.get(int(lbl))} {sc:.2f}", (x1, y1-5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 1)
|
| 407 |
-
|
| 408 |
-
# Crops
|
| 409 |
-
pad = 20
|
| 410 |
-
c = final_img[max(0, y1-pad):min(512, y2+pad), max(0, x1-pad):min(512, x2+pad)]
|
| 411 |
-
if c.size > 0:
|
| 412 |
-
crops.append({'name': CLASS_MAPPING.get(int(lbl)), 'img': b64(c)})
|
| 413 |
-
|
| 414 |
-
# Generate Report
|
| 415 |
-
report = get_comprehensive_report(findings, actions, rag_context, llm_advice, api_key)
|
| 416 |
|
| 417 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 418 |
disease_analyses = {}
|
| 419 |
for f in findings:
|
| 420 |
d_name = f['disease']
|
| 421 |
if d_name not in disease_analyses:
|
| 422 |
-
img_stats = {'mean': np.mean(final_img), 'std': np.std(final_img)}
|
| 423 |
disease_analyses[d_name] = get_enhanced_disease_analysis(d_name, f['confidence'], img_stats, api_key)
|
| 424 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 425 |
return jsonify({
|
| 426 |
-
"frames": [
|
| 427 |
"actions": actions,
|
| 428 |
"llm_advice": llm_advice,
|
| 429 |
-
"final_result":
|
| 430 |
-
"heatmap":
|
| 431 |
-
"crops":
|
| 432 |
"report": report,
|
| 433 |
"disease_analyses": disease_analyses,
|
| 434 |
-
"rag_context": rag_context
|
|
|
|
|
|
|
|
|
|
| 435 |
})
|
| 436 |
|
| 437 |
# Add route for PDF download if needed (requires implementation of PDF generation function)
|
| 438 |
@app.route('/download_pdf')
|
| 439 |
def download_pdf():
|
| 440 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 441 |
|
| 442 |
if __name__ == '__main__':
|
| 443 |
app.run(debug=True, host='0.0.0.0', port=7860)
|
|
|
|
| 2 |
import cv2
|
| 3 |
import torch
|
| 4 |
import numpy as np
|
|
|
|
| 5 |
import json
|
| 6 |
import traceback
|
| 7 |
import matplotlib
|
|
|
|
| 25 |
import seaborn as sns
|
| 26 |
from flask import Flask, render_template, request, send_file, jsonify
|
| 27 |
from dotenv import load_dotenv
|
| 28 |
+
import base64
|
| 29 |
+
import pydicom
|
| 30 |
|
| 31 |
load_dotenv()
|
| 32 |
|
|
|
|
| 266 |
except Exception as e:
|
| 267 |
return f"Report Error: {e}"
|
| 268 |
|
| 269 |
+
def get_llm_preprocessing_advice(img_np, api_key):
|
| 270 |
+
if not api_key:
|
| 271 |
+
return "Preprocessing analysis skipped"
|
| 272 |
+
try:
|
| 273 |
+
mean_intensity = np.mean(img_np)
|
| 274 |
+
std_intensity = np.std(img_np)
|
| 275 |
+
|
| 276 |
+
client = Groq(api_key=api_key)
|
| 277 |
+
prompt = f"""Analyze chest X-ray quality (mean: {mean_intensity:.1f}, std: {std_intensity:.1f}).
|
| 278 |
+
Recommend ONE preprocessing action: Increase/Decrease Brightness or Contrast. Max 2 sentences."""
|
| 279 |
+
|
| 280 |
+
resp = client.chat.completions.create(
|
| 281 |
+
messages=[{"role": "user", "content": prompt}],
|
| 282 |
+
model="llama-3.3-70b-versatile",
|
| 283 |
+
temperature=0.3,
|
| 284 |
+
max_tokens=100
|
| 285 |
+
)
|
| 286 |
+
return resp.choices[0].message.content
|
| 287 |
+
except Exception as e:
|
| 288 |
+
return f"LLM advice unavailable: {str(e)}"
|
| 289 |
+
|
| 290 |
# --- RL & PLOTTING ---
|
| 291 |
|
| 292 |
def run_rl_with_llm_guidance(img_np, llm_advice):
|
|
|
|
| 343 |
heatmap_colored = cv2.cvtColor(heatmap_colored, cv2.COLOR_BGR2RGB)
|
| 344 |
return cv2.addWeighted(img_np, 0.6, heatmap_colored, 0.4, 0)
|
| 345 |
|
| 346 |
+
def create_ensemble_boxplot(findings, output_path):
|
| 347 |
+
try:
|
| 348 |
+
fig, ax = plt.subplots(figsize=(12, 6))
|
| 349 |
+
fig.patch.set_facecolor('#1a1a1a')
|
| 350 |
+
ax.set_facecolor('#2a2a2a')
|
| 351 |
+
|
| 352 |
+
diseases = [f['disease'][:15] for f in findings]
|
| 353 |
+
confidences = [f['confidence'] * 100 for f in findings]
|
| 354 |
+
|
| 355 |
+
colors = plt.cm.RdYlGn(np.array(confidences) / 100)
|
| 356 |
+
bars = ax.barh(diseases, confidences, color=colors, edgecolor='#00ff00', linewidth=2)
|
| 357 |
+
|
| 358 |
+
for i, (bar, conf) in enumerate(zip(bars, confidences)):
|
| 359 |
+
ax.text(conf + 1, i, f'{conf:.1f}%', va='center', color='#00ff00', fontweight='bold')
|
| 360 |
+
|
| 361 |
+
ax.set_xlabel('Confidence (%)', color='#00ff00', fontsize=12, fontweight='bold')
|
| 362 |
+
ax.set_title('Disease Confidence Ensemble', color='#00ff00', fontsize=14, fontweight='bold')
|
| 363 |
+
ax.set_xlim(0, 105)
|
| 364 |
+
ax.tick_params(colors='#00ff00')
|
| 365 |
+
|
| 366 |
+
for spine in ax.spines.values():
|
| 367 |
+
spine.set_color('#00ff00')
|
| 368 |
+
spine.set_linewidth(2)
|
| 369 |
+
|
| 370 |
+
ax.grid(axis='x', alpha=0.2, color='#00ff00')
|
| 371 |
+
|
| 372 |
+
plt.tight_layout()
|
| 373 |
+
plt.savefig(output_path, dpi=150, bbox_inches='tight', facecolor='#1a1a1a')
|
| 374 |
+
plt.close()
|
| 375 |
+
return True
|
| 376 |
+
except Exception as e:
|
| 377 |
+
print(f"Ensemble plot error: {e}")
|
| 378 |
+
return False
|
| 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 |
+
if len(analysis) > 500:
|
| 509 |
+
analysis = analysis[:500] + "..."
|
| 510 |
+
|
| 511 |
+
pdf.disease_section(disease, confidence, analysis)
|
| 512 |
+
|
| 513 |
+
# Clinical Report
|
| 514 |
+
pdf.add_page()
|
| 515 |
+
pdf.section_title('RADIOLOGIST AI INTERPRETATION')
|
| 516 |
+
pdf.section_body(report_text[:3000])
|
| 517 |
+
|
| 518 |
+
# Crops if available
|
| 519 |
+
if 'crops' in images_data and images_data['crops']:
|
| 520 |
+
pdf.add_page()
|
| 521 |
+
pdf.section_title('DISEASE REGION CLOSE-UPS')
|
| 522 |
+
|
| 523 |
+
for i, crop_path in enumerate(images_data['crops'][:4]):
|
| 524 |
+
if os.path.exists(crop_path):
|
| 525 |
+
if i % 2 == 0:
|
| 526 |
+
pdf.ln(5)
|
| 527 |
+
y_pos = pdf.get_y()
|
| 528 |
+
x_pos = 15 if i % 2 == 0 else 115
|
| 529 |
+
pdf.image(crop_path, x=x_pos, y=y_pos, w=85)
|
| 530 |
+
|
| 531 |
+
# Footer page
|
| 532 |
+
pdf.add_page()
|
| 533 |
+
pdf.set_font('Arial', 'B', 12)
|
| 534 |
+
pdf.set_text_color(0, 255, 0)
|
| 535 |
+
pdf.cell(0, 10, 'CLINICAL NOTES', 0, 1)
|
| 536 |
+
pdf.set_font('Arial', '', 10)
|
| 537 |
+
pdf.set_text_color(0, 0, 0)
|
| 538 |
+
pdf.multi_cell(0, 5, """This report is generated by AI-assisted analysis of radiographic images.
|
| 539 |
+
|
| 540 |
+
IMPORTANT DISCLAIMERS:
|
| 541 |
+
• This analysis is intended to assist and not replace clinical judgment
|
| 542 |
+
• All findings must be correlated with patient clinical presentation
|
| 543 |
+
• Follow-up imaging may be recommended based on clinical context
|
| 544 |
+
• Final interpretation by qualified radiologist is essential
|
| 545 |
+
• AI confidence scores indicate model certainty, not diagnostic certainty
|
| 546 |
+
|
| 547 |
+
Report generated by Super-Doctor V2 Medical AI System""")
|
| 548 |
+
|
| 549 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 550 |
+
pdf_path = os.path.join(app.config['REPORT_FOLDER'], f"medical_report_{timestamp}.pdf")
|
| 551 |
+
pdf.output(pdf_path)
|
| 552 |
+
|
| 553 |
+
return pdf_path
|
| 554 |
+
except Exception as e:
|
| 555 |
+
raise RuntimeError(f"PDF generation failed: {str(e)}")
|
| 556 |
+
|
| 557 |
# --- ROUTES ---
|
| 558 |
|
| 559 |
@app.route('/')
|
|
|
|
| 574 |
return jsonify({'success': False, 'error': 'No filename'}), 400
|
| 575 |
|
| 576 |
api_key = request.form.get('api_key') or DEFAULT_GROQ_KEY
|
| 577 |
+
threshold = float(request.form.get('threshold', 0.2))
|
|
|
|
| 578 |
|
| 579 |
# Save Upload
|
| 580 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
|
|
| 584 |
|
| 585 |
# Preprocess
|
| 586 |
original_img = preprocess_image(file_path)
|
| 587 |
+
img_stats = {'mean': np.mean(original_img), 'std': np.std(original_img)}
|
|
|
|
|
|
|
|
|
|
| 588 |
|
| 589 |
+
# LLM Advice
|
| 590 |
+
llm_advice = get_llm_preprocessing_advice(original_img, api_key) if api_key else "Preprocessing optimization skipped"
|
|
|
|
|
|
|
|
|
|
| 591 |
|
| 592 |
# Run RL
|
| 593 |
frames, actions = run_rl_with_llm_guidance(original_img, llm_advice)
|
|
|
|
| 601 |
preds = detector(inp)[0]
|
| 602 |
|
| 603 |
keep = preds['scores'] > threshold
|
| 604 |
+
|
| 605 |
+
# Initialize results
|
| 606 |
+
boxes, scores, labels = [], [], []
|
| 607 |
+
findings = []
|
| 608 |
+
rag_context = "No significant findings."
|
| 609 |
+
|
| 610 |
if keep.sum() > 0:
|
| 611 |
nms_idx = torchvision.ops.nms(preds['boxes'][keep], preds['scores'][keep], 0.2)
|
| 612 |
boxes = preds['boxes'][keep][nms_idx].cpu().numpy()
|
|
|
|
| 615 |
|
| 616 |
findings = [{'disease': CLASS_MAPPING.get(int(l), "Unknown"), 'confidence': float(s)}
|
| 617 |
for l, s in zip(labels, scores)]
|
| 618 |
+
findings = sorted(findings, key=lambda x: x['confidence'], reverse=True)
|
| 619 |
|
|
|
|
| 620 |
if len(findings) > 0:
|
| 621 |
+
top_disease = findings[0]['disease']
|
| 622 |
+
rag_db.save_experience(top_disease, actions, float(scores[0]))
|
| 623 |
+
rag_context = rag_db.retrieve_context(top_disease)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 624 |
|
| 625 |
+
# Output directory for this specific run
|
| 626 |
+
output_dir = os.path.join(app.config['OUTPUT_FOLDER'], timestamp)
|
| 627 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 628 |
+
|
| 629 |
+
# Save Images
|
| 630 |
+
orig_path = os.path.join(output_dir, "original.png")
|
| 631 |
+
cv2.imwrite(orig_path, cv2.cvtColor(original_img, cv2.COLOR_RGB2BGR))
|
| 632 |
|
| 633 |
+
rl_path = os.path.join(output_dir, "rl_enhanced.png")
|
| 634 |
+
cv2.imwrite(rl_path, cv2.cvtColor(final_img, cv2.COLOR_RGB2BGR))
|
| 635 |
+
|
| 636 |
+
# Visuals Generation
|
| 637 |
+
heatmap_img = create_heatmap(final_img, boxes, scores)
|
| 638 |
+
heatmap_path = os.path.join(output_dir, "heatmap.png")
|
| 639 |
+
cv2.imwrite(heatmap_path, cv2.cvtColor(heatmap_img, cv2.COLOR_RGB2BGR))
|
| 640 |
+
|
| 641 |
+
# Annotate
|
| 642 |
annotated = final_img.copy()
|
|
|
|
| 643 |
for box, lbl, sc in zip(boxes, labels, scores):
|
| 644 |
x1, y1, x2, y2 = map(int, box)
|
| 645 |
cv2.rectangle(annotated, (x1, y1), (x2, y2), (255, 0, 0), 2)
|
| 646 |
cv2.putText(annotated, f"{CLASS_MAPPING.get(int(lbl))} {sc:.2f}", (x1, y1-5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 647 |
|
| 648 |
+
detect_path = os.path.join(output_dir, "detection.png")
|
| 649 |
+
cv2.imwrite(detect_path, cv2.cvtColor(annotated, cv2.COLOR_RGB2BGR))
|
| 650 |
+
|
| 651 |
+
# Ensemble Plot
|
| 652 |
+
ensemble_path = os.path.join(output_dir, "ensemble.png")
|
| 653 |
+
create_ensemble_boxplot(findings, ensemble_path)
|
| 654 |
+
|
| 655 |
+
# Crops
|
| 656 |
+
crops_data_for_frontend = []
|
| 657 |
+
crops_paths_for_pdf = []
|
| 658 |
+
if len(boxes) > 0:
|
| 659 |
+
crops_info = crop_detections(final_img, boxes, labels, scores)
|
| 660 |
+
for i, c_info in enumerate(crops_info):
|
| 661 |
+
safe_name = c_info['disease'].replace('/', '_')
|
| 662 |
+
c_path = os.path.join(output_dir, f"crop_{i}_{safe_name}.png")
|
| 663 |
+
cv2.imwrite(c_path, cv2.cvtColor(c_info['image'], cv2.COLOR_RGB2BGR))
|
| 664 |
+
crops_paths_for_pdf.append(c_path)
|
| 665 |
+
|
| 666 |
+
# For frontend JSON
|
| 667 |
+
crops_data_for_frontend.append({
|
| 668 |
+
'name': c_info['disease'],
|
| 669 |
+
'img': encode_img_b64(c_info['image'])
|
| 670 |
+
})
|
| 671 |
+
|
| 672 |
+
# Reports & Analysis
|
| 673 |
disease_analyses = {}
|
| 674 |
for f in findings:
|
| 675 |
d_name = f['disease']
|
| 676 |
if d_name not in disease_analyses:
|
|
|
|
| 677 |
disease_analyses[d_name] = get_enhanced_disease_analysis(d_name, f['confidence'], img_stats, api_key)
|
| 678 |
|
| 679 |
+
report = get_comprehensive_report(findings, actions, rag_context, llm_advice, api_key)
|
| 680 |
+
|
| 681 |
+
# PDF Generation
|
| 682 |
+
patient_data = {
|
| 683 |
+
'id': request.form.get('patient_id', 'UNKNOWN'),
|
| 684 |
+
'age': request.form.get('age', 'N/A'),
|
| 685 |
+
'gender': request.form.get('gender', 'N/A'),
|
| 686 |
+
'scan_date': datetime.now().strftime("%Y-%m-%d")
|
| 687 |
+
}
|
| 688 |
+
|
| 689 |
+
images_data_pdf = {
|
| 690 |
+
'original': orig_path,
|
| 691 |
+
'rl_enhanced': rl_path,
|
| 692 |
+
'detection': detect_path,
|
| 693 |
+
'heatmap': heatmap_path,
|
| 694 |
+
'ensemble': ensemble_path,
|
| 695 |
+
'crops': crops_paths_for_pdf
|
| 696 |
+
}
|
| 697 |
+
|
| 698 |
+
pdf_path = generate_enhanced_pdf(patient_data, images_data_pdf, findings, report, disease_analyses)
|
| 699 |
+
|
| 700 |
+
# Prepare Base64 response for Frontend
|
| 701 |
return jsonify({
|
| 702 |
+
"frames": [encode_img_b64(f) for f in frames],
|
| 703 |
"actions": actions,
|
| 704 |
"llm_advice": llm_advice,
|
| 705 |
+
"final_result": encode_img_b64(annotated),
|
| 706 |
+
"heatmap": encode_img_b64(heatmap_img),
|
| 707 |
+
"crops": crops_data_for_frontend,
|
| 708 |
"report": report,
|
| 709 |
"disease_analyses": disease_analyses,
|
| 710 |
+
"rag_context": rag_context,
|
| 711 |
+
# Serving the PDF via a static route or similar mechanism would be needed if downloading is required
|
| 712 |
+
# For now, just confirming it was generated
|
| 713 |
+
"pdf_generated": True
|
| 714 |
})
|
| 715 |
|
| 716 |
# Add route for PDF download if needed (requires implementation of PDF generation function)
|
| 717 |
@app.route('/download_pdf')
|
| 718 |
def download_pdf():
|
| 719 |
+
# Simplistic implementation finding the latest report
|
| 720 |
+
try:
|
| 721 |
+
reports = sorted([os.path.join(app.config['REPORT_FOLDER'], f) for f in os.listdir(app.config['REPORT_FOLDER'])], key=os.path.getmtime)
|
| 722 |
+
if reports:
|
| 723 |
+
return send_file(reports[-1], as_attachment=True)
|
| 724 |
+
except:
|
| 725 |
+
pass
|
| 726 |
+
return "No report found", 404
|
| 727 |
|
| 728 |
if __name__ == '__main__':
|
| 729 |
app.run(debug=True, host='0.0.0.0', port=7860)
|