Chris Addis commited on
Commit
b993ed1
·
1 Parent(s): ba4800b

fix additional models

Browse files
Files changed (1) hide show
  1. app.py +101 -78
app.py CHANGED
@@ -1,107 +1,130 @@
1
  import gradio as gr
2
  import os
3
 
4
- def check_access(request: gr.Request):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  """
6
- Checks if the user is logged in via HF OAuth and if they are authorized
7
- for full access.
8
  """
9
- user_info = request.auth # request.auth contains user info if hf_oauth is enabled
10
 
11
  if user_info is None:
12
  # User is not logged in
13
- return (
14
- gr.update(visible=True), # Show login prompt
15
- gr.update(visible=False), # Hide full content
16
- gr.update(visible=True), # Show limited content
17
- "Please sign in to check your access.",
18
- "Not Logged In"
19
- )
 
20
  else:
21
- # User is logged in, get their HF user ID
22
- user_id = user_info.get('sub') # 'sub' is the standard claim for user ID in OpenID Connect
23
- username = user_info.get('preferred_username', 'N/A') # Or use other claims like 'name', 'email'
24
 
25
  print(f"Logged in user: Username={username}, ID={user_id}") # Log for debugging
26
 
27
- if user_id in AUTHORIZED_USER_IDS:
28
  # User is authorized for full access
29
- return (
30
- gr.update(visible=False), # Hide login prompt
31
- gr.update(visible=True), # Show full content
32
- gr.update(visible=False), # Hide limited content
33
- f"Welcome, {username}! You have Full Access.",
34
- f"Logged in as: {username} (ID: {user_id})"
35
- )
 
36
  else:
37
  # User is logged in but not authorized for full access
38
- return (
39
- gr.update(visible=False), # Hide login prompt
40
- gr.update(visible=False), # Hide full content
41
- gr.update(visible=True), # Show limited content
42
- f"Welcome, {username}. You have Limited Access.",
43
- f"Logged in as: {username} (ID: {user_id})"
44
- )
 
45
 
46
  # --- Gradio Interface ---
47
 
48
  with gr.Blocks() as demo:
49
- # We'll use state to manage visibility based on access
50
- login_prompt = gr.Markdown("### Sign in with Hugging Face to check your access.")
51
- login_status_text = gr.Textbox(label="Status", interactive=False)
52
-
53
- # The gr.LoginButton component initiates the HF OAuth flow
54
- # This button itself doesn't need a click handler in this pattern;
55
- # the check_access function runs on page load or other events.
56
- # However, we can add a dummy event or rely on the initial load.
57
- # For demonstration, we'll have the check happen on page load
58
- # and re-check maybe with a button click if needed, but the
59
- # primary check should handle the redirect return.
60
- # A common pattern is to just rely on the state after redirect.
61
-
62
- with gr.Column(visible=False) as limited_content:
63
  gr.Markdown("## Limited Access Content")
64
- gr.Textbox(value="This is content available to all users (or non-authorized logged-in users).", interactive=False)
 
 
65
  # Add other limited features here
66
 
67
- with gr.Column(visible=False) as full_content:
 
68
  gr.Markdown("## Full Access Content")
69
- gr.Textbox(value="🥳 This is special content for authorized users! 🥳", interactive=False)
 
 
70
  # Add other full features here
71
 
72
- # Initial check on page load is tricky with Blocks and redirects.
73
- # A more reliable way is often to have a button that triggers the check
74
- # after the potential redirect or on first load, or use a mechanism
75
- # that runs logic on startup. For a simple example, let's add a check button.
76
- # In a real app, the check_access logic might be called by a function
77
- # that runs on initial page load or tied to a state change after login redirect.
78
-
79
- # Let's simulate the check happening after potential login on page load
80
- # by linking it to a component that is present from the start, or by
81
- # calling the check function and updating outputs.
82
- # Gradio often re-runs parts of the app logic after OAuth redirect.
83
- # The outputs of check_access will update the visibility of components.
84
-
85
- # A more robust pattern in Gradio might involve using the `load` event
86
- # or triggering `check_access` via a component interaction that happens
87
- # after the page loads and the request object is populated.
88
- # For simplicity in a runnable example, let's trigger check_access
89
- # with a button after the page is loaded and the user *might* have just logged in.
90
- # In a production app, you'd want this check to happen automatically.
91
-
92
- check_access_button = gr.Button("Check My Access Level") # Button to manually trigger check
93
-
94
- check_access_button.click(
95
- fn=check_access,
96
- inputs=None, # The request object is implicitly available
97
- outputs=[login_prompt, full_content, limited_content, login_status_text, login_status_text], # Update multiple outputs
98
- api_name="check_access" # Give it an API name if needed
 
 
 
 
 
 
99
  )
100
 
101
- # A more seamless approach in a real space would involve using Gradio's state
102
- # and potentially calling check_access when the space state indicates a user is present.
103
- # The gr.LoginButton handles the *initiation* of the login.
104
- # The *result* of the login populates the request.auth object on subsequent interactions
105
- # or potentially on page reload after redirect.
106
 
107
  demo.launch()
 
1
  import gradio as gr
2
  import os
3
 
4
+ # --- Configuration ---
5
+ # In your Hugging Face Space settings, add a Secret named `AUTHORIZED_USER_IDS`.
6
+ # The value should be a comma-separated string of the Hugging Face User IDs
7
+ # that you want to grant "full access" to (e.g., "user_id_123,user_id_456").
8
+ # You can find your Hugging Face User ID in your profile URL or settings.
9
+
10
+ # IMPORTANT: This secret should be set in the Hugging Face Space settings, NOT hardcoded here.
11
+ # We retrieve it using os.environ.get() which accesses the Space's environment variables/secrets.
12
+ # Provide a default empty string for local testing where the secret won't exist.
13
+ authorized_users_str = os.environ.get("AUTHORIZED_USER_IDS", "")
14
+ AUTHORIZED_USER_IDS = set(authorized_users_str.split(','))
15
+
16
+ # --- Application Logic ---
17
+
18
+ def get_user_access_level(request: gr.Request):
19
  """
20
+ Checks the request object to determine if a user is logged in via HF OAuth
21
+ and their access level based on the AUTHORIZED_USER_IDS list.
22
  """
23
+ user_info = request.auth # This contains user info if hf_oauth is enabled and user is logged in
24
 
25
  if user_info is None:
26
  # User is not logged in
27
+ print("User not logged in.")
28
+ return {
29
+ "status_message": "Please sign in to see your access level and potentially unlock full features.",
30
+ "user_identity": "Not Logged In",
31
+ "show_login_prompt": gr.update(visible=True),
32
+ "show_limited_content": gr.update(visible=True),
33
+ "show_full_content": gr.update(visible=False)
34
+ }
35
  else:
36
+ # User is logged in, get their HF user ID and username
37
+ user_id = user_info.get('sub') # 'sub' is the standard claim for user ID
38
+ username = user_info.get('preferred_username', user_id) # Use username or ID as fallback
39
 
40
  print(f"Logged in user: Username={username}, ID={user_id}") # Log for debugging
41
 
42
+ if user_id in AUTHORIZED_USER_IDS and user_id != "": # Also check if user_id is not empty string from split(",")
43
  # User is authorized for full access
44
+ print(f"User {user_id} is authorized for full access.")
45
+ return {
46
+ "status_message": f"Welcome, {username}! You have Full Access.",
47
+ "user_identity": f"Logged in as: {username} (ID: {user_id})",
48
+ "show_login_prompt": gr.update(visible=False),
49
+ "show_limited_content": gr.update(visible=False), # Hide limited content for full users
50
+ "show_full_content": gr.update(visible=True)
51
+ }
52
  else:
53
  # User is logged in but not authorized for full access
54
+ print(f"User {user_id} is logged in but not authorized.")
55
+ return {
56
+ "status_message": f"Welcome, {username}. You have Limited Access.",
57
+ "user_identity": f"Logged in as: {username} (ID: {user_id})",
58
+ "show_login_prompt": gr.update(visible=False),
59
+ "show_limited_content": gr.update(visible=True),
60
+ "show_full_content": gr.update(visible=False)
61
+ }
62
 
63
  # --- Gradio Interface ---
64
 
65
  with gr.Blocks() as demo:
66
+ gr.Markdown("# Hugging Face Spaces Tiered Access Example")
67
+
68
+ # Components to display status and user identity
69
+ status_message = gr.Markdown("Checking access status...")
70
+ user_identity_text = gr.Textbox(label="Logged In User Info", interactive=False)
71
+
72
+ # Placeholder for the Login Prompt (hidden if user is logged in)
73
+ with gr.Column(visible=False) as login_prompt_column:
74
+ gr.Markdown("### Please Sign in with Hugging Face")
75
+ gr.Markdown("*(A 'Sign in with Hugging Face' button will appear automatically above this section when deployed on HF Spaces with OAuth enabled)*")
76
+ # The actual login button is added by Hugging Face Spaces when hf_oauth: true is set in README.md
77
+
78
+ # Content for users with Limited Access (visible by default or for non-authorized users)
79
+ with gr.Column(visible=True) as limited_content_column:
80
  gr.Markdown("## Limited Access Content")
81
+ gr.Textbox(value="This is content visible to everyone or users with limited access.", interactive=False)
82
+ gr.Image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/welcome/hugging-face-logo.png", width=200)
83
+ gr.Markdown("*(Sign in and/or get authorized for more features!)*")
84
  # Add other limited features here
85
 
86
+ # Content for users with Full Access (only visible to authorized users)
87
+ with gr.Column(visible=False) as full_content_column:
88
  gr.Markdown("## Full Access Content")
89
+ gr.Textbox(value="🥳 Congratulations! You have unlocked the full version! 🥳", interactive=False)
90
+ gr.Video("https://huggingface.co/spaces/gradio/space-tourism/resolve/main/space-tourism.mp4")
91
+ gr.Markdown("*(This content is only for authorized accounts)*")
92
  # Add other full features here
93
 
94
+ # This button triggers the check_access_level function.
95
+ # In a real application, you might want this check to happen
96
+ # automatically on page load or after the OAuth redirect.
97
+ # For demonstration purposes, a button makes the flow clear.
98
+ check_button = gr.Button("Check My Access Level")
99
+
100
+ # Link the button click to the access check function
101
+ # The outputs will update the visibility and text components
102
+ check_button.click(
103
+ fn=get_user_access_level,
104
+ inputs=None, # Request object is implicitly passed by Gradio
105
+ outputs=[
106
+ status_message,
107
+ user_identity_text,
108
+ login_prompt_column,
109
+ limited_content_column,
110
+ full_content_column
111
+ ]
112
+ )
113
+
114
+ # Initial check when the page loads (might need a small delay or specific trigger depending on HF/Gradio loading)
115
+ # A common pattern is to call a load function or rely on the button click after redirect.
116
+ # Let's add a load event to trigger the check immediately on page load attempt.
117
+ demo.load(
118
+ fn=get_user_access_level,
119
+ inputs=None,
120
+ outputs=[
121
+ status_message,
122
+ user_identity_text,
123
+ login_prompt_column,
124
+ limited_content_column,
125
+ full_content_column
126
+ ]
127
  )
128
 
 
 
 
 
 
129
 
130
  demo.launch()