Simon Strandgaard commited on
Commit
08d4036
·
1 Parent(s): 792d6d7

multi user experiment using BrowserState

Browse files
Files changed (2) hide show
  1. app.py +3 -3
  2. src/huggingface_spaces/app_state3.py +45 -0
app.py CHANGED
@@ -3,9 +3,9 @@ During development, to mimic the same behavior as on Hugging Face Spaces.
3
  PROMPT> IS_HUGGINGFACE_SPACES=true python app.py
4
  """
5
  if __name__ == "__main__":
6
- from src.huggingface_spaces.print_gradio_info import print_gradio_info
7
- print_gradio_info()
8
  # from src.plan.app_text2plan import run_app_text2plan
9
  # run_app_text2plan()
10
- from src.huggingface_spaces.app_state2 import demo
11
  demo.launch()
 
3
  PROMPT> IS_HUGGINGFACE_SPACES=true python app.py
4
  """
5
  if __name__ == "__main__":
6
+ # from src.huggingface_spaces.print_gradio_info import print_gradio_info
7
+ # print_gradio_info()
8
  # from src.plan.app_text2plan import run_app_text2plan
9
  # run_app_text2plan()
10
+ from src.huggingface_spaces.app_state3 import demo
11
  demo.launch()
src/huggingface_spaces/app_state3.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Multi-user experiment. User data is isolated from other users.
3
+ When the page is open in multiple tabs, the API key is shared across all tabs.
4
+ When the user reloads the page, the API key is remembered.
5
+
6
+ However when the server is restarted, the API key is lost.
7
+ """
8
+ import random
9
+ import string
10
+ import gradio as gr
11
+ import time
12
+ with gr.Blocks() as demo:
13
+ gr.Markdown("Your Username and Password will get saved in the browser's local storage. "
14
+ "If you refresh the page, the values will be retained.")
15
+ username = gr.Textbox(label="Username")
16
+ password = gr.Textbox(label="Password", type="password")
17
+ btn = gr.Button("Generate Randomly")
18
+ local_storage = gr.BrowserState(["", ""])
19
+ saved_message = gr.Markdown("✅ Saved to local storage", visible=False)
20
+
21
+ @btn.click(outputs=[username, password])
22
+ def generate_randomly():
23
+ u = "".join(random.choices(string.ascii_letters + string.digits, k=10))
24
+ p = "".join(random.choices(string.ascii_letters + string.digits, k=10))
25
+ return u, p
26
+
27
+ @demo.load(inputs=[local_storage], outputs=[username, password])
28
+ def load_from_local_storage(saved_values):
29
+ print("loading from local storage", saved_values)
30
+ return saved_values[0], saved_values[1]
31
+
32
+ @gr.on([username.change, password.change], inputs=[username, password], outputs=[local_storage])
33
+ def save_to_local_storage(username, password):
34
+ return [username, password]
35
+
36
+ @gr.on(local_storage.change, outputs=[saved_message])
37
+ def show_saved_message():
38
+ timestamp = time.strftime("%I:%M:%S %p")
39
+ return gr.Markdown(
40
+ f"✅ Saved to local storage at {timestamp}",
41
+ visible=True
42
+ )
43
+
44
+ if __name__ == "__main__":
45
+ demo.launch()