broadfield-dev commited on
Commit
4e2684d
·
verified ·
1 Parent(s): d7e325f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +154 -154
app.py CHANGED
@@ -12,11 +12,12 @@ def get_hf_api(token):
12
  """Initializes the HfApi client. Allows read-only operations if no token is provided."""
13
  return HfApi(token=token if token else None)
14
 
15
- # --- UI Functions (Original Tab) ---
16
 
17
  def handle_token_change(token):
18
  """
19
- Called when the token is entered. Fetches user info and updates UI interactivity.
 
20
  """
21
  if not token:
22
  # No token, disable write actions and clear user-specific info
@@ -25,24 +26,26 @@ def handle_token_change(token):
25
  delete_repo_btn: gr.update(interactive=False),
26
  commit_btn: gr.update(interactive=False),
27
  author_input: gr.update(value=""),
 
28
  whoami_output: gr.update(value=None, visible=False)
29
  }
30
- return (None, "", *update_dict.values())
31
 
32
  try:
33
  api = get_hf_api(token)
34
  user_info = api.whoami()
35
  username = user_info.get('name')
36
 
37
- # Token is valid, enable write actions and set author
38
  update_dict = {
39
  manage_files_btn: gr.update(interactive=True),
40
  delete_repo_btn: gr.update(interactive=True),
41
  commit_btn: gr.update(interactive=True),
42
  author_input: gr.update(value=username),
 
43
  whoami_output: gr.update(value=user_info, visible=True)
44
  }
45
- return (token, username, *update_dict.values())
46
 
47
  except HfHubHTTPError as e:
48
  gr.Warning(f"Invalid Token: {e}. You can only perform read-only actions.")
@@ -52,81 +55,106 @@ def handle_token_change(token):
52
  commit_btn: gr.update(interactive=False),
53
  whoami_output: gr.update(value=None, visible=False)
54
  }
55
- return (token, "", *update_dict.values())
56
 
57
 
58
  def list_repos(token, author, repo_type):
59
- """Lists repositories for a given author and type."""
60
  if not author:
61
  gr.Info("Please enter an author (username or organization) to list repositories.")
62
- return gr.update(choices=[], value=None), gr.update(visible=False), gr.update(visible=False)
63
  try:
64
  api = get_hf_api(token)
65
- # Use the dedicated list functions for clarity e.g. api.list_models, api.list_spaces
66
  list_fn = getattr(api, f"list_{repo_type}s")
67
  repos = list_fn(author=author)
68
  repo_ids = [repo.id for repo in repos]
69
- return gr.update(choices=repo_ids, value=None), gr.update(visible=False), gr.update(visible=False)
 
70
  except HfHubHTTPError as e:
71
  gr.Error(f"Could not list repositories: {e}")
72
- return gr.update(choices=[], value=None), gr.update(visible=False), gr.update(visible=False)
73
 
74
- def handle_repo_selection(repo_id):
75
- """Called when a repo is selected. Makes action buttons visible."""
76
  if repo_id:
77
- return gr.update(visible=True), gr.update(visible=False) # Show actions, hide editor
78
- return gr.update(visible=False), gr.update(visible=False) # Hide everything
79
 
80
  def delete_repo(token, repo_id, repo_type):
81
  """Deletes the selected repository."""
82
  if not token:
83
  gr.Error("A write-enabled Hugging Face token is required to delete a repository.")
84
- return repo_id, gr.update(visible=True), gr.update(visible=False)
85
  if not repo_id:
86
  gr.Warning("No repository selected to delete.")
87
- return repo_id, gr.update(visible=True), gr.update(visible=False)
88
  try:
89
  api = get_hf_api(token)
90
  api.delete_repo(repo_id=repo_id, repo_type=repo_type)
91
  gr.Info(f"Successfully deleted '{repo_id}'.")
92
- return None, gr.update(visible=False), gr.update(visible=False)
 
93
  except HfHubHTTPError as e:
94
  gr.Error(f"Failed to delete repository: {e}")
95
- return repo_id, gr.update(visible=True), gr.update(visible=False)
96
 
97
- # --- File Editor Functions (Original Tab) ---
98
 
99
- def show_file_manager(token, repo_id, repo_type):
 
100
  if not repo_id:
101
  gr.Warning("No repository selected.")
102
- return gr.update(visible=False), gr.update(), gr.update(), gr.update()
103
  try:
104
  api = get_hf_api(token)
105
  repo_files = api.list_repo_files(repo_id=repo_id, repo_type=repo_type)
106
  filtered_files = [f for f in repo_files if not f.startswith('.')]
 
 
 
 
 
 
 
 
 
 
 
 
107
  return (
108
- gr.update(visible=True), gr.update(choices=filtered_files, value=None),
109
- gr.update(value="## Select a file to view or edit.", language='markdown'), ""
 
110
  )
111
  except Exception as e:
112
  gr.Error(f"Could not list files: {e}")
113
- return gr.update(visible=False), gr.update(), gr.update(), gr.update()
114
 
115
- def load_file_content(token, repo_id, repo_type, filepath):
 
116
  if not filepath:
117
- return gr.update(value="## Select a file to view its content.", language='markdown')
118
  try:
119
  api = get_hf_api(token)
120
  local_path = api.hf_hub_download(repo_id=repo_id, repo_type=repo_type, filename=filepath, token=token)
121
- with open(local_path, 'r', encoding='utf-8') as f: content = f.read()
 
 
122
  language = os.path.splitext(filepath)[1].lstrip('.').lower()
123
- if language == 'py': language = 'python'
124
- if language == 'js': language = 'javascript'
125
- if language == 'md': language = 'markdown'
126
- else: language = 'python'
127
- return gr.update(value=content, language=language)
 
128
  except Exception as e:
129
- return gr.update(value=f"Error loading file: {e}", language='plaintext')
 
 
 
 
 
 
130
 
131
  def commit_file(token, repo_id, repo_type, filepath, content, commit_message):
132
  if not token: gr.Error("A write-enabled token is required."); return
@@ -144,94 +172,54 @@ def commit_file(token, repo_id, repo_type, filepath, content, commit_message):
144
 
145
  # --- Download Tab Functions ---
146
 
147
- def list_spaces_for_download(token, author):
148
- """Lists spaces for a given author to populate the dropdown."""
149
- if not author:
150
- gr.Info("Please enter an author (username or organization) to list spaces.")
151
- return gr.update(choices=[], value=None)
152
- try:
153
- api = get_hf_api(token)
154
- spaces = api.list_spaces(author=author)
155
- repo_ids = [space.id for space in spaces]
156
- if not repo_ids:
157
- gr.Warning(f"No Spaces found for author '{author}'.")
158
- return gr.update(choices=repo_ids, value=None)
159
- except RepositoryNotFoundError:
160
- gr.Warning(f"Author '{author}' not found or has no public spaces.")
161
- return gr.update(choices=[], value=None)
162
- except HfHubHTTPError as e:
163
- gr.Error(f"Could not list spaces: {e}")
164
- return gr.update(choices=[], value=None)
165
-
166
- def download_spaces_as_zip(token, selected_space_ids, progress=gr.Progress()):
167
- """Downloads selected spaces and zips them up."""
168
- if not selected_space_ids:
169
- gr.Warning("No spaces selected for download.")
170
  return gr.update(visible=False, value=None)
171
 
172
- # Create a temporary directory for all the downloaded content
173
  download_root_dir = tempfile.mkdtemp()
174
-
175
  try:
176
- total_spaces = len(selected_space_ids)
177
  progress(0, desc="Starting download...")
178
 
179
- # 1. Download each space into a dedicated subfolder within the temp directory
180
- for i, repo_id in enumerate(selected_space_ids):
181
- progress((i) / total_spaces, desc=f"Downloading {repo_id} ({i+1}/{total_spaces})")
182
-
183
- # Sanitize repo_id to create a valid folder name for the zip
184
  folder_name = repo_id.replace("/", "__")
185
  target_path = os.path.join(download_root_dir, folder_name)
186
 
187
  try:
188
- # Use snapshot_download to get the entire repo efficiently
189
  snapshot_download(
190
- repo_id=repo_id,
191
- repo_type="space",
192
- local_dir=target_path,
193
- token=token,
194
- local_dir_use_symlinks=False, # Crucial for zipping
195
- resume_download=True,
196
  )
197
  except Exception as e:
198
- # Log the error and skip this repo
199
  gr.Error(f"Failed to download {repo_id}: {e}")
200
  continue
201
 
202
- # 2. Create the zip archive from the directory of downloaded spaces
203
- progress(0.95, desc="All spaces downloaded. Creating ZIP file...")
204
-
205
- # We create the zip file outside the download dir so we can clean up easily
206
- zip_base_name = os.path.join(tempfile.gettempdir(), f"hf_spaces_archive_{uuid.uuid4().hex}")
207
-
208
- # shutil.make_archive returns the full path to the created archive
209
- zip_path = shutil.make_archive(
210
- base_name=zip_base_name,
211
- format='zip',
212
- root_dir=download_root_dir # This becomes the root of the zip
213
- )
214
 
215
  progress(1, desc="Download ready!")
216
  gr.Info("ZIP file created successfully!")
217
-
218
- # Return the path to the zip file and make the component visible
219
  return gr.update(value=zip_path, visible=True)
220
-
221
  finally:
222
- # 3. Clean up the large download directory, regardless of success or failure
223
  shutil.rmtree(download_root_dir, ignore_errors=True)
224
 
 
225
  # --- Gradio UI Layout ---
226
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue"), title="Hugging Face Hub Toolkit") as demo:
227
  # State management
228
  hf_token_state = gr.State(None)
229
- author_state = gr.State("")
230
- selected_repo_id = gr.State(None)
231
- selected_repo_type = gr.State("space") # Default
232
 
233
  gr.Markdown("# Hugging Face Hub Toolkit")
234
- gr.Markdown("An intuitive interface to manage your Hugging Face repositories. **Enter a write-token for full access.**")
235
 
236
  with gr.Sidebar():
237
  hf_token = gr.Textbox(label="Hugging Face API Token", type="password", placeholder="hf_...", scale=3)
@@ -239,98 +227,110 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue"), title="Hugging Face Hub
239
 
240
  with gr.Tabs():
241
  with gr.TabItem("Manage Repositories"):
242
- with gr.Row(equal_height=False):
243
  with gr.Column(scale=1):
244
- gr.Markdown("### 1. Select a Repository")
245
  author_input = gr.Textbox(label="Author (Username or Org)", interactive=True)
246
- repo_selector = gr.Radio(label="Select a Repository", interactive=True, value=None)
247
- with gr.Tabs() as repo_type_tabs:
248
  for repo_type, label in [("space", "Spaces"), ("model", "Models"), ("dataset", "Datasets")]:
249
- with gr.Tab(label, id=repo_type):
250
- btn = gr.Button(f"List {label}")
251
- btn.click(
252
- fn=list_repos,
253
- inputs=[hf_token_state, author_input, gr.State(repo_type)],
254
- outputs=[repo_selector, gr.Column(), gr.Column()] # Dummy outputs for panels to hide them
255
- ).then(fn=lambda author: author, inputs=author_input, outputs=author_state)
256
-
257
- with gr.Column(scale=3):
 
 
 
 
 
 
258
  with gr.Column(visible=False) as action_panel:
259
- gr.Markdown("### 2. Choose an Action")
260
  with gr.Row():
261
- manage_files_btn = gr.Button("Manage Files", interactive=False, scale=1)
262
- delete_repo_btn = gr.Button("Delete This Repo", variant="stop", interactive=False, scale=1)
263
 
264
  with gr.Column(visible=False) as editor_panel:
265
- gr.Markdown("### 3. Edit Files")
266
  file_selector = gr.Dropdown(label="Select File", interactive=True)
267
  code_editor = gr.Code(label="File Content", language="markdown", interactive=True)
268
  commit_message_input = gr.Textbox(label="Commit Message", placeholder="e.g., Update README.md", interactive=True)
269
  commit_btn = gr.Button("Commit Changes", variant="primary", interactive=False)
270
 
271
- with gr.TabItem("Download Spaces (ZIP)"):
272
- gr.Markdown("## Bulk Download Spaces as a ZIP Archive")
273
- gr.Markdown("Select one or more Spaces from an author to download them as a single ZIP file. Each Space will be in its own folder inside the archive.")
274
 
275
  with gr.Row():
276
- download_author_input = gr.Textbox(
277
- label="Author (Username or Org)",
278
- interactive=True,
279
- placeholder="e.g., huggingface-projects or osanseviero"
280
- )
281
- list_spaces_btn = gr.Button("List Spaces", variant="secondary")
 
 
 
 
 
 
 
282
 
283
- spaces_dropdown = gr.Dropdown(label="Available Spaces", info="Select the spaces you want to download.", multiselect=True, interactive=True)
284
- download_btn = gr.Button("Download Selected Spaces as ZIP", variant="primary")
285
  download_output_file = gr.File(label="Your Downloaded ZIP File", visible=False)
286
-
287
- # --- Event Handlers for Download Tab ---
288
- list_spaces_btn.click(
289
- fn=list_spaces_for_download,
290
- inputs=[hf_token_state, download_author_input],
291
- outputs=[spaces_dropdown]
292
- )
293
 
294
- download_btn.click(
295
- fn=download_spaces_as_zip,
296
- inputs=[hf_token_state, spaces_dropdown],
297
- outputs=[download_output_file]
298
- )
299
-
300
- # --- Event Handlers (Original Tab) ---
301
  hf_token.change(
302
  fn=handle_token_change, inputs=hf_token,
303
- outputs=[hf_token_state, author_state, manage_files_btn, delete_repo_btn, commit_btn, author_input, whoami_output]
304
  )
305
- repo_type_tabs.select(
306
- fn=lambda rt: (rt, None, gr.update(choices=[], value=None), gr.update(visible=False), gr.update(visible=False)),
307
- inputs=repo_type_tabs,
308
- outputs=[selected_repo_type, selected_repo_id, repo_selector, action_panel, editor_panel]
309
- )
310
- repo_selector.select(
311
- fn=lambda repo_id: (repo_id, *handle_repo_selection(repo_id)),
312
- inputs=repo_selector, outputs=[selected_repo_id, action_panel, editor_panel]
313
  )
 
314
  manage_files_btn.click(
315
- fn=show_file_manager, inputs=[hf_token_state, selected_repo_id, selected_repo_type],
316
- outputs=[editor_panel, file_selector, code_editor, commit_message_input]
 
317
  )
 
318
  delete_repo_btn.click(
319
- fn=delete_repo, inputs=[hf_token_state, selected_repo_id, selected_repo_type],
320
- outputs=[selected_repo_id, action_panel, editor_panel],
 
321
  js="() => confirm('Are you sure you want to permanently delete this repository? This action cannot be undone.')"
322
- ).then(
323
- fn=list_repos,
324
- inputs=[hf_token_state, author_state, selected_repo_type],
325
- outputs=[repo_selector, action_panel, editor_panel]
326
  )
 
327
  file_selector.change(
328
- fn=load_file_content, inputs=[hf_token_state, selected_repo_id, selected_repo_type, file_selector],
 
329
  outputs=code_editor
330
  )
 
331
  commit_btn.click(
332
  fn=commit_file,
333
- inputs=[hf_token_state, selected_repo_id, selected_repo_type, file_selector, code_editor, commit_message_input]
 
 
 
 
 
 
 
334
  )
335
 
336
  if __name__ == "__main__":
 
12
  """Initializes the HfApi client. Allows read-only operations if no token is provided."""
13
  return HfApi(token=token if token else None)
14
 
15
+ # --- UI Functions ---
16
 
17
  def handle_token_change(token):
18
  """
19
+ Called when the token is entered. Fetches user info, updates UI interactivity,
20
+ and auto-fills the author fields in both tabs.
21
  """
22
  if not token:
23
  # No token, disable write actions and clear user-specific info
 
26
  delete_repo_btn: gr.update(interactive=False),
27
  commit_btn: gr.update(interactive=False),
28
  author_input: gr.update(value=""),
29
+ download_author_input: gr.update(value=""),
30
  whoami_output: gr.update(value=None, visible=False)
31
  }
32
+ return (None, *update_dict.values())
33
 
34
  try:
35
  api = get_hf_api(token)
36
  user_info = api.whoami()
37
  username = user_info.get('name')
38
 
39
+ # Token is valid, enable write actions and set author everywhere
40
  update_dict = {
41
  manage_files_btn: gr.update(interactive=True),
42
  delete_repo_btn: gr.update(interactive=True),
43
  commit_btn: gr.update(interactive=True),
44
  author_input: gr.update(value=username),
45
+ download_author_input: gr.update(value=username),
46
  whoami_output: gr.update(value=user_info, visible=True)
47
  }
48
+ return (token, *update_dict.values())
49
 
50
  except HfHubHTTPError as e:
51
  gr.Warning(f"Invalid Token: {e}. You can only perform read-only actions.")
 
55
  commit_btn: gr.update(interactive=False),
56
  whoami_output: gr.update(value=None, visible=False)
57
  }
58
+ return (token, *update_dict.values())
59
 
60
 
61
  def list_repos(token, author, repo_type):
62
+ """Lists repositories for a given author and type into a dropdown."""
63
  if not author:
64
  gr.Info("Please enter an author (username or organization) to list repositories.")
65
+ return gr.update(choices=[], value=None)
66
  try:
67
  api = get_hf_api(token)
 
68
  list_fn = getattr(api, f"list_{repo_type}s")
69
  repos = list_fn(author=author)
70
  repo_ids = [repo.id for repo in repos]
71
+ gr.Info(f"Found {len(repo_ids)} {repo_type}s for '{author}'.")
72
+ return gr.update(choices=repo_ids, value=None)
73
  except HfHubHTTPError as e:
74
  gr.Error(f"Could not list repositories: {e}")
75
+ return gr.update(choices=[], value=None)
76
 
77
+ def on_manage_repo_select(repo_id):
78
+ """Called when a repo is selected in the Manage tab. Makes action buttons visible."""
79
  if repo_id:
80
+ return gr.update(visible=True) # Show actions
81
+ return gr.update(visible=False) # Hide actions
82
 
83
  def delete_repo(token, repo_id, repo_type):
84
  """Deletes the selected repository."""
85
  if not token:
86
  gr.Error("A write-enabled Hugging Face token is required to delete a repository.")
87
+ return repo_id
88
  if not repo_id:
89
  gr.Warning("No repository selected to delete.")
90
+ return repo_id
91
  try:
92
  api = get_hf_api(token)
93
  api.delete_repo(repo_id=repo_id, repo_type=repo_type)
94
  gr.Info(f"Successfully deleted '{repo_id}'.")
95
+ # After deletion, hide panels and return None to clear selection
96
+ return None
97
  except HfHubHTTPError as e:
98
  gr.Error(f"Failed to delete repository: {e}")
99
+ return repo_id # Keep repo selected on failure
100
 
101
+ # --- File Management Functions ---
102
 
103
+ def show_files_and_load_first(token, repo_id, repo_type):
104
+ """Lists files and pre-loads the first file's content for editing."""
105
  if not repo_id:
106
  gr.Warning("No repository selected.")
107
+ return gr.update(visible=False), gr.update(), gr.update()
108
  try:
109
  api = get_hf_api(token)
110
  repo_files = api.list_repo_files(repo_id=repo_id, repo_type=repo_type)
111
  filtered_files = [f for f in repo_files if not f.startswith('.')]
112
+
113
+ if not filtered_files:
114
+ return (
115
+ gr.update(visible=True),
116
+ gr.update(choices=[], value=None),
117
+ gr.update(value="## This repository is empty or contains only hidden files.", language='markdown')
118
+ )
119
+
120
+ # Load the content of the first file automatically
121
+ first_file_path = filtered_files[0]
122
+ content, language = load_file_content_backend(token, repo_id, repo_type, first_file_path)
123
+
124
  return (
125
+ gr.update(visible=True),
126
+ gr.update(choices=filtered_files, value=first_file_path),
127
+ gr.update(value=content, language=language)
128
  )
129
  except Exception as e:
130
  gr.Error(f"Could not list files: {e}")
131
+ return gr.update(visible=False), gr.update(), gr.update()
132
 
133
+ def load_file_content_backend(token, repo_id, repo_type, filepath):
134
+ """Backend logic to fetch and format file content. Returns content and language."""
135
  if not filepath:
136
+ return "## Select a file to view its content.", 'markdown'
137
  try:
138
  api = get_hf_api(token)
139
  local_path = api.hf_hub_download(repo_id=repo_id, repo_type=repo_type, filename=filepath, token=token)
140
+ with open(local_path, 'r', encoding='utf-8') as f:
141
+ content = f.read()
142
+
143
  language = os.path.splitext(filepath)[1].lstrip('.').lower()
144
+ if language in ['py', 'python']: language = 'python'
145
+ elif language == 'js': language = 'javascript'
146
+ elif language == 'md': language = 'markdown'
147
+ else: language = 'plaintext' # Default
148
+
149
+ return content, language
150
  except Exception as e:
151
+ return f"Error loading file: {e}", 'plaintext'
152
+
153
+ def load_file_content_for_editor(token, repo_id, repo_type, filepath):
154
+ """Gradio wrapper to update the code editor when a new file is selected."""
155
+ content, language = load_file_content_backend(token, repo_id, repo_type, filepath)
156
+ return gr.update(value=content, language=language)
157
+
158
 
159
  def commit_file(token, repo_id, repo_type, filepath, content, commit_message):
160
  if not token: gr.Error("A write-enabled token is required."); return
 
172
 
173
  # --- Download Tab Functions ---
174
 
175
+ def download_repos_as_zip(token, selected_repo_ids, repo_type, progress=gr.Progress()):
176
+ """Downloads selected repos of a given type and zips them up."""
177
+ if not selected_repo_ids:
178
+ gr.Warning("No repositories selected for download.")
179
+ return gr.update(visible=False, value=None)
180
+ if not repo_type:
181
+ gr.Warning("Please list a repository type (Spaces, Models, etc.) before downloading.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
  return gr.update(visible=False, value=None)
183
 
 
184
  download_root_dir = tempfile.mkdtemp()
 
185
  try:
186
+ total_repos = len(selected_repo_ids)
187
  progress(0, desc="Starting download...")
188
 
189
+ for i, repo_id in enumerate(selected_repo_ids):
190
+ progress((i) / total_repos, desc=f"Downloading {repo_id} ({i+1}/{total_repos})")
 
 
 
191
  folder_name = repo_id.replace("/", "__")
192
  target_path = os.path.join(download_root_dir, folder_name)
193
 
194
  try:
 
195
  snapshot_download(
196
+ repo_id=repo_id, repo_type=repo_type, local_dir=target_path,
197
+ token=token, local_dir_use_symlinks=False, resume_download=True,
 
 
 
 
198
  )
199
  except Exception as e:
 
200
  gr.Error(f"Failed to download {repo_id}: {e}")
201
  continue
202
 
203
+ progress(0.95, desc="All items downloaded. Creating ZIP file...")
204
+ zip_base_name = os.path.join(tempfile.gettempdir(), f"hf_{repo_type}s_archive_{uuid.uuid4().hex}")
205
+ zip_path = shutil.make_archive(base_name=zip_base_name, format='zip', root_dir=download_root_dir)
 
 
 
 
 
 
 
 
 
206
 
207
  progress(1, desc="Download ready!")
208
  gr.Info("ZIP file created successfully!")
 
 
209
  return gr.update(value=zip_path, visible=True)
 
210
  finally:
 
211
  shutil.rmtree(download_root_dir, ignore_errors=True)
212
 
213
+
214
  # --- Gradio UI Layout ---
215
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue"), title="Hugging Face Hub Toolkit") as demo:
216
  # State management
217
  hf_token_state = gr.State(None)
218
+ manage_repo_type_state = gr.State(None)
219
+ download_repo_type_state = gr.State(None)
 
220
 
221
  gr.Markdown("# Hugging Face Hub Toolkit")
222
+ gr.Markdown("An intuitive interface to manage and download your Hugging Face repositories.")
223
 
224
  with gr.Sidebar():
225
  hf_token = gr.Textbox(label="Hugging Face API Token", type="password", placeholder="hf_...", scale=3)
 
227
 
228
  with gr.Tabs():
229
  with gr.TabItem("Manage Repositories"):
230
+ with gr.Row():
231
  with gr.Column(scale=1):
232
+ gr.Markdown("### 1. Select Author & Repo Type")
233
  author_input = gr.Textbox(label="Author (Username or Org)", interactive=True)
234
+ with gr.Row():
 
235
  for repo_type, label in [("space", "Spaces"), ("model", "Models"), ("dataset", "Datasets")]:
236
+ btn = gr.Button(f"List {label}")
237
+ btn.click(
238
+ fn=lambda rt: (rt, None, gr.update(visible=False), gr.update(visible=False)),
239
+ inputs=gr.State(repo_type),
240
+ outputs=[manage_repo_type_state, gr.Dropdown(), gr.Column(), gr.Column()] # Reset dropdown and hide panels
241
+ ).then(
242
+ fn=list_repos,
243
+ inputs=[hf_token_state, author_input, gr.State(repo_type)],
244
+ outputs=gr.Dropdown() # This is manage_repo_dropdown
245
+ )
246
+
247
+ gr.Markdown("### 2. Select Repository")
248
+ manage_repo_dropdown = gr.Dropdown(label="Select a Repository", interactive=True)
249
+
250
+ with gr.Column(scale=2):
251
  with gr.Column(visible=False) as action_panel:
252
+ gr.Markdown("### 3. Choose an Action")
253
  with gr.Row():
254
+ manage_files_btn = gr.Button("Manage Files", interactive=False)
255
+ delete_repo_btn = gr.Button("Delete This Repo", variant="stop", interactive=False)
256
 
257
  with gr.Column(visible=False) as editor_panel:
258
+ gr.Markdown("### 4. Edit Files")
259
  file_selector = gr.Dropdown(label="Select File", interactive=True)
260
  code_editor = gr.Code(label="File Content", language="markdown", interactive=True)
261
  commit_message_input = gr.Textbox(label="Commit Message", placeholder="e.g., Update README.md", interactive=True)
262
  commit_btn = gr.Button("Commit Changes", variant="primary", interactive=False)
263
 
264
+ with gr.TabItem("Bulk Download (ZIP)"):
265
+ gr.Markdown("## Bulk Download Repositories as a ZIP Archive")
266
+ gr.Markdown("Select one or more repositories from an author to download them as a single ZIP file.")
267
 
268
  with gr.Row():
269
+ download_author_input = gr.Textbox(label="Author (Username or Org)", interactive=True)
270
+ with gr.Row():
271
+ for repo_type, label in [("space", "Spaces"), ("model", "Models"), ("dataset", "Datasets")]:
272
+ btn = gr.Button(f"List {label}")
273
+ btn.click(
274
+ fn=lambda rt: rt,
275
+ inputs=gr.State(repo_type),
276
+ outputs=download_repo_type_state
277
+ ).then(
278
+ fn=list_repos,
279
+ inputs=[hf_token_state, download_author_input, gr.State(repo_type)],
280
+ outputs=gr.Dropdown() # This is download_repo_dropdown
281
+ )
282
 
283
+ download_repo_dropdown = gr.Dropdown(label="Available Repositories", info="Select the items you want to download.", multiselect=True, interactive=True)
284
+ download_btn = gr.Button("Download Selected as ZIP", variant="primary")
285
  download_output_file = gr.File(label="Your Downloaded ZIP File", visible=False)
 
 
 
 
 
 
 
286
 
287
+ # --- Event Handlers ---
288
+
289
+ # Token Authentication
 
 
 
 
290
  hf_token.change(
291
  fn=handle_token_change, inputs=hf_token,
292
+ outputs=[hf_token_state, manage_files_btn, delete_repo_btn, commit_btn, author_input, download_author_input, whoami_output]
293
  )
294
+
295
+ # --- Manage Tab Handlers ---
296
+ manage_repo_dropdown.select(
297
+ fn=on_manage_repo_select,
298
+ inputs=manage_repo_dropdown,
299
+ outputs=action_panel
 
 
300
  )
301
+
302
  manage_files_btn.click(
303
+ fn=show_files_and_load_first,
304
+ inputs=[hf_token_state, manage_repo_dropdown, manage_repo_type_state],
305
+ outputs=[editor_panel, file_selector, code_editor]
306
  )
307
+
308
  delete_repo_btn.click(
309
+ fn=delete_repo,
310
+ inputs=[hf_token_state, manage_repo_dropdown, manage_repo_type_state],
311
+ outputs=[manage_repo_dropdown],
312
  js="() => confirm('Are you sure you want to permanently delete this repository? This action cannot be undone.')"
313
+ ).then( # After deletion, hide panels
314
+ lambda: (gr.update(visible=False), gr.update(visible=False)),
315
+ outputs=[action_panel, editor_panel]
 
316
  )
317
+
318
  file_selector.change(
319
+ fn=load_file_content_for_editor,
320
+ inputs=[hf_token_state, manage_repo_dropdown, manage_repo_type_state, file_selector],
321
  outputs=code_editor
322
  )
323
+
324
  commit_btn.click(
325
  fn=commit_file,
326
+ inputs=[hf_token_state, manage_repo_dropdown, manage_repo_type_state, file_selector, code_editor, commit_message_input]
327
+ )
328
+
329
+ # --- Download Tab Handlers ---
330
+ download_btn.click(
331
+ fn=download_repos_as_zip,
332
+ inputs=[hf_token_state, download_repo_dropdown, download_repo_type_state],
333
+ outputs=[download_output_file]
334
  )
335
 
336
  if __name__ == "__main__":