Masakhane Hello World!¶
Overview¶
To use the Masakhane models to create a simple "Hello World" program, you can follow these steps:
- Install the Hugging Face Transformers library by running the command
pip install transformersin your terminal or command line. - Choose a model from the Masakhane Hugging Face models collection¹ that supports your language and task. For example, you can use the
masakhane/afri-mbart50model for machine translation or themasakhane/afroxlmr-large-ner-masakhaner-1.0_2.0model for named entity recognition. - Load the model and the tokenizer using the
AutoModelForSeq2SeqLMandAutoTokenizerclasses from the Transformers library. For example, you can use the following code to load themasakhane/afri-mbart50model and the tokenizer:
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
# Load the model and the tokenizer
model = AutoModelForSeq2SeqLM.from_pretrained("masakhane/afri-mbart50")
tokenizer = AutoTokenizer.from_pretrained("masakhane/afri-mbart50")
- Encode your input text using the tokenizer and generate the output text using the model. You can specify the source and target languages using the
src_langandtgt_langarguments. For example, you can use the following code to translate the text "Hello, world!" from English to Swahili:
# Encode the input text
input_ids = tokenizer.encode("Hello, world!", return_tensors="pt", src_lang="en_XX")
# Generate the output text
output_ids = model.generate(input_ids, max_length=20, tgt_lang="sw_KE")
# Decode the output text
output_text = tokenizer.decode(output_ids[0], skip_special_tokens=True)
print(output_text)
- Run the code by entering
python masakhane-test.pyin your terminal or command line, wheremasakhane-test.pyis the name of your Python file. You should get an output text that resembles the following: