import gradio as gr import logging, langdetect from huggingface_hub import InferenceClient from transformers import MarianTokenizer, MarianMTModel, pipeline # Khởi tạo client HF và translator client = InferenceClient("HuggingFaceH4/zephyr-7b-beta") # Gọi API public vi2en_tokenizer = MarianTokenizer.from_pretrained("Helsinki-NLP/opus-mt-vi-en") vi2en_model = MarianMTModel.from_pretrained("Helsinki-NLP/opus-mt-vi-en") en2vi_tokenizer = MarianTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-vi") en2vi_model = MarianMTModel.from_pretrained("Helsinki-NLP/opus-mt-en-vi") translator_vi2en = pipeline("translation", model=vi2en_model, tokenizer=vi2en_tokenizer) translator_en2vi = pipeline("translation", model=en2vi_model, tokenizer=en2vi_tokenizer) logging.basicConfig(level=logging.INFO) def translate_vi2en_fn(text: str) -> str: return translator_vi2en(text, max_length=512)[0]["translation_text"] def translate_en2vi_fn(text: str) -> str: return translator_en2vi(text, max_length=512)[0]["translation_text"] def respond( message, history: list[tuple[str, str]], system_message=""" You are a professional speaking AI assistant. You can help solving the problems. You can only speak English with correct spelling, punctuation and grammar. """, max_tokens=2048, temperature=0.0, 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 = translate_vi2en_fn(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 response += chunk.choices[0].delta.content except Exception as e: return f"Error: {str(e)}" logging.info(f"Successfully generated text: {response}") response_vi = translate_en2vi_fn(response) return response if langdetect.detect(response) == 'vi' else response_vi # Gradio UI demo = gr.ChatInterface(fn=respond, theme="soft") if __name__ == "__main__": demo.launch()