nazdridoy commited on
Commit
dcad214
·
verified ·
1 Parent(s): 1929e92
Files changed (2) hide show
  1. README.md +7 -3
  2. app.py +121 -62
README.md CHANGED
@@ -8,8 +8,12 @@ sdk_version: 5.42.0
8
  app_file: app.py
9
  pinned: false
10
  hf_oauth: true
11
- hf_oauth_scopes:
12
- - inference-api
13
  ---
14
 
15
- An example chatbot using [Gradio](https://gradio.app), [`huggingface_hub`](https://huggingface.co/docs/huggingface_hub/v0.22.2/en/index), and the [Hugging Face Inference API](https://huggingface.co/docs/api-inference/index).
 
 
 
 
 
 
 
8
  app_file: app.py
9
  pinned: false
10
  hf_oauth: true
 
 
11
  ---
12
 
13
+ Buttons-only Gradio Space to test "Sign-In with HF" and inspect:
14
+
15
+ - OAuth profile details returned by the login flow
16
+ - Token info via whoami (masked preview)
17
+ - Selected environment variables and system info
18
+
19
+ See docs: [HF Spaces OAuth](https://huggingface.co/docs/hub/spaces-oauth), [Gradio LoginButton](https://www.gradio.app/docs/gradio/loginbutton).
app.py CHANGED
@@ -1,69 +1,128 @@
 
 
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
-
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
14
- """
15
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
16
- """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
18
-
19
- messages = [{"role": "system", "content": system_message}]
20
-
21
- messages.extend(history)
22
-
23
- messages.append({"role": "user", "content": message})
24
-
25
- response = ""
26
-
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- chatbot = gr.ChatInterface(
47
- respond,
48
- type="messages",
49
- additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
54
- minimum=0.1,
55
- maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
- ],
61
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  with gr.Blocks() as demo:
64
- with gr.Sidebar():
 
 
 
 
 
65
  gr.LoginButton()
66
- chatbot.render()
 
 
 
 
 
 
 
 
 
 
67
 
68
 
69
  if __name__ == "__main__":
 
1
+ import os
2
+ import platform
3
+ import sys
4
+ import time
5
+ from typing import Any
6
+
7
  import gradio as gr
8
+ from huggingface_hub import HfApi
9
+
10
+
11
+ def _safe_preview_secret(value: str | None, *, start: int = 6, end: int = 4) -> str | None:
12
+ if not value:
13
+ return None
14
+ if len(value) <= start + end:
15
+ return "*" * len(value)
16
+ return f"{value[:start]}...{value[-end:]}"
17
+
18
+
19
+ def _serialize_obj(obj: Any) -> dict[str, Any]:
20
+ # Try common serialization paths, then fallback to attribute introspection
21
+ for attr in ("model_dump", "dict", "to_dict"):
22
+ if hasattr(obj, attr) and callable(getattr(obj, attr)):
23
+ try:
24
+ return dict(getattr(obj, attr)()) # type: ignore[arg-type]
25
+ except Exception:
26
+ pass
27
+ if hasattr(obj, "__dict__") and isinstance(obj.__dict__, dict):
28
+ return {k: v for k, v in obj.__dict__.items() if not k.startswith("_")}
29
+ # Last resort: pick readable attributes
30
+ result: dict[str, Any] = {}
31
+ for name in dir(obj):
32
+ if name.startswith("_"):
33
+ continue
34
+ try:
35
+ value = getattr(obj, name)
36
+ except Exception:
37
+ continue
38
+ if isinstance(value, (str, int, float, bool, dict, list, tuple, type(None))):
39
+ result[name] = value
40
+ return result
41
+
42
+
43
+ def show_profile(profile: gr.OAuthProfile | None) -> dict[str, Any]:
44
+ if profile is None:
45
+ return {"error": "No profile found. Please sign in with the button first."}
46
+ data = _serialize_obj(profile)
47
+ return {
48
+ "profile": data,
49
+ }
50
+
51
+
52
+ def show_token_info(token: gr.OAuthToken | None) -> dict[str, Any]:
53
+ if token is None or not getattr(token, "token", None):
54
+ return {"error": "No OAuth token available. Please sign in first."}
55
+
56
+ token_str = token.token # type: ignore[assignment]
57
+ info: dict[str, Any] = {
58
+ "present": True,
59
+ "length": len(token_str),
60
+ "preview": _safe_preview_secret(token_str),
61
+ }
62
+ try:
63
+ api = HfApi()
64
+ who = api.whoami(token=token_str)
65
+ # who typically contains: {"name": username, "email": ..., "orgs": [...]}
66
+ info["whoami"] = who
67
+ except Exception as e:
68
+ info["whoami_error"] = str(e)
69
+ return info
70
+
71
+
72
+ def show_env_info() -> dict[str, Any]:
73
+ keys_of_interest = [
74
+ "SPACE_HOST",
75
+ "OPENID_PROVIDER_URL",
76
+ "OAUTH_CLIENT_ID",
77
+ "OAUTH_CLIENT_SECRET",
78
+ "OAUTH_SCOPES",
79
+ "HF_TOKEN",
80
+ "HUGGING_FACE_HUB_TOKEN",
81
+ "HF_HOME",
82
+ "PYTHONPATH",
83
+ ]
84
+ env_details: dict[str, Any] = {}
85
+ for k in keys_of_interest:
86
+ v = os.getenv(k)
87
+ if v is None:
88
+ env_details[k] = None
89
+ else:
90
+ env_details[k] = _safe_preview_secret(v)
91
+
92
+ system_info = {
93
+ "python_version": sys.version,
94
+ "platform": platform.platform(),
95
+ "time": time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()),
96
+ }
97
+
98
+ all_env_names = sorted(list(os.environ.keys()))
99
+
100
+ return {
101
+ "selected_environment": env_details,
102
+ "all_environment_variable_names": all_env_names,
103
+ "system": system_info,
104
+ }
105
+
106
 
107
  with gr.Blocks() as demo:
108
+ gr.Markdown("""
109
+ # HF OAuth Info Tester
110
+ 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.
111
+ """)
112
+
113
+ with gr.Row():
114
  gr.LoginButton()
115
+
116
+ info = gr.JSON(label="Output")
117
+
118
+ with gr.Row():
119
+ btn_profile = gr.Button("Show User Profile")
120
+ btn_token = gr.Button("Show Token Info (whoami)")
121
+ btn_env = gr.Button("Show Environment Info")
122
+
123
+ btn_profile.click(fn=show_profile, inputs=None, outputs=info)
124
+ btn_token.click(fn=show_token_info, inputs=None, outputs=info)
125
+ btn_env.click(fn=show_env_info, inputs=None, outputs=info)
126
 
127
 
128
  if __name__ == "__main__":