luigi12345 commited on
Commit
64fa10c
·
verified ·
1 Parent(s): 629f534

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +302 -0
app.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import google.generativeai as genai
2
+ import gradio as gr
3
+ import os
4
+ from dotenv import load_dotenv
5
+ import time
6
+ from reportlab.pdfgen import canvas
7
+ from reportlab.lib.pagesizes import letter
8
+ from reportlab.lib.units import inch
9
+ import shutil
10
+ from datetime import datetime
11
+ import traceback
12
+ from PIL import Image
13
+ import io
14
+ from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
15
+ from reportlab.lib.styles import getSampleStyleSheet
16
+ from reportlab.lib import colors
17
+ from reportlab.lib.enums import TA_CENTER
18
+ from reportlab.lib.utils import simpleSplit
19
+ from xhtml2pdf import pisa
20
+ import logging
21
+ import uuid
22
+ import json
23
+ from gradio_client import Client
24
+ from gradio_pdf import PDF
25
+ from gradio_code import Code
26
+ from gradio_image_rotate import ImageRotate
27
+ from gradio_multiselect import MultiSelect
28
+ from gradio_analytics import Analytics
29
+ from gradio_dataframe import DataFrame
30
+
31
+ load_dotenv()
32
+
33
+ # --- Hardcoded API Key (Use with caution!) ---
34
+ GOOGLE_API_KEY = "YOUR_API_KEY"
35
+ genai.configure(api_key=GOOGLE_API_KEY)
36
+ model = genai.GenerativeModel('gemini-pro-vision')
37
+ # --- End API Key ---
38
+
39
+ # Configure logging
40
+ logging.basicConfig(filename='app.log', level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')
41
+
42
+ # --- User Settings Handling ---
43
+ USER_SETTINGS_FILE = 'user_settings.json'
44
+ 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."
45
+
46
+ def load_user_settings():
47
+ try:
48
+ with open(USER_SETTINGS_FILE, 'r') as f:
49
+ return json.load(f)
50
+ except (FileNotFoundError, json.JSONDecodeError):
51
+ return {'disclaimer': DEFAULT_DISCLAIMER, 'api_key': ''}
52
+
53
+ def save_user_settings(settings):
54
+ with open(USER_SETTINGS_FILE, 'w') as f:
55
+ json.dump(settings, f)
56
+
57
+ user_settings = load_user_settings()
58
+ # --- End User Settings ---
59
+
60
+ def generate_report_pdf(report_html, filename="report.pdf"):
61
+ """Generates a PDF report from HTML."""
62
+ try:
63
+ with open("report.html", "w", encoding="utf-8") as f:
64
+ f.write(report_html)
65
+ with open("report.html", "r", encoding="utf-8") as f:
66
+ html = f.read()
67
+ pdf = pisa.CreatePDF(html, dest=filename)
68
+ if not pdf.err:
69
+ return filename
70
+ else:
71
+ logging.error(f"PDF Generation error: {pdf.err}")
72
+ return None
73
+ except Exception as e:
74
+ logging.error(f"Exception during PDF generation: {e}")
75
+ traceback.print_exc()
76
+ return None
77
+ finally:
78
+ if os.path.exists("report.html"):
79
+ os.remove("report.html")
80
+
81
+
82
+ def format_report_html(report_text, disclaimer):
83
+ """Formats the report text into an HTML structure similar to the given example."""
84
+
85
+ html_template = """
86
+ <!DOCTYPE html>
87
+ <html lang="en">
88
+ <head>
89
+ <meta charset="UTF-8">
90
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
91
+ <title>Ophthalmology Report</title>
92
+ <style>
93
+ body {{ font-family: sans-serif; margin: 20px; }}
94
+ .header {{ text-align: center; margin-bottom: 20px; padding-bottom: 10px; border-bottom: 1px solid #ccc; }}
95
+ .header h1 {{ margin-bottom: 5px; }}
96
+ .section {{ margin-bottom: 15px; }}
97
+ .section-title {{ font-weight: bold; margin-bottom: 5px; }}
98
+ .section-step {{ font-weight: normal; margin-left:20px; }}
99
+ .footer {{ text-align: center; margin-top: 20px; font-size: 0.8em; color: #777; padding-top: 10px; border-top: 1px solid #ccc;}}
100
+ pre {{ white-space: pre-wrap; word-wrap: break-word;}}
101
+ </style>
102
+ </head>
103
+ <body>
104
+ <div class="header">
105
+ <h1>Hospital Universitario 12 de Octubre</h1>
106
+ <p>Informe Oftalmológico</p>
107
+ </div>
108
+ <div class="report-content">
109
+ {report_content}
110
+ </div>
111
+ <div class="footer">
112
+ <p>{disclaimer}</p>
113
+ </div>
114
+ </body>
115
+ </html>
116
+ """
117
+
118
+ formatted_content = ""
119
+ sections = report_text.split("\n\n")
120
+ for section in sections:
121
+ if ":" in section:
122
+ parts = section.split(":", 1)
123
+ title = parts[0].strip()
124
+ content = parts[1].strip() if len(parts) > 1 else ""
125
+ formatted_content += f'<div class="section"><div class="section-title">{title}:</div>'
126
+ if 'Step' in title:
127
+ formatted_content += f'<div class="section-step"><pre>{content}</pre></div></div>'
128
+ else:
129
+ formatted_content += f'<pre>{content}</pre></div>'
130
+ else:
131
+ formatted_content += f'<pre>{section}</pre>'
132
+
133
+ return html_template.format(report_content=formatted_content, disclaimer=disclaimer)
134
+
135
+ def analyze_medical_document(files, progress=gr.Progress(), api_key_input = None):
136
+ """Analyzes medical documents (images, text) using Gemini Pro Vision.
137
+
138
+ Args:
139
+ files (list): List of file paths to be analyzed.
140
+ progress (gr.Progress): Progress object for UI updates.
141
+ api_key_input: API key if not using default
142
+
143
+ Returns:
144
+ str, str: Structured analysis of the document and path to downloadable PDF
145
+ """
146
+ progress(0, desc="Preparing for analysis...")
147
+ try:
148
+ if not files:
149
+ return "No file provided", None
150
+
151
+ if api_key_input:
152
+ genai.configure(api_key=api_key_input)
153
+ else:
154
+ genai.configure(api_key=GOOGLE_API_KEY)
155
+
156
+ valid_files = []
157
+ for file_path in files:
158
+ file_ext = os.path.splitext(file_path)[1].lower()
159
+ if file_ext in ['.png','.jpg','.jpeg','.pdf','.txt']:
160
+ valid_files.append(file_path)
161
+ else:
162
+ logging.error(f"Invalid file type:{file_path}")
163
+ return f"Invalid file type: {os.path.basename(file_path)}. Please use JPEG, PNG, PDF, or TXT", None
164
+
165
+ contents = []
166
+ for i, file_path in enumerate(valid_files):
167
+ try:
168
+ progress((i + 1) / len(valid_files), desc=f"Reading file: {os.path.basename(file_path)}")
169
+ # Load image files to ensure they are read correctly
170
+ if file_path.lower().endswith(('.png', '.jpg', '.jpeg')):
171
+ try:
172
+ img = Image.open(file_path)
173
+ img_byte_arr = io.BytesIO()
174
+ img.save(img_byte_arr, format=img.format)
175
+ contents.append(genai.Part.from_data(img_byte_arr.getvalue(), mime_type=f'image/{img.format.lower()}'))
176
+ except Exception as e:
177
+ logging.error(f"Error reading image file {file_path}: {e}")
178
+ return f"Error reading image file {os.path.basename(file_path)}", None
179
+ else:
180
+ contents.append(genai.Part.from_file(file_path))
181
+ except Exception as e:
182
+ logging.error(f"Error reading file {file_path}: {e}")
183
+ return f"Error reading file {os.path.basename(file_path)}", None
184
+
185
+ prompt = f"""
186
+ 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.
187
+
188
+ 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.
189
+
190
+ Please provide the analysis as a structured output in the following format:
191
+
192
+ Image Type(s): (Identify the types of images provided: OCT, visual field, fundus photo, ophthalmology report, or a combination).
193
+ Overall Impression: (Give an overall impression of the images, whether they show signs of glaucoma or are normal for a healthy eye).
194
+ Individual Image Analysis:
195
+ For each image or report:
196
+ (Image type):
197
+ 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).
198
+ 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).
199
+ 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).
200
+ 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. ).
201
+ Summary of Findings: (Summarize your findings across all images).
202
+ Differential Diagnosis: (List possible conditions that should be considered for differential diagnosis).
203
+ 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).
204
+ Limitations: (Acknowledge limitations of your analysis and emphasize this is for research and not a substitute for a professional medical opinion).
205
+ 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.)
206
+ 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.
207
+ """
208
+ progress(0.8, desc="Analyzing document...")
209
+ response = model.generate_content([prompt, contents])
210
+ report_text = response.text
211
+ progress(0.9, desc="Preparing Download...")
212
+ current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
213
+ report_html = format_report_html(report_text, user_settings['disclaimer'])
214
+ pdf_file = generate_report_pdf(report_html, filename=f"ophthalmology_report_{current_time}.pdf")
215
+ progress(1, desc="Done!")
216
+ return report_text, pdf_file
217
+ except Exception as e:
218
+ logging.error(f"Exception during document analysis: {e}")
219
+ traceback.print_exc()
220
+ return f"An error occurred: {e}", None
221
+
222
+ def update_disclaimer(new_disclaimer):
223
+ user_settings['disclaimer'] = new_disclaimer
224
+ save_user_settings(user_settings)
225
+ return new_disclaimer
226
+
227
+ def update_api_key(new_api_key):
228
+ user_settings['api_key'] = new_api_key
229
+ save_user_settings(user_settings)
230
+ return new_api_key
231
+
232
+
233
+ def clear_settings():
234
+ user_settings['api_key'] = ''
235
+ user_settings['disclaimer'] = DEFAULT_DISCLAIMER
236
+ save_user_settings(user_settings)
237
+ return DEFAULT_DISCLAIMER
238
+
239
+ # Gradio Interface
240
+ with gr.Blocks() as iface:
241
+ gr.Markdown("# Medical Document Analyzer for Ophthalmology Research")
242
+ 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.")
243
+
244
+ with gr.TabbedInterface(["Upload Documents", "View Report", "Settings"]) as tabbed_interface:
245
+ with tabbed_interface.tabs[0]:
246
+ file_input = gr.FileExplorer(file_count="multiple", label="Upload Files")
247
+ with gr.Row():
248
+ analyze_button = gr.Button("Analyze")
249
+ report_progress = gr.Text("")
250
+
251
+ with tabbed_interface.tabs[1]:
252
+ report_output = gr.Textbox(label="Analysis Report", placeholder="Generated report will appear here...")
253
+ download_button = gr.File(label="Download Report", file_types=['.pdf'])
254
+ with gr.Row():
255
+ code_output = Code(label="Code Output (for advanced users)")
256
+ with tabbed_interface.tabs[2]:
257
+ with gr.Accordion("Disclaimer Settings"):
258
+ disclaimer_text = gr.Textarea(label="Disclaimer Message", value=user_settings['disclaimer'])
259
+ update_disclaimer_button = gr.Button("Update Disclaimer")
260
+ with gr.Accordion("API Key"):
261
+ api_key_input = gr.Textbox(label="API key", value = user_settings['api_key'])
262
+ update_api_key_button = gr.Button("Update API Key")
263
+ clear_settings_button = gr.Button("Clear settings")
264
+
265
+ def process_analysis(files, progress = gr.Progress()):
266
+ report, pdf = analyze_medical_document(files,progress, api_key_input=user_settings['api_key'])
267
+ if pdf:
268
+ return report, pdf, format_report_html(report, user_settings['disclaimer'])
269
+ else:
270
+ return report, None, format_report_html(report, user_settings['disclaimer'])
271
+
272
+
273
+ analyze_button.click(process_analysis, inputs=[file_input], outputs=[report_output,download_button, code_output],)
274
+ update_disclaimer_button.click(update_disclaimer, inputs=[disclaimer_text], outputs=disclaimer_text)
275
+ update_api_key_button.click(update_api_key, inputs=[api_key_input], outputs = api_key_input)
276
+ clear_settings_button.click(clear_settings, outputs = disclaimer_text)
277
+
278
+ # Test function (using local files for test)
279
+ def test_analyze_medical_document():
280
+ # Create dummy files for testing
281
+ with open("test_image_1.txt", "w") as f:
282
+ f.write("This is a test image description of some simulated visual field defects for research purposes.")
283
+ with open("test_image_2.txt", "w") as f:
284
+ f.write("This is a test image description of a normal optic disc for research purposes.")
285
+ test_files = ["test_image_1.txt", "test_image_2.txt"]
286
+ result, pdf_file = analyze_medical_document(test_files)
287
+ assert isinstance(result, str), "The result should be a string."
288
+ assert len(result) > 0, "The result should not be an empty string"
289
+ assert "Image Type(s):" in result, "The result should contain the key text 'Image Type(s):'"
290
+ if pdf_file:
291
+ os.remove(pdf_file)
292
+ os.remove("test_image_1.txt")
293
+ os.remove("test_image_2.txt")
294
+ print("Test passed")
295
+
296
+
297
+ # Run tests
298
+ test_analyze_medical_document()
299
+
300
+ # Launch Gradio app
301
+ if __name__ == "__main__":
302
+ iface.launch(share=False)