broadfield-dev commited on
Commit
2414030
·
verified ·
1 Parent(s): 2d0a69d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -29
app.py CHANGED
@@ -44,7 +44,7 @@ def handle_token_change(token):
44
  }
45
  return (token, *updates.values())
46
 
47
- def list_repos(token, author, repo_type):
48
  """Backend function to fetch repository IDs."""
49
  if not author:
50
  gr.Info("Please enter an author (username or organization).")
@@ -62,20 +62,19 @@ def list_repos(token, author, repo_type):
62
 
63
  def list_repos_for_management(token, author, repo_type):
64
  """Gradio wrapper to update the management dropdown and reset the UI."""
65
- repo_ids = list_repos(token, author, repo_type)
66
  return (
67
  repo_type,
68
- gr.update(choices=repo_ids, value=None), # Update dropdown choices
69
- gr.update(visible=False), # Hide action panel
70
- gr.update(visible=False) # Hide editor panel
71
  )
72
 
73
  def list_repos_for_download(token, author, repo_type):
74
  """Gradio wrapper to update the download dropdown."""
75
- repo_ids = list_repos(token, author, repo_type)
76
  return repo_type, gr.update(choices=repo_ids, value=None)
77
 
78
-
79
  def on_manage_repo_select(repo_id):
80
  """Shows action buttons when a repo is selected in the Manage tab."""
81
  return gr.update(visible=bool(repo_id))
@@ -100,7 +99,7 @@ def show_files_and_load_first(token, repo_id, repo_type):
100
  """Lists files in a dropdown and pre-loads the first file's content."""
101
  if not repo_id:
102
  gr.Warning("No repository selected.")
103
- return gr.update(visible=False), gr.update(), gr.update()
104
  try:
105
  api = get_hf_api(token)
106
  repo_files = api.list_repo_files(repo_id=repo_id, repo_type=repo_type)
@@ -117,7 +116,7 @@ def show_files_and_load_first(token, repo_id, repo_type):
117
  gr.update(value=content, language=language))
118
  except Exception as e:
119
  gr.Error(f"Could not manage files: {e}")
120
- return gr.update(visible=False), gr.update(), gr.update()
121
 
122
  def load_file_content_backend(token, repo_id, repo_type, filepath):
123
  """Backend logic to fetch and format file content."""
@@ -156,23 +155,26 @@ def commit_file(token, repo_id, repo_type, filepath, content, commit_message):
156
  def download_repos_as_zip(token, selected_repo_ids, repo_type, progress=gr.Progress()):
157
  """Downloads selected repos and zips them."""
158
  if not selected_repo_ids:
159
- gr.Warning("No repositories selected for download."); return
160
  if not repo_type:
161
- gr.Warning("Please list a repository type (Spaces, etc.) before downloading."); return
162
 
163
  download_root_dir = tempfile.mkdtemp()
164
  try:
 
165
  for i, repo_id in enumerate(selected_repo_ids):
166
- progress((i) / len(selected_repo_ids), desc=f"Downloading {repo_id}")
167
  try:
168
- snapshot_download(repo_id=repo_id, repo_type=repo_type, local_dir=os.path.join(download_root_dir, repo_id.replace("/", "__")),
 
169
  token=token, local_dir_use_symlinks=False, resume_download=True)
170
  except Exception as e: gr.Error(f"Failed to download {repo_id}: {e}")
171
 
172
- progress(0.95, desc="Creating ZIP file...")
173
- zip_base_name = os.path.join(tempfile.gettempdir(), f"hf_{repo_type}s_{uuid.uuid4().hex}")
174
  zip_path = shutil.make_archive(zip_base_name, 'zip', download_root_dir)
175
  progress(1, desc="Download ready!")
 
176
  return gr.update(value=zip_path, visible=True)
177
  finally:
178
  shutil.rmtree(download_root_dir, ignore_errors=True)
@@ -191,18 +193,14 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue"), title="Hugging Face Hub
191
 
192
  with gr.Tabs():
193
  with gr.TabItem("Manage Repositories"):
 
194
  with gr.Row():
195
  with gr.Column(scale=1):
196
  gr.Markdown("### 1. Select a Repository")
197
  author_input = gr.Textbox(label="Author (Username or Org)")
198
  with gr.Row():
199
- for repo_type, label in [("space", "Spaces"), ("model", "Models"), ("dataset", "Datasets")]:
200
- btn = gr.Button(f"List {label}")
201
- btn.click(fn=list_repos_for_management,
202
- inputs=[hf_token_state, author_input, gr.State(repo_type)],
203
- outputs=[manage_repo_type_state, gr.Dropdown(), action_panel, editor_panel])
204
  manage_repo_dropdown = gr.Dropdown(label="Select a Repository", interactive=True)
205
-
206
  with gr.Column(scale=2):
207
  with gr.Column(visible=False) as action_panel:
208
  gr.Markdown("### 2. Choose an Action")
@@ -214,22 +212,29 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue"), title="Hugging Face Hub
214
  code_editor = gr.Code(label="File Content", interactive=True)
215
  commit_message_input = gr.Textbox(label="Commit Message", placeholder="e.g., Update README.md")
216
  commit_btn = gr.Button("Commit Changes", variant="primary", interactive=False)
 
 
 
 
 
 
217
 
218
  with gr.TabItem("Bulk Download (ZIP)"):
 
219
  gr.Markdown("## Download Multiple Repositories as a ZIP")
 
220
  with gr.Row():
221
- download_author_input = gr.Textbox(label="Author (Username or Org)")
222
- with gr.Row():
223
- for repo_type, label in [("space", "Spaces"), ("model", "Models"), ("dataset", "Datasets")]:
224
- btn = gr.Button(f"List {label}")
225
- btn.click(fn=list_repos_for_download,
226
- inputs=[hf_token_state, download_author_input, gr.State(repo_type)],
227
- outputs=[download_repo_type_state, gr.Dropdown()])
228
  download_repo_dropdown = gr.Dropdown(label="Select Repositories", multiselect=True, interactive=True)
229
  download_btn = gr.Button("Download Selected as ZIP", variant="primary")
230
  download_output_file = gr.File(label="Your Downloaded ZIP File", visible=False)
 
 
 
 
 
231
 
232
- # --- Event Handlers ---
233
  hf_token.change(fn=handle_token_change, inputs=hf_token,
234
  outputs=[hf_token_state, manage_files_btn, delete_repo_btn, commit_btn, author_input, download_author_input, whoami_output])
235
 
 
44
  }
45
  return (token, *updates.values())
46
 
47
+ def list_repos_backend(token, author, repo_type):
48
  """Backend function to fetch repository IDs."""
49
  if not author:
50
  gr.Info("Please enter an author (username or organization).")
 
62
 
63
  def list_repos_for_management(token, author, repo_type):
64
  """Gradio wrapper to update the management dropdown and reset the UI."""
65
+ repo_ids = list_repos_backend(token, author, repo_type)
66
  return (
67
  repo_type,
68
+ gr.update(choices=repo_ids, value=None),
69
+ gr.update(visible=False),
70
+ gr.update(visible=False)
71
  )
72
 
73
  def list_repos_for_download(token, author, repo_type):
74
  """Gradio wrapper to update the download dropdown."""
75
+ repo_ids = list_repos_backend(token, author, repo_type)
76
  return repo_type, gr.update(choices=repo_ids, value=None)
77
 
 
78
  def on_manage_repo_select(repo_id):
79
  """Shows action buttons when a repo is selected in the Manage tab."""
80
  return gr.update(visible=bool(repo_id))
 
99
  """Lists files in a dropdown and pre-loads the first file's content."""
100
  if not repo_id:
101
  gr.Warning("No repository selected.")
102
+ return gr.update(visible=False), gr.update(choices=[], value=None), gr.update(value="")
103
  try:
104
  api = get_hf_api(token)
105
  repo_files = api.list_repo_files(repo_id=repo_id, repo_type=repo_type)
 
116
  gr.update(value=content, language=language))
117
  except Exception as e:
118
  gr.Error(f"Could not manage files: {e}")
119
+ return gr.update(visible=False), gr.update(choices=[], value=None), gr.update(value="")
120
 
121
  def load_file_content_backend(token, repo_id, repo_type, filepath):
122
  """Backend logic to fetch and format file content."""
 
155
  def download_repos_as_zip(token, selected_repo_ids, repo_type, progress=gr.Progress()):
156
  """Downloads selected repos and zips them."""
157
  if not selected_repo_ids:
158
+ gr.Warning("No repositories selected for download."); return gr.update(value=None, visible=False)
159
  if not repo_type:
160
+ gr.Warning("Please list a repository type (Spaces, etc.) before downloading."); return gr.update(value=None, visible=False)
161
 
162
  download_root_dir = tempfile.mkdtemp()
163
  try:
164
+ total_repos = len(selected_repo_ids)
165
  for i, repo_id in enumerate(selected_repo_ids):
166
+ progress((i) / total_repos, desc=f"Downloading {repo_id} ({i+1}/{total_repos})")
167
  try:
168
+ folder_name = repo_id.replace("/", "__")
169
+ snapshot_download(repo_id=repo_id, repo_type=repo_type, local_dir=os.path.join(download_root_dir, folder_name),
170
  token=token, local_dir_use_symlinks=False, resume_download=True)
171
  except Exception as e: gr.Error(f"Failed to download {repo_id}: {e}")
172
 
173
+ progress(0.95, desc="All items downloaded. Creating ZIP file...")
174
+ zip_base_name = os.path.join(tempfile.gettempdir(), f"hf_{repo_type}s_archive_{uuid.uuid4().hex}")
175
  zip_path = shutil.make_archive(zip_base_name, 'zip', download_root_dir)
176
  progress(1, desc="Download ready!")
177
+ gr.Info("ZIP file created successfully!")
178
  return gr.update(value=zip_path, visible=True)
179
  finally:
180
  shutil.rmtree(download_root_dir, ignore_errors=True)
 
193
 
194
  with gr.Tabs():
195
  with gr.TabItem("Manage Repositories"):
196
+ # Define all components first
197
  with gr.Row():
198
  with gr.Column(scale=1):
199
  gr.Markdown("### 1. Select a Repository")
200
  author_input = gr.Textbox(label="Author (Username or Org)")
201
  with gr.Row():
202
+ manage_buttons = [gr.Button(f"List {label}") for label in ["Spaces", "Models", "Datasets"]]
 
 
 
 
203
  manage_repo_dropdown = gr.Dropdown(label="Select a Repository", interactive=True)
 
204
  with gr.Column(scale=2):
205
  with gr.Column(visible=False) as action_panel:
206
  gr.Markdown("### 2. Choose an Action")
 
212
  code_editor = gr.Code(label="File Content", interactive=True)
213
  commit_message_input = gr.Textbox(label="Commit Message", placeholder="e.g., Update README.md")
214
  commit_btn = gr.Button("Commit Changes", variant="primary", interactive=False)
215
+ # Now, attach event handlers
216
+ repo_types = ["space", "model", "dataset"]
217
+ for i, btn in enumerate(manage_buttons):
218
+ btn.click(fn=list_repos_for_management,
219
+ inputs=[hf_token_state, author_input, gr.State(repo_types[i])],
220
+ outputs=[manage_repo_type_state, manage_repo_dropdown, action_panel, editor_panel])
221
 
222
  with gr.TabItem("Bulk Download (ZIP)"):
223
+ # Define all components first
224
  gr.Markdown("## Download Multiple Repositories as a ZIP")
225
+ download_author_input = gr.Textbox(label="Author (Username or Org)")
226
  with gr.Row():
227
+ download_buttons = [gr.Button(f"List {label}") for label in ["Spaces", "Models", "Datasets"]]
 
 
 
 
 
 
228
  download_repo_dropdown = gr.Dropdown(label="Select Repositories", multiselect=True, interactive=True)
229
  download_btn = gr.Button("Download Selected as ZIP", variant="primary")
230
  download_output_file = gr.File(label="Your Downloaded ZIP File", visible=False)
231
+ # Now, attach event handlers
232
+ for i, btn in enumerate(download_buttons):
233
+ btn.click(fn=list_repos_for_download,
234
+ inputs=[hf_token_state, download_author_input, gr.State(repo_types[i])],
235
+ outputs=[download_repo_type_state, download_repo_dropdown])
236
 
237
+ # --- Global and Cross-Tab Event Handlers ---
238
  hf_token.change(fn=handle_token_change, inputs=hf_token,
239
  outputs=[hf_token_state, manage_files_btn, delete_repo_btn, commit_btn, author_input, download_author_input, whoami_output])
240