File size: 1,940 Bytes
76f85b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f8dd51
76f85b9
 
8f8dd51
 
76f85b9
 
8f8dd51
76f85b9
 
 
8f8dd51
76f85b9
 
 
 
 
cc13458
 
76f85b9
 
 
8f8dd51
76f85b9
8f8dd51
76f85b9
 
8f8dd51
76f85b9
8f8dd51
1387c21
76f85b9
cc13458
 
76f85b9
 
cc13458
76f85b9
 
 
cc13458
 
76f85b9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import requests
import gradio as gr
from dotenv import load_dotenv
import os

# Load environment variables
load_dotenv()
HF_TOKEN = os.getenv("HF_TOKEN")
headers = {"Authorization": f"Bearer {HF_TOKEN}"}

# Language to ISO 639-3 codes (used for NLLB-200)
LANGUAGES = {
    "English β†’ Afrikaans": "afr",
    "English β†’ Xhosa": "xho",
    "English β†’ Zulu": "zul",
    "English β†’ Sesotho": "sot",
    "English β†’ Tswana": "tsn",
    "English β†’ Northern Sotho": "nso",
    "English β†’ Swati": "ssw",
    "English β†’ Tsonga": "tso",
    "English β†’ Venda": "ven",
}

MODEL_NAME = "facebook/nllb-200-distilled-600M"
API_URL = f"https://api-inference.huggingface.co/models/{MODEL_NAME}"


def query(payload):
    response = requests.post(API_URL, headers=headers, json=payload)

    if response.status_code != 200:
        print(f"[ERROR] API failed: {response.status_code} - {response.text}")
        return {"error": f"Request failed with {response.status_code}"}

    try:
        return response.json()
    except requests.exceptions.JSONDecodeError:
        print(f"[ERROR] Failed to parse JSON: {response.text}")
        return {"error": "Invalid JSON from API"}


def translate(input_text, language_label):
    language_code = LANGUAGES[language_label]
    formatted_input = f">>{language_code}<< {input_text}"

    response = query({"inputs": formatted_input, "options": {"wait_for_model": True}})

    if "error" in response:
        return f"Error: {response['error']}"

    return response[0]["translation_text"]


translator = gr.Interface(
    fn=translate,
    inputs=[
        gr.Textbox(label="Input Text", placeholder="Type text here..."),
        gr.Dropdown(list(LANGUAGES.keys()), label="Select Language Target"),
    ],
    outputs=gr.Textbox(label="Translation"),
    title="Translademia",
    description="Translate English text to South African languages using Meta's NLLB-200 model.",
)

translator.launch()