Spaces:
Sleeping
Sleeping
Update app.py
Browse files1 unmodified line23456717 unmodified lines2526272829303132233 unmodified lines26626726826927027127227327427527627727827928028128228328428528628728828929029129250 unmodified lines34334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855914 unmodified lines5745755765775785795803 unmodified lines5845855865875885895905915925937 unmodified lines6016026036046056066076086096106116122 unmodified lines6156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287291 unmodified lineimport cv2import torchimport numpy as npimport jsonimport tracebackimport matplotlib17 unmodified linesimport seaborn as snsfrom flask import Flask, render_template, request, send_file, jsonifyfrom dotenv import load_dotenvimport base64import pydicomload_dotenv()233 unmodified linesexcept Exception as e:return f"Report Error: {e}"def get_llm_preprocessing_advice(img_np, api_key):if not api_key:return "Preprocessing analysis skipped"try:mean_intensity = np.mean(img_np)std_intensity = np.std(img_np)client = Groq(api_key=api_key)prompt = f"""Analyze chest X-ray quality (mean: {mean_intensity:.1f}, std: {std_intensity:.1f}).Recommend ONE preprocessing action: Increase/Decrease Brightness or Contrast. Max 2 sentences."""resp = client.chat.completions.create(messages=[{"role": "user", "content": prompt}],model="llama-3.3-70b-versatile",temperature=0.3,max_tokens=100)return resp.choices[0].message.contentexcept Exception as e:return f"LLM advice unavailable: {str(e)}"# --- RL & PLOTTING ---def run_rl_with_llm_guidance(img_np, llm_advice):50 unmodified linesheatmap_colored = cv2.cvtColor(heatmap_colored, cv2.COLOR_BGR2RGB)return cv2.addWeighted(img_np, 0.6, heatmap_colored, 0.4, 0)def create_ensemble_boxplot(findings, output_path):try:fig, ax = plt.subplots(figsize=(12, 6))fig.patch.set_facecolor('#1a1a1a')ax.set_facecolor('#2a2a2a')diseases = [f['disease'][:15] for f in findings]confidences = [f['confidence'] * 100 for f in findings]colors = plt.cm.RdYlGn(np.array(confidences) / 100)bars = ax.barh(diseases, confidences, color=colors, edgecolor='#00ff00', linewidth=2)for i, (bar, conf) in enumerate(zip(bars, confidences)):ax.text(conf + 1, i, f'{conf:.1f}%', va='center', color='#00ff00', fontweight='bold')ax.set_xlabel('Confidence (%)', color='#00ff00', fontsize=12, fontweight='bold')ax.set_title('Disease Confidence Ensemble', color='#00ff00', fontsize=14, fontweight='bold')ax.set_xlim(0, 105)ax.tick_params(colors='#00ff00')for spine in ax.spines.values():spine.set_color('#00ff00')spine.set_linewidth(2)ax.grid(axis='x', alpha=0.2, color='#00ff00')plt.tight_layout()plt.savefig(output_path, dpi=150, bbox_inches='tight', facecolor='#1a1a1a')plt.close()return Trueexcept Exception as e:print(f"Ensemble plot error: {e}")return Falsedef crop_detections(img_np, boxes, labels, scores):crops = []try:for box, lbl, score in zip(boxes, labels, scores):x1, y1, x2, y2 = map(int, box)pad = 15x1, y1 = max(0, x1-pad), max(0, y1-pad)x2, y2 = min(512, x2+pad), min(512, y2+pad)crop = img_np[y1:y2, x1:x2].copy()disease_name = CLASS_MAPPING.get(int(lbl), "Unknown")crops.append({'image': crop,'disease': disease_name,'confidence': float(score),'bbox': (x1, y1, x2, y2)})except Exception as e:print(f"Crop error: {e}")return crops# --- ENHANCED PDF GENERATION ---class EnhancedMedicalPDF(FPDF):def __init__(self):super().__init__()self.WIDTH = 210self.HEIGHT = 297def header(self):self.set_fill_color(30, 30, 30)self.rect(0, 0, self.WIDTH, 30, 'F')self.set_font('Arial', 'B', 20)self.set_text_color(0, 255, 0)self.cell(0, 15, 'SUPER-DOCTOR V2', 0, 1, 'C')self.set_font('Arial', 'I', 10)self.cell(0, 8, f'Medical AI Analysis Report | {datetime.now().strftime("%Y-%m-%d %H:%M")}', 0, 1, 'C')self.ln(5)def footer(self):self.set_y(-20)self.set_font('Arial', 'I', 8)self.set_text_color(128, 128, 128)self.cell(0, 10, f'Page {self.page_no()} | AI-Assisted Analysis - Not a substitute for clinical judgment', 0, 0, 'C')def section_title(self, title):self.set_font('Arial', 'B', 14)self.set_fill_color(0, 255, 0)self.set_text_color(0, 0, 0)self.cell(0, 8, f' {title}', 0, 1, 'L', 1)self.set_text_color(0, 0, 0)self.ln(2)def section_body(self, text):self.set_font('Arial', '', 10)self.set_text_color(0, 0, 0)self.multi_cell(0, 5, text)self.ln(2)def disease_section(self, disease_name, confidence, description):self.set_font('Arial', 'B', 12)self.set_text_color(0, 0, 0)self.cell(0, 7, f'• {disease_name}', 0, 1, 'L')self.set_font('Arial', 'I', 9)self.set_text_color(100, 100, 100)self.cell(0, 5, f' Confidence: {confidence:.1%}', 0, 1, 'L')self.set_font('Arial', '', 9)self.set_text_color(0, 0, 0)self.multi_cell(0, 4, description)self.ln(1)def generate_enhanced_pdf(patient_data, images_data, findings, report_text, disease_analyses):try:pdf = EnhancedMedicalPDF()pdf.add_page()# Patient Infopdf.section_title('PATIENT INFORMATION')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')}Scan Date: {patient_data.get('scan_date', 'N/A')}Report Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}""")# Quick Summarypdf.section_title('SUMMARY')num_findings = len(findings)summary_text = f"Total Detected Conditions: {num_findings}\n"if num_findings > 0:top_finding = max(findings, key=lambda x: x['confidence'])summary_text += f"Primary Finding: {top_finding['disease']} ({top_finding['confidence']:.1%})\n"summary_text += f"Average Confidence: {np.mean([f['confidence'] for f in findings]):.1%}"pdf.section_body(summary_text)# Imagespdf.add_page()pdf.section_title('IMAGING ANALYSIS')img_configs = [('original', 'Original X-Ray', 50),('rl_enhanced', 'AI-Enhanced X-Ray', 100),('detection', 'Detection Results', 150),]for key, title, y_pos in img_configs:if key in images_data and os.path.exists(images_data[key]):pdf.set_font('Arial', 'B', 11)pdf.set_xy(10, y_pos)pdf.cell(0, 5, title, 0, 1)pdf.image(images_data[key], x=15, y=y_pos+5, w=180)# Heatmap & Ensemblepdf.add_page()if 'heatmap' in images_data and os.path.exists(images_data['heatmap']):pdf.section_title('CONFIDENCE HEATMAP')pdf.image(images_data['heatmap'], x=20, y=pdf.get_y()+5, w=170)pdf.ln(100)if 'ensemble' in images_data and os.path.exists(images_data['ensemble']):pdf.section_title('DISEASE CONFIDENCE ENSEMBLE')pdf.image(images_data['ensemble'], x=20, y=pdf.get_y()+5, w=170)# Detailed Findingspdf.add_page()pdf.section_title('DETAILED DISEASE ANALYSIS')for finding in findings:disease = finding['disease']confidence = finding['confidence']analysis = disease_analyses.get(disease, DISEASE_DESCRIPTIONS.get(disease, "No detailed analysis available."))if len(analysis) > 500:analysis = analysis[:500] + "..."pdf.disease_section(disease, confidence, analysis)# Clinical Reportpdf.add_page()pdf.section_title('RADIOLOGIST AI INTERPRETATION')pdf.section_body(report_text[:3000])# Crops if availableif 'crops' in images_data and images_data['crops']:pdf.add_page()pdf.section_title('DISEASE REGION CLOSE-UPS')for i, crop_path in enumerate(images_data['crops'][:4]):if os.path.exists(crop_path):if i % 2 == 0:pdf.ln(5)y_pos = pdf.get_y()x_pos = 15 if i % 2 == 0 else 115pdf.image(crop_path, x=x_pos, y=y_pos, w=85)# Footer pagepdf.add_page()pdf.set_font('Arial', 'B', 12)pdf.set_text_color(0, 255, 0)pdf.cell(0, 10, 'CLINICAL NOTES', 0, 1)pdf.set_font('Arial', '', 10)pdf.set_text_color(0, 0, 0)pdf.multi_cell(0, 5, """This report is generated by AI-assisted analysis of radiographic images.IMPORTANT DISCLAIMERS:• This analysis is intended to assist and not replace clinical judgment• All findings must be correlated with patient clinical presentation• Follow-up imaging may be recommended based on clinical context• Final interpretation by qualified radiologist is essential• AI confidence scores indicate model certainty, not diagnostic certaintyReport generated by Super-Doctor V2 Medical AI System""")timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")pdf_path = os.path.join(app.config['REPORT_FOLDER'], f"medical_report_{timestamp}.pdf")pdf.output(pdf_path)return pdf_pathexcept Exception as e:raise RuntimeError(f"PDF generation failed: {str(e)}")# --- ROUTES ---@app.route('/')14 unmodified linesreturn jsonify({'success': False, 'error': 'No filename'}), 400api_key = request.form.get('api_key') or DEFAULT_GROQ_KEYthreshold = float(request.form.get('threshold', 0.2))# Save Uploadtimestamp = datetime.now().strftime("%Y%m%d_%H%M%S")3 unmodified lines# Preprocessoriginal_img = preprocess_image(file_path)img_stats = {'mean': np.mean(original_img), 'std': np.std(original_img)}# LLM Advicellm_advice = get_llm_preprocessing_advice(original_img, api_key) if api_key else "Preprocessing optimization skipped"# Run RLframes, actions = run_rl_with_llm_guidance(original_img, llm_advice)7 unmodified linespreds = detector(inp)[0]keep = preds['scores'] > threshold# Initialize resultsboxes, scores, labels = [], [], []findings = []rag_context = "No significant findings."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()2 unmodified linesfindings = [{'disease': CLASS_MAPPING.get(int(l), "Unknown"), 'confidence': float(s)}for l, s in zip(labels, scores)]findings = sorted(findings, key=lambda x: x['confidence'], reverse=True)if len(findings) > 0:top_disease = findings[0]['disease']rag_db.save_experience(top_disease, actions, float(scores[0]))rag_context = rag_db.retrieve_context(top_disease)# Output directory for this specific runoutput_dir = os.path.join(app.config['OUTPUT_FOLDER'], timestamp)os.makedirs(output_dir, exist_ok=True)# Save Imagesorig_path = os.path.join(output_dir, "original.png")cv2.imwrite(orig_path, cv2.cvtColor(original_img, cv2.COLOR_RGB2BGR))rl_path = os.path.join(output_dir, "rl_enhanced.png")cv2.imwrite(rl_path, cv2.cvtColor(final_img, cv2.COLOR_RGB2BGR))# Visuals Generationheatmap_img = create_heatmap(final_img, boxes, scores)heatmap_path = os.path.join(output_dir, "heatmap.png")cv2.imwrite(heatmap_path, cv2.cvtColor(heatmap_img, cv2.COLOR_RGB2BGR))# Annotateannotated = final_img.copy()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)detect_path = os.path.join(output_dir, "detection.png")cv2.imwrite(detect_path, cv2.cvtColor(annotated, cv2.COLOR_RGB2BGR))# Ensemble Plotensemble_path = os.path.join(output_dir, "ensemble.png")create_ensemble_boxplot(findings, ensemble_path)# Cropscrops_data_for_frontend = []crops_paths_for_pdf = []if len(boxes) > 0:crops_info = crop_detections(final_img, boxes, labels, scores)for i, c_info in enumerate(crops_info):safe_name = c_info['disease'].replace('/', '_')c_path = os.path.join(output_dir, f"crop_{i}_{safe_name}.png")cv2.imwrite(c_path, cv2.cvtColor(c_info['image'], cv2.COLOR_RGB2BGR))crops_paths_for_pdf.append(c_path)# For frontend JSONcrops_data_for_frontend.append({'name': c_info['disease'],'img': encode_img_b64(c_info['image'])})# Reports & Analysisdisease_analyses = {}for f in findings:d_name = f['disease']if d_name not in disease_analyses:disease_analyses[d_name] = get_enhanced_disease_analysis(d_name, f['confidence'], img_stats, api_key)report = get_comprehensive_report(findings, actions, rag_context, llm_advice, api_key)# PDF Generationpatient_data = {'id': request.form.get('patient_id', 'UNKNOWN'),'age': request.form.get('age', 'N/A'),'gender': request.form.get('gender', 'N/A'),'scan_date': datetime.now().strftime("%Y-%m-%d")}images_data_pdf = {'original': orig_path,'rl_enhanced': rl_path,'detection': detect_path,'heatmap': heatmap_path,'ensemble': ensemble_path,'crops': crops_paths_for_pdf}pdf_path = generate_enhanced_pdf(patient_data, images_data_pdf, findings, report, disease_analyses)# Prepare Base64 response for Frontendreturn jsonify({"frames": [encode_img_b64(f) for f in frames],"actions": actions,"llm_advice": llm_advice,"final_result": encode_img_b64(annotated),"heatmap": encode_img_b64(heatmap_img),"crops": crops_data_for_frontend,"report": report,"disease_analyses": disease_analyses,"rag_context": rag_context,# Serving the PDF via a static route or similar mechanism would be needed if downloading is required# For now, just confirming it was generated"pdf_generated": True})# Add route for PDF download if needed (requires implementation of PDF generation function)@app.route('/download_pdf')def download_pdf():# Simplistic implementation finding the latest reporttry:reports = sorted([os.path.join(app.config['REPORT_FOLDER'], f) for f in os.listdir(app.config['REPORT_FOLDER'])], key=os.path.getmtime)if reports:return send_file(reports[-1], as_attachment=True)except:passreturn "No report found", 404if __name__ == '__main__':app.run(debug=True, host='0.0.0.0', port=7860)1 unmodified line234567817 unmodified lines262728293031233 unmodified lines26526626726826927050 unmodified lines32132232332432532614 unmodified lines3413423433443453463473483 unmodified lines3523533543553563573583593603613623633643653663677 unmodified lines3753763773783793802 unmodified lines3833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424431 unmodified lineimport cv2import torchimport numpy as npimport pydicomimport jsonimport tracebackimport matplotlib17 unmodified linesimport seaborn as snsfrom flask import Flask, render_template, request, send_file, jsonifyfrom dotenv import load_dotenvload_dotenv()233 unmodified linesexcept Exception as e:return f"Report Error: {e}"# --- RL & PLOTTING ---def run_rl_with_llm_guidance(img_np, llm_advice):50 unmodified linesheatmap_colored = cv2.cvtColor(heatmap_colored, cv2.COLOR_BGR2RGB)return cv2.addWeighted(img_np, 0.6, heatmap_colored, 0.4, 0)# --- ROUTES ---@app.route('/')14 unmodified linesreturn jsonify({'success': False, 'error': 'No filename'}), 400api_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 Uploadtimestamp = datetime.now().strftime("%Y%m%d_%H%M%S")3 unmodified lines# Preprocessoriginal_img = preprocess_image(file_path)import base64def 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 herellm_advice = "AI analysis running..."# Run RLframes, actions = run_rl_with_llm_guidance(original_img, llm_advice)7 unmodified linespreds = detector(inp)[0]keep = preds['scores'] > thresholdif keep.sum() > 0:nms_idx = torchvision.ops.nms(preds['boxes'][keep], preds['scores'][keep], 0.2)boxes = preds['boxes'][keep][nms_idx].cpu().numpy()2 unmodified linesfindings = [{'disease': CLASS_MAPPING.get(int(l), "Unknown"), 'confidence': float(s)}for l, s in zip(labels, scores)]# Save to RAGif 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 Visualsheatmap = create_heatmap(final_img, boxes, scores)# Annotate Finalannotated = 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)# Cropspad = 20c = 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 Reportreport = get_comprehensive_report(findings, actions, rag_context, llm_advice, api_key)# Disease Analysisdisease_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", 404if __name__ == '__main__':app.run(debug=True, host='0.0.0.0', port=7860)
app.py+41-327