|
import gradio as gr |
|
from huggingface_hub import InferenceClient |
|
from transformers import AutoTokenizer, AutoModelForCausalLM |
|
import torch |
|
|
|
|
|
client = InferenceClient("Qwen/Qwen2.5-3B-Instruct") |
|
|
|
|
|
tokenizer = AutoTokenizer.from_pretrained("livekit/turn-detector") |
|
model = AutoModelForCausalLM.from_pretrained("livekit/turn-detector") |
|
|
|
|
|
def compute_eou_probability(chat_ctx: list[dict[str, str]], max_tokens: int = 512) -> float: |
|
|
|
conversation = ["Assistant ready to help."] |
|
|
|
|
|
for msg in chat_ctx: |
|
content = msg.get("content", "") |
|
if content: |
|
conversation.append(content) |
|
|
|
|
|
inputs = tokenizer( |
|
conversation, padding=True, truncation=True, max_length=max_tokens, return_tensors="pt" |
|
) |
|
|
|
|
|
with torch.no_grad(): |
|
outputs = model(**inputs) |
|
|
|
|
|
logits = outputs.logits[0, -1, :] |
|
|
|
|
|
probabilities = torch.nn.functional.softmax(logits, dim=-1) |
|
|
|
|
|
eou_token_id = tokenizer.encode("<|im_end|>")[0] |
|
eou_probability = probabilities[eou_token_id].item() |
|
|
|
return eou_probability |
|
|
|
|
|
def respond( |
|
message, |
|
history: list[tuple[str, str]], |
|
system_message, |
|
max_tokens, |
|
temperature, |
|
top_p, |
|
eou_threshold: float = 0.2, |
|
): |
|
messages = [{"role": "system", "content": system_message}] |
|
|
|
for val in history: |
|
if val[0]: |
|
messages.append({"role": "user", "content": val[0]}) |
|
if val[1]: |
|
messages.append({"role": "assistant", "content": val[1]}) |
|
|
|
|
|
eou_probability = compute_eou_probability(messages, max_tokens=max_tokens) |
|
print(eou_probability) |
|
|
|
if eou_probability >= eou_threshold: |
|
|
|
messages.append({"role": "user", "content": message}) |
|
|
|
response = "" |
|
|
|
for message in client.chat_completion( |
|
messages, |
|
max_tokens=max_tokens, |
|
stream=True, |
|
temperature=temperature, |
|
top_p=top_p, |
|
): |
|
token = message.choices[0].delta.content |
|
response += token |
|
yield response |
|
else: |
|
|
|
yield "Waiting for user to finish... Please continue." |
|
print("Waiting for user to finish... Please continue.") |
|
|
|
|
|
demo = gr.ChatInterface( |
|
respond, |
|
additional_inputs=[ |
|
gr.Textbox(value="Bạn là một trợ lý ảo", label="System message"), |
|
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"), |
|
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"), |
|
gr.Slider( |
|
minimum=0.1, |
|
maximum=1.0, |
|
value=0.95, |
|
step=0.05, |
|
label="Top-p (nucleus sampling)", |
|
), |
|
gr.Slider( |
|
minimum=0.0, maximum=1.0, value=0.7, step=0.05, label="EOU Threshold" |
|
), |
|
], |
|
) |
|
|
|
if __name__ == "__main__": |
|
demo.launch() |
|
|