wuhp commited on
Commit
3991883
·
verified ·
1 Parent(s): c01df60

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +133 -34
app.py CHANGED
@@ -1,8 +1,14 @@
1
  import gradio as gr
2
- from huggingface_hub import create_repo, list_models
 
 
 
 
 
 
 
3
 
4
  def show_profile(profile: gr.OAuthProfile | None) -> str:
5
- """Update login status."""
6
  if profile is None:
7
  return "*Not logged in.*"
8
  return f"✅ Logged in as **{profile.username}**"
@@ -11,15 +17,17 @@ def list_private_models(
11
  profile: gr.OAuthProfile | None,
12
  oauth_token: gr.OAuthToken | None
13
  ) -> str:
14
- """Demo: list user’s private/public models."""
15
  if profile is None or oauth_token is None:
16
  return "Please log in to see your models."
17
  models = [
18
- f"{model.id} ({'private' if model.private else 'public'})"
19
- for model in list_models(author=profile.username, token=oauth_token.token)
20
  ]
21
- return "No models found." if not models \
 
 
22
  else "Models:\n\n" + "\n - ".join(models)
 
23
 
24
  def create_space(
25
  repo_name: str,
@@ -27,10 +35,6 @@ def create_space(
27
  profile: gr.OAuthProfile | None,
28
  oauth_token: gr.OAuthToken | None
29
  ) -> tuple[str, str, str]:
30
- """
31
- Create (or get) a Hugging Face Space with the chosen SDK template,
32
- returning (repo_id, logs, iframe).
33
- """
34
  if profile is None or oauth_token is None:
35
  return "", "⚠️ Please log in first.", "<p>No Space created yet.</p>"
36
  repo_id = f"{profile.username}/{repo_name}"
@@ -46,46 +50,141 @@ def create_space(
46
  iframe = f'<iframe src="{url}" width="100%" height="500px"></iframe>'
47
  return repo_id, logmsg, iframe
48
 
49
- with gr.Blocks(title="HF OAuth + Space Creator") as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  gr.Markdown(
51
- "## Sign in with Hugging Face + Create a Space\n\n"
52
- "1. Click **Sign in**.\n"
53
- "2. Pick a template, enter a name, and **Create Space**.\n\n"
 
 
54
  "---"
55
  )
56
 
57
- # — Login UI
58
  login_btn = gr.LoginButton(variant="huggingface", size="lg")
59
  status_md = gr.Markdown("*Not logged in.*")
60
  models_md = gr.Markdown()
 
 
 
 
61
 
62
- demo.load(show_profile, inputs=None, outputs=status_md)
63
- login_btn.click(show_profile, inputs=None, outputs=status_md)
64
- demo.load(list_private_models, inputs=None, outputs=models_md)
65
- login_btn.click(list_private_models,inputs=None, outputs=models_md)
66
-
67
- # — Create Space UI —
68
- repo_name = gr.Textbox(label="New Space name", placeholder="my-space-name")
69
- sdk_selector = gr.Radio(
70
  choices=["gradio", "streamlit"],
71
  value="gradio",
72
  label="Space template (SDK)"
73
  )
74
- create_btn = gr.Button("Create Space", interactive=False)
75
- session_id = gr.Textbox(visible=False)
76
- logs = gr.Textbox(label="Logs", interactive=False, lines=3)
77
- preview_iframe = gr.HTML("<p>No Space created yet.</p>")
78
 
79
- def enable_create(profile: gr.OAuthProfile | None):
80
- return gr.update(interactive=profile is not None)
81
-
82
- demo.load(enable_create, inputs=None, outputs=create_btn)
83
- login_btn.click(enable_create, inputs=None, outputs=create_btn)
 
84
 
85
  create_btn.click(
86
  fn=create_space,
87
- inputs=[repo_name, sdk_selector],
88
- outputs=[session_id, logs, preview_iframe]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  )
90
 
91
  if __name__ == "__main__":
 
1
  import gradio as gr
2
+ import requests
3
+ from huggingface_hub import (
4
+ create_repo,
5
+ list_models,
6
+ upload_file,
7
+ )
8
+
9
+ # — CALLBACKS —
10
 
11
  def show_profile(profile: gr.OAuthProfile | None) -> str:
 
12
  if profile is None:
13
  return "*Not logged in.*"
14
  return f"✅ Logged in as **{profile.username}**"
 
17
  profile: gr.OAuthProfile | None,
18
  oauth_token: gr.OAuthToken | None
19
  ) -> str:
 
20
  if profile is None or oauth_token is None:
21
  return "Please log in to see your models."
22
  models = [
23
+ f"{m.id} ({'private' if m.private else 'public'})"
24
+ for m in list_models(author=profile.username, token=oauth_token.token)
25
  ]
26
+ return (
27
+ "No models found."
28
+ if not models
29
  else "Models:\n\n" + "\n - ".join(models)
30
+ )
31
 
32
  def create_space(
33
  repo_name: str,
 
35
  profile: gr.OAuthProfile | None,
36
  oauth_token: gr.OAuthToken | None
37
  ) -> tuple[str, str, str]:
 
 
 
 
38
  if profile is None or oauth_token is None:
39
  return "", "⚠️ Please log in first.", "<p>No Space created yet.</p>"
40
  repo_id = f"{profile.username}/{repo_name}"
 
50
  iframe = f'<iframe src="{url}" width="100%" height="500px"></iframe>'
51
  return repo_id, logmsg, iframe
52
 
53
+ def enable_button(
54
+ profile: gr.OAuthProfile | None,
55
+ oauth_token: gr.OAuthToken | None,
56
+ repo_id: str
57
+ ):
58
+ """Enable an action button only once logged in & repo exists."""
59
+ return gr.update(interactive=bool(profile and oauth_token and repo_id))
60
+
61
+ def upload_file_to_space(
62
+ file: gr.components.FileData | None,
63
+ path_in_repo: str,
64
+ repo_id: str,
65
+ oauth_token: gr.OAuthToken | None
66
+ ) -> str:
67
+ if oauth_token is None:
68
+ return "⚠️ Please log in first."
69
+ if not repo_id:
70
+ return "⚠️ Please create a Space first."
71
+ if file is None:
72
+ return "⚠️ No file selected."
73
+ # Gradio FileData gives us a path on disk:
74
+ upload_file(
75
+ path_or_fileobj=file.name,
76
+ path_in_repo=path_in_repo,
77
+ repo_id=repo_id,
78
+ token=oauth_token.token,
79
+ repo_type="space"
80
+ )
81
+ return f"✅ Uploaded `{path_in_repo}` to `{repo_id}`" # :contentReference[oaicite:0]{index=0}
82
+
83
+ def get_space_logs(
84
+ repo_id: str,
85
+ profile: gr.OAuthProfile | None,
86
+ oauth_token: gr.OAuthToken | None
87
+ ) -> str:
88
+ if profile is None or oauth_token is None:
89
+ return "⚠️ Please log in and create a Space first."
90
+ # This endpoint is currently undocumented; usage may change :contentReference[oaicite:1]{index=1}.
91
+ endpoint = f"https://huggingface.co/api/spaces/{repo_id}/logs"
92
+ headers = {"Authorization": f"Bearer {oauth_token.token}"}
93
+ resp = requests.get(endpoint, headers=headers)
94
+ if resp.status_code != 200:
95
+ return f"❌ Failed to fetch logs ({resp.status_code})"
96
+ entries = resp.json() # expecting a list of {text, timestamp,…}
97
+ return "\n".join(e.get("text", "") for e in entries)
98
+
99
+ # — BUILD UI —
100
+
101
+ with gr.Blocks(title="HF OAuth + Space Manager") as demo:
102
  gr.Markdown(
103
+ "## Sign in with Hugging Face + Manage Your Space\n\n"
104
+ "1. **Sign in**\n"
105
+ "2. **Create** a Space (Gradio/Streamlit)\n"
106
+ "3. **Upload** files to it\n"
107
+ "4. **Fetch** its runtime logs\n\n"
108
  "---"
109
  )
110
 
111
+ # — LOGIN STATUS & MODEL LIST
112
  login_btn = gr.LoginButton(variant="huggingface", size="lg")
113
  status_md = gr.Markdown("*Not logged in.*")
114
  models_md = gr.Markdown()
115
+ demo.load(show_profile, inputs=None, outputs=status_md)
116
+ login_btn.click(show_profile, inputs=None, outputs=status_md)
117
+ demo.load(list_private_models, inputs=None, outputs=models_md)
118
+ login_btn.click(list_private_models, inputs=None, outputs=models_md)
119
 
120
+ # — CREATE SPACE —
121
+ repo_name = gr.Textbox(label="New Space name", placeholder="my-space")
122
+ sdk_selector = gr.Radio(
 
 
 
 
 
123
  choices=["gradio", "streamlit"],
124
  value="gradio",
125
  label="Space template (SDK)"
126
  )
127
+ create_btn = gr.Button("Create Space", interactive=False)
128
+ session_id = gr.Textbox(visible=False) # holds the repo_id
129
+ logs = gr.Textbox(label="Logs", interactive=False, lines=3)
130
+ preview = gr.HTML("<p>No Space created yet.</p>")
131
 
132
+ demo.load(enable_button,
133
+ inputs=[login_btn, login_btn, session_id],
134
+ outputs=create_btn)
135
+ login_btn.click(enable_button,
136
+ inputs=[login_btn, login_btn, session_id],
137
+ outputs=create_btn)
138
 
139
  create_btn.click(
140
  fn=create_space,
141
+ inputs=[repo_name, sdk_selector, login_btn, login_btn],
142
+ outputs=[session_id, logs, preview]
143
+ )
144
+
145
+ # — UPLOAD FILES —
146
+ path_in_repo = gr.Textbox(label="Path in Space", value="app.py")
147
+ file_uploader= gr.File(label="Select file to upload")
148
+ upload_btn = gr.Button("Upload File", interactive=False)
149
+ upload_logs = gr.Textbox(label="Upload Logs", interactive=False, lines=2)
150
+
151
+ # Enable upload once the space exists and you’re signed in
152
+ session_id.change(
153
+ fn=enable_button,
154
+ inputs=[login_btn, login_btn, session_id],
155
+ outputs=[upload_btn]
156
+ )
157
+ login_btn.click(
158
+ fn=enable_button,
159
+ inputs=[login_btn, login_btn, session_id],
160
+ outputs=[upload_btn]
161
+ )
162
+
163
+ upload_btn.click(
164
+ fn=upload_file_to_space,
165
+ inputs=[file_uploader, path_in_repo, session_id, login_btn],
166
+ outputs=[upload_logs]
167
+ )
168
+
169
+ # — FETCH SPACE LOGS —
170
+ logs_btn = gr.Button("Get Space Logs", interactive=False)
171
+ space_logs_md = gr.Textbox(label="Space Logs", interactive=False, lines=10)
172
+
173
+ session_id.change(
174
+ fn=enable_button,
175
+ inputs=[login_btn, login_btn, session_id],
176
+ outputs=[logs_btn]
177
+ )
178
+ login_btn.click(
179
+ fn=enable_button,
180
+ inputs=[login_btn, login_btn, session_id],
181
+ outputs=[logs_btn]
182
+ )
183
+
184
+ logs_btn.click(
185
+ fn=get_space_logs,
186
+ inputs=[session_id, login_btn, login_btn],
187
+ outputs=[space_logs_md]
188
  )
189
 
190
  if __name__ == "__main__":