Spaces:
Sleeping

talkt2api / app.py
Notbobjoe's picture
Create app.py
1d1116b verified
Raw History Blame Contribute Delete
1.9 kB
import gradio as gr
import spaces
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
MODEL_ID = "Notbobjoe/TalkT2-0.1b"
# Load the model on CPU; ZeroGPU grants GPU only while a decorated function runs.
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
model = AutoModelForCausalLM.from_pretrained(MODEL_ID)
model.eval()
@spaces.GPU(duration=60)
def generate_reply(message, history):
message = (message or "").strip()
if not message:
return ""
# Preserve TalkT2's familiar prompt format.
prompt = "You: " + message + "\nTalkT2:"
inputs = tokenizer(prompt, return_tensors="pt")
try:
model.to("cuda")
inputs = {k: v.to("cuda") for k, v in inputs.items()}
with torch.inference_mode():
output = model.generate(
**inputs,
max_new_tokens=100,
do_sample=True,
temperature=0.4,
top_p=0.95,
top_k=50,
repetition_penalty=1.1,
pad_token_id=tokenizer.eos_token_id,
eos_token_id=tokenizer.eos_token_id,
)
new_tokens = output[0, inputs["input_ids"].shape[1]:]
reply = tokenizer.decode(new_tokens, skip_special_tokens=True)
# Stop if the model begins another speaker turn.
reply = reply.split("\nYou:", 1)[0].split("\nTalkT2:", 1)[0].strip()
return reply or "(TalkT2 returned an empty response.)"
finally:
model.to("cpu")
if torch.cuda.is_available():
torch.cuda.empty_cache()
demo = gr.ChatInterface(
fn=generate_reply,
title="TalkT2-0.1b",
description="Experimental TalkT2 chatbot hosted on Hugging Face Spaces.",
examples=["Hello, who are you?", "What do you think about creativity?"],
)
# Gradio creates its public app and API automatically.
demo.queue().launch()