mobenta commited on
Commit
584da5f
Β·
verified Β·
1 Parent(s): afedc7f

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. app 22.py +270 -0
  2. requirements 17.txt +3 -0
app 22.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import git
3
+ import shutil
4
+ import zipfile
5
+ from huggingface_hub import HfApi, create_repo
6
+ import gradio as gr
7
+ import requests
8
+
9
+ # Initialize Hugging Face API
10
+ api = HfApi()
11
+
12
+ def clone_repo(repo_url, repo_type=None, auth_token=None):
13
+ try:
14
+ print(f"Cloning repository from URL: {repo_url}")
15
+ repo_name = repo_url.split('/')[-1]
16
+ if os.path.exists(repo_name):
17
+ print(f"Removing existing directory: {repo_name}")
18
+ shutil.rmtree(repo_name)
19
+
20
+ if "huggingface.co" in repo_url:
21
+ repo_id = "/".join(repo_url.split("/")[-2:])
22
+ if repo_type is None:
23
+ repo_type = 'model'
24
+ api.snapshot_download(repo_id=repo_id, repo_type=repo_type, token=auth_token, local_dir=repo_name)
25
+ else:
26
+ if auth_token:
27
+ repo_url = repo_url.replace("https://", f"https://{auth_token}@")
28
+ git.Repo.clone_from(repo_url, repo_name)
29
+
30
+ print(f"Repository cloned successfully: {repo_name}")
31
+ zip_file = f"{repo_name}.zip"
32
+ shutil.make_archive(repo_name, 'zip', repo_name)
33
+ print(f"Repository zipped successfully: {zip_file}")
34
+ return zip_file
35
+ except git.exc.GitCommandError as e:
36
+ if "could not read Username" in str(e):
37
+ return "Authentication error: Please provide a valid token for private repositories."
38
+ return f"Git error: {str(e)}"
39
+ except requests.exceptions.RequestException as e:
40
+ return "Network error: Unable to connect to the repository."
41
+ except Exception as e:
42
+ return f"An error occurred: {str(e)}"
43
+
44
+ def zip_download_link(repo_type, repo_url, auth_token):
45
+ result = clone_repo(repo_url, repo_type, auth_token)
46
+ if isinstance(result, str) and result.endswith(".zip"):
47
+ return gr.update(value=result), ""
48
+ else:
49
+ return gr.update(value=None), result
50
+
51
+ def push_to_huggingface(repo_type, repo_name, files_or_zip, hf_token):
52
+ try:
53
+ repo_name = repo_name.lstrip("/")
54
+ if not "/" in repo_name:
55
+ repo_name = f"{hf_token.split(':')[0]}/{repo_name}"
56
+ target_dir = f"./{repo_name}"
57
+ if os.path.exists(target_dir):
58
+ shutil.rmtree(target_dir)
59
+ os.makedirs(target_dir, exist_ok=True)
60
+
61
+ if isinstance(files_or_zip, list):
62
+ for file_obj in files_or_zip:
63
+ if file_obj.endswith(".zip"):
64
+ with zipfile.ZipFile(file_obj, 'r') as zip_ref:
65
+ zip_ref.extractall(target_dir)
66
+ else:
67
+ shutil.copy(file_obj, os.path.join(target_dir, os.path.basename(file_obj)))
68
+ else:
69
+ if files_or_zip.endswith(".zip"):
70
+ with zipfile.ZipFile(files_or_zip, 'r') as zip_ref:
71
+ zip_ref.extractall(target_dir)
72
+ else:
73
+ shutil.copy(files_or_zip, os.path.join(target_dir, os.path.basename(files_or_zip)))
74
+
75
+ if repo_type == "Space":
76
+ api.upload_folder(folder_path=target_dir, path_in_repo="", repo_id=repo_name, repo_type="space", token=hf_token)
77
+ return f"Files pushed to Hugging Face Space: {repo_name}"
78
+ else:
79
+ api.upload_folder(folder_path=target_dir, path_in_repo="", repo_id=repo_name, token=hf_token)
80
+ return f"Files pushed to Hugging Face repository: {repo_name}"
81
+ except Exception as e:
82
+ return f"An error occurred: {str(e)}"
83
+
84
+ def create_huggingface_space(space_name, space_type, hardware, visibility, hf_token):
85
+ try:
86
+ if "/" not in space_name:
87
+ space_name = f"{hf_token.split(':')[0]}/{space_name}"
88
+
89
+ create_repo(repo_id=space_name, repo_type="space", space_sdk=space_type, token=hf_token, private=(visibility == "private"))
90
+ return f"Successfully created Hugging Face Space: {space_name}"
91
+ except Exception as e:
92
+ return f"An error occurred while creating the Space: {str(e)}"
93
+
94
+ def remove_files_from_huggingface(repo_type, repo_name, file_paths, remove_all, hf_token):
95
+ try:
96
+ print(f"Removing files from {repo_type}: {repo_name}")
97
+ repo_name = repo_name.lstrip("/")
98
+ if not "/" in repo_name:
99
+ repo_name = f"{hf_token.split(':')[0]}/{repo_name}"
100
+
101
+ if remove_all:
102
+ try:
103
+ files = api.list_repo_files(repo_id=repo_name, repo_type=repo_type.lower(), token=hf_token)
104
+ if not files:
105
+ return "No files found to remove."
106
+
107
+ successful_removals = []
108
+ failed_removals = []
109
+ for file_path in files:
110
+ try:
111
+ api.delete_file(path_in_repo=file_path, repo_id=repo_name, repo_type=repo_type.lower(), token=hf_token)
112
+ successful_removals.append(file_path)
113
+ except Exception as e:
114
+ failed_removals.append((file_path, str(e)))
115
+
116
+ result = []
117
+ if successful_removals:
118
+ result.append(f"Successfully removed files: {', '.join(successful_removals)}")
119
+ if failed_removals:
120
+ result.append("Failed to remove the following files:")
121
+ for path, error in failed_removals:
122
+ result.append(f"- {path}: {error}")
123
+
124
+ return "\n".join(result)
125
+ except Exception as e:
126
+ return f"Error removing all files: {str(e)}"
127
+ else:
128
+ if isinstance(file_paths, str):
129
+ file_paths = [path.strip() for path in file_paths.split(',') if path.strip()]
130
+
131
+ if not file_paths:
132
+ return "Error: No valid file paths provided."
133
+
134
+ successful_removals = []
135
+ failed_removals = []
136
+ for file_path in file_paths:
137
+ try:
138
+ api.delete_file(path_in_repo=file_path, repo_id=repo_name, repo_type=repo_type.lower(), token=hf_token)
139
+ successful_removals.append(file_path)
140
+ except Exception as e:
141
+ failed_removals.append((file_path, str(e)))
142
+
143
+ result = []
144
+ if successful_removals:
145
+ result.append(f"Successfully removed files: {', '.join(successful_removals)}")
146
+ if failed_removals:
147
+ result.append("Failed to remove the following files:")
148
+ for path, error in failed_removals:
149
+ result.append(f"- {path}: {error}")
150
+
151
+ return "\n".join(result)
152
+ except Exception as e:
153
+ return f"An error occurred during file removal: {str(e)}"
154
+
155
+ # Define the Gradio interface using Blocks API
156
+ with gr.Blocks(css="footer {display:none;}.title {color: blue; font-size: 36px;}") as app:
157
+ gr.Markdown("""
158
+ # πŸš€ Hugging Face Repo & Space Manager
159
+
160
+ Welcome to the next-gen tool for effortlessly managing your Hugging Face ecosystem! Whether you're a seasoned ML engineer or just getting started with AI, this all-in-one interface streamlines your workflow and boosts productivity.
161
+
162
+ ## 🌟 Key Features & Why Use This Tool?
163
+
164
+ - **Seamless File Management**: Push, pull, and organize your files across Spaces and Repos with drag-and-drop simplicity.
165
+ - **Git Integration**: Clone repositories from GitHub or Hugging Face with a single click, and download them as ready-to-use ZIP files.
166
+ - **Smart File Removal**: Selectively clean up your Spaces and Repos, or perform a total reset with our bulk file removal option.
167
+ - **Time-Saver**: Automate repetitive tasks and focus on what matters - your AI projects.
168
+ - **User-Friendly**: No more command-line headaches. Our GUI makes complex operations a breeze.
169
+ - **Versatile**: From creating Spaces to managing large datasets, handle it all in one place.
170
+ - **Secure**: Built-in token management ensures your credentials stay safe while you work.
171
+
172
+ ## πŸ”§ How to Use This Tool
173
+
174
+ 1. **Create a New Space**: Start by creating a fresh Hugging Face Space for your project.
175
+ 2. **Manage Existing Spaces**: Remove Files" tab to clean up your Space or Repository.
176
+ 3. **Push Your Content**: Upload your files or a ZIP archive to your Space or Repository.
177
+ 4. **Clone and Modify**: Modify the files locally, then push them back using the "Push to Hugging Face" feature.
178
+
179
+ Embrace the future of AI project management. Let's innovate together! πŸ€—βœ¨
180
+ ---
181
+ Created with ❀️ by MoBenTa | Empowering AI enthusiasts worldwide
182
+ """)
183
+
184
+ with gr.Tabs():
185
+ with gr.Tab("🌟 Manage Hugging Face Space/Repo"):
186
+ with gr.Tabs():
187
+ with gr.TabItem("Create Space"):
188
+ space_name = gr.Textbox(label="Space Name (format: username/space-name)")
189
+ space_type = gr.Dropdown(["streamlit", "gradio", "static", "docker"], label="Space Type")
190
+ hardware = gr.Textbox(label="Hardware (optional)")
191
+ visibility = gr.Radio(choices=["public", "private"], label="Visibility")
192
+ create_hf_token = gr.Textbox(label="Hugging Face Token", type="password")
193
+ create_space_button = gr.Button("Create Space", variant="primary")
194
+ create_space_output = gr.Textbox(label="Creation Result")
195
+
196
+ create_space_button.click(
197
+ fn=create_huggingface_space,
198
+ inputs=[space_name, space_type, hardware, visibility, create_hf_token],
199
+ outputs=create_space_output
200
+ )
201
+
202
+ with gr.TabItem("Remove Files"):
203
+ remove_type = gr.Dropdown(["Space", "Repository"], label="Remove from")
204
+ remove_repo_name = gr.Textbox(label="Repository/Space Name")
205
+ remove_all_checkbox = gr.Checkbox(label="Remove All Files", info="Warning: This will remove all files from the repository!")
206
+ remove_file_paths = gr.Textbox(label="File Paths to Remove (comma-separated)", interactive=True)
207
+ remove_hf_token = gr.Textbox(label="Hugging Face Token", type="password")
208
+ remove_button = gr.Button("Remove Files", variant="primary")
209
+ remove_output = gr.Textbox(label="Removal Result")
210
+
211
+ def update_file_paths_interactivity(remove_all):
212
+ return gr.update(interactive=not remove_all)
213
+
214
+ remove_all_checkbox.change(
215
+ fn=update_file_paths_interactivity,
216
+ inputs=remove_all_checkbox,
217
+ outputs=remove_file_paths
218
+ )
219
+
220
+ remove_button.click(
221
+ fn=remove_files_from_huggingface,
222
+ inputs=[remove_type, remove_repo_name, remove_file_paths, remove_all_checkbox, remove_hf_token],
223
+ outputs=remove_output
224
+ )
225
+
226
+ with gr.Tab("☁️ Push to Hugging Face"):
227
+ push_type = gr.Dropdown(["Space", "Repository"], label="Push to")
228
+ repo_name = gr.Textbox(label="Repository/Space Name")
229
+ files_upload = gr.File(label="Upload File(s) or Zip", file_count="multiple", type="filepath")
230
+ hf_token = gr.Textbox(label="Hugging Face Token", type="password")
231
+ push_button = gr.Button("Push to Hugging Face", variant="primary")
232
+ push_output = gr.Textbox(label="Push Result")
233
+
234
+ push_button.click(
235
+ fn=push_to_huggingface,
236
+ inputs=[push_type, repo_name, files_upload, hf_token],
237
+ outputs=push_output
238
+ )
239
+
240
+ with gr.Tab("πŸ” Clone Repository"):
241
+ repo_type_input = gr.Radio(choices=["GitHub", "Hugging Face Model", "Hugging Face Dataset", "Hugging Face Space"], label="Repository Type")
242
+ repo_url_input = gr.Textbox(label="Repository URL")
243
+ auth_token_input = gr.Textbox(label="Authentication Token (optional)", type="password")
244
+ clone_button = gr.Button("Clone and Download", variant="primary")
245
+ output_zip = gr.File(label="Downloaded Repository")
246
+ clone_error_output = gr.Textbox(label="Cloning Result", visible=False)
247
+
248
+ def handle_clone_result(repo_type_input, repo_url, auth_token):
249
+ if repo_type_input == "GitHub":
250
+ repo_type = None
251
+ elif repo_type_input == "Hugging Face Model":
252
+ repo_type = "model"
253
+ elif repo_type_input == "Hugging Face Dataset":
254
+ repo_type = "dataset"
255
+ elif repo_type_input == "Hugging Face Space":
256
+ repo_type = "space"
257
+ else:
258
+ repo_type = "model"
259
+
260
+ file_output, error_message = zip_download_link(repo_type, repo_url, auth_token)
261
+ return file_output, error_message, gr.update(visible=bool(error_message))
262
+
263
+ clone_button.click(
264
+ fn=handle_clone_result,
265
+ inputs=[repo_type_input, repo_url_input, auth_token_input],
266
+ outputs=[output_zip, clone_error_output, clone_error_output]
267
+ )
268
+
269
+ if __name__ == "__main__":
270
+ app.launch()
requirements 17.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio
2
+ huggingface_hub
3
+ gitpython