Update app.py
Browse files
app.py
CHANGED
|
@@ -1,45 +1,48 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
reply = query_hf_model(chat_history)
|
| 34 |
-
chat_history.append({"role": "assistant", "content": reply})
|
| 35 |
-
return "", chat_history
|
| 36 |
|
| 37 |
with gr.Blocks() as demo:
|
| 38 |
-
gr.Markdown("### 🤖
|
| 39 |
|
| 40 |
-
chatbot = gr.Chatbot(label="Chat
|
| 41 |
-
|
| 42 |
|
| 43 |
-
|
|
|
|
|
|
|
| 44 |
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
# Load model directly from Hugging Face Hub
|
| 6 |
+
model_name = "sshleifer/tiny-gpt2"
|
| 7 |
+
|
| 8 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 9 |
+
model = AutoModelForCausalLM.from_pretrained(model_name)
|
| 10 |
+
model.eval()
|
| 11 |
+
|
| 12 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 13 |
+
model.to(device)
|
| 14 |
+
|
| 15 |
+
def generate_reply(messages):
|
| 16 |
+
# Concatenate messages into a simple prompt
|
| 17 |
+
prompt = "\n".join([m["content"] for m in messages])
|
| 18 |
+
|
| 19 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(device)
|
| 20 |
+
outputs = model.generate(
|
| 21 |
+
**inputs,
|
| 22 |
+
max_new_tokens=100,
|
| 23 |
+
do_sample=True,
|
| 24 |
+
top_p=0.95,
|
| 25 |
+
temperature=0.7,
|
| 26 |
+
pad_token_id=tokenizer.eos_token_id
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
output_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 30 |
+
# Extract the newly generated part
|
| 31 |
+
reply = output_text[len(prompt):].strip().split("\n")[0]
|
| 32 |
+
return messages + [{"role": "assistant", "content": reply}]
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
with gr.Blocks() as demo:
|
| 35 |
+
gr.Markdown("### 🤖 Tiny GPT-2 Chatbot (No API Key, Hugging Face Model)")
|
| 36 |
|
| 37 |
+
chatbot = gr.Chatbot(label="Chat", type="messages")
|
| 38 |
+
user_input = gr.Textbox(label="Type your message here")
|
| 39 |
|
| 40 |
+
def on_submit(message, chat_history):
|
| 41 |
+
chat_history.append({"role": "user", "content": message})
|
| 42 |
+
return "", chat_history
|
| 43 |
|
| 44 |
+
user_input.submit(on_submit, [user_input, chatbot], [user_input, chatbot]).then(
|
| 45 |
+
generate_reply, chatbot, chatbot
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
demo.launch()
|