Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,28 +1,31 @@
|
|
| 1 |
-
import torch
|
| 2 |
import gradio as gr
|
|
|
|
| 3 |
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 4 |
|
| 5 |
-
model_name = "
|
| 6 |
|
| 7 |
-
# Load tokenizer and model
|
| 8 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 9 |
-
model =
|
| 10 |
|
| 11 |
-
# Create text generation pipeline
|
| 12 |
generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
| 13 |
|
| 14 |
-
# Chat function (ChatGPT-style with faster, shorter replies)
|
| 15 |
def chat(user_input, history=[]):
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 4 |
|
| 5 |
+
model_name = "sshleifer/tiny-gpt2" # Light model for free CPU Space
|
| 6 |
|
|
|
|
| 7 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 8 |
+
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto")
|
| 9 |
|
|
|
|
| 10 |
generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
| 11 |
|
|
|
|
| 12 |
def chat(user_input, history=[]):
|
| 13 |
+
prompt = "You are a helpful and friendly assistant.\n"
|
| 14 |
+
for msg in history:
|
| 15 |
+
prompt += f"User: {msg[0]}\nAI: {msg[1]}\n"
|
| 16 |
+
prompt += f"User: {user_input}\nAI:"
|
| 17 |
+
|
| 18 |
+
response = generator(prompt, max_new_tokens=60, do_sample=True, temperature=0.7)[0]["generated_text"]
|
| 19 |
+
reply = response.split("AI:")[-1].split("User:")[0].strip()
|
| 20 |
+
history.append((user_input, reply))
|
| 21 |
+
return history, history
|
| 22 |
+
|
| 23 |
+
with gr.Blocks() as demo:
|
| 24 |
+
gr.Markdown("# 🤖 Tiny GPT-2 Chatbot")
|
| 25 |
+
chatbot = gr.Chatbot()
|
| 26 |
+
msg = gr.Textbox(label="Ask something...")
|
| 27 |
+
state = gr.State([])
|
| 28 |
+
|
| 29 |
+
msg.submit(chat, [msg, state], [chatbot, state])
|
| 30 |
+
|
| 31 |
+
demo.launch()
|