| import numpy as np |
| import onnxruntime as ort |
| from transformers import AutoTokenizer |
| import gradio as gr |
|
|
| |
| model_path = "model.onnx" |
| translation_session = ort.InferenceSession(model_path) |
| translation_tokenizer = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-fr") |
|
|
| def translate_text(input_text): |
| |
| tokenized_input = translation_tokenizer( |
| input_text, return_tensors="np", padding=True, truncation=True, max_length=512 |
| ) |
| |
| |
| input_ids = tokenized_input["input_ids"].astype(np.int64) |
| attention_mask = tokenized_input["attention_mask"].astype(np.int64) |
|
|
| |
| decoder_start_token_id = translation_tokenizer.cls_token_id or translation_tokenizer.pad_token_id |
| decoder_input_ids = np.array([[decoder_start_token_id]], dtype=np.int64) |
|
|
| |
| translated_tokens = [] |
| for _ in range(512): |
| |
| outputs = translation_session.run( |
| None, |
| { |
| "input_ids": input_ids, |
| "attention_mask": attention_mask, |
| "decoder_input_ids": decoder_input_ids, |
| } |
| ) |
|
|
| |
| next_token_id = np.argmax(outputs[0][0, -1, :], axis=-1) |
| translated_tokens.append(next_token_id) |
|
|
| |
| if next_token_id == translation_tokenizer.eos_token_id: |
| break |
|
|
| |
| decoder_input_ids = np.concatenate( |
| [decoder_input_ids, np.array([[next_token_id]], dtype=np.int64)], axis=1 |
| ) |
|
|
| |
| translated_text = translation_tokenizer.decode(translated_tokens, skip_special_tokens=True) |
| return translated_text |
|
|
| |
| interface = gr.Interface( |
| fn=translate_text, |
| inputs="text", |
| outputs="text", |
| title="Frenchizer Translation Model", |
| description="Translate text from English to French using an ONNX model." |
| ) |
|
|
| |
| interface.launch() |