Simon Strandgaard commited on
Commit
9dce94e
·
1 Parent(s): f6e1a1e

multi user experiment using BrowserState

Browse files
app.py CHANGED
@@ -5,5 +5,5 @@ PROMPT> IS_HUGGINGFACE_SPACES=true python app.py
5
  if __name__ == "__main__":
6
  # from src.plan.app_text2plan import run_app_text2plan
7
  # run_app_text2plan()
8
- from src.huggingface_spaces.app_state1 import demo
9
  demo.launch()
 
5
  if __name__ == "__main__":
6
  # from src.plan.app_text2plan import run_app_text2plan
7
  # run_app_text2plan()
8
+ from src.huggingface_spaces.app_state2 import demo
9
  demo.launch()
src/huggingface_spaces/app_state1.py CHANGED
@@ -1,5 +1,6 @@
1
  """
2
  Multi-user experiment. User data is isolated from other users.
 
3
 
4
  However when the user reloads the page, the API key is lost.
5
  """
 
1
  """
2
  Multi-user experiment. User data is isolated from other users.
3
+ When the page is open in multiple tabs, then each tab is isolated from the other tabs.
4
 
5
  However when the user reloads the page, the API key is lost.
6
  """
src/huggingface_spaces/app_state2.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 gradio as gr
9
+
10
+ def store_api_key(api_key, browser_state):
11
+ # Update browser state with the new API key.
12
+ browser_state = api_key
13
+ return browser_state, f"API key stored: {api_key}"
14
+
15
+ def perform_action(browser_state):
16
+ if browser_state:
17
+ return f"Action performed using API key: {browser_state}"
18
+ else:
19
+ return "No API key stored. Please enter and store one first."
20
+
21
+ with gr.Blocks() as demo:
22
+ gr.Markdown("## API Key Persistence using BrowserState")
23
+
24
+ # Create a BrowserState component.
25
+ # The initial value is an empty string, and the key "api_key" is used to store/retrieve the value.
26
+ browser_state = gr.BrowserState("")
27
+
28
+ with gr.Row():
29
+ api_key_input = gr.Textbox(label="Enter your API Key", elem_id="api_key_input")
30
+ store_button = gr.Button("Store API Key")
31
+
32
+ action_button = gr.Button("Perform Action")
33
+ output_text = gr.Textbox(label="Output")
34
+
35
+ # Clicking "Store API Key" saves the key to BrowserState.
36
+ store_button.click(store_api_key, inputs=[api_key_input, browser_state], outputs=[browser_state, output_text])
37
+ # "Perform Action" uses the stored API key.
38
+ action_button.click(perform_action, inputs=browser_state, outputs=output_text)
39
+
40
+ if __name__ == "__main__":
41
+ demo.launch()