import gradio as gr import spaces from transformers import pipeline generator = pipeline("text-generation", model="Qwen/Qwen2.5-0.5B-Instruct") @spaces.GPU def translate(text): if not text.strip(): return "" messages = [ {"role": "system", "content": "You are a translator. Translate the following English text to natural Vietnamese. Output only the translated text."}, {"role": "user", "content": f"Translate: {text}"} ] prompt = generator.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) output = generator(prompt, max_new_tokens=100, do_sample=False)[0]["generated_text"] return output.split("<|im_start|>assistant\n")[-1].strip() demo = gr.Interface( fn=translate, inputs=gr.Textbox(lines=3, placeholder="Enter English text to translate..."), outputs=gr.Textbox(lines=3, label="Vietnamese Translation"), title="Prompt-Based Translation (Text Generation)", description="Using Qwen2.5-0.5B-Instruct via text-generation pipeline for translation." ) if __name__ == "__main__": demo.launch()