gradio-app / gradio

Build and share delightful machine learning apps, all in Python. 🌟 Star to support our work!
http://www.gradio.app
Apache License 2.0
32.47k stars 2.43k forks source link

How to modify gr. State (global variable) while the global variable changes #8383

Closed coolboyqu closed 4 months ago

coolboyqu commented 4 months ago

gr. State() will be initialized with a deep copy at the beginning, so after admin modifies the global variable, the user's gr.State (global variable) will not change either. May I ask how to input the latest value as gr.State (global variable).Because some functions are placed in other py files, global variables cannot be loaded directly into the functions.

` ac = A(1, 3)

def func_1(s): x, y = map(int, s.split(' ')) ac.a = x ac.b = y

def func_2(ac_state): return gr.update(value=f"a={ac_state.a}, b={ac_state.b}")

with gr.Blocks() as admin: text = gr.Textbox() btn1 = gr.Button('click') btn1.click(fn=func_1, inputs=text, outputs=None)

with gr.Blocks() as user: btn2 = gr.Button('show') text_show = gr.Textbox() btn2.click(fn=func_2, inputs=gr.State(ac), outputs=text_show) //here, I want to input gr.State(ac),but it doesn't change

def launch_block(block, port): (block .launch(server_name='127.0.0.1', server_port=port, show_api=False, share=False, inbrowser=False))

if name == "main": thread1 = threading.Thread(target=launch_block, args=(user, 7861)) thread2 = threading.Thread(target=launch_block, args=(admin, 7860))

thread1.start()
thread2.start()

thread1.join()
thread2.join()`
abidlabs commented 4 months ago

Hi @coolboyqu thanks for the question. To make sure I understand, you would like to update the value of gr.State() programmatically? Or would you like to trigger an event when gr.State() changes?

The code is not properly formatted in Markdown so its hard to understand what is going on

coolboyqu commented 4 months ago

Hi @coolboyqu thanks for the question. To make sure I understand, you would like to update the value of gr.State() programmatically? Or would you like to trigger an event when gr.State() changes?

The code is not properly formatted in Markdown so its hard to understand what is going on

Sorry, there was a problem copying my code. I want to be able to synchronously retrieve the modified global variable from the user after admin modifies it.

abidlabs commented 4 months ago

Ok so basically what you can do is read from the file or record every second. Here's an example of reading from a file every second to mirror the terminal output: https://github.com/gradio-app/gradio/issues/2362#issuecomment-1424446778