ferferefer commited on
Commit
1f60b55
·
verified ·
1 Parent(s): 51e3105

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +290 -0
  2. requirements.txt +4 -0
app.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import google.generativeai as genai
4
+ from typing import List, Dict
5
+ import PyPDF2
6
+ import tempfile
7
+
8
+ # Initialize the Gemini model
9
+ api_key = os.environ.get("GEMINI_API_KEY")
10
+ genai.configure(api_key=api_key)
11
+ model = genai.GenerativeModel('gemini-2.0-flash-exp')
12
+
13
+ # System prompt
14
+ 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.
15
+
16
+ Regarding the "Holiday Drop" concept:
17
+ When a patient is preparing for glaucoma surgery, they typically need to follow a specific protocol called the "holiday drop" period. This involves:
18
+ 1. Stopping glaucoma eye drops ONLY in the eye that will be operated on
19
+ 2. Taking oral acetazolamide as prescribed
20
+ 3. Maintaining proper potassium levels by eating bananas
21
+ 4. Using Softacort as directed
22
+ 5. CONTINUING to use eye drops in the other eye (the non-surgical eye)
23
+ This protocol helps reduce inflammation and increases the likelihood of surgical success.
24
+
25
+ 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.
26
+
27
+ When discussing the holiday drop protocol:
28
+ - Always emphasize that the timing and specific instructions must come from their doctor
29
+ - Stress the importance of continuing drops in the non-surgical eye
30
+ - Remind them about oral acetazolamide, potassium intake (bananas), and Softacort
31
+ - Emphasize that these are general guidelines and their doctor's specific instructions take precedence
32
+
33
+ You can provide general information about:
34
+ - What glaucoma is and how it affects vision
35
+ - Common treatment approaches
36
+ - General pre and post-operative care
37
+ - Terminology explanation from doctor's letters
38
+ - The holiday drop concept and its importance
39
+ - The role of different medications
40
+
41
+ Always remind patients to:
42
+ 1. Follow their doctor's specific instructions
43
+ 2. Not stop any medication without doctor approval
44
+ 3. Continue all prescribed treatments for the non-surgical eye
45
+ 4. Maintain regular follow-up appointments
46
+ 5. Report any concerning symptoms to their doctor immediately"""
47
+
48
+ def format_message(role: str, content: str) -> Dict[str, str]:
49
+ return {"role": role, "content": content}
50
+
51
+ def extract_text_from_pdf(pdf_file) -> str:
52
+ if pdf_file is None:
53
+ return ""
54
+
55
+ # Create a temporary file to save the uploaded PDF
56
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as temp_pdf:
57
+ temp_pdf.write(pdf_file)
58
+ temp_pdf_path = temp_pdf.name
59
+
60
+ try:
61
+ # Open the PDF file
62
+ with open(temp_pdf_path, 'rb') as file:
63
+ # Create a PDF reader object
64
+ pdf_reader = PyPDF2.PdfReader(file)
65
+
66
+ # Extract text from all pages
67
+ text = ""
68
+ for page in pdf_reader.pages:
69
+ text += page.extract_text() + "\n"
70
+
71
+ return text.strip()
72
+ except Exception as e:
73
+ return f"Error processing PDF: {str(e)}"
74
+ finally:
75
+ # Clean up the temporary file
76
+ if os.path.exists(temp_pdf_path):
77
+ os.unlink(temp_pdf_path)
78
+
79
+ def process_uploaded_files(files) -> str:
80
+ if not files:
81
+ return ""
82
+
83
+ all_text = []
84
+ for file in files:
85
+ text = extract_text_from_pdf(file)
86
+ if text:
87
+ all_text.append(text)
88
+
89
+ return "\n\n=== Next Document ===\n\n".join(all_text)
90
+
91
+ def chat_with_bot(message: str, history: List[List[str]], doctor_letter: str = None, pdf_content: str = None) -> tuple:
92
+ try:
93
+ # Initialize messages list with system prompt if it's the first message
94
+ messages = []
95
+ context = SYSTEM_PROMPT
96
+ if doctor_letter and doctor_letter.strip():
97
+ context += f"\n\nDoctor's letter content: {doctor_letter}"
98
+ if pdf_content and pdf_content.strip():
99
+ context += f"\n\nAdditional medical documents content: {pdf_content}"
100
+
101
+ # Format conversation history for Gemini
102
+ prompt = context + "\n\nConversation history:\n"
103
+ for user_msg, assistant_msg in history:
104
+ prompt += f"User: {user_msg}\nAssistant: {assistant_msg}\n"
105
+
106
+ # Add current message
107
+ prompt += f"User: {message}\nAssistant:"
108
+
109
+ # Get completion from the model
110
+ completion = model.generate_content(prompt)
111
+
112
+ # Extract the response
113
+ response = completion.text
114
+
115
+ # Debug print
116
+ print("API Response:", response)
117
+
118
+ return response
119
+
120
+ except Exception as e:
121
+ print(f"Error: {str(e)}")
122
+ return f"I apologize, but I encountered an error: {str(e)}. Please try again or contact support if the issue persists."
123
+
124
+ with gr.Blocks(
125
+ theme=gr.themes.Soft(
126
+ primary_hue="blue",
127
+ secondary_hue="gray",
128
+ ),
129
+ css="""
130
+ .container { max-width: 900px; margin: auto; padding: 20px; }
131
+ .header { text-align: center; margin-bottom: 30px; }
132
+ .header h1 { font-size: 2.5em; color: #2C3E50; margin-bottom: 20px; }
133
+ .header p { font-size: 1.2em; line-height: 1.6; color: #34495E; }
134
+ .upload-section {
135
+ background: #f8f9fa;
136
+ padding: 25px;
137
+ border-radius: 15px;
138
+ margin-bottom: 30px;
139
+ border: 2px solid #E0E5EC;
140
+ }
141
+ .upload-section label { font-size: 1.2em; color: #2C3E50; }
142
+ .chat-section {
143
+ background: white;
144
+ padding: 25px;
145
+ border-radius: 15px;
146
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
147
+ }
148
+ .help-section {
149
+ background: #EBF5FB;
150
+ padding: 20px;
151
+ border-radius: 15px;
152
+ margin: 20px 0;
153
+ }
154
+ .help-section h3 {
155
+ color: #2C3E50;
156
+ font-size: 1.4em;
157
+ margin-bottom: 15px;
158
+ }
159
+ .help-section ul {
160
+ font-size: 1.1em;
161
+ line-height: 1.6;
162
+ }
163
+ footer {
164
+ text-align: center;
165
+ margin-top: 30px;
166
+ padding: 20px;
167
+ color: #34495E;
168
+ font-size: 1.1em;
169
+ background: #f8f9fa;
170
+ border-radius: 15px;
171
+ }
172
+ .button-primary { font-size: 1.2em !important; }
173
+ .button-secondary { font-size: 1.1em !important; }
174
+ """
175
+ ) as demo:
176
+ with gr.Column(elem_classes="container"):
177
+ gr.Markdown(
178
+ """
179
+ # 👁️ Glaucoma Support Assistant
180
+
181
+ Welcome! I'm here to help you understand glaucoma and provide general information about eye care.
182
+ Please remember that I cannot provide medical advice - always consult your doctor for specific guidance.
183
+
184
+ **Need help?** Just type your question below or upload your doctor's letter for more specific information.
185
+ """,
186
+ elem_classes="header"
187
+ )
188
+
189
+ with gr.Column(elem_classes="upload-section"):
190
+ gr.Markdown(
191
+ """
192
+ ### 📄 Share Your Medical Documents (Optional)
193
+ You can either:
194
+ 1. Copy and paste your doctor's letter in the text box below, or
195
+ 2. Upload PDF documents using the upload button
196
+ """,
197
+ )
198
+ doctor_letter = gr.TextArea(
199
+ label="Type or Paste Doctor's Letter Here",
200
+ placeholder="You can copy and paste your doctor's letter here. This will help me provide more specific information based on your case.",
201
+ lines=4
202
+ )
203
+
204
+ pdf_files = gr.File(
205
+ label="Or Upload Medical Documents (PDF files)",
206
+ file_types=[".pdf"],
207
+ file_count="multiple"
208
+ )
209
+
210
+ with gr.Column(elem_classes="chat-section"):
211
+ chatbot = gr.Chatbot(
212
+ label="Our Conversation",
213
+ height=400,
214
+ bubble_full_width=False,
215
+ show_copy_button=True,
216
+ container=True
217
+ )
218
+
219
+ with gr.Row():
220
+ msg = gr.Textbox(
221
+ label="Type your question here",
222
+ placeholder="What would you like to know about glaucoma?",
223
+ lines=2,
224
+ scale=9
225
+ )
226
+ submit_btn = gr.Button("Send Question", scale=1, variant="primary", elem_classes="button-primary")
227
+
228
+ clear = gr.Button("Start New Conversation", variant="secondary", elem_classes="button-secondary")
229
+
230
+ with gr.Column(elem_classes="help-section"):
231
+ gr.Markdown(
232
+ """
233
+ ### 💡 Examples of Questions You Can Ask:
234
+ - What is glaucoma and how does it affect my eyes?
235
+ - What are the common treatments for glaucoma?
236
+ - What should I expect before and after eye surgery?
237
+ - Can you explain the terms in my doctor's letter?
238
+ - What are the different types of eye drops used for glaucoma?
239
+
240
+ **Remember:** For specific medical advice, always consult your eye doctor.
241
+ """
242
+ )
243
+
244
+ gr.Markdown(
245
+ """
246
+ ---
247
+ ### ⚠️ Important Notice
248
+ This AI assistant provides general information only and is not a substitute for professional medical advice.
249
+ Always consult your healthcare provider for medical guidance.
250
+ """,
251
+ elem_classes="footer"
252
+ )
253
+
254
+ # Store PDF content in state
255
+ pdf_content = gr.State("")
256
+
257
+ def update_pdf_content(files):
258
+ return process_uploaded_files(files)
259
+
260
+ def respond(message, chat_history, doctor_letter_text, current_pdf_content):
261
+ if not message.strip():
262
+ return "", chat_history
263
+ bot_message = chat_with_bot(message, chat_history, doctor_letter_text, current_pdf_content)
264
+ chat_history.append((message, bot_message))
265
+ return "", chat_history
266
+
267
+ # Update PDF content when files are uploaded
268
+ pdf_files.change(
269
+ fn=update_pdf_content,
270
+ inputs=[pdf_files],
271
+ outputs=[pdf_content]
272
+ )
273
+
274
+ # Handle message submission
275
+ msg.submit(
276
+ respond,
277
+ inputs=[msg, chatbot, doctor_letter, pdf_content],
278
+ outputs=[msg, chatbot]
279
+ )
280
+ submit_btn.click(
281
+ respond,
282
+ inputs=[msg, chatbot, doctor_letter, pdf_content],
283
+ outputs=[msg, chatbot]
284
+ )
285
+
286
+ # Handle conversation clearing
287
+ clear.click(lambda: ([], ""), outputs=[chatbot, pdf_content])
288
+
289
+ demo.queue()
290
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ gradio==4.21.0
2
+ huggingface-hub==0.21.1
3
+ PyPDF2==3.0.1
4
+ openai==1.6.1