ferferefer commited on
Commit
ceb250f
·
verified ·
1 Parent(s): a47d0b7

Upload 4 files

Browse files
Files changed (4) hide show
  1. .gitignore +41 -0
  2. README.md +32 -0
  3. app.py +259 -0
  4. requirements.txt +3 -0
.gitignore ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Environment variables
2
+ .env
3
+ .env.*
4
+
5
+ # Python
6
+ __pycache__/
7
+ *.py[cod]
8
+ *$py.class
9
+ *.so
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ *.egg-info/
24
+ .installed.cfg
25
+ *.egg
26
+
27
+ # Virtual Environment
28
+ venv/
29
+ ENV/
30
+ env/
31
+ .venv/
32
+
33
+ # IDE
34
+ .idea/
35
+ .vscode/
36
+ *.swp
37
+ *.swo
38
+
39
+ # OS
40
+ .DS_Store
41
+ Thumbs.db
README.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 👁️ Glaucoma Support Assistant
2
+
3
+ A specialized AI chatbot designed to support glaucoma patients by providing information and guidance about glaucoma care. Created by Dr. Chris Panos.
4
+
5
+ ## Features
6
+
7
+ - **General Glaucoma Information**: Learn about glaucoma types, risk factors, and how it affects vision
8
+ - **Treatment Options**: Understand common treatment approaches (general information only)
9
+ - **Pre/Post-Operative Care**: Get general information about typical care procedures
10
+ - **Doctor's Letter Support**: Upload your doctor's letter for more personalized responses
11
+ - **User-Friendly Interface**: Easy-to-use chat interface with clear information display
12
+
13
+ ## Important Notes
14
+
15
+ - This assistant provides general information only and is not a substitute for professional medical advice
16
+ - Always consult your healthcare provider for medical guidance
17
+ - The chatbot will prioritize information from your doctor's letter when provided
18
+ - No medical advice is given - the assistant will always refer you to your doctor for specific medical questions
19
+
20
+ ## Technical Details
21
+
22
+ - Built using Gradio for the user interface
23
+ - Powered by DeepSeek-R1 language model
24
+ - Runs on Hugging Face Spaces
25
+
26
+ ## Credits
27
+
28
+ Created by Dr. Chris Panos
29
+
30
+ ## Disclaimer
31
+
32
+ This AI assistant is for informational purposes only. It does not provide medical advice, diagnosis, or treatment. Always seek the advice of your physician or other qualified health provider with any questions you may have regarding a medical condition.
app.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ from huggingface_hub import InferenceClient
4
+ from typing import List, Dict
5
+ import PyPDF2
6
+ import tempfile
7
+
8
+ # Initialize the client using environment variable
9
+ client = InferenceClient(
10
+ provider="together",
11
+ api_key=os.environ.get("TOGETHER_API_KEY")
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. 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."""
16
+
17
+ def extract_text_from_pdf(pdf_file) -> str:
18
+ if pdf_file is None:
19
+ return ""
20
+
21
+ # Create a temporary file to save the uploaded PDF
22
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as temp_pdf:
23
+ temp_pdf.write(pdf_file)
24
+ temp_pdf_path = temp_pdf.name
25
+
26
+ try:
27
+ # Open the PDF file
28
+ with open(temp_pdf_path, 'rb') as file:
29
+ # Create a PDF reader object
30
+ pdf_reader = PyPDF2.PdfReader(file)
31
+
32
+ # Extract text from all pages
33
+ text = ""
34
+ for page in pdf_reader.pages:
35
+ text += page.extract_text() + "\n"
36
+
37
+ return text.strip()
38
+ except Exception as e:
39
+ return f"Error processing PDF: {str(e)}"
40
+ finally:
41
+ # Clean up the temporary file
42
+ if os.path.exists(temp_pdf_path):
43
+ os.unlink(temp_pdf_path)
44
+
45
+ def format_message(role: str, content: str) -> Dict[str, str]:
46
+ return {"role": role, "content": content}
47
+
48
+ def process_uploaded_files(files) -> str:
49
+ if not files:
50
+ return ""
51
+
52
+ all_text = []
53
+ for file in files:
54
+ text = extract_text_from_pdf(file)
55
+ if text:
56
+ all_text.append(text)
57
+
58
+ return "\n\n=== Next Document ===\n\n".join(all_text)
59
+
60
+ def chat_with_bot(message: str, history: List[List[str]], doctor_letter: str = None, pdf_content: str = None) -> tuple:
61
+ # Format conversation history
62
+ messages = [format_message("system", SYSTEM_PROMPT)]
63
+
64
+ # Add doctor's letter if provided
65
+ if doctor_letter and doctor_letter.strip():
66
+ messages.append(format_message("system", f"Doctor's letter content: {doctor_letter}"))
67
+
68
+ # Add PDF content if provided
69
+ if pdf_content and pdf_content.strip():
70
+ messages.append(format_message("system", f"Additional medical documents content: {pdf_content}"))
71
+
72
+ # Add conversation history
73
+ for user_msg, assistant_msg in history:
74
+ messages.append(format_message("user", user_msg))
75
+ messages.append(format_message("assistant", assistant_msg))
76
+
77
+ # Add current message
78
+ messages.append(format_message("user", message))
79
+
80
+ try:
81
+ # Get response from the model
82
+ completion = client.chat.completions.create(
83
+ model="deepseek-ai/DeepSeek-R1",
84
+ messages=messages,
85
+ max_tokens=500
86
+ )
87
+
88
+ response = completion.choices[0].message.content
89
+ return response
90
+ except Exception as e:
91
+ return f"I apologize, but I encountered an error: {str(e)}. Please try again or contact support if the issue persists."
92
+
93
+ with gr.Blocks(
94
+ theme=gr.themes.Soft(
95
+ primary_hue="blue",
96
+ secondary_hue="gray",
97
+ ),
98
+ css="""
99
+ .container { max-width: 900px; margin: auto; padding: 20px; }
100
+ .header { text-align: center; margin-bottom: 30px; }
101
+ .header h1 { font-size: 2.5em; color: #2C3E50; margin-bottom: 20px; }
102
+ .header p { font-size: 1.2em; line-height: 1.6; color: #34495E; }
103
+ .upload-section {
104
+ background: #f8f9fa;
105
+ padding: 25px;
106
+ border-radius: 15px;
107
+ margin-bottom: 30px;
108
+ border: 2px solid #E0E5EC;
109
+ }
110
+ .upload-section label { font-size: 1.2em; color: #2C3E50; }
111
+ .chat-section {
112
+ background: white;
113
+ padding: 25px;
114
+ border-radius: 15px;
115
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
116
+ }
117
+ .help-section {
118
+ background: #EBF5FB;
119
+ padding: 20px;
120
+ border-radius: 15px;
121
+ margin: 20px 0;
122
+ }
123
+ .help-section h3 {
124
+ color: #2C3E50;
125
+ font-size: 1.4em;
126
+ margin-bottom: 15px;
127
+ }
128
+ .help-section ul {
129
+ font-size: 1.1em;
130
+ line-height: 1.6;
131
+ }
132
+ footer {
133
+ text-align: center;
134
+ margin-top: 30px;
135
+ padding: 20px;
136
+ color: #34495E;
137
+ font-size: 1.1em;
138
+ background: #f8f9fa;
139
+ border-radius: 15px;
140
+ }
141
+ .button-primary { font-size: 1.2em !important; }
142
+ .button-secondary { font-size: 1.1em !important; }
143
+ """
144
+ ) as demo:
145
+ with gr.Column(elem_classes="container"):
146
+ gr.Markdown(
147
+ """
148
+ # 👁️ Glaucoma Support Assistant
149
+
150
+ Welcome! I'm here to help you understand glaucoma and provide general information about eye care.
151
+ Please remember that I cannot provide medical advice - always consult your doctor for specific guidance.
152
+
153
+ **Need help?** Just type your question below or upload your doctor's letter for more specific information.
154
+ """,
155
+ elem_classes="header"
156
+ )
157
+
158
+ with gr.Column(elem_classes="upload-section"):
159
+ gr.Markdown(
160
+ """
161
+ ### 📄 Share Your Medical Documents (Optional)
162
+ You can either:
163
+ 1. Copy and paste your doctor's letter in the text box below, or
164
+ 2. Upload PDF documents using the upload button
165
+ """,
166
+ )
167
+ doctor_letter = gr.TextArea(
168
+ label="Type or Paste Doctor's Letter Here",
169
+ placeholder="You can copy and paste your doctor's letter here. This will help me provide more specific information based on your case.",
170
+ lines=4
171
+ )
172
+
173
+ pdf_files = gr.File(
174
+ label="Or Upload Medical Documents (PDF files)",
175
+ file_types=[".pdf"],
176
+ file_count="multiple"
177
+ )
178
+
179
+ with gr.Column(elem_classes="chat-section"):
180
+ chatbot = gr.Chatbot(
181
+ label="Our Conversation",
182
+ height=400,
183
+ bubble_full_width=False,
184
+ show_copy_button=True,
185
+ container=True
186
+ )
187
+
188
+ with gr.Row():
189
+ msg = gr.Textbox(
190
+ label="Type your question here",
191
+ placeholder="What would you like to know about glaucoma?",
192
+ lines=2,
193
+ scale=9
194
+ )
195
+ submit_btn = gr.Button("Send Question", scale=1, variant="primary", elem_classes="button-primary")
196
+
197
+ clear = gr.Button("Start New Conversation", variant="secondary", elem_classes="button-secondary")
198
+
199
+ with gr.Column(elem_classes="help-section"):
200
+ gr.Markdown(
201
+ """
202
+ ### 💡 Examples of Questions You Can Ask:
203
+ - What is glaucoma and how does it affect my eyes?
204
+ - What are the common treatments for glaucoma?
205
+ - What should I expect before and after eye surgery?
206
+ - Can you explain the terms in my doctor's letter?
207
+ - What are the different types of eye drops used for glaucoma?
208
+
209
+ **Remember:** For specific medical advice, always consult your eye doctor.
210
+ """
211
+ )
212
+
213
+ gr.Markdown(
214
+ """
215
+ ---
216
+ ### ⚠️ Important Notice
217
+ This AI assistant provides general information only and is not a substitute for professional medical advice.
218
+ Always consult your healthcare provider for medical guidance.
219
+ """,
220
+ elem_classes="footer"
221
+ )
222
+
223
+ # Store PDF content in state
224
+ pdf_content = gr.State("")
225
+
226
+ def update_pdf_content(files):
227
+ return process_uploaded_files(files)
228
+
229
+ def respond(message, chat_history, doctor_letter_text, current_pdf_content):
230
+ if not message.strip():
231
+ return "", chat_history
232
+ bot_message = chat_with_bot(message, chat_history, doctor_letter_text, current_pdf_content)
233
+ chat_history.append((message, bot_message))
234
+ return "", chat_history
235
+
236
+ # Update PDF content when files are uploaded
237
+ pdf_files.change(
238
+ fn=update_pdf_content,
239
+ inputs=[pdf_files],
240
+ outputs=[pdf_content]
241
+ )
242
+
243
+ # Handle message submission
244
+ msg.submit(
245
+ respond,
246
+ inputs=[msg, chatbot, doctor_letter, pdf_content],
247
+ outputs=[msg, chatbot]
248
+ )
249
+ submit_btn.click(
250
+ respond,
251
+ inputs=[msg, chatbot, doctor_letter, pdf_content],
252
+ outputs=[msg, chatbot]
253
+ )
254
+
255
+ # Handle conversation clearing
256
+ clear.click(lambda: ([], ""), outputs=[chatbot, pdf_content])
257
+
258
+ demo.queue()
259
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio==4.21.0
2
+ huggingface-hub==0.20.3
3
+ PyPDF2==3.0.1