michsethowusu's picture
Update app.py
81ae68a verified
Raw History Blame Contribute Delete
4.26 kB
import gradio as gr
import torch
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
from peft import PeftModel
ADAPTER_ID = "mclanorjeff/NLLB-Twi-Human-Aligned"
BASE_MODEL = "facebook/nllb-200-distilled-600M"
print("Loading model and tokenizer...")
tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL, src_lang="aka_Latn")
model = AutoModelForSeq2SeqLM.from_pretrained(BASE_MODEL)
model = PeftModel.from_pretrained(model, ADAPTER_ID)
model.eval()
def translate(text, direction):
if not text.strip():
return ""
if direction == "English to Twi":
src_lang, tgt_lang = "eng_Latn", "aka_Latn"
else: # Twi to English
src_lang, tgt_lang = "aka_GH", "eng_Latn"
# keyboard-friendly mapping from the original app
text = text.replace('3', 'ɛ').replace('c', 'ɔ').replace('C', 'Ɔ')
tokenizer.src_lang = src_lang
inputs = tokenizer(text, return_tensors="pt", max_length=128, truncation=True)
with torch.no_grad():
output_ids = model.generate(
**inputs,
forced_bos_token_id=tokenizer.convert_tokens_to_ids(tgt_lang),
max_length=128,
num_beams=5,
)
return tokenizer.decode(output_ids[0], skip_special_tokens=True)
custom_css = """
footer {visibility: hidden}
.gradio-container {
font-family: 'Inter', sans-serif;
max-width: 900px !important;
margin: auto;
}
.header-box {
text-align: center;
padding: 20px;
background: linear-gradient(90deg, #1f77b4 0%, #2ca02c 100%);
color: white;
border-radius: 10px;
margin-bottom: 20px;
}
"""
with gr.Blocks() as demo:
with gr.Column(elem_classes="header-box"):
gr.Markdown("# 🇬🇭 NLLB-Twi Translator (Phase 2)")
gr.Markdown("### Professional Human-Aligned Machine Translation")
gr.Markdown("This model uses a two-stage QLoRA approach, combining 192k synthetic sentences with human-verified polish.")
direction = gr.Radio(
choices=["English to Twi", "Twi to English"],
value="English to Twi",
label="Translation Direction"
)
with gr.Row():
with gr.Column(scale=1):
input_label = gr.Markdown("**Input (English)**")
input_text = gr.Textbox(
label="Input Text",
placeholder="Type your English text here...",
lines=8
)
with gr.Column(scale=1):
output_label = gr.Markdown("**Output (Twi)**")
output_text = gr.Textbox(label="Translation", lines=8, interactive=False)
with gr.Row():
gr.Column(scale=1)
translate_btn = gr.Button("Translate", variant="primary", scale=1)
gr.Column(scale=1)
gr.Examples(
examples=[
["I am learning Twi to speak with you."],
["If someone goes to school, they should work hard."],
["Please show me the way to the school."],
["Ghana is a very beautiful country."],
],
inputs=input_text,
label="English Examples"
)
gr.Examples(
examples=[
["Meresua Twi kasa kyerɛ wo."],
["Sɛ obi kɔ sukuu a, ɛsɛ sɛ obu mbudɛn."],
["Mepa wo kyɛw, kyerɛ me kwan a ɛkɔ sukuu hɔ."],
["Ghana yɛ ɔman a ɛyɛ fɛ paa."],
],
inputs=input_text,
label="Twi Examples"
)
def update_labels(direction):
if direction == "English to Twi":
return (
gr.update(value="**Input (English)**"),
gr.update(value="**Output (Twi)**"),
gr.update(placeholder="Type your English text here...")
)
else:
return (
gr.update(value="**Input (Twi)**"),
gr.update(value="**Output (English)**"),
gr.update(placeholder="Type your Twi text here...")
)
direction.change(
update_labels,
inputs=direction,
outputs=[input_label, output_label, input_text]
)
translate_btn.click(translate, inputs=[input_text, direction], outputs=output_text)
if __name__ == "__main__":
demo.launch(
css=custom_css,
theme=gr.themes.Soft(primary_hue="blue")
)