import streamlit as st import google.generativeai as genai from PIL import Image import os from dotenv import load_dotenv import PyPDF2 import io from datetime import datetime # Page configuration must be the first Streamlit command st.set_page_config( page_title="OCT Retina Analysis Assistant", page_icon="👁️", layout="wide", initial_sidebar_state="expanded" ) # Load environment variables load_dotenv() # Configure Gemini API genai.configure(api_key=os.getenv("GOOGLE_API_KEY")) model = genai.GenerativeModel("gemini-2.0-flash-exp") # Custom CSS st.markdown(""" """, unsafe_allow_html=True) # System prompts SINGLE_TIMEPOINT_PROMPT = """You are an expert ophthalmologist specializing in interpreting macular Optical Coherence Tomography (OCT) scans. Your goal is to provide an accurate description and a possible diagnosis, supported by clear medical reasoning. These scans are from the same patient at a single timepoint. Please provide a comprehensive analysis. Step 1: Image Quality Assessment For each scan, describe the overall image quality, noting any artifacts or limitations that may affect your analysis. Step 2: Layer-by-Layer Analysis Across All Scans Analyze each of the retinal layers across all provided scans, describing: • Thickness patterns: Note any variations or consistencies in layer thickness • Morphological changes: Compare layer appearance across scans • Reflectivity patterns: Identify any recurring patterns or changes • Document abnormalities and their distribution across scans Step 3: Comprehensive Foveal Analysis Analyze the foveal region across all scans: • Compare foveal contour and thickness • Note any consistent or varying abnormalities • Identify patterns of foveal involvement Step 4: Integrated Abnormality Assessment Provide a unified analysis of abnormalities across all scans: • Distribution patterns • Progression or variation in appearance • Relationship between findings in different scans Step 5: Differential Diagnoses Based on the comprehensive analysis: • List potential diagnoses supported by findings across multiple scans • Explain how the pattern of findings supports each diagnosis • Note any temporal or spatial progression that helps narrow the diagnosis Step 6: Most Likely Diagnosis Provide a unified diagnosis considering all scans: • Explain how the combined findings support this diagnosis • Discuss any progression or pattern that confirms the diagnosis • Address any variations or inconsistencies Step 7: Recommendations Suggest: • Additional tests or imaging if needed • Follow-up scanning recommendations • Treatment considerations based on the comprehensive analysis""" COMPARISON_PROMPT = """You are an expert ophthalmologist specializing in interpreting macular Optical Coherence Tomography (OCT) scans. Your goal is to provide an accurate description and a possible diagnosis, supported by clear medical reasoning. These scans are from the same patient at two different timepoints. Please provide a comprehensive analysis and comparison. Step 1: Image Quality Assessment For each set of scans, describe the overall image quality, noting any artifacts or limitations that may affect your analysis. Step 2: Layer-by-Layer Comparison Compare the retinal layers between timepoints: • Changes in thickness patterns • Evolution of morphological features • Alterations in reflectivity patterns • Progression or regression of abnormalities Step 3: Foveal Evolution Analysis Compare the foveal region between timepoints: • Changes in contour and thickness • Evolution of abnormalities • Progression or improvement patterns Step 4: Disease Progression Assessment Analyze changes between timepoints: • Quantify and describe changes in abnormalities • Identify new or resolved findings • Assess overall disease progression or improvement Step 5: Treatment Response Evaluation If treatment was administered: • Evaluate effectiveness • Identify areas of improvement • Note resistant or worsening areas Step 6: Updated Diagnosis and Prognosis Based on the temporal comparison: • Confirm or revise previous diagnosis • Assess disease trajectory • Provide prognostic insights Step 7: Recommendations Suggest: • Treatment modifications if needed • Follow-up interval • Additional testing if required • Preventive measures""" TREATMENT_GUIDELINES_PROMPT = """Based on the current diagnosis and findings, please provide evidence-based treatment recommendations following established ophthalmological guidelines. Consider: 1. Standard of Care • First-line treatments • Alternative options • Contraindications 2. Treatment Plan • Immediate interventions • Long-term management • Follow-up schedule 3. Monitoring Parameters • Key metrics to track • Warning signs • Success indicators 4. Patient Education • Lifestyle modifications • Self-monitoring instructions • Prevention strategies""" def extract_pdf_text(pdf_file): """Extract text from uploaded PDF file""" pdf_reader = PyPDF2.PdfReader(pdf_file) text = "" for page in pdf_reader.pages: text += page.extract_text() return text def analyze_oct_images(images, timepoint=None, patient_data=None): """Analyze OCT images with optional timepoint and patient data""" if timepoint: prompt = f"{SINGLE_TIMEPOINT_PROMPT}\n\nTimepoint: {timepoint}\n" else: prompt = f"{SINGLE_TIMEPOINT_PROMPT}\n" if patient_data: prompt += f"\nPatient Information:\n{patient_data}\n" prompt += "\nPlease analyze these OCT scans:" content = [prompt] + images response = model.generate_content(content) return response.text def compare_oct_timepoints(images1, date1, images2, date2, patient_data=None): """Compare OCT images from two timepoints""" prompt = f"{COMPARISON_PROMPT}\n\nTimepoint 1: {date1}\nTimepoint 2: {date2}\n" if patient_data: prompt += f"\nPatient Information:\n{patient_data}\n" prompt += "\nPlease compare these OCT scans:" content = [prompt] + images1 + images2 response = model.generate_content(content) return response.text def get_treatment_recommendations(diagnosis, findings): """Get treatment recommendations based on guidelines""" prompt = f"{TREATMENT_GUIDELINES_PROMPT}\n\nDiagnosis: {diagnosis}\nFindings: {findings}" response = model.generate_content(prompt) return response.text def main(): # Header with custom styling st.markdown("""
Developed by Dr. Fernando Ly
This tool assists in the analysis of OCT retina scans using advanced AI technology. It provides detailed layer analysis and potential diagnoses to support clinical decision-making.
Note: This tool is for assistance only and should not replace professional medical judgment.