|
import torch |
|
from peft import PeftModel, PeftConfig |
|
from transformers import AutoModelForCausalLM, AutoTokenizer |
|
from huggingface_hub import login |
|
import os |
|
import gradio as gr |
|
|
|
|
|
access_token = os.environ.get("HUGGING_FACE_HUB_TOKEN") |
|
login(token=access_token) |
|
|
|
|
|
peft_model_id = "kuyesu22/sunbird-ug-lang-v1.0-bloom-7b1-lora" |
|
config = PeftConfig.from_pretrained(peft_model_id) |
|
|
|
|
|
model = AutoModelForCausalLM.from_pretrained( |
|
config.base_model_name_or_path, |
|
torch_dtype=torch.float16, |
|
device_map="auto" |
|
) |
|
tokenizer = AutoTokenizer.from_pretrained(config.base_model_name_or_path) |
|
|
|
|
|
model = PeftModel.from_pretrained(model, peft_model_id) |
|
|
|
|
|
model.eval() |
|
|
|
|
|
def make_inference(english_text): |
|
|
|
batch = tokenizer( |
|
f"### English:\n{english_text}\n\n### Runyankole:", |
|
return_tensors="pt", |
|
padding=True, |
|
truncation=True |
|
).to(model.device) |
|
|
|
|
|
with torch.no_grad(): |
|
with torch.cuda.amp.autocast(): |
|
output_tokens = model.generate( |
|
input_ids=batch["input_ids"], |
|
attention_mask=batch["attention_mask"], |
|
max_new_tokens=100, |
|
do_sample=True, |
|
temperature=0.7, |
|
num_return_sequences=1, |
|
pad_token_id=tokenizer.eos_token_id |
|
) |
|
|
|
|
|
translated_text = tokenizer.decode(output_tokens[0], skip_special_tokens=True) |
|
return translated_text |
|
|
|
|
|
def launch_gradio_interface(): |
|
inputs = gr.components.Textbox(lines=2, label="English Text") |
|
outputs = gr.components.Textbox(label="Translated Runyankole Text") |
|
|
|
|
|
gr.Interface( |
|
fn=make_inference, |
|
inputs=inputs, |
|
outputs=outputs, |
|
title="Sunbird UG Lang Translator", |
|
description="Translate English to Runyankole using BLOOM model fine-tuned with LoRA.", |
|
).launch() |
|
|
|
|
|
if __name__ == "__main__": |
|
launch_gradio_interface() |
|
|