File size: 2,070 Bytes
0bd62e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 gradio as gr

with gr.Blocks() as demo:

    with gr.Row():
        state_a = gr.State(0)
        btn_a = gr.Button("Increment A")
        value_a = gr.Number(label="Number A")
        btn_a.click(lambda x: x + 1, state_a, state_a)
        state_a.change(lambda x: x, state_a, value_a)
    with gr.Row():
        state_b = gr.State(0)
        btn_b = gr.Button("Increment B")
        value_b = gr.Number(label="Number B")
        btn_b.click(lambda x: x + 1, state_b, state_b)

        @gr.on(inputs=state_b, outputs=value_b)
        def identity(x):
            return x

    @gr.render(inputs=[state_a, state_b])
    def render(a, b):
        for x in range(a):
            with gr.Row():
                for y in range(b):
                    gr.Button(f"Button {x}, {y}")

    list_state = gr.State([])
    dict_state = gr.State(dict())
    nested_list_state = gr.State([])
    set_state = gr.State(set())

    def transform_list(x):
        return {n: n for n in x}, [x[:] for _ in range(len(x))], set(x)

    list_state.change(
        transform_list,
        inputs=list_state,
        outputs=[dict_state, nested_list_state, set_state],
    )

    all_textbox = gr.Textbox(label="Output")
    click_count = gr.Number(label="Clicks")
    change_count = gr.Number(label="Changes")
    gr.on(
        inputs=[change_count, dict_state, nested_list_state, set_state],
        triggers=[dict_state.change, nested_list_state.change, set_state.change],
        fn=lambda x, *args: (x + 1, "\n".join(str(arg) for arg in args)),
        outputs=[change_count, all_textbox],
    )

    count_to_3_btn = gr.Button("Count to 3")
    count_to_3_btn.click(lambda: [1, 2, 3], outputs=list_state)
    zero_all_btn = gr.Button("Zero All")
    zero_all_btn.click(lambda x: [0] * len(x), inputs=list_state, outputs=list_state)

    gr.on(
        [count_to_3_btn.click, zero_all_btn.click],
        lambda x: x + 1,
        click_count,
        click_count,
    )

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