Spaces:
Sleeping
Sleeping
File size: 3,888 Bytes
dcad214 38e28c0 dcad214 38e28c0 dcad214 38e28c0 dcad214 38e28c0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 |
import os
import platform
import sys
import time
from typing import Any
import gradio as gr
from huggingface_hub import HfApi
def _safe_preview_secret(value: str | None, *, start: int = 6, end: int = 4) -> str | None:
if not value:
return None
if len(value) <= start + end:
return "*" * len(value)
return f"{value[:start]}...{value[-end:]}"
def _serialize_obj(obj: Any) -> dict[str, Any]:
# Try common serialization paths, then fallback to attribute introspection
for attr in ("model_dump", "dict", "to_dict"):
if hasattr(obj, attr) and callable(getattr(obj, attr)):
try:
return dict(getattr(obj, attr)()) # type: ignore[arg-type]
except Exception:
pass
if hasattr(obj, "__dict__") and isinstance(obj.__dict__, dict):
return {k: v for k, v in obj.__dict__.items() if not k.startswith("_")}
# Last resort: pick readable attributes
result: dict[str, Any] = {}
for name in dir(obj):
if name.startswith("_"):
continue
try:
value = getattr(obj, name)
except Exception:
continue
if isinstance(value, (str, int, float, bool, dict, list, tuple, type(None))):
result[name] = value
return result
def show_profile(profile: gr.OAuthProfile | None) -> dict[str, Any]:
if profile is None:
return {"error": "No profile found. Please sign in with the button first."}
data = _serialize_obj(profile)
return {
"profile": data,
}
def show_token_info(token: gr.OAuthToken | None) -> dict[str, Any]:
if token is None or not getattr(token, "token", None):
return {"error": "No OAuth token available. Please sign in first."}
token_str = token.token # type: ignore[assignment]
info: dict[str, Any] = {
"present": True,
"length": len(token_str),
"preview": _safe_preview_secret(token_str),
}
try:
api = HfApi()
who = api.whoami(token=token_str)
# who typically contains: {"name": username, "email": ..., "orgs": [...]}
info["whoami"] = who
except Exception as e:
info["whoami_error"] = str(e)
return info
def show_env_info() -> dict[str, Any]:
keys_of_interest = [
"SPACE_HOST",
"OPENID_PROVIDER_URL",
"OAUTH_CLIENT_ID",
"OAUTH_CLIENT_SECRET",
"OAUTH_SCOPES",
"HF_TOKEN",
"HUGGING_FACE_HUB_TOKEN",
"HF_HOME",
"PYTHONPATH",
]
env_details: dict[str, Any] = {}
for k in keys_of_interest:
v = os.getenv(k)
if v is None:
env_details[k] = None
else:
env_details[k] = _safe_preview_secret(v)
system_info = {
"python_version": sys.version,
"platform": platform.platform(),
"time": time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()),
}
all_env_names = sorted(list(os.environ.keys()))
return {
"selected_environment": env_details,
"all_environment_variable_names": all_env_names,
"system": system_info,
}
with gr.Blocks() as demo:
gr.Markdown("""
# HF OAuth Info Tester
Use the button below to sign in with Hugging Face. Then click the buttons to inspect the signed-in profile, token-derived info, and selected environment details.
""")
with gr.Row():
gr.LoginButton()
info = gr.JSON(label="Output")
with gr.Row():
btn_profile = gr.Button("Show User Profile")
btn_token = gr.Button("Show Token Info (whoami)")
btn_env = gr.Button("Show Environment Info")
btn_profile.click(fn=show_profile, inputs=None, outputs=info)
btn_token.click(fn=show_token_info, inputs=None, outputs=info)
btn_env.click(fn=show_env_info, inputs=None, outputs=info)
if __name__ == "__main__":
demo.launch()
|