File size: 2,761 Bytes
375fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/env python

import gradio as gr

DESCRIPTION_JA = """\
# 言語切り替えデモ

これは Gradio での言語切り替えのデモです。

このアプリではブラウザの言語設定に応じて、このテキスト自身と、テキストボックスのラベルとプレースホルダーを切り替えます。\
また、ページ下部のボタンでも言語を切り替えることができます。

このデモでは簡単のため、`gr.Markdown` と `gr.Textbox` のみを切り替えますが、\
同様にして、他のコンポーネントの表示言語も切り替えることができます。
"""
DESCRIPTION_EN = """\
# Language Switch Demo

This is a demo of language switching in Gradio.

This app switches this text itself, as well as the textbox label and placeholder, according to the browser's language settings.
You can also switch languages using the button at the bottom of the page.

For simplicity, this demo only switches the `gr.Markdown` and `gr.Textbox`, but
you can switch the display language of other components in the same way.
"""
TEXTBOX_LABEL_JA = "入力テキスト"
TEXTBOX_LABEL_EN = "Input Text"
TEXTBOX_PLACEHOLDER_JA = "ここにテキストを入力してください。"
TEXTBOX_PLACEHOLDER_EN = "Please input text here."


def set_default_language(request: gr.Request) -> gr.Radio:
    if request.headers["Accept-Language"].split(",")[0].lower().startswith("ja"):
        return gr.Radio(value="🇯🇵 JA")
    else:
        return gr.Radio(value="🇺🇸 EN")


def switch_ui_language(language: str) -> tuple[gr.Markdown, gr.Textbox]:
    if language == "🇯🇵 JA":
        return (
            gr.Markdown(value=DESCRIPTION_JA),
            gr.Textbox(label=TEXTBOX_LABEL_JA, placeholder=TEXTBOX_PLACEHOLDER_JA),
        )
    else:
        return (
            gr.Markdown(value=DESCRIPTION_EN),
            gr.Textbox(label=TEXTBOX_LABEL_EN, placeholder=TEXTBOX_PLACEHOLDER_EN),
        )


with gr.Blocks(css_paths="style.css") as demo:
    description = gr.Markdown(DESCRIPTION_EN)

    text = gr.Textbox(label=TEXTBOX_LABEL_EN, placeholder=TEXTBOX_PLACEHOLDER_EN)

    language_selector = gr.Radio(
        choices=["🇯🇵 JA", "🇺🇸 EN"],
        value="🇯🇵 JA",
        elem_classes="language-selector",
        show_label=False,
        container=False,
    )

    demo.load(
        fn=set_default_language,
        outputs=language_selector,
        api_name=False,
        queue=False,
    )
    language_selector.change(
        fn=switch_ui_language,
        inputs=language_selector,
        outputs=[
            description,
            text,
        ],
        api_name=False,
        queue=False,
    )

if __name__ == "__main__":
    demo.launch()