ThongCoding commited on
Commit
6731ed0
·
verified ·
1 Parent(s): 4108589

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -52
app.py CHANGED
@@ -1,56 +1,76 @@
1
- import os
2
  import gradio as gr
3
- from llama_cpp import Llama
4
- from huggingface_hub import hf_hub_download
5
-
6
- # --- Cấu hình model ---
7
- REPO_ID = "TheBloke/phi-2-GGUF"
8
- FILENAME = "phi-2.Q4_K_M.gguf"
9
- HF_TOKEN = os.getenv("HF_AUTH_TOKEN")
10
-
11
- # --- Tự động tải model ---
12
- model_path = hf_hub_download(
13
- repo_id=REPO_ID,
14
- filename=FILENAME,
15
- token=HF_TOKEN,
16
- )
17
 
18
- # --- Load model tối ưu RAM ---
19
- llm = Llama(
20
- model_path=model_path,
21
- n_ctx=2048,
22
- n_threads=os.cpu_count(), # Sử dụng tối đa CPU core
23
- n_batch=512, # Cỡ batch hợp lý để tiết kiệm RAM
24
- n_gpu_layers=0, # Vì Huggingface CPU Space nên để 0
25
- verbose=False,
26
- )
27
 
28
- # --- Hàm chat ---
29
- def chat_fn(message, history):
30
- history = history or []
31
- system_prompt = {"role": "system", "content": "Bạn là trợ lý AI tiếng Việt hữu ích."}
32
- messages = [system_prompt]
33
- for user_msg, bot_msg in history:
34
- messages.append({"role": "user", "content": user_msg})
35
- messages.append({"role": "assistant", "content": bot_msg})
36
- messages.append({"role": "user", "content": message})
37
-
38
- response = llm.create_chat_completion(
39
- messages=messages,
40
- max_tokens=512,
41
- temperature=0.7,
42
- stop=["<|user|>", "<|assistant|>"],
 
 
 
 
 
 
 
 
43
  )
44
- reply = response["choices"][0]["message"]["content"].strip()
45
-
46
- history.append((message, reply))
47
- return history # <-- trả về luôn cả history, không tách riêng ra nữa
48
-
49
- # --- Giao diện Gradio ---
50
- gr.ChatInterface(
51
- fn=chat_fn,
52
- chatbot=gr.Chatbot(height=450),
53
- title="🤖 Chatbot Phi-2 (Tiếng Việt)",
54
- description="Trợ AI tiếng Việt chạy bằng Phi-2 - GGUF (nhẹ, nhanh, tiết kiệm RAM)",
55
- theme="soft",
56
- ).launch(share=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from huggingface_hub import InferenceClient
3
+ from deep_translator import GoogleTranslator
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
+ # Khởi tạo client HF translator
6
+ client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
7
+ translator_vi2en = GoogleTranslator(source='vi', target='en')
8
+ translator_en2vi = GoogleTranslator(source='en', target='vi')
 
 
 
 
 
9
 
10
+ def respond(
11
+ message,
12
+ history: list[tuple[str, str]],
13
+ temperature=0.5,
14
+ top_p=0.9,
15
+ ):
16
+ history = []
17
+
18
+ if len(message) > 500:
19
+ return "⚠️ Câu hỏi quá dài! Vui lòng rút gọn dưới 500 ký tự."
20
+ if message.count("?") > 10 or message.count("!") > 10:
21
+ 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."
22
+
23
+ try:
24
+ message_en = translator_vi2en.translate(message)
25
+ except Exception:
26
+ return "⚠️ Không thể dịch câu hỏi sang tiếng Anh."
27
+
28
+ # --- Tạo prompt với lịch sử hội thoại ---
29
+ prompt = (
30
+ "You are a professional Vietnamese-speaking AI assistant.\n"
31
+ "Answer concisely and accurately; do not fabricate details.\n"
32
+ "If the user simply greets, reply briefly with a polite greeting.\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 # Bỏ qua nếu dịch lỗi
41
+
42
+ prompt += f"User: {user_msg_en}\nAssistant: {bot_msg_en}\n"
43
+
44
+ # Gắn câu hỏi mới
45
+ prompt += f"User: {message_en}\nAssistant:"
46
+
47
+ # Gửi lên model
48
+ try:
49
+ resp = client.text_generation(
50
+ prompt,
51
+ max_new_tokens=128,
52
+ temperature=temperature,
53
+ top_p=top_p,
54
+ )
55
+ answer_en = resp.strip().split("Assistant:")[-1].strip()
56
+ except Exception:
57
+ return "⚠️ Lỗi khi gọi API chatbot."
58
+
59
+ # Dịch câu trả lời về tiếng Việt
60
+ try:
61
+ answer_vi = translator_en2vi.translate(answer_en)
62
+ except Exception:
63
+ answer_vi = "(Không thể dịch câu trả lời về tiếng Việt)"
64
+
65
+ return answer_vi
66
+
67
+ # Gradio UI
68
+ demo = gr.ChatInterface(
69
+ fn=respond,
70
+ title="🤖 Trợ lý AI Tiếng Việt (Translate-then-Predict)",
71
+ description="💬 Nhập tiếng Việt ➔ dịch tiếng Anh ➔ hỏi model ➔ dịch lại tiếng Việt.",
72
+ theme="soft"
73
+ )
74
+
75
+ if __name__ == "__main__":
76
+ demo.launch()