Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
# Load pretrained model
|
| 6 |
+
model_name = "microsoft/DialoGPT-medium"
|
| 7 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 8 |
+
model = AutoModelForCausalLM.from_pretrained(model_name)
|
| 9 |
+
|
| 10 |
+
# Keep track of chat history
|
| 11 |
+
chat_history_ids = None
|
| 12 |
+
|
| 13 |
+
def chatbot(user_input):
|
| 14 |
+
global chat_history_ids
|
| 15 |
+
|
| 16 |
+
# Encode user message
|
| 17 |
+
new_input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors='pt')
|
| 18 |
+
|
| 19 |
+
# Append previous history if any
|
| 20 |
+
bot_input_ids = torch.cat([chat_history_ids, new_input_ids], dim=-1) if chat_history_ids is not None else new_input_ids
|
| 21 |
+
|
| 22 |
+
# Generate response
|
| 23 |
+
chat_history_ids = model.generate(
|
| 24 |
+
bot_input_ids,
|
| 25 |
+
max_length=1000,
|
| 26 |
+
pad_token_id=tokenizer.eos_token_id,
|
| 27 |
+
do_sample=True,
|
| 28 |
+
top_k=50,
|
| 29 |
+
top_p=0.95
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
# Decode reply
|
| 33 |
+
reply = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
|
| 34 |
+
return reply
|
| 35 |
+
|
| 36 |
+
# Create simple Gradio UI
|
| 37 |
+
demo = gr.Interface(
|
| 38 |
+
fn=chatbot,
|
| 39 |
+
inputs=gr.Textbox(label="👤 You:"),
|
| 40 |
+
outputs=gr.Textbox(label="🤖 Bot:"),
|
| 41 |
+
title="Mini Chatbot using DialoGPT",
|
| 42 |
+
description="Chat with a pretrained conversational model built using Hugging Face Transformers + Gradio."
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
demo.launch()
|