import os import cv2 import torch import numpy as np import pydicom import json import traceback import matplotlib # Set backend to Agg before importing pyplot to prevent GUI errors matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.patches as patches import torchvision from torchvision.models.detection import fasterrcnn_resnet50_fpn from torchvision.models.detection.faster_rcnn import FastRCNNPredictor from groq import Groq from stable_baselines3 import PPO import gymnasium as gym from gymnasium import spaces from PIL import Image from fpdf import FPDF from datetime import datetime from werkzeug.exceptions import HTTPException from pydicom.pixel_data_handlers.util import apply_voi_lut # Ensure seaborn is installed in requirements.txt import seaborn as sns from flask import Flask, render_template, request, send_file, jsonify from dotenv import load_dotenv load_dotenv() app = Flask(__name__) # --- PATH CONFIGURATION (LINUX/DOCKER FRIENDLY) --- BASE_DIR = os.path.dirname(os.path.abspath(__file__)) app.config['UPLOAD_FOLDER'] = os.path.join(BASE_DIR, 'uploads') app.config['OUTPUT_FOLDER'] = os.path.join(BASE_DIR, 'outputs') app.config['REPORT_FOLDER'] = os.path.join(BASE_DIR, 'reports') app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # Create directories with proper permissions for folder in [app.config['UPLOAD_FOLDER'], app.config['OUTPUT_FOLDER'], app.config['REPORT_FOLDER']]: os.makedirs(folder, exist_ok=True) # Correct Relative Paths MODEL_PATH = os.path.join(BASE_DIR, "models", "judge_model_epoch5.pth") RL_AGENT_PATH = os.path.join(BASE_DIR, "strict_rl_agent") MEMORY_FILE = os.path.join(BASE_DIR, "medical_memory.json") # API Key (Load from Env for security, fallback to None) DEFAULT_GROQ_KEY = os.getenv("GROQ_API_KEY") DEVICE = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') CLASS_MAPPING = { 1: 'Aortic enlargement', 2: 'Atelectasis', 3: 'Calcification', 4: 'Cardiomegaly', 5: 'Consolidation', 6: 'ILD', 7: 'Infiltration', 8: 'Lung Opacity', 9: 'Nodule/Mass', 10: 'Other lesion', 11: 'Pleural effusion', 12: 'Pleural thickening', 13: 'Pneumothorax', 14: 'Pulmonary fibrosis' } DISEASE_DESCRIPTIONS = { 'Aortic enlargement': 'Abnormal dilation of the aorta. May indicate hypertension, aortic aneurysm, or connective tissue disorders.', 'Atelectasis': 'Partial or complete collapse of lung tissue. Can be caused by airway obstruction, shallow breathing, or compression.', 'Calcification': 'Abnormal calcium deposits in lung tissue. Often indicates previous infections (TB, fungal) or chronic inflammation.', 'Cardiomegaly': 'Enlarged heart. Common causes include hypertension, heart failure, or valvular disease.', 'Consolidation': 'Solidification of lung tissue with fluid/pus. Classic sign of pneumonia or acute inflammation.', 'ILD': 'Interstitial Lung Disease - chronic inflammation affecting lung tissue. Includes conditions like pulmonary fibrosis.', 'Infiltration': 'Abnormal material in lung fields. May indicate infection, inflammation, or neoplastic process.', 'Lung Opacity': 'Non-specific white/gray areas on X-ray. Requires correlation with clinical findings.', 'Nodule/Mass': 'Discrete rounded lesion. Requires follow-up imaging and possibly biopsy to rule out malignancy.', 'Other lesion': 'Various other pathological findings. Clinical context essential for interpretation.', 'Pleural effusion': 'Fluid accumulation between lungs and chest wall. Causes include heart failure, infection, or malignancy.', 'Pleural thickening': 'Thickening of pleural membrane. May indicate previous infection, inflammation, or asbestos exposure.', 'Pneumothorax': 'Collapsed lung due to air in pleural space. Medical emergency requiring immediate intervention.', 'Pulmonary fibrosis': 'Progressive lung scarring reducing elasticity. Serious condition with various causes.' } # --- ERROR HANDLERS --- @app.errorhandler(Exception) def handle_generic_exception(e): error_trace = traceback.format_exc() print(f"ERROR: {error_trace}") return jsonify({"success": False, "error": str(e), "message": "Internal Server Error"}), 500 # --- RAG MEMORY --- class RAGMemory: def __init__(self, filepath): self.filepath = filepath if not os.path.exists(filepath): with open(filepath, 'w') as f: json.dump([], f) def save_experience(self, disease, actions, confidence): try: new_entry = { "disease": disease, "actions": actions, "confidence": float(confidence), "timestamp": datetime.now().isoformat() } # Read existing data = [] if os.path.exists(self.filepath): try: with open(self.filepath, 'r') as f: data = json.load(f) except: pass data.append(new_entry) # Write back with open(self.filepath, 'w') as f: json.dump(data, f, indent=2) except Exception as e: print(f"RAG save error: {e}") def retrieve_context(self, suspected_disease): try: with open(self.filepath, 'r') as f: data = json.load(f) except: return "Memory Empty." relevant = [d for d in data if d.get('disease') == suspected_disease and d.get('confidence', 0) > 0.5] if not relevant: return "No prior memory of this condition." # Simple strategy aggregation action_counts = {} for r in relevant: action_str = ", ".join(r.get('actions', [])) action_counts[action_str] = action_counts.get(action_str, 0) + 1 if action_counts: best_strategy = max(action_counts, key=action_counts.get) return f"In {len(relevant)} past cases of {suspected_disease}, the most frequent strategy was: [{best_strategy}]" return "No clear strategy found." rag_db = RAGMemory(MEMORY_FILE) # --- MODEL LOADING --- class DummyEnv(gym.Env): def __init__(self): self.action_space = spaces.Discrete(5) self.observation_space = spaces.Box(low=0, high=255, shape=(512, 512, 3), dtype=np.uint8) def load_models(): try: print("Loading Detector...") detector = fasterrcnn_resnet50_fpn(weights=None) in_features = detector.roi_heads.box_predictor.cls_score.in_features detector.roi_heads.box_predictor = FastRCNNPredictor(in_features, 15) if os.path.exists(MODEL_PATH): detector.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE)) print(f"✓ Detector weights loaded from {MODEL_PATH}") else: print(f"⚠️ Detector weights NOT found at {MODEL_PATH}") detector.to(DEVICE) detector.eval() print("Loading RL Agent...") agent = None # Check for both path and path.zip if os.path.exists(RL_AGENT_PATH + ".zip") or os.path.exists(RL_AGENT_PATH): try: agent = PPO.load(RL_AGENT_PATH, env=DummyEnv(), device=DEVICE) print(f"✓ RL Agent loaded") except Exception as e: print(f"⚠️ RL Agent load error: {e}") else: print(f"⚠️ RL Agent not found at {RL_AGENT_PATH}") return detector, agent except Exception as e: print(f"❌ Critical Model loading error: {e}") raise detector, agent = load_models() # --- HELPER FUNCTIONS --- def preprocess_image(file_path): try: if file_path.lower().endswith(('.dcm', '.dicom')): dcm = pydicom.dcmread(file_path) try: img = apply_voi_lut(dcm.pixel_array, dcm) except: img = dcm.pixel_array if dcm.PhotometricInterpretation == "MONOCHROME1": img = np.amax(img) - img img = img - np.min(img) if np.max(img) > 0: img = img / np.max(img) img = (img * 255).astype(np.uint8) img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) else: image = Image.open(file_path).convert('RGB') img = np.array(image) return cv2.resize(img, (512, 512)) except Exception as e: raise ValueError(f"Image preprocessing failed: {str(e)}") def encode_img_b64(img_np): _, buffer = cv2.imencode('.jpg', cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)) return base64.b64encode(buffer).decode('utf-8') # --- LLM FUNCTIONS --- def get_groq_client(user_key=None): api_key = user_key if user_key else DEFAULT_GROQ_KEY if not api_key: return None return Groq(api_key=api_key) def get_enhanced_disease_analysis(disease_name, confidence, image_stats, api_key): client = get_groq_client(api_key) if not client: return DISEASE_DESCRIPTIONS.get(disease_name, "Analysis requires API Key.") try: prompt = f"""You are an expert radiologist. Provide detailed clinical analysis for: **Disease:** {disease_name} **AI Confidence:** {confidence:.1%} **Image Statistics:** Mean: {image_stats['mean']:.1f}, Std: {image_stats['std']:.1f} Format: 1. Definition 2. Clinical Significance 3. Recommended Follow-up Keep it concise.""" resp = client.chat.completions.create( messages=[{"role": "user", "content": prompt}], model="openai/gpt-oss-120b", max_tokens=400 ) return resp.choices[0].message.content except Exception as e: return f"LLM Error: {e}" def get_comprehensive_report(findings, actions, rag_context, llm_advice, api_key): client = get_groq_client(api_key) if not client: return "Comprehensive report requires API Key." try: findings_str = "\n".join([f"- {f['disease']}: {f['confidence']:.1%}" for f in findings]) prompt = f"""Role: Senior Radiologist. Context: - Findings: {findings_str} - AI Actions taken: {" -> ".join(actions)} - History: {rag_context} Write a formal medical report including Impression, Findings, and Recommendations. Do not mention AI or RL internals.""" resp = client.chat.completions.create( messages=[{"role": "user", "content": prompt}], model="openai/gpt-oss-120b", max_tokens=1000 ) return resp.choices[0].message.content except Exception as e: return f"Report Error: {e}" # --- RL & PLOTTING --- def run_rl_with_llm_guidance(img_np, llm_advice): if agent is None: return [img_np], ["RL Unavailable"] current = img_np.copy() frames = [current.copy()] actions_log = [] # Parse simple advice logic llm_hint = -1 advice_lower = str(llm_advice).lower() if "bright" in advice_lower and "increase" in advice_lower: llm_hint = 0 elif "bright" in advice_lower and "decrease" in advice_lower: llm_hint = 1 elif "contrast" in advice_lower and "increase" in advice_lower: llm_hint = 2 elif "contrast" in advice_lower and "decrease" in advice_lower: llm_hint = 3 for step in range(5): if step == 0 and llm_hint >= 0: action = llm_hint else: action, _ = agent.predict(current) if action == 0: current = np.clip(current + 15, 0, 255).astype(np.uint8) actions_log.append("Bright+") elif action == 1: current = np.clip(current - 15, 0, 255).astype(np.uint8) actions_log.append("Bright-") elif action == 2: current = np.clip((current - 127.5)*1.2 + 127.5, 0, 255).astype(np.uint8) actions_log.append("Cont+") elif action == 3: current = np.clip((current - 127.5)*0.8 + 127.5, 0, 255).astype(np.uint8) actions_log.append("Cont-") elif action == 4: actions_log.append("Submit") frames.append(current.copy()) break frames.append(current.copy()) return frames, actions_log def create_heatmap(img_np, boxes, scores): heatmap = np.zeros((512, 512), dtype=np.float32) for box, score in zip(boxes, scores): x1, y1, x2, y2 = map(int, box) heatmap[max(0, y1):min(512, y2), max(0, x1):min(512, x2)] += score if heatmap.max() > 0: heatmap /= heatmap.max() heatmap_colored = cv2.applyColorMap((heatmap * 255).astype(np.uint8), cv2.COLORMAP_JET) heatmap_colored = cv2.cvtColor(heatmap_colored, cv2.COLOR_BGR2RGB) return cv2.addWeighted(img_np, 0.6, heatmap_colored, 0.4, 0) # --- ROUTES --- @app.route('/') def index(): return render_template('landing.html') @app.route('/app') def dashboard(): return render_template('dashboard.html') @app.route('/process', methods=['POST']) def process(): if 'file' not in request.files: return jsonify({'success': False, 'error': 'No file'}), 400 file = request.files['file'] if file.filename == '': return jsonify({'success': False, 'error': 'No filename'}), 400 api_key = request.form.get('api_key') or DEFAULT_GROQ_KEY # Changed default threshold from 0.2 to 0.4 (40%) threshold = float(request.form.get('threshold', 0.4)) # Save Upload timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = f"{timestamp}_{file.filename}" file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) file.save(file_path) # Preprocess original_img = preprocess_image(file_path) import base64 def b64(img): _, buf = cv2.imencode('.jpg', cv2.cvtColor(img, cv2.COLOR_RGB2BGR)) return base64.b64encode(buf).decode('utf-8') # LLM Advice (Simulated or Real) llm_advice = "Preprocessing skipped" if api_key: # Simple advice prompt could go here llm_advice = "AI analysis running..." # Run RL frames, actions = run_rl_with_llm_guidance(original_img, llm_advice) final_img = frames[-1] # Run Detector inp = torch.tensor(final_img).permute(2, 0, 1).float() / 255.0 inp = inp.unsqueeze(0).to(DEVICE) with torch.no_grad(): preds = detector(inp)[0] keep = preds['scores'] > threshold if keep.sum() > 0: nms_idx = torchvision.ops.nms(preds['boxes'][keep], preds['scores'][keep], 0.2) boxes = preds['boxes'][keep][nms_idx].cpu().numpy() scores = preds['scores'][keep][nms_idx].cpu().numpy() labels = preds['labels'][keep][nms_idx].cpu().numpy() findings = [{'disease': CLASS_MAPPING.get(int(l), "Unknown"), 'confidence': float(s)} for l, s in zip(labels, scores)] # Save to RAG if len(findings) > 0: rag_db.save_experience(findings[0]['disease'], actions, float(scores[0])) rag_context = rag_db.retrieve_context(findings[0]['disease']) else: rag_context = "No significant findings." else: boxes, scores, labels, findings = [], [], [], [] rag_context = "No findings." # Generate Visuals heatmap = create_heatmap(final_img, boxes, scores) # Annotate Final annotated = final_img.copy() crops = [] for box, lbl, sc in zip(boxes, labels, scores): x1, y1, x2, y2 = map(int, box) cv2.rectangle(annotated, (x1, y1), (x2, y2), (255, 0, 0), 2) cv2.putText(annotated, f"{CLASS_MAPPING.get(int(lbl))} {sc:.2f}", (x1, y1-5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 1) # Crops pad = 20 c = final_img[max(0, y1-pad):min(512, y2+pad), max(0, x1-pad):min(512, x2+pad)] if c.size > 0: crops.append({'name': CLASS_MAPPING.get(int(lbl)), 'img': b64(c)}) # Generate Report report = get_comprehensive_report(findings, actions, rag_context, llm_advice, api_key) # Disease Analysis disease_analyses = {} for f in findings: d_name = f['disease'] if d_name not in disease_analyses: img_stats = {'mean': np.mean(final_img), 'std': np.std(final_img)} disease_analyses[d_name] = get_enhanced_disease_analysis(d_name, f['confidence'], img_stats, api_key) return jsonify({ "frames": [b64(f) for f in frames], "actions": actions, "llm_advice": llm_advice, "final_result": b64(annotated), "heatmap": b64(heatmap), "crops": crops, "report": report, "disease_analyses": disease_analyses, "rag_context": rag_context }) # Add route for PDF download if needed (requires implementation of PDF generation function) @app.route('/download_pdf') def download_pdf(): return "PDF Download Not Configured in this version", 404 if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=7860)