med / app.py
mgbam's picture
Update app.py
81dc1a4 verified
raw
history blame
16.9 kB
import streamlit as st
import google.generativeai as genai
import os
from PIL import Image
import io # Needed for handling image bytes
from typing import Optional, Tuple, Any # For type hinting
# --- Page Configuration (MUST BE THE FIRST STREAMLIT COMMAND) ---
st.set_page_config(
page_title="AI Clinical Support Demonstrator",
layout="wide",
initial_sidebar_state="expanded"
)
# --- Introductory Explanation ---
st.markdown(
"""
### Welcome to the AI Clinical Support Demonstrator
This application demonstrates how Generative AI (Google Gemini) can be guided to assist with analyzing clinical information.
- **Agentic Text Analysis:** Simulates a structured reasoning process on clinical text to identify key findings, suggest considerations, and note information gaps.
- **Medical Image Analysis:** Provides descriptive observations of potential anomalies in medical images.
**Crucially, this tool is for demonstration purposes ONLY. It does NOT provide medical advice or diagnosis.**
"""
)
st.markdown("---") # Visual separator
# --- Configuration and Initialization ---
# Securely load API key (Secrets > Env Var)
GEMINI_API_KEY = st.secrets.get("GEMINI_API_KEY", os.environ.get("GEMINI_API_KEY"))
# Configure Gemini Client
genai_client_configured = False
if GEMINI_API_KEY:
try:
genai.configure(api_key=GEMINI_API_KEY)
genai_client_configured = True
except Exception as e:
st.error(f"Fatal Error: Failed to configure Google Generative AI. Check API Key. Details: {e}", icon="🚨")
st.stop()
else:
st.error("⚠️ Gemini API Key not found. Please configure `GEMINI_API_KEY` in Streamlit secrets or environment variables.", icon="πŸ”‘")
st.stop()
# Initialize models
TEXT_MODEL_NAME = 'gemini-1.5-pro-latest' # For agentic text reasoning
VISION_MODEL_NAME = 'gemini-1.5-flash' # For image analysis
# Use session state to initialize models only once
if 'models_initialized' not in st.session_state:
st.session_state.models_initialized = False
st.session_state.text_model = None
st.session_state.vision_model = None
if genai_client_configured and not st.session_state.models_initialized:
try:
st.session_state.text_model = genai.GenerativeModel(TEXT_MODEL_NAME)
st.session_state.vision_model = genai.GenerativeModel(VISION_MODEL_NAME)
st.session_state.models_initialized = True
# Display success message subtly in sidebar perhaps, or remove if too noisy
# st.sidebar.success("AI Models Ready.", icon="βœ…")
except Exception as e:
st.error(f"Fatal Error: Failed to initialize Gemini models. Text: {TEXT_MODEL_NAME}, Vision: {VISION_MODEL_NAME}. Details: {e}", icon="πŸ’₯")
st.stop()
elif not genai_client_configured:
# Should have stopped already, but defensive check
st.error("AI Models could not be initialized due to configuration issues.", icon="🚫")
st.stop()
# --- Core AI Interaction Functions ---
# Refined AGENTIC prompt for Text Analysis with formatting request
AGENTIC_TEXT_ANALYSIS_PROMPT_TEMPLATE = """
**Simulated Clinical Reasoning Agent Task:**
**Role:** AI assistant simulating an agentic clinical reasoning process to support a healthcare professional by structuring information, generating possibilities, and suggesting investigation pathways based *strictly* on the provided text. **This is NOT a diagnosis.**
**Input Data:** Unstructured clinical information (e.g., symptoms, history, basic findings).
**Output Format:** Please structure your response using Markdown headings for each step (e.g., `## 1. Information Extraction`).
**Simulated Agentic Steps (Perform sequentially):**
1. **Information Extraction & Structuring:**
* Key Demographics (Age, Sex if provided).
* Primary Symptoms/Signs.
* Relevant Medical History.
* Pertinent Negatives (if mentioned).
2. **Differential Considerations Generation:**
* Based *only* on Step 1, list **potential differential considerations** (possible conditions).
* **Use cautious language:** "could be consistent with," "warrants consideration," "less likely but possible." **AVOID definitive statements.**
* Briefly justify each consideration based on findings.
3. **Information Gap Analysis:**
* Identify critical missing information (e.g., lab results, imaging, exam specifics, duration/onset).
4. **Suggested Next Steps for Investigation (for Clinician):**
* Propose logical next steps a **healthcare professional might consider**.
* Categorize (e.g., Further History, Exam Points, Labs, Imaging).
* Frame as *suggestions* (e.g., "Consider ordering...", "Assessment of X may be informative").
5. **Mandatory Disclaimer:** Conclude with: "This AI-generated analysis is for informational support only. It is **NOT** a diagnosis and cannot replace the judgment of a qualified healthcare professional."
**Input Clinical Information:**
---
{text_input}
---
**Agentic Analysis:**
"""
# Refined prompt for Image Analysis with formatting request
IMAGE_ANALYSIS_PROMPT_TEMPLATE = """
**Medical Image Analysis Request:**
**Context:** Analyze the provided medical image. User may provide additional context or questions.
**Output Format:** Please structure your response using Markdown headings for each step (e.g., `## 1. Visible Structures`).
**Task:**
1. **Describe Visible Structures:** Briefly describe main anatomical structures.
2. **Identify Potential Anomalies:** Point out areas that *appear* abnormal or deviate from typical presentation (e.g., "potential opacity," "altered signal intensity," "possible asymmetry"). Use cautious, descriptive language. **This is not a definitive finding.**
3. **Correlate with User Prompt (if provided):** Address specific user questions based *only* on visual information. State if the image cannot answer the question.
4. **Limitations:** State that image quality, view, lack of clinical context, and the AI's nature limit analysis.
5. **Mandatory Disclaimer:** Explicitly state this is AI visual analysis, not radiological interpretation or diagnosis, requiring review by a qualified professional with clinical context.
**User's Additional Context/Question (if any):**
---
{user_prompt}
---
**Image Analysis:**
"""
def run_agentic_text_analysis(text_input: str) -> Tuple[Optional[str], Optional[str]]:
"""Sends clinical text to the configured text model for simulated agentic analysis."""
if not text_input or not text_input.strip():
return None, "Input text cannot be empty."
if not st.session_state.models_initialized or not st.session_state.text_model:
return None, "Text analysis model not initialized."
try:
prompt = AGENTIC_TEXT_ANALYSIS_PROMPT_TEMPLATE.format(text_input=text_input)
response = st.session_state.text_model.generate_content(prompt)
if response.parts:
return response.text, None
elif response.prompt_feedback.block_reason:
return None, f"Analysis blocked by safety filters: {response.prompt_feedback.block_reason.name}. Review input."
else:
candidate = response.candidates[0] if response.candidates else None
if candidate and candidate.finish_reason != "STOP":
return None, f"Analysis stopped prematurely. Reason: {candidate.finish_reason.name}."
else:
return None, "Received an empty or unexpected response from the AI model."
except Exception as e:
print(f"ERROR in run_agentic_text_analysis: {e}") # Basic server-side log
st.error("An error occurred during text analysis.", icon="🚨") # User-facing error
return None, "An internal error occurred during text analysis. Please try again later."
def analyze_medical_image(image_file: Any, user_prompt: str = "") -> Tuple[Optional[str], Optional[str]]:
"""Sends a medical image to the configured vision model for analysis."""
if not image_file:
return None, "Image file cannot be empty."
if not st.session_state.models_initialized or not st.session_state.vision_model:
return None, "Image analysis model not initialized."
try:
try:
image = Image.open(image_file)
# Convert to RGB ensure compatibility, common requirement for vision models
if image.mode != 'RGB':
image = image.convert('RGB')
except Exception as img_e:
return None, f"Error opening or processing the uploaded image file: {img_e}"
prompt_text = IMAGE_ANALYSIS_PROMPT_TEMPLATE.format(user_prompt=user_prompt if user_prompt else "N/A")
model_input = [prompt_text, image]
response = st.session_state.vision_model.generate_content(model_input)
if response.parts:
return response.text, None
elif response.prompt_feedback.block_reason:
return None, f"Image analysis blocked by safety filters: {response.prompt_feedback.block_reason.name}. This may relate to sensitive content policies."
else:
candidate = response.candidates[0] if response.candidates else None
if candidate and candidate.finish_reason != "STOP":
return None, f"Image analysis stopped prematurely. Reason: {candidate.finish_reason.name}."
else:
return None, "Received an empty or unexpected response from the AI model for image analysis."
except Exception as e:
print(f"ERROR in analyze_medical_image: {e}") # Basic server-side log
st.error("An error occurred during image analysis.", icon="πŸ–ΌοΈ") # User-facing error
return None, "An internal error occurred during image analysis. Please try again later."
# --- Streamlit User Interface ---
def main():
# Page title and model info
st.title("πŸ€– AI Clinical Support Demonstrator")
st.caption(f"Utilizing: Text Model ({TEXT_MODEL_NAME}), Vision Model ({VISION_MODEL_NAME})")
# --- CRITICAL DISCLAIMER ---
# Positioned prominently after title/intro
st.warning(
"""
**πŸ”΄ IMPORTANT SAFETY & USE DISCLAIMER πŸ”΄**
* This tool **DEMONSTRATES** AI capabilities. It **DOES NOT** provide medical advice or diagnosis.
* **Agentic Text Analysis:** Simulates reasoning on text input. Output is illustrative, not diagnostic.
* **Image Analysis:** Provides observations on images. Output is **NOT** a radiological interpretation.
* AI analysis lacks full clinical context, may be inaccurate, and **CANNOT** replace professional judgment.
* **ALWAYS consult qualified healthcare professionals** for diagnosis and treatment.
* **PRIVACY:** Do **NOT** upload identifiable patient information (PHI) without explicit consent and adherence to all privacy laws (e.g., HIPAA). You are responsible for the data you input.
""",
icon="⚠️"
)
st.markdown("---")
# --- Sidebar Controls ---
st.sidebar.header("Analysis Options")
input_method = st.sidebar.radio(
"Select Analysis Type:",
("Agentic Text Analysis", "Medical Image Analysis"),
key="input_method_radio",
help="Choose 'Agentic Text Analysis' for reasoning simulation on clinical text, or 'Medical Image Analysis' for visual observations on images."
)
st.sidebar.markdown("---") # Visual separator
# --- Main Area Layout (Input and Output Columns) ---
col1, col2 = st.columns(2)
analysis_result = None # Initialize results variables for this run
error_message = None
output_header = "Analysis Results" # Default header
# --- Column 1: Input Area ---
with col1:
st.header("Input Data")
# Conditional Input UI based on selection
if input_method == "Agentic Text Analysis":
st.subheader("Clinical Text for Agentic Analysis")
st.caption("Please ensure data is de-identified before pasting.")
text_input = st.text_area(
"Paste clinical information:",
height=350,
placeholder="Example: 68yo male, sudden SOB & pleuritic chest pain post-flight. HR 110, SpO2 92% RA. No known cardiac hx...",
key="text_input_area"
)
analyze_button_key = "analyze_text_button"
analyze_button_label = "▢️ Run Agentic Text Analysis"
if st.button(analyze_button_label, key=analyze_button_key, type="primary"):
if text_input:
with st.spinner("🧠 Simulating agentic reasoning..."):
analysis_result, error_message = run_agentic_text_analysis(text_input)
output_header = "Simulated Agentic Analysis Output"
else:
st.warning("Please enter clinical text to analyze.", icon="☝️")
elif input_method == "Medical Image Analysis":
st.subheader("Medical Image for Analysis")
st.caption("Upload a de-identified medical image (PNG, JPG, JPEG).")
image_file = st.file_uploader(
"Choose an image file:",
type=["png", "jpg", "jpeg"],
key="image_uploader"
)
user_image_prompt = st.text_input(
"Optional: Add context or specific question for image analysis:",
placeholder="Example: 'Describe findings in the lung fields' or 'Any visible fractures?'",
key="image_prompt_input"
)
analyze_button_key = "analyze_image_button"
analyze_button_label = "πŸ–ΌοΈ Analyze Medical Image"
if image_file:
# Display preview immediately after upload inside the input column
st.image(image_file, caption="Uploaded Image Preview", use_column_width=True)
if st.button(analyze_button_label, key=analyze_button_key, type="primary"):
if image_file:
with st.spinner("πŸ‘οΈ Analyzing image..."):
analysis_result, error_message = analyze_medical_image(image_file, user_image_prompt)
output_header = "Medical Image Analysis Output"
else:
st.warning("Please upload an image file to analyze.", icon="☝️")
# --- Column 2: Output Area ---
with col2:
st.header(output_header)
# Display results or errors if an analysis was attempted
# Check if button was pressed and corresponding result/error exists
button_pressed = st.session_state.get(analyze_button_key, False) if 'analyze_button_key' in locals() else False
if button_pressed and (analysis_result or error_message):
if error_message:
st.error(f"Analysis Failed: {error_message}", icon="❌")
elif analysis_result:
# Use st.markdown to render potential formatting from AI
st.markdown(analysis_result)
elif not button_pressed :
st.info("Analysis results will appear here after providing input and clicking the corresponding analysis button.")
# Add a condition for button pressed but no input provided (already handled by st.warning in col1)
# --- Sidebar Explanations ---
st.sidebar.markdown("---")
st.sidebar.header("About The Prompts")
with st.sidebar.expander("View Agentic Text Prompt Structure", icon="πŸ“„"):
st.markdown(f"```plaintext\n{AGENTIC_TEXT_ANALYSIS_PROMPT_TEMPLATE.split('---')[0]} ... [Input Text] ...\n```")
st.caption("Guides the AI through structured reasoning steps for text.")
with st.sidebar.expander("View Image Analysis Prompt Structure", icon="πŸ–ΌοΈ"):
st.markdown(f"```plaintext\n{IMAGE_ANALYSIS_PROMPT_TEMPLATE.split('---')[0]} ... [User Prompt] ...\n```")
st.caption("Guides the AI to describe visual features and potential anomalies in images.")
st.sidebar.markdown("---")
st.sidebar.error(
"**Ethical Use Reminder:** AI in medicine requires extreme caution. This tool is for demonstration and education, not clinical practice. Verify all information and rely on professional expertise.",
icon = "βš•οΈ"
)
# --- Main Execution Guard ---
if __name__ == "__main__":
# Check if models are initialized before running the main UI components
if st.session_state.models_initialized:
main()
else:
# If models failed to initialize, errors would have been shown already.
# We might add a placeholder or further message here if needed.
st.info("Waiting for model initialization...") # Or check specific errors if needed
# The script might stop earlier if initialization fails critically.