|
import gradio as gr |
|
from transformers import AutoTokenizer |
|
import onnxruntime as ort |
|
import numpy as np |
|
import string |
|
from huggingface_hub import InferenceClient |
|
import os |
|
|
|
client = InferenceClient(api_key=os.environ.get('HF_TOKEN')) |
|
|
|
|
|
HG_MODEL = "livekit/turn-detector" |
|
ONNX_FILENAME = "model_quantized.onnx" |
|
PUNCS = string.punctuation.replace("'", "") |
|
MAX_HISTORY = 4 |
|
MAX_HISTORY_TOKENS = 512 |
|
EOU_THRESHOLD = 0.5 |
|
|
|
|
|
tokenizer = AutoTokenizer.from_pretrained(HG_MODEL) |
|
onnx_session = ort.InferenceSession(ONNX_FILENAME, providers=["CPUExecutionProvider"]) |
|
|
|
|
|
def softmax(logits): |
|
exp_logits = np.exp(logits - np.max(logits)) |
|
return exp_logits / np.sum(exp_logits) |
|
|
|
|
|
def normalize_text(text): |
|
def strip_puncs(text): |
|
return text.translate(str.maketrans("", "", PUNCS)) |
|
return " ".join(strip_puncs(text).lower().split()) |
|
|
|
|
|
def format_chat_ctx(chat_ctx): |
|
new_chat_ctx = [] |
|
for msg in chat_ctx: |
|
if msg["role"] in ("user", "assistant"): |
|
content = normalize_text(msg["content"]) |
|
if content: |
|
msg["content"] = content |
|
new_chat_ctx.append(msg) |
|
|
|
|
|
convo_text = tokenizer.apply_chat_template( |
|
new_chat_ctx, add_generation_prompt=False, add_special_tokens=False, tokenize=False |
|
) |
|
|
|
|
|
ix = convo_text.rfind("<|im_end|>") |
|
return convo_text[:ix] |
|
|
|
|
|
def calculate_eou(chat_ctx, session): |
|
formatted_text = format_chat_ctx(chat_ctx[-MAX_HISTORY:]) |
|
inputs = tokenizer( |
|
formatted_text, |
|
return_tensors="np", |
|
truncation=True, |
|
max_length=MAX_HISTORY_TOKENS, |
|
) |
|
input_ids = np.array(inputs["input_ids"], dtype=np.int64) |
|
outputs = session.run(["logits"], {"input_ids": input_ids}) |
|
logits = outputs[0][0, -1, :] |
|
probs = softmax(logits) |
|
eou_token_id = tokenizer.encode("<|im_end|>")[-1] |
|
return probs[eou_token_id] |
|
|
|
|
|
|
|
def respond( |
|
message, |
|
history: list[tuple[str, str]], |
|
max_tokens, |
|
temperature, |
|
top_p, |
|
): |
|
|
|
messages = [{"role": "system", "content": os.environ.get("CHARACTER_DESC")}] |
|
|
|
for val in history[-20:]: |
|
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}) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
stream = client.chat.completions.create( |
|
model=os.environ.get('MODEL_ID'), |
|
messages=messages, |
|
temperature = 0.6, |
|
max_tokens= 2048, |
|
top_p = 0.9, |
|
stream=True |
|
) |
|
|
|
bot_response = "" |
|
for chunk in stream: |
|
bot_response += chunk.choices[0].delta.content |
|
yield bot_response |
|
|
|
|
|
|
|
|
|
demo = gr.ChatInterface( |
|
respond, |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
) |
|
|
|
if __name__ == "__main__": |
|
demo.launch() |
|
|