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

Delete app.py

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