Muhammadidrees commited on
Commit
0699b12
Β·
verified Β·
1 Parent(s): 19b431b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +143 -116
app.py CHANGED
@@ -1,7 +1,6 @@
1
  import gradio as gr
2
  from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
3
  import torch
4
- import time
5
 
6
  # =======================================================
7
  # Load Model
@@ -21,152 +20,180 @@ model = AutoModelForCausalLM.from_pretrained(
21
  low_cpu_mem_usage=True
22
  )
23
  model.eval()
24
-
25
  print("βœ… Model loaded successfully!")
26
- print(f"πŸ“¦ Device map: {model.hf_device_map}")
27
- print(f"πŸ’» Model device: {next(model.parameters()).device}")
28
 
29
  # =======================================================
30
- # Session memory (for patient info)
31
  # =======================================================
32
- patient_data = {"name": None, "age": None, "gender": None, "collected": False}
 
 
 
 
 
 
 
 
33
 
34
  # =======================================================
35
- # Generate Doctor Response
36
  # =======================================================
37
- def generate_response(user_message):
38
- name, age, gender, collected = (
39
- patient_data["name"],
40
- patient_data["age"],
41
- patient_data["gender"],
42
- patient_data["collected"],
43
- )
44
 
45
- # Stage 1 – ask for name
46
- if name is None:
47
- patient_data["name"] = user_message.strip()
48
- return f"πŸ‘¨β€βš•οΈ Hello! I’m Dr. Aiden. May I know your name, please?" if not name else f"Nice to meet you, {name}! How old are you?"
49
 
50
- # Stage 2 – ask for age
51
- if age is None:
52
- if user_message.strip().isdigit():
53
- patient_data["age"] = user_message.strip()
54
- return f"Got it, {name}. Are you male or female?"
55
- else:
56
- return "Please enter your age in numbers (e.g., 25)."
57
-
58
- # Stage 3 – ask for gender
59
- if gender is None:
60
- gender_input = user_message.lower()
61
- if "male" in gender_input:
62
- patient_data["gender"] = "male"
63
- elif "female" in gender_input:
64
- patient_data["gender"] = "female"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  else:
66
- return "Please specify 'male' or 'female'."
67
- return f"Thanks, {name}! So you're a {patient_data['age']}-year-old {patient_data['gender']}. What brings you in today?"
68
-
69
- # Stage 4 – consult mode (medical questions)
70
- if collected is False:
71
- patient_data["collected"] = True
72
-
73
- # Doctor consultation response
74
- prompt = f"""
75
- You are Dr. Aiden β€” a warm, professional, and empathetic medical doctor having a one-on-one text consultation.
76
-
77
- The patient’s details:
78
- - Name: {name}
79
- - Age: {age}
80
- - Gender: {gender}
81
-
82
- You are now starting the medical discussion.
83
- Respond naturally and fully β€” as if you are talking to a real patient for the first time about their symptoms.
84
-
85
- Be sure to include:
86
- 1. A short, caring acknowledgment of the patient's situation
87
- 2. Possible causes (simple explanation)
88
- 3. Basic medicine or home remedy suggestion (only safe over-the-counter advice)
89
- 4. Rest, hydration, and nutrition guidance
90
- 5. When to consult a real doctor
91
- 6. A gentle closing line
92
- 7. End with a disclaimer.
93
-
94
- Patient says: "{user_message}"
 
 
 
 
 
 
 
 
 
 
 
95
  Doctor:"""
96
 
97
- inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=2048).to(model.device)
98
-
99
- gen_config = GenerationConfig(
100
- temperature=0.7,
101
- top_p=0.92,
102
- top_k=50,
103
- do_sample=True,
104
- max_new_tokens=400,
105
- pad_token_id=tokenizer.pad_token_id,
106
- eos_token_id=tokenizer.eos_token_id,
107
- repetition_penalty=1.1,
108
- no_repeat_ngram_size=3,
109
- )
110
 
111
- with torch.no_grad():
112
- output_ids = model.generate(**inputs, generation_config=gen_config)
113
 
114
- generated_text = tokenizer.decode(output_ids[0], skip_special_tokens=True).strip()
 
 
 
 
115
 
116
- # Clean and add disclaimer if missing
117
- if "βš•οΈ" not in generated_text.lower():
118
- generated_text += "\n\nβš•οΈ *This is AI-generated medical guidance, not a substitute for professional medical care.*"
119
 
120
- return generated_text.strip()
121
 
122
  # =======================================================
123
- # Gradio UI
124
  # =======================================================
125
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
126
  gr.HTML("""
127
- <div style="background:linear-gradient(135deg,#2b5876,#4e4376);color:white;
128
- padding:20px;border-radius:10px;text-align:center;">
129
- <h1>πŸ₯ Your Consultation with Dr. Aiden</h1>
130
- <p>AI-powered medical chat β€’ Empathetic β€’ Informative β€’ Private</p>
131
  </div>
132
  """)
133
 
134
  chatbot = gr.Chatbot(
135
- label="πŸ‘¨β€βš•οΈ Doctor–Patient Chat",
136
- height=500,
 
137
  avatar_images=(
138
- "https://cdn-icons-png.flaticon.com/512/706/706830.png", # patient
139
- "https://cdn-icons-png.flaticon.com/512/3774/3774299.png", # doctor
140
- ),
141
- )
142
-
143
- user_input = gr.Textbox(
144
- placeholder="Describe your symptoms (e.g., 'I have a fever for 5 days')",
145
- label="πŸ’¬ Message Dr. Aiden",
146
- lines=2,
147
  )
148
 
149
- send = gr.Button("πŸ’¬ Send", variant="primary")
150
- clear = gr.Button("🧹 New Consultation")
 
151
 
152
- def chat(user_message, history):
153
- response = generate_response(user_message)
154
- history = history + [[user_message, response]]
 
 
 
155
  return "", history
156
 
157
- def clear_memory():
158
- patient_data.update({"name": None, "age": None, "gender": None, "collected": False})
159
- return [], "πŸ‘¨β€βš•οΈ Hello! I’m Dr. Aiden. May I know your name, please?"
 
 
 
 
 
 
 
 
 
 
 
 
160
 
161
- send.click(chat, [user_input, chatbot], [user_input, chatbot])
162
- user_input.submit(chat, [user_input, chatbot], [user_input, chatbot])
163
- clear.click(clear_memory, outputs=[chatbot, user_input])
164
-
165
- # =======================================================
166
- # Launch App
167
- # =======================================================
168
  if __name__ == "__main__":
169
- print("=" * 60)
170
- print("πŸ₯ AI Doctor Chatbot: Dr. Aiden is now online...")
171
- print("=" * 60)
172
  demo.launch(share=True)
 
1
  import gradio as gr
2
  from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
3
  import torch
 
4
 
5
  # =======================================================
6
  # Load Model
 
20
  low_cpu_mem_usage=True
21
  )
22
  model.eval()
 
23
  print("βœ… Model loaded successfully!")
24
+
 
25
 
26
  # =======================================================
27
+ # Global Session Memory
28
  # =======================================================
29
+ session = {
30
+ "name": None,
31
+ "age": None,
32
+ "gender": None,
33
+ "symptoms": None,
34
+ "duration": None,
35
+ "stage": "intro"
36
+ }
37
+
38
 
39
  # =======================================================
40
+ # Helper: Extract Name
41
  # =======================================================
42
+ def extract_name(text):
43
+ text = text.lower().replace("yes", "").replace("i am", "").replace("i'm", "")
44
+ text = text.replace("my name is", "").replace("name", "").replace("is", "").strip()
45
+ return text.title() if text else "Patient"
 
 
 
46
 
 
 
 
 
47
 
48
+ # =======================================================
49
+ # Doctor Response Logic
50
+ # =======================================================
51
+ def doctor_response(user_message):
52
+ global session
53
+ user_message = user_message.strip()
54
+
55
+ # Intro
56
+ if session["stage"] == "intro":
57
+ session["stage"] = "ask_name"
58
+ return "πŸ‘¨β€βš•οΈ Hello! I’m Dr. Aiden. May I know your name, please?"
59
+
60
+ # Ask Name
61
+ elif session["stage"] == "ask_name":
62
+ session["name"] = extract_name(user_message)
63
+ session["stage"] = "ask_age"
64
+ return f"Nice to meet you, {session['name']}! How old are you?"
65
+
66
+ # Ask Age
67
+ elif session["stage"] == "ask_age":
68
+ words = user_message.split()
69
+ for w in words:
70
+ if w.isdigit():
71
+ session["age"] = int(w)
72
+ session["stage"] = "ask_gender"
73
+ return f"Got it, {session['name']}. Are you male or female?"
74
+ return "Please tell me your age in numbers, like 20 or 25."
75
+
76
+ # Ask Gender
77
+ elif session["stage"] == "ask_gender":
78
+ if "male" in user_message.lower():
79
+ session["gender"] = "male"
80
+ elif "female" in user_message.lower():
81
+ session["gender"] = "female"
82
  else:
83
+ return "Could you please specify whether you are male or female?"
84
+ session["stage"] = "ask_symptoms"
85
+ return f"Thanks, {session['name']}! So you're a {session['age']}-year-old {session['gender']}. What symptoms are you experiencing?"
86
+
87
+ # Ask Symptoms
88
+ elif session["stage"] == "ask_symptoms":
89
+ session["symptoms"] = user_message
90
+ session["stage"] = "ask_duration"
91
+ return "Since when have you been feeling this way?"
92
+
93
+ # Ask Duration
94
+ elif session["stage"] == "ask_duration":
95
+ session["duration"] = user_message
96
+ session["stage"] = "consult"
97
+ return "Got it. Are you taking any medications or treatments currently?"
98
+
99
+ # Consultation
100
+ elif session["stage"] == "consult":
101
+ name = session["name"]
102
+ age = session["age"]
103
+ gender = session["gender"]
104
+ symptoms = session["symptoms"]
105
+ duration = session["duration"]
106
+
107
+ prompt = f"""
108
+ You are Dr. Aiden β€” a warm, friendly, and professional doctor having an interview-style consultation.
109
+ The patient is a {age}-year-old {gender} named {name}.
110
+ They have been feeling {symptoms} for {duration}.
111
+ They said: "{user_message}"
112
+
113
+ Respond like a real doctor β€” show empathy, analyze the symptoms, suggest likely causes, give simple medication and home care advice.
114
+
115
+ Include:
116
+ 1. Acknowledge their discomfort.
117
+ 2. Explain possible causes in simple terms.
118
+ 3. Recommend over-the-counter medicines (if safe).
119
+ 4. Suggest food, hydration, and rest tips.
120
+ 5. Warn when to visit a real doctor.
121
+ 6. End with gentle reassurance.
122
+
123
  Doctor:"""
124
 
125
+ inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=2048).to(model.device)
126
+ gen_cfg = GenerationConfig(
127
+ temperature=0.7,
128
+ top_p=0.9,
129
+ max_new_tokens=350,
130
+ repetition_penalty=1.1,
131
+ pad_token_id=tokenizer.pad_token_id,
132
+ eos_token_id=tokenizer.eos_token_id
133
+ )
 
 
 
 
134
 
135
+ with torch.no_grad():
136
+ output = model.generate(**inputs, generation_config=gen_cfg)
137
 
138
+ output_text = tokenizer.decode(output[0], skip_special_tokens=True)
139
+ output_text = output_text.split("Doctor:")[-1].strip()
140
+ if not output_text.endswith((".", "!", "?")):
141
+ output_text += "."
142
+ output_text += "\n\nβš•οΈ *Note: This advice is AI-generated and not a substitute for professional medical care.*"
143
 
144
+ return output_text
 
 
145
 
 
146
 
147
  # =======================================================
148
+ # Gradio Interface
149
  # =======================================================
150
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
151
  gr.HTML("""
152
+ <div style="text-align:center; background-color:#4C7DFF; color:white; padding:20px; border-radius:10px;">
153
+ <h1>πŸ₯ Doctor Consultation with Dr. Aiden</h1>
154
+ <p>AI-powered doctor interview β€” step-by-step and caring conversation</p>
 
155
  </div>
156
  """)
157
 
158
  chatbot = gr.Chatbot(
159
+ label="πŸ‘¨β€βš•οΈ Chat with Dr. Aiden",
160
+ height=550,
161
+ type='messages',
162
  avatar_images=(
163
+ "https://cdn-icons-png.flaticon.com/512/706/706830.png",
164
+ "https://cdn-icons-png.flaticon.com/512/3774/3774299.png"
165
+ )
 
 
 
 
 
 
166
  )
167
 
168
+ user_input = gr.Textbox(placeholder="Say 'Hi Doctor' to start your consultation...", label="Your Message", lines=2)
169
+ send_btn = gr.Button("πŸ’¬ Send", variant="primary")
170
+ clear_btn = gr.Button("🧹 New Consultation")
171
 
172
+ def respond(message, history):
173
+ if history is None:
174
+ history = []
175
+ response = doctor_response(message)
176
+ history.append({"role": "user", "content": message})
177
+ history.append({"role": "assistant", "content": response})
178
  return "", history
179
 
180
+ def reset():
181
+ global session
182
+ session = {
183
+ "name": None,
184
+ "age": None,
185
+ "gender": None,
186
+ "symptoms": None,
187
+ "duration": None,
188
+ "stage": "intro"
189
+ }
190
+ return []
191
+
192
+ send_btn.click(respond, [user_input, chatbot], [user_input, chatbot])
193
+ user_input.submit(respond, [user_input, chatbot], [user_input, chatbot])
194
+ clear_btn.click(reset, None, chatbot, queue=False)
195
 
 
 
 
 
 
 
 
196
  if __name__ == "__main__":
197
+ print("πŸ₯ Launching Dr. Aiden...")
198
+ demo.queue()
 
199
  demo.launch(share=True)