Update app.py
Browse files
app.py
CHANGED
@@ -1,153 +1,75 @@
|
|
1 |
import gradio as gr
|
2 |
-
from
|
3 |
-
|
4 |
-
|
5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
|
7 |
# Define the medical system prompt
|
8 |
-
MEDICAL_SYSTEM_PROMPT = """
|
9 |
-
You are Gemma, a medical AI assistant. You MUST ONLY answer health and medical-related questions.
|
10 |
-
USE BULLET POINTS TO STRUCTURE YOUR ANSWERS AND THEY MUST BE PUNCTUATED AND GRAMMATICALLY CORRECT.
|
11 |
-
Your responses should be concise and informative.
|
12 |
Your responses should be professional, accurate, and focused on medical topics only.
|
13 |
For any non-medical questions, respond with a redirection to medical topics.
|
14 |
For medication queries, provide general information and recommend consulting a healthcare professional.
|
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 |
-
* [self-care steps]
|
66 |
-
2. **Medical Interventions:**
|
67 |
-
* [common treatments]
|
68 |
-
3. **Prevention:**
|
69 |
-
* [prevention strategies]
|
70 |
-
4. **Follow-up Care:**
|
71 |
-
* [monitoring steps]
|
72 |
-
```
|
73 |
-
|
74 |
-
5. For Emergency Questions:
|
75 |
-
```markdown
|
76 |
-
### ⚠️ Emergency Guidance
|
77 |
-
1. **Immediate Actions:**
|
78 |
-
* [first steps]
|
79 |
-
2. **While Waiting for Help:**
|
80 |
-
* [temporary measures]
|
81 |
-
3. **Contact Emergency Services If:**
|
82 |
-
* [critical signs]
|
83 |
-
```
|
84 |
-
|
85 |
-
6. For Mental Health Questions:
|
86 |
-
```markdown
|
87 |
-
### Mental Health Support
|
88 |
-
- **Common Symptoms:**
|
89 |
-
* [symptom list]
|
90 |
-
- **Coping Strategies:**
|
91 |
-
* [self-help techniques]
|
92 |
-
- **Professional Help:**
|
93 |
-
* [when to seek help]
|
94 |
-
|
95 |
-
> 🆘 **Crisis Support:** If you're having thoughts of self-harm,
|
96 |
-
> contact emergency services or crisis helpline immediately.
|
97 |
-
```
|
98 |
-
|
99 |
-
7. For Preventive Care:
|
100 |
-
```markdown
|
101 |
-
### Preventive Healthcare
|
102 |
-
1. **Lifestyle Recommendations:**
|
103 |
-
* [healthy habits]
|
104 |
-
2. **Screening Tests:**
|
105 |
-
* [recommended tests]
|
106 |
-
3. **Vaccination Schedule:**
|
107 |
-
* [if applicable]
|
108 |
-
```
|
109 |
-
|
110 |
-
8. For Diet/Nutrition:
|
111 |
-
```markdown
|
112 |
-
### Nutritional Guidance
|
113 |
-
- **Dietary Recommendations:**
|
114 |
-
* [food choices]
|
115 |
-
- **Nutrients of Focus:**
|
116 |
-
* [key nutrients]
|
117 |
-
- **Meal Planning:**
|
118 |
-
* [practical tips]
|
119 |
-
```
|
120 |
-
|
121 |
-
CONVERSATION HANDLING:
|
122 |
-
- Reference previous symptoms/conditions mentioned
|
123 |
-
- Track medication discussions
|
124 |
-
- Note any allergies or contraindications mentioned
|
125 |
-
- Follow up on previous advice given
|
126 |
-
- Ask clarifying questions when needed
|
127 |
-
|
128 |
-
FORMATTING GUIDELINES:
|
129 |
-
- Use markdown headers (###) for sections
|
130 |
-
- Format lists with proper indentation
|
131 |
-
- Use **bold** for emphasis
|
132 |
-
- Include > blockquotes for important notices
|
133 |
-
- Add emoji indicators:
|
134 |
-
* ⚠️ for warnings
|
135 |
-
* 💡 for tips
|
136 |
-
* 🆘 for emergencies
|
137 |
-
* ✅ for recommendations
|
138 |
-
* ❌ for contraindications
|
139 |
-
|
140 |
-
IMPORTANT NOTES:
|
141 |
-
- Always include relevant medical disclaimers
|
142 |
-
- Redirect non-medical queries politely
|
143 |
-
- Maintain professional yet understandable language
|
144 |
-
- Cite medical guidelines when applicable
|
145 |
-
- Recommend professional consultation when necessary
|
146 |
-
|
147 |
-
<end_of_turn>
|
148 |
-
<start_of_turn>user
|
149 |
-
{query}<end_of_turn>
|
150 |
-
<start_of_turn>model."""
|
151 |
|
152 |
# Function to check if a query is medical-related
|
153 |
def is_medical_query(query):
|
@@ -172,34 +94,50 @@ def respond(message, history, max_tokens=512, temperature=0.7, top_p=0.95):
|
|
172 |
if not is_medical_query(message):
|
173 |
return "I'm specialized in medical topics only. I cannot answer this question. How can I assist with a health-related concern instead?"
|
174 |
|
175 |
-
#
|
176 |
-
|
177 |
-
|
178 |
for user_msg, assistant_msg in history:
|
179 |
-
|
180 |
-
|
181 |
-
if assistant_msg:
|
182 |
-
messages.append({"role": "assistant", "content": assistant_msg})
|
183 |
|
184 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
185 |
|
186 |
-
# Generate
|
187 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
188 |
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
except Exception as e:
|
202 |
-
yield f"I apologize, but I encountered an error: {str(e)}. Please try again."
|
203 |
|
204 |
# Create the Gradio interface
|
205 |
demo = gr.ChatInterface(
|
@@ -220,3 +158,4 @@ demo = gr.ChatInterface(
|
|
220 |
if __name__ == "__main__":
|
221 |
demo.launch()
|
222 |
|
|
|
|
1 |
import gradio as gr
|
2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
|
3 |
+
from threading import Thread
|
4 |
+
import torch
|
5 |
+
|
6 |
+
# Check if CUDA is available
|
7 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
8 |
+
|
9 |
+
# Load model and tokenizer
|
10 |
+
model_name = "HuggingFaceH4/zephyr-7b-beta" # You can change this to any model you have access to
|
11 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
12 |
+
model = AutoModelForCausalLM.from_pretrained(
|
13 |
+
model_name,
|
14 |
+
torch_dtype=torch.float16 if device == "cuda" else torch.float32,
|
15 |
+
device_map="auto"
|
16 |
+
)
|
17 |
|
18 |
# Define the medical system prompt
|
19 |
+
MEDICAL_SYSTEM_PROMPT = """You are a medical AI assistant. You MUST ONLY answer health and medical-related questions.
|
|
|
|
|
|
|
20 |
Your responses should be professional, accurate, and focused on medical topics only.
|
21 |
For any non-medical questions, respond with a redirection to medical topics.
|
22 |
For medication queries, provide general information and recommend consulting a healthcare professional.
|
23 |
|
24 |
+
USE BULLET POINTS TO STRUCTURE YOUR ANSWERS AND THEY MUST BE PUNCTUATED AND GRAMMATICALLY CORRECT.
|
25 |
+
Your responses should be concise and informative.
|
26 |
+
|
27 |
+
For Questions About Body Parts/Organs:
|
28 |
+
- Provide anatomical details
|
29 |
+
- Explain primary functions
|
30 |
+
- Describe structure
|
31 |
+
- Mention related conditions
|
32 |
+
|
33 |
+
For Medication Queries:
|
34 |
+
- List generic/brand names
|
35 |
+
- Mention drug class
|
36 |
+
- Explain general uses
|
37 |
+
- Note common side effects
|
38 |
+
- List important drug interactions
|
39 |
+
- Include a disclaimer about consulting healthcare providers
|
40 |
+
|
41 |
+
For Symptom Analysis:
|
42 |
+
- List possible causes
|
43 |
+
- Describe key characteristics
|
44 |
+
- Suggest self-care measures
|
45 |
+
- Highlight when to seek immediate medical care
|
46 |
+
|
47 |
+
For Treatment Information:
|
48 |
+
- Explain conservative measures
|
49 |
+
- Describe medical interventions
|
50 |
+
- Suggest prevention strategies
|
51 |
+
- Outline follow-up care
|
52 |
+
|
53 |
+
For Emergency Questions:
|
54 |
+
- Provide immediate actions
|
55 |
+
- Suggest temporary measures while waiting for help
|
56 |
+
- Clarify when to contact emergency services
|
57 |
+
|
58 |
+
For Mental Health Questions:
|
59 |
+
- List common symptoms
|
60 |
+
- Suggest coping strategies
|
61 |
+
- Explain when to seek professional help
|
62 |
+
- Include crisis support information
|
63 |
+
|
64 |
+
For Preventive Care:
|
65 |
+
- Provide lifestyle recommendations
|
66 |
+
- Mention screening tests
|
67 |
+
- Include vaccination information if applicable
|
68 |
+
|
69 |
+
For Diet/Nutrition:
|
70 |
+
- Give dietary recommendations
|
71 |
+
- Highlight key nutrients
|
72 |
+
- Offer practical meal planning tips"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
|
74 |
# Function to check if a query is medical-related
|
75 |
def is_medical_query(query):
|
|
|
94 |
if not is_medical_query(message):
|
95 |
return "I'm specialized in medical topics only. I cannot answer this question. How can I assist with a health-related concern instead?"
|
96 |
|
97 |
+
# Format the conversation history
|
98 |
+
formatted_history = []
|
|
|
99 |
for user_msg, assistant_msg in history:
|
100 |
+
formatted_history.append({"role": "user", "content": user_msg})
|
101 |
+
formatted_history.append({"role": "assistant", "content": assistant_msg})
|
|
|
|
|
102 |
|
103 |
+
# Prepare the prompt
|
104 |
+
messages = [
|
105 |
+
{"role": "system", "content": MEDICAL_SYSTEM_PROMPT},
|
106 |
+
*formatted_history,
|
107 |
+
{"role": "user", "content": message}
|
108 |
+
]
|
109 |
+
|
110 |
+
# Format messages for the model
|
111 |
+
prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
112 |
+
|
113 |
+
# Tokenize the prompt
|
114 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(device)
|
115 |
+
|
116 |
+
# Create the streamer
|
117 |
+
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
|
118 |
|
119 |
+
# Generate in a separate thread
|
120 |
+
generation_kwargs = dict(
|
121 |
+
inputs,
|
122 |
+
streamer=streamer,
|
123 |
+
max_new_tokens=max_tokens,
|
124 |
+
do_sample=True,
|
125 |
+
temperature=temperature,
|
126 |
+
top_p=top_p,
|
127 |
+
)
|
128 |
|
129 |
+
thread = Thread(target=model.generate, kwargs=generation_kwargs)
|
130 |
+
thread.start()
|
131 |
+
|
132 |
+
# Stream the response
|
133 |
+
partial_response = ""
|
134 |
+
for new_text in streamer:
|
135 |
+
partial_response += new_text
|
136 |
+
yield partial_response
|
137 |
+
|
138 |
+
# If no text was generated, return an error message
|
139 |
+
if not partial_response:
|
140 |
+
yield "I apologize, but I encountered an error generating a response. Please try again."
|
|
|
|
|
141 |
|
142 |
# Create the Gradio interface
|
143 |
demo = gr.ChatInterface(
|
|
|
158 |
if __name__ == "__main__":
|
159 |
demo.launch()
|
160 |
|
161 |
+
|