khanhnhu2007 commited on
Commit
af3366a
·
verified ·
1 Parent(s): 323f353

Upload main_gradio_chat.py

Browse files
Files changed (1) hide show
  1. main_gradio_chat.py +46 -0
main_gradio_chat.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # main_gradio_chat_all.py
2
+ import os
3
+ from transformers import pipeline, AutoTokenizer, AutoModelForQuestionAnswering
4
+ import gradio as gr
5
+ from dotenv import load_dotenv
6
+
7
+ # Load token Hugging Face từ file .env
8
+ load_dotenv()
9
+ HF_TOKEN = os.getenv("HF_TOKEN")
10
+ if not HF_TOKEN:
11
+ raise ValueError("Bạn chưa đặt token Hugging Face trong file .env hoặc biến môi trường")
12
+
13
+ # Load model (GPU nếu có)
14
+ device = 0 if pipeline("question-answering").model.device.type == "cuda" else -1
15
+ print(f"Đang sử dụng {'GPU' if device==0 else 'CPU'} để chạy model")
16
+
17
+ qa_pipeline = pipeline(
18
+ "question-answering",
19
+ model="nguyenvulebinh/vi-mrc-base",
20
+ tokenizer="nguyenvulebinh/vi-mrc-base",
21
+ device=device,
22
+ token=HF_TOKEN
23
+ )
24
+
25
+ # Hàm trả lời chatbot
26
+ def answer_question(chat_history, user_input):
27
+ context = "\n".join([h[1] for h in chat_history] + [user_input])
28
+ result = qa_pipeline({
29
+ "question": user_input,
30
+ "context": context if context else "Không có dữ liệu"
31
+ })
32
+ answer = result.get("answer", "Xin lỗi, tôi không biết câu trả lời.")
33
+ chat_history.append((user_input, answer))
34
+ return chat_history, ""
35
+
36
+ # Giao diện Gradio
37
+ with gr.Blocks() as demo:
38
+ chatbot = gr.Chatbot()
39
+ msg = gr.Textbox(label="Nhập câu hỏi của bạn")
40
+ clear = gr.Button("Xóa")
41
+
42
+ msg.submit(answer_question, [chatbot, msg], [chatbot, msg])
43
+ clear.click(lambda: [], None, chatbot)
44
+
45
+ # Chạy công khai
46
+ demo.launch(server_name="0.0.0.0", server_port=7860, share=True)