ferferefer's picture
Upload 2 files
1f60b55 verified
import gradio as gr
import os
import google.generativeai as genai
from typing import List, Dict
import PyPDF2
import tempfile
# Initialize the Gemini model
api_key = os.environ.get("GEMINI_API_KEY")
genai.configure(api_key=api_key)
model = genai.GenerativeModel('gemini-2.0-flash-exp')
# System prompt
SYSTEM_PROMPT = """You are an AI assistant specialized in providing information and support to glaucoma patients. Your goal is to help patients understand glaucoma, treatment options, and related care. You can provide general information on glaucoma and related topics, however, your answers will always be general advice. You cannot provide medical advice.
Regarding the "Holiday Drop" concept:
When a patient is preparing for glaucoma surgery, they typically need to follow a specific protocol called the "holiday drop" period. This involves:
1. Stopping glaucoma eye drops ONLY in the eye that will be operated on
2. Taking oral acetazolamide as prescribed
3. Maintaining proper potassium levels by eating bananas
4. Using Softacort as directed
5. CONTINUING to use eye drops in the other eye (the non-surgical eye)
This protocol helps reduce inflammation and increases the likelihood of surgical success.
If a patient provides you with their doctor's letter, you must base your answers on the content of the letter provided and any additional information you provide must be from the letter. Prioritize the information provided in the doctor's letter. If the doctor's letter does not answer the question, then respond that you do not know. If the user asks for medical advice, always tell them that you are an AI and cannot provide medical advice, and tell them to consult with their doctor instead. Be polite and supportive.
When discussing the holiday drop protocol:
- Always emphasize that the timing and specific instructions must come from their doctor
- Stress the importance of continuing drops in the non-surgical eye
- Remind them about oral acetazolamide, potassium intake (bananas), and Softacort
- Emphasize that these are general guidelines and their doctor's specific instructions take precedence
You can provide general information about:
- What glaucoma is and how it affects vision
- Common treatment approaches
- General pre and post-operative care
- Terminology explanation from doctor's letters
- The holiday drop concept and its importance
- The role of different medications
Always remind patients to:
1. Follow their doctor's specific instructions
2. Not stop any medication without doctor approval
3. Continue all prescribed treatments for the non-surgical eye
4. Maintain regular follow-up appointments
5. Report any concerning symptoms to their doctor immediately"""
def format_message(role: str, content: str) -> Dict[str, str]:
return {"role": role, "content": content}
def extract_text_from_pdf(pdf_file) -> str:
if pdf_file is None:
return ""
# Create a temporary file to save the uploaded PDF
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as temp_pdf:
temp_pdf.write(pdf_file)
temp_pdf_path = temp_pdf.name
try:
# Open the PDF file
with open(temp_pdf_path, 'rb') as file:
# Create a PDF reader object
pdf_reader = PyPDF2.PdfReader(file)
# Extract text from all pages
text = ""
for page in pdf_reader.pages:
text += page.extract_text() + "\n"
return text.strip()
except Exception as e:
return f"Error processing PDF: {str(e)}"
finally:
# Clean up the temporary file
if os.path.exists(temp_pdf_path):
os.unlink(temp_pdf_path)
def process_uploaded_files(files) -> str:
if not files:
return ""
all_text = []
for file in files:
text = extract_text_from_pdf(file)
if text:
all_text.append(text)
return "\n\n=== Next Document ===\n\n".join(all_text)
def chat_with_bot(message: str, history: List[List[str]], doctor_letter: str = None, pdf_content: str = None) -> tuple:
try:
# Initialize messages list with system prompt if it's the first message
messages = []
context = SYSTEM_PROMPT
if doctor_letter and doctor_letter.strip():
context += f"\n\nDoctor's letter content: {doctor_letter}"
if pdf_content and pdf_content.strip():
context += f"\n\nAdditional medical documents content: {pdf_content}"
# Format conversation history for Gemini
prompt = context + "\n\nConversation history:\n"
for user_msg, assistant_msg in history:
prompt += f"User: {user_msg}\nAssistant: {assistant_msg}\n"
# Add current message
prompt += f"User: {message}\nAssistant:"
# Get completion from the model
completion = model.generate_content(prompt)
# Extract the response
response = completion.text
# Debug print
print("API Response:", response)
return response
except Exception as e:
print(f"Error: {str(e)}")
return f"I apologize, but I encountered an error: {str(e)}. Please try again or contact support if the issue persists."
with gr.Blocks(
theme=gr.themes.Soft(
primary_hue="blue",
secondary_hue="gray",
),
css="""
.container { max-width: 900px; margin: auto; padding: 20px; }
.header { text-align: center; margin-bottom: 30px; }
.header h1 { font-size: 2.5em; color: #2C3E50; margin-bottom: 20px; }
.header p { font-size: 1.2em; line-height: 1.6; color: #34495E; }
.upload-section {
background: #f8f9fa;
padding: 25px;
border-radius: 15px;
margin-bottom: 30px;
border: 2px solid #E0E5EC;
}
.upload-section label { font-size: 1.2em; color: #2C3E50; }
.chat-section {
background: white;
padding: 25px;
border-radius: 15px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.help-section {
background: #EBF5FB;
padding: 20px;
border-radius: 15px;
margin: 20px 0;
}
.help-section h3 {
color: #2C3E50;
font-size: 1.4em;
margin-bottom: 15px;
}
.help-section ul {
font-size: 1.1em;
line-height: 1.6;
}
footer {
text-align: center;
margin-top: 30px;
padding: 20px;
color: #34495E;
font-size: 1.1em;
background: #f8f9fa;
border-radius: 15px;
}
.button-primary { font-size: 1.2em !important; }
.button-secondary { font-size: 1.1em !important; }
"""
) as demo:
with gr.Column(elem_classes="container"):
gr.Markdown(
"""
# ๐Ÿ‘๏ธ Glaucoma Support Assistant
Welcome! I'm here to help you understand glaucoma and provide general information about eye care.
Please remember that I cannot provide medical advice - always consult your doctor for specific guidance.
**Need help?** Just type your question below or upload your doctor's letter for more specific information.
""",
elem_classes="header"
)
with gr.Column(elem_classes="upload-section"):
gr.Markdown(
"""
### ๐Ÿ“„ Share Your Medical Documents (Optional)
You can either:
1. Copy and paste your doctor's letter in the text box below, or
2. Upload PDF documents using the upload button
""",
)
doctor_letter = gr.TextArea(
label="Type or Paste Doctor's Letter Here",
placeholder="You can copy and paste your doctor's letter here. This will help me provide more specific information based on your case.",
lines=4
)
pdf_files = gr.File(
label="Or Upload Medical Documents (PDF files)",
file_types=[".pdf"],
file_count="multiple"
)
with gr.Column(elem_classes="chat-section"):
chatbot = gr.Chatbot(
label="Our Conversation",
height=400,
bubble_full_width=False,
show_copy_button=True,
container=True
)
with gr.Row():
msg = gr.Textbox(
label="Type your question here",
placeholder="What would you like to know about glaucoma?",
lines=2,
scale=9
)
submit_btn = gr.Button("Send Question", scale=1, variant="primary", elem_classes="button-primary")
clear = gr.Button("Start New Conversation", variant="secondary", elem_classes="button-secondary")
with gr.Column(elem_classes="help-section"):
gr.Markdown(
"""
### ๐Ÿ’ก Examples of Questions You Can Ask:
- What is glaucoma and how does it affect my eyes?
- What are the common treatments for glaucoma?
- What should I expect before and after eye surgery?
- Can you explain the terms in my doctor's letter?
- What are the different types of eye drops used for glaucoma?
**Remember:** For specific medical advice, always consult your eye doctor.
"""
)
gr.Markdown(
"""
---
### โš ๏ธ Important Notice
This AI assistant provides general information only and is not a substitute for professional medical advice.
Always consult your healthcare provider for medical guidance.
""",
elem_classes="footer"
)
# Store PDF content in state
pdf_content = gr.State("")
def update_pdf_content(files):
return process_uploaded_files(files)
def respond(message, chat_history, doctor_letter_text, current_pdf_content):
if not message.strip():
return "", chat_history
bot_message = chat_with_bot(message, chat_history, doctor_letter_text, current_pdf_content)
chat_history.append((message, bot_message))
return "", chat_history
# Update PDF content when files are uploaded
pdf_files.change(
fn=update_pdf_content,
inputs=[pdf_files],
outputs=[pdf_content]
)
# Handle message submission
msg.submit(
respond,
inputs=[msg, chatbot, doctor_letter, pdf_content],
outputs=[msg, chatbot]
)
submit_btn.click(
respond,
inputs=[msg, chatbot, doctor_letter, pdf_content],
outputs=[msg, chatbot]
)
# Handle conversation clearing
clear.click(lambda: ([], ""), outputs=[chatbot, pdf_content])
demo.queue()
demo.launch()