Skip to content

Commit 6670a12

Browse files
znationabidlabs
andauthored
Fix: allow fine grained write-access tokens (#68)
* Fix: allow fine grained write-access tokens Refactor the logic in deploy_as_space to attempt reading info or creation of a space, and handling the exception to present a login screen. This way the server can handle the authenticity of the token and we don't need logic to validate it. * Check both 401 and 403 in both places * simplify * retry after acquiring token --------- Co-authored-by: Abubakar Abid <abubakar@huggingface.co>
1 parent d7390cf commit 6670a12

1 file changed

Lines changed: 29 additions & 18 deletions

File tree

trackio/deploy.py

Lines changed: 29 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from gradio_client import Client, handle_file
1010
from httpx import ReadTimeout
1111
from huggingface_hub.errors import RepositoryNotFoundError
12+
from requests import HTTPError
1213

1314
from trackio.sqlite_storage import SQLiteStorage
1415

@@ -27,25 +28,26 @@ def deploy_as_space(
2728
trackio_path = files("trackio")
2829

2930
hf_api = huggingface_hub.HfApi()
30-
whoami = None
31-
login = False
31+
3232
try:
33-
whoami = hf_api.whoami()
34-
if whoami["auth"]["accessToken"]["role"] != "write":
35-
login = True
36-
except OSError:
37-
login = True
38-
if login:
39-
print("Need 'write' access token to create a Spaces repo.")
40-
huggingface_hub.login(add_to_git_credential=False)
41-
whoami = hf_api.whoami()
42-
43-
huggingface_hub.create_repo(
44-
space_id,
45-
space_sdk="gradio",
46-
repo_type="space",
47-
exist_ok=True,
48-
)
33+
huggingface_hub.create_repo(
34+
space_id,
35+
space_sdk="gradio",
36+
repo_type="space",
37+
exist_ok=True,
38+
)
39+
except HTTPError as e:
40+
if e.response.status_code in [401, 403]: # unauthorized or forbidden
41+
print("Need 'write' access token to create a Spaces repo.")
42+
huggingface_hub.login(add_to_git_credential=False)
43+
huggingface_hub.create_repo(
44+
space_id,
45+
space_sdk="gradio",
46+
repo_type="space",
47+
exist_ok=True,
48+
)
49+
else:
50+
raise ValueError(f"Failed to create Space: {e}")
4951

5052
with open(Path(trackio_path, "README.md"), "r") as f:
5153
readme_content = f.read()
@@ -102,6 +104,15 @@ def create_space_if_not_exists(
102104
return
103105
except RepositoryNotFoundError:
104106
pass
107+
except HTTPError as e:
108+
if e.response.status_code in [401, 403]: # unauthorized or forbidden
109+
print("Need 'write' access token to create a Spaces repo.")
110+
huggingface_hub.login(add_to_git_credential=False)
111+
huggingface_hub.add_space_variable(
112+
space_id, "TRACKIO_DATASET_ID", dataset_id
113+
)
114+
else:
115+
raise ValueError(f"Failed to create Space: {e}")
105116

106117
print(f"* Creating new space: {SPACE_URL.format(space_id=space_id)}")
107118
deploy_as_space(space_id, dataset_id)

0 commit comments

Comments
 (0)