File size: 11,258 Bytes
1f60b55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
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()