ThongCoding commited on
Commit
c51caae
·
verified ·
1 Parent(s): 5864050

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -37
app.py CHANGED
@@ -1,52 +1,70 @@
1
  import gradio as gr
2
  import logging
 
3
  from huggingface_hub import InferenceClient
4
- from google_trans_new import google_translator
5
-
6
- # Khởi tạo client HF và Google Translator
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
- translator = google_translator() # googletrans
9
 
10
  logging.basicConfig(level=logging.INFO)
11
 
 
 
 
 
 
 
 
12
  SYSTEM_MSG = """
13
  You are a professional speaking AI assistant.
14
  Always output in perfect English that is translateable to Vietnamese that is correct spelling, punctuation and grammar.
15
  """
16
 
 
 
 
 
 
 
 
 
 
17
  def respond(message, history):
18
- # Build system + user messages
19
- messages = [{"role": "system", "content": SYSTEM_MSG}]
20
- # Dịch user sang Anh
21
- message_en = translator.translate(message, lang_tgt='en')
22
- messages.append({"role": "user", "content": message_en})
23
-
24
- # (Nếu history muốn giữ, bạn có thể dịch append tương tự ở đây)
25
-
26
- # Gọi chat_completion
27
- try:
28
- response = ""
29
- for chunk in client.chat_completion(
30
- model="HuggingFaceH4/zephyr-7b-beta",
31
- messages=messages,
32
- max_tokens=2048,
33
- temperature=0.0,
34
- top_p=0.9,
35
- stream=True
36
- ):
37
- response += chunk.choices[0].delta.content
38
- except Exception as e:
39
- return f"Error: {e}"
40
-
41
- # Dịch ngược sang tiếng Việt
42
- answer_vi = translator.translate(response, lang_tgt='vi')
43
- logging.info(f"Bot (EN): {response}")
44
- logging.info(f"Bot (VI): {answer_vi}")
45
-
46
- return answer_vi
47
-
48
- # Gradio UI
49
- demo = gr.ChatInterface(fn=respond, theme="soft")
 
 
 
 
 
 
50
 
51
  if __name__ == "__main__":
52
  demo.launch()
 
1
  import gradio as gr
2
  import logging
3
+ from transformers import pipeline
4
  from huggingface_hub import InferenceClient
 
 
 
 
 
5
 
6
  logging.basicConfig(level=logging.INFO)
7
 
8
+ # 1) Khởi tạo pipelines dịch
9
+ vi2en = pipeline("translation", model="Helsinki-NLP/opus-mt-vi-en")
10
+ en2vi = pipeline("translation", model="Helsinki-NLP/opus-mt-en-vi")
11
+
12
+ # 2) Khởi tạo client chat
13
+ client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
14
+
15
  SYSTEM_MSG = """
16
  You are a professional speaking AI assistant.
17
  Always output in perfect English that is translateable to Vietnamese that is correct spelling, punctuation and grammar.
18
  """
19
 
20
+ def translate_vi2en(text: str) -> str:
21
+ # Chia nhỏ nếu quá dài, pipeline tự handle batch
22
+ res = vi2en(text, max_length=512)
23
+ return res[0]["translation_text"]
24
+
25
+ def translate_en2vi(text: str) -> str:
26
+ res = en2vi(text, max_length=512)
27
+ return res[0]["translation_text"]
28
+
29
  def respond(message, history):
30
+ # 1) Dịch sang Anh
31
+ message_en = translate_vi2en(message)
32
+
33
+ # 2) Build messages
34
+ msgs = [{"role": "system", "content": SYSTEM_MSG},
35
+ {"role": "user", "content": message_en}]
36
+ # Nếu bạn muốn context, bạn có thể append history đã dịch ở đây...
37
+
38
+ # 3) Gọi Hugging Face chat
39
+ response = ""
40
+ for chunk in client.chat_completion(
41
+ model="HuggingFaceH4/zephyr-7b-beta",
42
+ messages=msgs,
43
+ max_tokens=128,
44
+ temperature=0.0,
45
+ top_p=0.9,
46
+ stream=True,
47
+ ):
48
+ response += chunk.choices[0].delta.content
49
+
50
+ logging.info("Response (EN): %s", response)
51
+
52
+ # 4) Dịch ngược về Việt
53
+ answer_vi = translate_en2vi(response)
54
+ logging.info("Response (VI): %s", answer_vi)
55
+
56
+ # 5) Cập nhật history và trả về
57
+ history.append((message, answer_vi))
58
+ return "", history
59
+
60
+ # 6) Gradio UI
61
+ with gr.Blocks(theme="soft") as demo:
62
+ gr.Markdown("# 🤖 Trợ lý AI Tiếng Việt (HF Translation)")
63
+ chatbot = gr.Chatbot()
64
+ txt = gr.Textbox(placeholder="Nhập câu hỏi của bạn...")
65
+ clear = gr.Button("🧹 Xóa trò chuyện")
66
+ txt.submit(respond, [txt, chatbot], [txt, chatbot])
67
+ clear.click(lambda: ([], ""), None, [chatbot, txt])
68
 
69
  if __name__ == "__main__":
70
  demo.launch()