ThongAccount commited on
Commit
b1041b8
·
1 Parent(s): 05966d6
Files changed (1) hide show
  1. app.py +35 -36
app.py CHANGED
@@ -5,13 +5,18 @@ from deep_translator import GoogleTranslator
5
 
6
  hf_token = os.getenv("HF_AUTH_TOKEN")
7
 
8
- # Khởi tạo client HF và translator
9
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta", token=hf_token)
10
  translator_vi2en = GoogleTranslator(source='vi', target='en')
11
  translator_en2vi = GoogleTranslator(source='en', target='vi')
12
 
13
- def respond(message, chat_history):
14
- # Không dùng chat_history cũ để tạo prompt
 
 
 
 
 
 
15
  if len(message) > 500:
16
  return "⚠️ Câu hỏi quá dài! Vui lòng rút gọn dưới 500 ký tự."
17
  if message.count("?") > 10 or message.count("!") > 10:
@@ -22,50 +27,44 @@ def respond(message, chat_history):
22
  except Exception:
23
  return "⚠️ Không thể dịch câu hỏi sang tiếng Anh."
24
 
25
- # Tạo prompt mới tinh mỗi lần
26
  prompt = (
27
  "You are a helpful, professional AI assistant who communicates fluently in Vietnamese.\n"
28
  "If the user greets, reply briefly. If the user asks, answer accurately.\n\n"
29
- f"User: {message_en}\nAssistant:"
30
  )
 
 
 
 
 
 
 
 
31
 
32
- # Gửi lên model
33
- try:
34
- resp = client.text_generation(
35
- prompt,
36
- max_new_tokens=256,
37
- temperature=0.5,
38
- top_p=0.9,
39
- )
40
- answer_en = resp.strip().split("Assistant:")[-1].strip()
41
- except Exception:
42
- return "⚠️ Không thể lấy phản hồi từ mô hình."
43
 
44
- # Dịch câu trả lời về tiếng Việt
45
  try:
46
  answer_vi = translator_en2vi.translate(answer_en)
47
  except Exception:
48
  answer_vi = "(Không thể dịch câu trả lời về tiếng Việt)"
49
 
50
- # Update lịch sử chat
51
- chat_history.append((message, answer_vi))
52
- return "", chat_history
53
-
54
- def clear_chat():
55
- return [], ""
56
-
57
- # Tạo Gradio app
58
- with gr.Blocks(theme="soft") as demo:
59
- gr.Markdown("# 🤖 Trợ lý AI Tiếng Việt (Translate-then-Predict)")
60
- gr.Markdown("💬 Nhập tiếng Việt ➔ dịch tiếng Anh ➔ hỏi model ➔ dịch lại tiếng Việt.")
61
-
62
- chatbot = gr.Chatbot()
63
- msg = gr.Textbox(label="Nhập tin nhắn...")
64
- send = gr.Button("Gửi")
65
- clear = gr.Button("🧹 Xóa trò chuyện")
66
 
67
- send.click(respond, [msg, chatbot], [msg, chatbot])
68
- clear.click(clear_chat, [], [chatbot, msg])
 
 
 
 
 
 
69
 
70
  if __name__ == "__main__":
71
- demo.launch(share=False, enable_queue=True, enable_api=True)
 
5
 
6
  hf_token = os.getenv("HF_AUTH_TOKEN")
7
 
 
8
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta", token=hf_token)
9
  translator_vi2en = GoogleTranslator(source='vi', target='en')
10
  translator_en2vi = GoogleTranslator(source='en', target='vi')
11
 
12
+ def respond(
13
+ message,
14
+ history: list[tuple[str, str]],
15
+ temperature=0.5,
16
+ top_p=0.9,
17
+ ):
18
+ history = []
19
+
20
  if len(message) > 500:
21
  return "⚠️ Câu hỏi quá dài! Vui lòng rút gọn dưới 500 ký tự."
22
  if message.count("?") > 10 or message.count("!") > 10:
 
27
  except Exception:
28
  return "⚠️ Không thể dịch câu hỏi sang tiếng Anh."
29
 
 
30
  prompt = (
31
  "You are a helpful, professional AI assistant who communicates fluently in Vietnamese.\n"
32
  "If the user greets, reply briefly. If the user asks, answer accurately.\n\n"
 
33
  )
34
+
35
+ for user_msg, bot_msg in history:
36
+ try:
37
+ user_msg_en = translator_vi2en.translate(user_msg)
38
+ bot_msg_en = translator_vi2en.translate(bot_msg)
39
+ except Exception:
40
+ continue
41
+ prompt += f"User: {user_msg_en}\nAssistant: {bot_msg_en}\n"
42
 
43
+ prompt += f"User: {message_en}\nAssistant:"
44
+
45
+ resp = client.text_generation(
46
+ prompt,
47
+ max_new_tokens=128,
48
+ temperature=temperature,
49
+ top_p=top_p,
50
+ )
51
+ answer_en = resp.strip().split("Assistant:")[-1].strip()
 
 
52
 
 
53
  try:
54
  answer_vi = translator_en2vi.translate(answer_en)
55
  except Exception:
56
  answer_vi = "(Không thể dịch câu trả lời về tiếng Việt)"
57
 
58
+ return answer_vi
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
+ # Quan trọng: bật api_open=True ngay lúc tạo
61
+ demo = gr.ChatInterface(
62
+ fn=respond,
63
+ title="🤖 Trợ lý AI Tiếng Việt (Translate-then-Predict)",
64
+ description="💬 Nhập tiếng Việt ➔ dịch tiếng Anh ➔ hỏi model ➔ dịch lại tiếng Việt.",
65
+ theme="soft",
66
+ api_open=True, # <- thêm dòng này để mở API mode
67
+ )
68
 
69
  if __name__ == "__main__":
70
+ demo.launch(share=False)