ThongCoding commited on
Commit
de2702a
·
verified ·
1 Parent(s): 917d560

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -54
app.py CHANGED
@@ -1,76 +1,68 @@
1
  import gradio as gr
2
- import os
3
  from huggingface_hub import InferenceClient
4
  from deep_translator import GoogleTranslator
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:
23
- return "⚠️ Tin nhắn có quá nhiều dấu hỏi hoặc dấu chấm than. Vui lòng chỉnh sửa lại."
24
-
25
- try:
26
- message_en = translator_vi2en.translate(message)
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
- # Tạo ChatInterface
61
- chat = gr.ChatInterface(
62
- fn=respond,
63
- title="🤖 Trợ 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
- )
67
-
68
- # Gói nó trong gr.Blocks
69
- with gr.Blocks() as demo:
70
- chat.render()
71
 
72
- # Bật OpenAPI để Huggingface Spaces nhận diện được API
73
- demo.openapi = True
74
 
75
  if __name__ == "__main__":
76
- demo.launch()
 
1
  import gradio as gr
2
+ import logging, langdetect
3
  from huggingface_hub import InferenceClient
4
  from deep_translator import GoogleTranslator
5
 
6
+ # Khởi tạo client HF và translator
7
+ client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
 
8
  translator_vi2en = GoogleTranslator(source='vi', target='en')
9
  translator_en2vi = GoogleTranslator(source='en', target='vi')
10
 
11
+ logging.basicConfig(level=logging.INFO)
12
+
13
  def respond(
14
  message,
15
  history: list[tuple[str, str]],
16
+ system_message="""
17
+ You are a professional speaking AI assistant.
18
+ You can help solving the problems.
19
+ You can only speak English with correct spelling, punctuation and grammar.
20
+ """,
21
+ max_tokens=2048,
22
+ temperature=0.0,
23
  top_p=0.9,
24
  ):
25
+ # Tạo list tin nhắn bắt đầu từ hệ thống
26
+ messages = [{"role": "system", "content": system_message}]
27
+
28
+ # Dịch câu hỏi của người dùng từ tiếng Việt sang tiếng Anh
29
+ message_en = translator_vi2en.translate(message)
 
 
 
 
 
 
 
 
 
 
 
30
 
31
+ # Thêm các tin nhắn lịch sử vào messages
32
+ for val in history:
33
+ if val[0]: # Tin nhắn của người dùng
34
+ messages.append({"role": "user", "content": val[0]})
35
+ if val[1]: # Tin nhắn của trợ lý
36
+ messages.append({"role": "assistant", "content": val[1]})
 
37
 
38
+ # Thêm câu hỏi của người dùng vào cuối lịch sử
39
+ messages.append({"role": "user", "content": message_en})
40
 
41
+ response = ""
 
 
 
 
 
 
42
 
43
+ # Gửi yêu cầu tới mô hình và nhận kết quả
44
  try:
45
+ for chunk in client.chat_completion(
46
+ model="HuggingFaceH4/zephyr-7b-beta",
47
+ messages=messages,
48
+ max_tokens=max_tokens,
49
+ temperature=temperature,
50
+ top_p=top_p,
51
+ stream=True
52
+ ):
53
+ # Tiến hành nhận phản hồi từ mô hình
54
+ response += chunk.choices[0].delta.content
55
 
56
+ except Exception as e:
57
+ return f"Error: {str(e)}"
58
 
59
+ response_vi = translator_en2vi.translate(response)
60
+ logging.info(f"Successfully generated text: {response}")
61
+
62
+ return response if langdetect.detect(response) == 'vi' else response_vi
 
 
 
 
 
 
 
63
 
64
+ # Gradio UI
65
+ demo = gr.ChatInterface(fn=respond, theme="soft")
66
 
67
  if __name__ == "__main__":
68
+ demo.launch()