ferferefer's picture
Upload 4 files
ceb250f verified
raw
history blame
9.77 kB
import gradio as gr
import os
from huggingface_hub import InferenceClient
from typing import List, Dict
import PyPDF2
import tempfile
# Initialize the client using environment variable
client = InferenceClient(
provider="together",
api_key=os.environ.get("TOGETHER_API_KEY")
)
# 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. 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."""
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 format_message(role: str, content: str) -> Dict[str, str]:
return {"role": role, "content": content}
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:
# Format conversation history
messages = [format_message("system", SYSTEM_PROMPT)]
# Add doctor's letter if provided
if doctor_letter and doctor_letter.strip():
messages.append(format_message("system", f"Doctor's letter content: {doctor_letter}"))
# Add PDF content if provided
if pdf_content and pdf_content.strip():
messages.append(format_message("system", f"Additional medical documents content: {pdf_content}"))
# Add conversation history
for user_msg, assistant_msg in history:
messages.append(format_message("user", user_msg))
messages.append(format_message("assistant", assistant_msg))
# Add current message
messages.append(format_message("user", message))
try:
# Get response from the model
completion = client.chat.completions.create(
model="deepseek-ai/DeepSeek-R1",
messages=messages,
max_tokens=500
)
response = completion.choices[0].message.content
return response
except Exception as 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()