| import numpy as np |
| import onnxruntime as ort |
| from transformers import MarianTokenizer |
| import gradio as gr |
|
|
| |
| tokenizer_path = "./onnx_model" |
| tokenizer = MarianTokenizer.from_pretrained(tokenizer_path) |
|
|
| |
| onnx_model_path = "./model.onnx" |
| session = ort.InferenceSession(onnx_model_path) |
|
|
| def translate(texts, max_length=512): |
| |
| inputs = tokenizer(texts, return_tensors="np", padding=True, truncation=True, max_length=max_length) |
| input_ids = inputs["input_ids"].astype(np.int64) |
| attention_mask = inputs["attention_mask"].astype(np.int64) |
|
|
| |
| batch_size = input_ids.shape[0] |
| decoder_input_ids = np.array([[tokenizer.pad_token_id]] * batch_size, dtype=np.int64) |
| eos_reached = np.zeros(batch_size, dtype=bool) |
|
|
| |
| for _ in range(max_length): |
| |
| onnx_outputs = session.run( |
| None, |
| { |
| "input_ids": input_ids, |
| "attention_mask": attention_mask, |
| "decoder_input_ids": decoder_input_ids, |
| }, |
| ) |
|
|
| |
| next_token_logits = onnx_outputs[0][:, -1, :] |
|
|
| |
| next_tokens = np.argmax(next_token_logits, axis=-1) |
|
|
| |
| decoder_input_ids = np.concatenate([decoder_input_ids, next_tokens[:, None]], axis=-1) |
|
|
| |
| eos_reached = eos_reached | (next_tokens == tokenizer.eos_token_id) |
|
|
| |
| if all(eos_reached): |
| break |
|
|
| |
| translations = tokenizer.batch_decode(decoder_input_ids, skip_special_tokens=True) |
| return translations |
|
|
| |
| def gradio_translate(input_text): |
| |
| texts = input_text.strip().split("\n") |
| translations = translate(texts) |
| |
| return "\n".join(translations) |
|
|
| |
| interface = gr.Interface( |
| fn=gradio_translate, |
| inputs=gr.Textbox(lines=5, placeholder="Enter text to translate...", label="Input Text"), |
| outputs=gr.Textbox(lines=5, label="Translated Text"), |
| title="ONNX English to French Translation", |
| description="Translate English text to French using a MarianMT ONNX model.", |
| ) |
|
|
| |
| interface.launch() |