luigi12345's picture
Update app.py
e1c39b9 verified
import google.generativeai as genai
import gradio as gr
import os
from dotenv import load_dotenv
import time
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import inch
import shutil
from datetime import datetime
import traceback
from PIL import Image
import io
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER
from reportlab.lib.utils import simpleSplit
from xhtml2pdf import pisa
import logging
import uuid
import json
from gradio_client import Client
from gradio_pdf import PDF
from gradio_code import Code
from gradio_image_rotate import ImageRotate
from gradio_multiselect import MultiSelect
from gradio_analytics import Analytics
from gradio_dataframe import DataFrame
load_dotenv()
# --- Hardcoded API Key (Use with caution!) ---
GOOGLE_API_KEY = "AIzaSyCdo5NC_9qNcYAI_21qevkHcWaGrXzZzng"
genai.configure(api_key=GOOGLE_API_KEY)
model = genai.GenerativeModel('gemini-2.0-flash-exp')
# --- End API Key ---
# Configure logging
logging.basicConfig(filename='app.log', level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')
# --- User Settings Handling ---
USER_SETTINGS_FILE = 'user_settings.json'
DEFAULT_DISCLAIMER = "AVISO IMPORTANTE: Este documento se ha generado con fines de investigaci贸n. No debe utilizarse para el diagn贸stico o tratamiento de pacientes. Debe ser interpretado por un m茅dico especialista en oftalmolog铆a."
def load_user_settings():
try:
with open(USER_SETTINGS_FILE, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
return {'disclaimer': DEFAULT_DISCLAIMER, 'api_key': ''}
def save_user_settings(settings):
with open(USER_SETTINGS_FILE, 'w') as f:
json.dump(settings, f)
user_settings = load_user_settings()
# --- End User Settings ---
def generate_report_pdf(report_html, filename="report.pdf"):
"""Generates a PDF report from HTML."""
try:
with open("report.html", "w", encoding="utf-8") as f:
f.write(report_html)
with open("report.html", "r", encoding="utf-8") as f:
html = f.read()
pdf = pisa.CreatePDF(html, dest=filename)
if not pdf.err:
return filename
else:
logging.error(f"PDF Generation error: {pdf.err}")
return None
except Exception as e:
logging.error(f"Exception during PDF generation: {e}")
traceback.print_exc()
return None
finally:
if os.path.exists("report.html"):
os.remove("report.html")
def format_report_html(report_text, disclaimer):
"""Formats the report text into an HTML structure similar to the given example."""
html_template = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ophthalmology Report</title>
<style>
body {{ font-family: sans-serif; margin: 20px; }}
.header {{ text-align: center; margin-bottom: 20px; padding-bottom: 10px; border-bottom: 1px solid #ccc; }}
.header h1 {{ margin-bottom: 5px; }}
.section {{ margin-bottom: 15px; }}
.section-title {{ font-weight: bold; margin-bottom: 5px; }}
.section-step {{ font-weight: normal; margin-left:20px; }}
.footer {{ text-align: center; margin-top: 20px; font-size: 0.8em; color: #777; padding-top: 10px; border-top: 1px solid #ccc;}}
pre {{ white-space: pre-wrap; word-wrap: break-word;}}
</style>
</head>
<body>
<div class="header">
<h1>Hospital Universitario 12 de Octubre</h1>
<p>Informe Oftalmol贸gico</p>
</div>
<div class="report-content">
{report_content}
</div>
<div class="footer">
<p>{disclaimer}</p>
</div>
</body>
</html>
"""
formatted_content = ""
sections = report_text.split("\n\n")
for section in sections:
if ":" in section:
parts = section.split(":", 1)
title = parts[0].strip()
content = parts[1].strip() if len(parts) > 1 else ""
formatted_content += f'<div class="section"><div class="section-title">{title}:</div>'
if 'Step' in title:
formatted_content += f'<div class="section-step"><pre>{content}</pre></div></div>'
else:
formatted_content += f'<pre>{content}</pre></div>'
else:
formatted_content += f'<pre>{section}</pre>'
return html_template.format(report_content=formatted_content, disclaimer=disclaimer)
def analyze_medical_document(files, progress=gr.Progress(), api_key_input = None):
"""Analyzes medical documents (images, text) using Gemini Pro Vision.
Args:
files (list): List of file paths to be analyzed.
progress (gr.Progress): Progress object for UI updates.
api_key_input: API key if not using default
Returns:
str, str: Structured analysis of the document and path to downloadable PDF
"""
progress(0, desc="Preparing for analysis...")
try:
if not files:
return "No file provided", None
if api_key_input:
genai.configure(api_key=api_key_input)
else:
genai.configure(api_key=GOOGLE_API_KEY)
valid_files = []
for file_path in files:
file_ext = os.path.splitext(file_path)[1].lower()
if file_ext in ['.png','.jpg','.jpeg','.pdf','.txt']:
valid_files.append(file_path)
else:
logging.error(f"Invalid file type:{file_path}")
return f"Invalid file type: {os.path.basename(file_path)}. Please use JPEG, PNG, PDF, or TXT", None
contents = []
for i, file_path in enumerate(valid_files):
try:
progress((i + 1) / len(valid_files), desc=f"Reading file: {os.path.basename(file_path)}")
# Load image files to ensure they are read correctly
if file_path.lower().endswith(('.png', '.jpg', '.jpeg')):
try:
img = Image.open(file_path)
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format=img.format)
contents.append(genai.Part.from_data(img_byte_arr.getvalue(), mime_type=f'image/{img.format.lower()}'))
except Exception as e:
logging.error(f"Error reading image file {file_path}: {e}")
return f"Error reading image file {os.path.basename(file_path)}", None
else:
contents.append(genai.Part.from_file(file_path))
except Exception as e:
logging.error(f"Error reading file {file_path}: {e}")
return f"Error reading file {os.path.basename(file_path)}", None
prompt = f"""
You are an expert AI assistant trained to analyze medical documents for ophthalmology research. Your primary task is glaucoma analysis but also note if you see any obvious other findings such as cataracts. You will be provided with one or more images or documents related to a patient's eye, which may include OCT scans, visual field plots, fundus photographs, and/or ophthalmology reports.
Your task is to provide a detailed analysis of these documents, focusing on features relevant to glaucoma diagnosis and monitoring and any other obvious findings. You must follow a Chain-of-Thought approach, describing the findings step-by-step and justifying the conclusions. You will reference established medical knowledge and known diagnostic features of glaucoma to support your analysis.
Please provide the analysis as a structured output in the following format:
Image Type(s): (Identify the types of images provided: OCT, visual field, fundus photo, ophthalmology report, or a combination).
Overall Impression: (Give an overall impression of the images, whether they show signs of glaucoma or are normal for a healthy eye).
Individual Image Analysis:
For each image or report:
(Image type):
Step 1: Description of Key Features: (Describe the key features: for OCT, describe the RNFL thickness, GCL thickness, optic nerve head parameters; for visual field, describe the pattern of defects, including GHT (Global Hemifield Test) results, MD (Mean Deviation), PSD (Pattern Standard Deviation), and VFI (Visual Field Index), and also try to extract the numerical values of the visual field such as the total number of points tested. For fundus photos, describe optic disc appearance, cup-to-disc ratio, presence of hemorrhages, and if you can identify a disc hemorrhage, be explicit about that, including its location. For ophthalmology reports, describe the key findings and numerical values if provided. Be specific with terms such as 'superior' or 'inferior' for the location of the defects or findings).
Step 2: Comparison to Normative Data: (Compare the findings to what is considered normal based on reference data. Use terms like: within normal limits, thinning, cupping, or reduced sensitivity).
Step 3: Correlation of Findings: (if multiple images are provided, describe the correlation between findings in the different image types. For example, if there is RNFL thinning in the superior temporal region in an OCT and a corresponding visual field loss, mention that, as well as if a disc hemorrhage is seen in the fundus photo, mention if a corresponding visual field defect exists. If no correlation exists state that no correlation can be found).
Step 4: Discussion of Potential Glaucoma Indicators: (Discuss whether the findings are indicative of glaucoma or not, and why. Also note any other obvious findings if present, such as cataracts or retinal lesions. ).
Summary of Findings: (Summarize your findings across all images).
Differential Diagnosis: (List possible conditions that should be considered for differential diagnosis).
Medical Reasoning: (Provide medical justification for your conclusions, linking the identified features to their significance in glaucoma, such as visual field loss corresponds to RNFL thinning in certain sectors, or optic disc cupping and RNFL thinning).
Limitations: (Acknowledge limitations of your analysis and emphasize this is for research and not a substitute for a professional medical opinion).
Disclaimer: (State clearly that this analysis is for research purposes only and cannot be used for clinical diagnoses or treatment decisions. Medical decisions must be made by a qualified medical professional.)
Remember, you do not have clinical access to the patient's history, so focus on what you can tell from the documents. If you can detect a language other than English, mention the language of the text.
"""
progress(0.8, desc="Analyzing document...")
response = model.generate_content([prompt, contents])
report_text = response.text
progress(0.9, desc="Preparing Download...")
current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
report_html = format_report_html(report_text, user_settings['disclaimer'])
pdf_file = generate_report_pdf(report_html, filename=f"ophthalmology_report_{current_time}.pdf")
progress(1, desc="Done!")
return report_text, pdf_file
except Exception as e:
logging.error(f"Exception during document analysis: {e}")
traceback.print_exc()
return f"An error occurred: {e}", None
def update_disclaimer(new_disclaimer):
user_settings['disclaimer'] = new_disclaimer
save_user_settings(user_settings)
return new_disclaimer
def update_api_key(new_api_key):
user_settings['api_key'] = new_api_key
save_user_settings(user_settings)
return new_api_key
def clear_settings():
user_settings['api_key'] = ''
user_settings['disclaimer'] = DEFAULT_DISCLAIMER
save_user_settings(user_settings)
return DEFAULT_DISCLAIMER
# Gradio Interface
with gr.Blocks() as iface:
gr.Markdown("# Medical Document Analyzer for Ophthalmology Research")
gr.Markdown("Upload one or more medical images or documents for analysis. This application utilizes Gemini Pro Vision to provide insights into possible glaucoma indicators and other findings. Supported formats: JPEG, PNG, PDF, TXT.")
with gr.TabbedInterface(["Upload Documents", "View Report", "Settings"]) as tabbed_interface:
with tabbed_interface.tabs[0]:
file_input = gr.FileExplorer(file_count="multiple", label="Upload Files")
with gr.Row():
analyze_button = gr.Button("Analyze")
report_progress = gr.Text("")
with tabbed_interface.tabs[1]:
report_output = gr.Textbox(label="Analysis Report", placeholder="Generated report will appear here...")
download_button = gr.File(label="Download Report", file_types=['.pdf'])
with gr.Row():
code_output = Code(label="Code Output (for advanced users)")
with tabbed_interface.tabs[2]:
with gr.Accordion("Disclaimer Settings"):
disclaimer_text = gr.Textarea(label="Disclaimer Message", value=user_settings['disclaimer'])
update_disclaimer_button = gr.Button("Update Disclaimer")
with gr.Accordion("API Key"):
api_key_input = gr.Textbox(label="API key", value = user_settings['api_key'])
update_api_key_button = gr.Button("Update API Key")
clear_settings_button = gr.Button("Clear settings")
def process_analysis(files, progress = gr.Progress()):
report, pdf = analyze_medical_document(files,progress, api_key_input=user_settings['api_key'])
if pdf:
return report, pdf, format_report_html(report, user_settings['disclaimer'])
else:
return report, None, format_report_html(report, user_settings['disclaimer'])
analyze_button.click(process_analysis, inputs=[file_input], outputs=[report_output,download_button, code_output],)
update_disclaimer_button.click(update_disclaimer, inputs=[disclaimer_text], outputs=disclaimer_text)
update_api_key_button.click(update_api_key, inputs=[api_key_input], outputs = api_key_input)
clear_settings_button.click(clear_settings, outputs = disclaimer_text)
# Test function (using local files for test)
def test_analyze_medical_document():
# Create dummy files for testing
with open("test_image_1.txt", "w") as f:
f.write("This is a test image description of some simulated visual field defects for research purposes.")
with open("test_image_2.txt", "w") as f:
f.write("This is a test image description of a normal optic disc for research purposes.")
test_files = ["test_image_1.txt", "test_image_2.txt"]
result, pdf_file = analyze_medical_document(test_files)
assert isinstance(result, str), "The result should be a string."
assert len(result) > 0, "The result should not be an empty string"
assert "Image Type(s):" in result, "The result should contain the key text 'Image Type(s):'"
if pdf_file:
os.remove(pdf_file)
os.remove("test_image_1.txt")
os.remove("test_image_2.txt")
print("Test passed")
# Run tests
test_analyze_medical_document()
# Launch Gradio app
if __name__ == "__main__":
iface.launch(share=False)