The error happens because you are using the variables tokenizer and model before declaring them as global inside the function. In Python, the global statement must appear before any usage of those variables in the function.
How to fix it:
Move the global tokenizer, model line to the very top of the function, before you use model or tokenizer.
Corrected function:
from transformers import MarianMTModel, MarianTokenizer
# Load model and tokenizer once (cached for faster subsequent calls)
model_name = "Helsinki-NLP/opus-mt-en-ko"
tokenizer = MarianTokenizer.from_pretrained(model_name)
model = MarianMTModel.from_pretrained(model_name)
def translate_text(text: str, source_lang: str = "en", target_lang: str = "ko") -> str:
global tokenizer, model # <-- Move this here, at the top
# Adjust model if translating between different languages
current_model_name = f"Helsinki-NLP/opus-mt-{source_lang}-{target_lang}"
if model.config._name_or_path != current_model_name:
tokenizer = MarianTokenizer.from_pretrained(current_model_name)
model = MarianMTModel.from_pretrained(current_model_name)
# Tokenize and translate
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
translated_tokens = model.generate(**inputs, max_length=512)
return tokenizer.decode(translated_tokens[0], skip_special_tokens=True)
Explanation:
global tells Python you want to use the module-level variables tokenizer and model inside the function.
- You must declare
global before you use or assign those variables inside the function.
If you want, I can also help you refactor this to avoid globals altogether! Just ask.