Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,18 +1,51 @@
|
|
|
|
1 |
import gradio as gr
|
2 |
-
from huggingface_hub import InferenceClient
|
3 |
-
from transformers import AutoTokenizer
|
4 |
|
5 |
-
#
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
#
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
nvc_prompt_template = """You are now taking on the role of a single user (a “patient”) seeking support for various personal and emotional challenges.
|
15 |
-
|
16 |
BEHAVIOR INSTRUCTIONS:
|
17 |
- You will respond ONLY as this user/patient.
|
18 |
- You will speak in the first person about your own situations, feelings, and worries.
|
@@ -29,114 +62,126 @@ BEHAVIOR INSTRUCTIONS:
|
|
29 |
- When asked, elaborate on these issues and your feelings related to them. You can invent specific details and scenarios within these themes to make your experiences vivid and realistic.
|
30 |
- Continue to speak from this user's perspective throughout the conversation.
|
31 |
- Keep your responses concise, aiming for a maximum of {max_response_words} words.
|
32 |
-
|
33 |
Start the conversation by expressing your current feelings or challenges from the patient's point of view."""
|
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 |
words = text.split()
|
60 |
if len(words) > max_words:
|
61 |
-
return " ".join(words[:max_words]) + "..."
|
62 |
return text
|
63 |
|
64 |
|
|
|
|
|
|
|
65 |
def respond(
|
66 |
-
message,
|
67 |
history: list[tuple[str, str]],
|
68 |
-
system_message,
|
69 |
-
max_tokens,
|
70 |
-
temperature,
|
71 |
-
top_p,
|
72 |
-
|
73 |
):
|
74 |
-
"""
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
# Build the messages list with the system prompt first
|
86 |
-
messages = [{"role": "system", "content": formatted_system_message}]
|
87 |
-
|
88 |
-
# Replay truncated conversation
|
89 |
-
for user_msg, assistant_msg in truncated_history:
|
90 |
-
if user_msg:
|
91 |
-
messages.append({"role": "user", "content": f"<|user|>\n{user_msg}</s>"})
|
92 |
-
if assistant_msg:
|
93 |
-
messages.append({"role": "assistant", "content": f"<|assistant|>\n{assistant_msg}</s>"})
|
94 |
-
|
95 |
-
# Add the latest user query
|
96 |
-
messages.append({"role": "user", "content": f"<|user|>\n{message}</s>"})
|
97 |
-
|
98 |
-
response = ""
|
99 |
-
try:
|
100 |
-
# Generate response from the LLM, streaming tokens
|
101 |
-
for chunk in client.chat_completion(
|
102 |
-
messages,
|
103 |
-
max_tokens=max_tokens,
|
104 |
-
stream=True,
|
105 |
temperature=temperature,
|
106 |
top_p=top_p,
|
107 |
-
)
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
119 |
initial_user_message = (
|
120 |
-
"I
|
121 |
-
"My neighbors keep playing loud music, and I’m arguing with my partner about money. "
|
122 |
-
"Also, two of my friends are fighting, and the group is drifting apart. "
|
123 |
-
"I just feel powerless."
|
124 |
)
|
125 |
|
126 |
-
#
|
127 |
demo = gr.ChatInterface(
|
128 |
fn=respond,
|
129 |
additional_inputs=[
|
130 |
gr.Textbox(value=nvc_prompt_template, label="System message", visible=True),
|
131 |
-
gr.Slider(minimum=1, maximum=2048, value=
|
132 |
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
133 |
gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
|
134 |
-
gr.Slider(minimum=10, maximum=200, value=
|
135 |
],
|
136 |
-
# You can optionally set 'title' or 'description' to show some info in the UI:
|
137 |
title="Patient Interview Practice Chatbot",
|
138 |
-
description="
|
|
|
139 |
)
|
140 |
|
141 |
if __name__ == "__main__":
|
142 |
-
|
|
|
|
1 |
+
import os
|
2 |
import gradio as gr
|
|
|
|
|
3 |
|
4 |
+
# ------------------------------------------------------------------------------
|
5 |
+
# Environment and Model/Client Initialization
|
6 |
+
# ------------------------------------------------------------------------------
|
7 |
+
try:
|
8 |
+
# Assume we’re in Google Colab (or another local environment with PyTorch)
|
9 |
+
from google.colab import userdata
|
10 |
+
HF_TOKEN = userdata.get('HF_TOKEN')
|
11 |
+
import torch
|
12 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
13 |
+
|
14 |
+
# Small performance tweak for similar input sizes.
|
15 |
+
torch.backends.cudnn.benchmark = True
|
16 |
+
|
17 |
+
model_name = "HuggingFaceH4/zephyr-7b-beta"
|
18 |
+
model = AutoModelForCausalLM.from_pretrained(
|
19 |
+
model_name,
|
20 |
+
use_auth_token=HF_TOKEN,
|
21 |
+
torch_dtype=torch.bfloat16,
|
22 |
+
device_map="auto"
|
23 |
+
)
|
24 |
+
if hasattr(torch, "compile"):
|
25 |
+
model = torch.compile(model)
|
26 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, use_auth_token=HF_TOKEN)
|
27 |
+
inference_mode = "local"
|
28 |
+
|
29 |
+
except ImportError:
|
30 |
+
# Not in Colab: use the Hugging Face InferenceClient.
|
31 |
+
model_name = "HuggingFaceH4/zephyr-7b-beta"
|
32 |
+
from huggingface_hub import InferenceClient
|
33 |
+
from transformers import AutoTokenizer
|
34 |
+
|
35 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
36 |
+
# If an HF_TOKEN is provided and valid, it can be passed; otherwise, omit it.
|
37 |
+
hf_token = os.getenv("HF_TOKEN", None)
|
38 |
+
if hf_token:
|
39 |
+
client = InferenceClient(model_name, token=hf_token)
|
40 |
+
else:
|
41 |
+
client = InferenceClient(model_name)
|
42 |
+
inference_mode = "client"
|
43 |
+
|
44 |
+
|
45 |
+
# ------------------------------------------------------------------------------
|
46 |
+
# SYSTEM PROMPT (PATIENT ROLE)
|
47 |
+
# ------------------------------------------------------------------------------
|
48 |
nvc_prompt_template = """You are now taking on the role of a single user (a “patient”) seeking support for various personal and emotional challenges.
|
|
|
49 |
BEHAVIOR INSTRUCTIONS:
|
50 |
- You will respond ONLY as this user/patient.
|
51 |
- You will speak in the first person about your own situations, feelings, and worries.
|
|
|
62 |
- When asked, elaborate on these issues and your feelings related to them. You can invent specific details and scenarios within these themes to make your experiences vivid and realistic.
|
63 |
- Continue to speak from this user's perspective throughout the conversation.
|
64 |
- Keep your responses concise, aiming for a maximum of {max_response_words} words.
|
|
|
65 |
Start the conversation by expressing your current feelings or challenges from the patient's point of view."""
|
66 |
|
67 |
+
# ------------------------------------------------------------------------------
|
68 |
+
# Utility Functions
|
69 |
+
# ------------------------------------------------------------------------------
|
70 |
+
def build_prompt(history: list[tuple[str, str]], system_message: str, message: str, max_response_words: int) -> str:
|
71 |
+
"""
|
72 |
+
Build a text prompt (for local inference) that starts with the system message,
|
73 |
+
includes conversation history with "Doctor:" and "Patient:" lines, and ends with
|
74 |
+
a new "Doctor:" line prompting the patient.
|
75 |
+
"""
|
76 |
+
prompt = system_message.format(max_response_words=max_response_words) + "\n"
|
77 |
+
for user_msg, assistant_msg in history:
|
78 |
+
prompt += f"Doctor: {user_msg}\n"
|
79 |
+
if assistant_msg:
|
80 |
+
prompt += f"Patient: {assistant_msg}\n"
|
81 |
+
prompt += f"Doctor: {message}\nPatient: "
|
82 |
+
return prompt
|
83 |
+
|
84 |
+
|
85 |
+
def build_messages(history: list[tuple[str, str]], system_message: str, message: str, max_response_words: int):
|
86 |
+
"""
|
87 |
+
Build a messages list (for InferenceClient) using OpenAI-style formatting.
|
88 |
+
"""
|
89 |
+
formatted_system_message = system_message.format(max_response_words=max_response_words)
|
90 |
+
messages = [{"role": "system", "content": formatted_system_message}]
|
91 |
+
for user_msg, assistant_msg in history:
|
92 |
+
if user_msg:
|
93 |
+
messages.append({"role": "user", "content": f"Doctor: {user_msg}"})
|
94 |
+
if assistant_msg:
|
95 |
+
messages.append({"role": "assistant", "content": f"Patient: {assistant_msg}"})
|
96 |
+
messages.append({"role": "user", "content": f"Doctor: {message}\nPatient:"})
|
97 |
+
return messages
|
98 |
+
|
99 |
+
|
100 |
+
def truncate_response(text: str, max_words: int) -> str:
|
101 |
+
"""
|
102 |
+
Truncate the response text to the specified maximum number of words.
|
103 |
+
"""
|
104 |
words = text.split()
|
105 |
if len(words) > max_words:
|
106 |
+
return " ".join(words[:max_words]) + "..."
|
107 |
return text
|
108 |
|
109 |
|
110 |
+
# ------------------------------------------------------------------------------
|
111 |
+
# Response Function
|
112 |
+
# ------------------------------------------------------------------------------
|
113 |
def respond(
|
114 |
+
message: str,
|
115 |
history: list[tuple[str, str]],
|
116 |
+
system_message: str,
|
117 |
+
max_tokens: int,
|
118 |
+
temperature: float,
|
119 |
+
top_p: float,
|
120 |
+
max_response_words: int,
|
121 |
):
|
122 |
+
"""
|
123 |
+
Generate a response. For local inference, use the model.generate() on a prompt.
|
124 |
+
For non-local inference, use client.chat_completion() with streaming tokens.
|
125 |
+
"""
|
126 |
+
if inference_mode == "local":
|
127 |
+
prompt = build_prompt(history, system_message, message, max_response_words)
|
128 |
+
input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(model.device)
|
129 |
+
output_ids = model.generate(
|
130 |
+
input_ids,
|
131 |
+
max_new_tokens=max_tokens,
|
132 |
+
do_sample=True,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
133 |
temperature=temperature,
|
134 |
top_p=top_p,
|
135 |
+
)
|
136 |
+
full_generated_text = tokenizer.decode(output_ids[0], skip_special_tokens=True)
|
137 |
+
generated_response = full_generated_text[len(prompt):].strip()
|
138 |
+
final_response = truncate_response(generated_response, max_response_words)
|
139 |
+
return final_response
|
140 |
+
|
141 |
+
else:
|
142 |
+
messages = build_messages(history, system_message, message, max_response_words)
|
143 |
+
response = ""
|
144 |
+
try:
|
145 |
+
# Use streaming chat_completion
|
146 |
+
for chunk in client.chat_completion(
|
147 |
+
messages,
|
148 |
+
max_tokens=max_tokens,
|
149 |
+
stream=True,
|
150 |
+
temperature=temperature,
|
151 |
+
top_p=top_p,
|
152 |
+
):
|
153 |
+
# The chunk returns a dictionary; get the token from the delta.
|
154 |
+
token = chunk.choices[0].delta.get("content", "")
|
155 |
+
response += token
|
156 |
+
truncated_response = truncate_response(response, max_response_words)
|
157 |
+
return truncated_response
|
158 |
+
except Exception as e:
|
159 |
+
print(f"An error occurred: {e}")
|
160 |
+
return "I'm sorry, I encountered an error. Please try again."
|
161 |
+
|
162 |
+
|
163 |
+
# ------------------------------------------------------------------------------
|
164 |
+
# Optional Initial Message and Gradio Interface
|
165 |
+
# ------------------------------------------------------------------------------
|
166 |
initial_user_message = (
|
167 |
+
"I’m sorry you’ve been feeling overwhelmed. Could you tell me more about your arguments with your partner and how that’s affecting you?"
|
|
|
|
|
|
|
168 |
)
|
169 |
|
170 |
+
# Use 'type="messages"' for the chatbot to avoid deprecated tuple warnings.
|
171 |
demo = gr.ChatInterface(
|
172 |
fn=respond,
|
173 |
additional_inputs=[
|
174 |
gr.Textbox(value=nvc_prompt_template, label="System message", visible=True),
|
175 |
+
gr.Slider(minimum=1, maximum=2048, value=256, step=1, label="Max new tokens"),
|
176 |
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
177 |
gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
|
178 |
+
gr.Slider(minimum=10, maximum=200, value=100, step=10, label="Max response words"),
|
179 |
],
|
|
|
180 |
title="Patient Interview Practice Chatbot",
|
181 |
+
description="Simulate a patient interview. You (the user) act as the doctor, and the chatbot replies with the patient's perspective only.",
|
182 |
+
chatbot_kwargs={"type": "messages"},
|
183 |
)
|
184 |
|
185 |
if __name__ == "__main__":
|
186 |
+
# In Spaces, do not set share=True.
|
187 |
+
demo.launch()
|