Update app.py
Browse files
app.py
CHANGED
|
@@ -2,21 +2,43 @@ import gradio as gr
|
|
| 2 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 3 |
import torch
|
| 4 |
|
| 5 |
-
# Tải mô hình chỉ 1 lần
|
| 6 |
tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-small")
|
| 7 |
model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-small")
|
| 8 |
|
| 9 |
-
#
|
|
|
|
|
|
|
| 10 |
def chatbot(msg):
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
return f"Dr. Mom AI: {reply}"
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
-
demo.launch()
|
|
|
|
| 2 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 3 |
import torch
|
| 4 |
|
| 5 |
+
# Tải mô hình chỉ 1 lần
|
| 6 |
tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-small")
|
| 7 |
model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-small")
|
| 8 |
|
| 9 |
+
# Biến toàn cục lưu lịch sử hội thoại
|
| 10 |
+
chat_history_ids = None
|
| 11 |
+
|
| 12 |
def chatbot(msg):
|
| 13 |
+
global chat_history_ids
|
| 14 |
+
|
| 15 |
+
# Encode câu hỏi mới
|
| 16 |
+
new_input_ids = tokenizer.encode(msg + tokenizer.eos_token, return_tensors='pt')
|
| 17 |
+
|
| 18 |
+
# Nếu chưa có lịch sử, khởi tạo; nếu có thì nối thêm
|
| 19 |
+
if chat_history_ids is None:
|
| 20 |
+
bot_input_ids = new_input_ids
|
| 21 |
+
else:
|
| 22 |
+
bot_input_ids = torch.cat([chat_history_ids, new_input_ids], dim=-1)
|
| 23 |
+
|
| 24 |
+
# Sinh câu trả lời dựa trên toàn bộ lịch sử
|
| 25 |
+
chat_history_ids = model.generate(
|
| 26 |
+
bot_input_ids,
|
| 27 |
+
max_length=1000, # tăng để giữ nhiều context
|
| 28 |
+
pad_token_id=tokenizer.eos_token_id
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
# Decode câu trả lời (chỉ lấy phần mới sinh ra)
|
| 32 |
+
reply = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
|
| 33 |
return f"Dr. Mom AI: {reply}"
|
| 34 |
|
| 35 |
+
# Giao diện Gradio
|
| 36 |
+
demo = gr.Interface(
|
| 37 |
+
fn=chatbot,
|
| 38 |
+
inputs=gr.Textbox(label="Bạn hỏi gì nè?"),
|
| 39 |
+
outputs=gr.Textbox(label="Dr. Mom AI trả lời"),
|
| 40 |
+
title="Dr. Mom AI",
|
| 41 |
+
theme="default"
|
| 42 |
+
)
|
| 43 |
|
| 44 |
+
demo.launch()
|