Spaces:
Sleeping
Sleeping
File size: 1,631 Bytes
58dd524 705a10e 58dd524 705a10e 58dd524 705a10e 58dd524 705a10e |
1 2 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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
# مدل مورد نظر: میتونی اینو با هر مدل دیگه مثل HooshvareLab/gpt2-fa عوض کنی
model_name = "microsoft/DialoGPT-medium"
# بارگذاری مدل و توکنایزر
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
# تاریخچه چت را نگه میداریم
chat_history_ids = None
def chat_with_bot(user_input, history=[]):
global chat_history_ids
# توکنایز ورودی
new_input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors='pt')
# ترکیب با تاریخچه قبلی (context-aware)
bot_input_ids = torch.cat([chat_history_ids, new_input_ids], dim=-1) if chat_history_ids is not None else new_input_ids
# تولید پاسخ
chat_history_ids = model.generate(bot_input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id)
# گرفتن پاسخ آخر فقط
response = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
# به تاریخچه اضافه کن
history.append((user_input, response))
return history, history
# رابط Gradio
with gr.Blocks() as demo:
gr.Markdown("## 🤖 Chat with DialoGPT")
chatbot = gr.Chatbot()
msg = gr.Textbox(label="Type your message")
clear = gr.Button("Clear")
state = gr.State([])
msg.submit(chat_with_bot, [msg, state], [chatbot, state])
clear.click(lambda: ([], []), None, [chatbot, state])
demo.launch()
|