File size: 15,820 Bytes
64fa10c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1c39b9
64fa10c
e1c39b9
64fa10c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
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)