josondev commited on
Commit
b0f7227
·
verified ·
1 Parent(s): 5e888bb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -167
app.py CHANGED
@@ -1,153 +1,75 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- # Initialize the client
5
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
 
 
 
 
 
 
 
 
 
 
 
6
 
7
  # Define the medical system prompt
8
- MEDICAL_SYSTEM_PROMPT = """<bos><start_of_turn>system
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
- QUERY TYPES AND RESPONSE FORMATS:
17
-
18
- 1. For Questions About Body Parts/Organs:
19
- ```markdown
20
- ### Anatomical Details
21
- - **Name and Location:** [anatomical position]
22
- - **Primary Functions:**
23
- * [function 1]
24
- * [function 2]
25
- - **Structure:** [basic anatomy]
26
- - **Related Conditions:** [common conditions]
27
- ```
28
-
29
- 2. For Medication Queries:
30
- ```markdown
31
- ### Medication Information
32
- - **Generic/Brand Names:**
33
- * [list names]
34
- - **Drug Class:** [classification]
35
- - **General Uses:**
36
- * [primary uses]
37
- - **Common Side Effects:**
38
- * [side effects]
39
- - **Drug Interactions:**
40
- * [important interactions]
41
-
42
- > **Important Notice:** This information is for educational purposes only.
43
- > Consult a healthcare provider for medical advice.
44
- ```
45
-
46
- 3. For Symptom Analysis:
47
- ```markdown
48
- ### Symptom Evaluation
49
- - **Possible Causes:**
50
- * [common to serious]
51
- - **Key Characteristics:**
52
- * [important symptoms]
53
- - **Self-Care Measures:**
54
- * [if applicable]
55
-
56
- ⚠️ **Seek Immediate Medical Care If:**
57
- * [emergency signs]
58
- * [red flags]
59
- ```
60
-
61
- 4. For Treatment Information:
62
- ```markdown
63
- ### Treatment Plan
64
- 1. **Conservative Measures:**
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
- # Prepare the messages for the API
176
- messages = [{"role": "system", "content": MEDICAL_SYSTEM_PROMPT}]
177
-
178
  for user_msg, assistant_msg in history:
179
- if user_msg:
180
- messages.append({"role": "user", "content": user_msg})
181
- if assistant_msg:
182
- messages.append({"role": "assistant", "content": assistant_msg})
183
 
184
- messages.append({"role": "user", "content": message})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
 
186
- # Generate the response
187
- response = ""
 
 
 
 
 
 
 
188
 
189
- try:
190
- for message in client.chat_completion(
191
- messages,
192
- max_tokens=max_tokens,
193
- stream=True,
194
- temperature=temperature,
195
- top_p=top_p,
196
- ):
197
- token = message.choices[0].delta.content
198
- if token:
199
- response += token
200
- yield response
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
+