qew / app.py
beyoru's picture
Update app.py
ead29d0 verified
raw
history blame
2.99 kB
import gradio as gr
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
import numpy as np
import string
# Load tokenizer and model for EOU detection
tokenizer = AutoTokenizer.from_pretrained("livekit/turn-detector")
model = AutoModelForCausalLM.from_pretrained("livekit/turn-detector")
# Define function to calculate softmax
def _softmax(logits: np.ndarray) -> np.ndarray:
exp_logits = np.exp(logits - np.max(logits))
return exp_logits / np.sum(exp_logits)
# Define the EOU probability calculation
def get_eou_probability(chat_ctx: list) -> float:
"""Calculate the probability of End of Utterance (EOU)"""
# Normalize and prepare the chat context
text = " ".join([msg["content"] for msg in chat_ctx])
inputs = tokenizer(text, return_tensors="pt", max_length=512, truncation=True)
# Run the model and get the logits
with torch.no_grad():
outputs = model(**inputs)
logits = outputs.logits[0, -1, :] # Get logits of the last token
probs = _softmax(logits.numpy()) # Convert logits to probabilities
# Assuming <|im_end|> token corresponds to EOU, get the probability of that token
eou_token_id = tokenizer.encode("<|im_end|>")[-1]
return probs[eou_token_id]
# Define the main response function for Gradio
def respond(
message,
history: list[tuple[str, str]],
system_message,
max_tokens,
temperature,
top_p,
):
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]})
messages.append({"role": "user", "content": message})
# Get the response from the Qwen model (e.g., for conversation generation)
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
# After generating the response, get the EOU probability
eou_probability = get_eou_probability(messages) # Get EOU prediction
print(f"EOU Probability: {eou_probability}")
# Include the EOU probability in the output
yield f"\nEOU Probability: {eou_probability:.2f}"
# Gradio interface setup
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)",
),
],
)
if __name__ == "__main__":
demo.launch()