Skip to main content

Reactive Multi-language Gradio App with minimal effort

Project description

gradio-i18n

GitHub License PyPI - Version Huggingface

Reactive Multi-language Gradio App with minimal effort. Enables Gradio app displayiing localized UI responding to the browser language settings.

Installation

pip install gradio-i18n

Basic Example

If you want localized UI based on users' browser language, simply wrap your block definition with gradio_i18n.Translate().

  • Wrap all your texts to localize with gradio_i18n.gettext().
  • It supports a filepath or dict as the translation dict.
import gradio as gr

from gradio_i18n import Translate, gettext as _

def greet(name, lang):
    return f"Hello {name} in {lang}!"

with gr.Blocks() as demo:
    with Translate("translation.yaml", placeholder_langs=["en", "zh"]) as lang:
        name = gr.Textbox(
            label=_("Name"), placeholder=_("Input your name here.")
        )
        output = gr.Textbox(label=_("Greeting"))
        submit_btn = gr.Button(value=_("Submit"))

    submit_btn.click(greet, inputs=[name, lang], outputs=output)

demo.launch()

Change UI language Example

You may want user to choose their expected language, pass the component storing the language value to gradion_i18n.Translate().

import gradio as gr

from gradio_i18n import Translate
from gradio_i18n import gettext as _


def greet(name, lang):
    return f"Hello {name} in {lang}!"


with gr.Blocks() as demo:
    lang = gr.Radio(choices=[("English", "en"), ("中文", "zh")], label=_("Language"))
    with Translate("translation.yaml", lang, placeholder_langs=["en", "zh"]):
        name = gr.Textbox(label=_("Name"), placeholder=_("Input your name here."))
        output = gr.Textbox(label=_("Greeting"))
        submit_btn = gr.Button(value=_("Submit"))

    submit_btn.click(greet, inputs=[name, lang], outputs=output)

demo.launch(server_name="0.0.0.0")

Advanced Usage for better control

  1. Prepare a translation dict like examples below.
  2. Wrap text intended to be localized with gradio_i18n.gettext()
  3. Invoke gradio_i18n.translate_blocks(), within the context of gradio blocks.
import gradio as gr
from gradio_i18n import gettext, translate_blocks


def greet(name):
    return f"Hello {name}!"


lang_store = {
    "en": {
        "Submit": "Submit✅",
        "Name": "Name 📛",
        "Greeting": "Greeting 🎉",
        "Input your name here.": "Input your name here. 📝",
    },
    "zh": {
        "Submit": "提交",
        "Name": "名字",
        "Greeting": "问候",
        "Input your name here.": "在这里输入你的名字。",
    },
}

with gr.Interface(
    fn=greet,
    inputs=gr.Textbox(
        label=gettext("Name"), placeholder=gettext("Input your name here.")
    ),
    outputs=gr.Textbox(label=gettext("Greeting")),
    submit_btn=gettext("Submit"),
) as demo:
    translate_blocks(translation=lang_store)

demo.launch()

[!NOTE] Keep in mind that the translate_blocks() function MUST BE called in the gradio block context (with)

Get/Set current language

Except for automatically translated text value in Gradio components, user may expect to get the current language of the user for localizing contents. To get the current language, simply pass in any component into argument lang of translate_blocks(), and you will get the language value in the object.

Also, if you change the value of the passed in object, the overall UI will update accordingly.

Example:

import gradio as gr
import gradio_i18n

def get_lang(lang):
    return f"You are using language: {lang}"


with gr.Blocks() as block:
    lang = gr.State()
    display_lang = gr.Text()
    btn = gr.Button()
    btn.click(get_lang, inputs=[lang], outputs=[display_lang])
    gradio_i18n.translate_blocks(lang_state=lang)

block.launch()

[!NOTE] Only dict type state is supported at this moment.

Generate a translation dictionary placeholder

To build the transtion dictionary, we provide function dump_blocks() to dump all the i18n texts from the gradio blocks object.

This is an example of using yaml/json to persist the translation.

JSON

import gradio as gr
import gradio_i18n
import json

trans_file = "translations.json"
if not os.path.exists(trans_file):
    lang_store = {}
else:
    lang_store = json.load(open(trans_file))

# define your gradio block here....
# with gr.Blocks() as block:
#     ....
#     gradio_i18n.translate_blocks(block, lang_store)

collected_texts = gradio_i18n.dump_blocks(block, langs=["zh", "en"], include_translations=lang_store)
json.dump(collected_texts, open(trans_file, "w"), indent=2, ensure_ascii=False)

YAML

import gradio as gr
import gradio_i18n
import yaml

trans_file = "translations.yaml"
if not os.path.exists(trans_file):
    lang_store = {}
else:
    lang_store = yaml.safe_load(open(trans_file))

# define your gradio block here....
# with gr.Blocks() as block:
#     ....
#     gradio_i18n.translate_blocks(block, lang_store)

collected_texts = gradio_i18n.dump_blocks(block, langs=["zh", "en"], include_translations=lang_store)
yaml.safe_dump(collected_texts, open(trans_file, "w"), allow_unicode=True)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

gradio_i18n-0.0.7.tar.gz (10.1 kB view details)

Uploaded Source

Built Distribution

gradio_i18n-0.0.7-py3-none-any.whl (9.1 kB view details)

Uploaded Python 3

File details

Details for the file gradio_i18n-0.0.7.tar.gz.

File metadata

  • Download URL: gradio_i18n-0.0.7.tar.gz
  • Upload date:
  • Size: 10.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.9.19

File hashes

Hashes for gradio_i18n-0.0.7.tar.gz
Algorithm Hash digest
SHA256 dd7f8041c25cdef0349eb09baba13f519040d0de7935ff3ee428d6561379d84e
MD5 9ee61cc14dd34b3bcdbc367494be093b
BLAKE2b-256 2930226e50c5dca8522aea4a470a314da4a7535889ad482d0108d1e4f02ca133

See more details on using hashes here.

File details

Details for the file gradio_i18n-0.0.7-py3-none-any.whl.

File metadata

  • Download URL: gradio_i18n-0.0.7-py3-none-any.whl
  • Upload date:
  • Size: 9.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.9.19

File hashes

Hashes for gradio_i18n-0.0.7-py3-none-any.whl
Algorithm Hash digest
SHA256 99b2a3c61e9bc4fa8c4c2ec87d2e086c386b81e117c2c13b7cb092603f4633e3
MD5 527977dace06b1f0ac3b2936ccd9782e
BLAKE2b-256 75559ebd048a8bfef1d3401afcae5d941f941709d47ef6ee69b297d1b2b6e06c

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page