sadw / app.py
ThongCoding's picture
Update app.py
75b947c verified
raw
history blame
2.09 kB
import gradio as gr
from huggingface_hub import InferenceClient
from deep_translator import GoogleTranslator
# Khởi tạo client HF và translator
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
translator_vi2en = GoogleTranslator(source='vi', target='en')
translator_en2vi = GoogleTranslator(source='en', target='vi')
def respond(
message,
history: list[tuple[str, str]],
system_message,
max_tokens=128,
temperature=0.5,
top_p=0.9,
):
# Tạo list tin nhắn bắt đầu từ hệ thống
messages = [{"role": "system", "content": system_message}]
# Dịch câu hỏi của người dùng từ tiếng Việt sang tiếng Anh
message_en = translator_vi2en.translate(message)
# Thêm các tin nhắn lịch sử vào messages
for val in history:
if val[0]: # Tin nhắn của người dùng
messages.append({"role": "user", "content": val[0]})
if val[1]: # Tin nhắn của trợ lý
messages.append({"role": "assistant", "content": val[1]})
# Thêm câu hỏi của người dùng vào cuối lịch sử
messages.append({"role": "user", "content": message_en})
response = ""
# Gửi yêu cầu tới mô hình và nhận kết quả
try:
for chunk in client.chat_completion(
model="HuggingFaceH4/zephyr-7b-beta",
messages=messages,
max_tokens=max_tokens,
temperature=temperature,
top_p=top_p,
stream=True
):
# Tiến hành nhận phản hồi từ mô hình
token = chunk["choices"][0]["delta"]["content"]
response += token
except Exception as e:
return f"Error: {str(e)}"
# Dịch câu trả lời về tiếng Việt
try:
response_vi = translator_en2vi.translate(response)
except Exception:
response_vi = "(Không thể dịch câu trả lời về tiếng Việt)"
return response_vi
# Gradio UI
demo = gr.ChatInterface(fn=respond)
if __name__ == "__main__":
demo.launch()