Duskfallcrew commited on
Commit
3d65c27
·
verified ·
1 Parent(s): 498d674

Upload 7 files

Browse files
2025_Notebooks-HF.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:31fb237efb29858be8adc22932b1d77fe1b8ae0d6da0b5b0b20fe92dcdeb94ff
3
+ size 21216
Hf-Backup_NoColab.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import glob
3
+ import time
4
+ from pathlib import Path
5
+ from huggingface_hub import HfApi
6
+ from tqdm import tqdm
7
+
8
+ def format_size(size):
9
+ """Formats a file size into a human-readable string."""
10
+ for unit in ['B', 'KB', 'MB', 'GB']:
11
+ if size < 1024:
12
+ return f"{size:.2f} {unit}"
13
+ size /= 1024
14
+ return f"{size:.2f} TB"
15
+
16
+ def find_files(file_location, file_type):
17
+ """Finds files matching the selected file type in the given directory."""
18
+ try:
19
+ files = sorted(
20
+ glob.glob(os.path.join(file_location, f"*.{file_type}")),
21
+ key=os.path.getmtime
22
+ )
23
+ return files
24
+ except Exception as e:
25
+ print(f"❌ Error finding files: {e}")
26
+ return []
27
+
28
+ def upload_files(hfuser, hfrepo, file_location, file_type, commit_message, create_pr):
29
+ """Uploads selected files to the Hugging Face repository."""
30
+ if not hfuser or not hfrepo:
31
+ print("❗ Please enter both your Organization/Username and Repository name.")
32
+ return
33
+ if not file_location:
34
+ print("No directory was selected!")
35
+ return
36
+ files = find_files(file_location, file_type)
37
+ if not files:
38
+ print("📝 No files found matching your criteria. Check your file type and ensure files are in the location specified above.")
39
+ return
40
+
41
+ api = HfApi()
42
+ repo_id = f"{hfuser}/{hfrepo}"
43
+ print(f"🎯 Preparing to upload to: huggingface.co/{repo_id}")
44
+
45
+ total_files = len(files)
46
+ print(f"\n🚀 Starting upload of {total_files} file(s)...")
47
+ # Create a progress bar for the overall upload
48
+ with tqdm(total=total_files, desc="Total Progress", unit="file") as pbar:
49
+ for idx, file in enumerate(files, 1):
50
+ size = os.path.getsize(file)
51
+ print(f"\n📦 Uploading file {idx}/{total_files}: {file} ({format_size(size)})")
52
+ try:
53
+ start_time = time.time()
54
+ response = api.upload_file(
55
+ path_or_fileobj=file,
56
+ path_in_repo=os.path.basename(file),
57
+ repo_id=repo_id,
58
+ repo_type=None,
59
+ create_pr=create_pr,
60
+ commit_message=commit_message
61
+ )
62
+ duration = time.time() - start_time
63
+ print(f"✅ Upload completed in {duration:.1f} seconds")
64
+ except Exception as e:
65
+ print(f"❌ Error uploading {file}: {e}")
66
+
67
+ pbar.update(1)
68
+
69
+ print("\n✨ All uploads complete!")
70
+ if create_pr:
71
+ print("🎉 Check your repository for the new Pull Request!")
72
+ else:
73
+ print("🎉 Files uploaded directly to your repository!")
74
+
75
+ if __name__ == "__main__":
76
+ print("🌟 Hugging Face File Uploader - Standalone 🌟")
77
+
78
+ hfuser = input("Enter your Hugging Face Username/Organization: ")
79
+ hfrepo = input("Enter your Hugging Face Repository Name: ")
80
+ file_type = input("Enter the file type to upload (e.g., safetensors, mp3, png): ")
81
+ file_location = input("Enter the directory to search for files (e.g., /content/drive/MyDrive/MyModels, or /content/my_models): ")
82
+ commit_message = input("Enter your commit message: ")
83
+ create_pr_input = input("Create a Pull Request? (yes/no): ").lower()
84
+ create_pr = create_pr_input == "yes"
85
+
86
+ upload_files(hfuser, hfrepo, file_location, file_type, commit_message, create_pr)
HuggingFace_Backup_2024_Colab.ipynb ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "private_outputs": true,
7
+ "provenance": [],
8
+ "collapsed_sections": [
9
+ "IZ_JYwvBLrg-",
10
+ "PNF2kdyeO3Dn"
11
+ ]
12
+ },
13
+ "kernelspec": {
14
+ "name": "python3",
15
+ "display_name": "Python 3"
16
+ },
17
+ "language_info": {
18
+ "name": "python"
19
+ }
20
+ },
21
+ "cells": [
22
+ {
23
+ "cell_type": "markdown",
24
+ "source": [
25
+ "# 🌈 HuggingFace Backup - Colab Edition\n",
26
+ "\n",
27
+ "Hey there, fellow adventurers in AI! Welcome to our delightfully unique corner of the universe! ✨\n",
28
+ "\n",
29
+ "## 💫 What's This All About?\n",
30
+ "This is our cozy mashup of Nocrypt's notebook and everyday AI tools, but with our own special twist! Think of it as the Colab-flavored version of our Jupyter notebook - because sometimes you need your AI magic on the go!\n",
31
+ "\n",
32
+ "### 🎯 Quick Features:\n",
33
+ "- Fast uploads to HuggingFace (because waiting is overrated!)\n",
34
+ "- Focus on checkpoints (keeping it simple and sweet)\n",
35
+ "- Built for Google Colab (our cloud-powered playground)\n",
36
+ "- All the same magic as our Jupyter version, just with cloud sprinkles! ✨\n",
37
+ "\n",
38
+ "## 🔍 Lost & Found\n",
39
+ "- Repo doing a disappearing act? [Find us on GitHub!](https://github.com/duskfallcrew/HuggingFace_Backup)\n",
40
+ "- CivitAI friends: Updates drop faster than a cat chasing a laser!\n",
41
+ "\n",
42
+ "## ☕ Support the Magic\n",
43
+ "[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/Z8Z8L4EO)\n",
44
+ "\n",
45
+ "## 🎮 Join Our Adventure!\n",
46
+ "We're a system of 300+ alters, rocking life with DID, ADHD, Autism, and CPTSD. We believe AI can be a game-changer for mental health and creativity. Come explore with us!\n",
47
+ "\n",
48
+ "### 🌟 Find Us Here:\n",
49
+ "- 🏠 [End Media](https://www.end-media.org/)\n",
50
+ "- 🎮 [Discord](https://discord.gg/5t2kYxt7An)\n",
51
+ "- 🤗 [HuggingFace](https://huggingface.co/EarthnDusk)\n",
52
+ "- 🎵 [YouTube](https://www.youtube.com/channel/UCk7MGP7nrJz5awBSP75xmVw)\n",
53
+ "- 🎪 [Reddit](https://www.reddit.com/r/earthndusk/)\n",
54
+ "- 🎨 [DeviantArt](https://www.deviantart.com/diffusionai)\n",
55
+ "\n",
56
+ "### 🏴‍☠️ Special Thanks To:\n",
57
+ "- [Pirate Diffusion](https://www.piratediffusion.com/)\n",
58
+ "- [Yodayo](https://yodayo.com/)\n",
59
+ "\n",
60
+ "## 💝 Credits & Cool People\n",
61
+ "Huge thanks to our code ancestors:\n",
62
+ "- EVERYDREAM2 TRAINER\n",
63
+ "- LINAQRUF\n",
64
+ "- NOCRYPT [![](https://dcbadge.vercel.app/api/shield/442099748669751297?style=flat)](https://lookup.guru/442099748669751297)\n",
65
+ "\n",
66
+ "Want more AI adventures? Check out the original SD Colab:\n",
67
+ "<a target=\"_blank\" href=\"https://colab.research.google.com/drive/1wEa-tS10h4LlDykd87TF5zzpXIIQoCmq\">\n",
68
+ " <img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/>\n",
69
+ "</a>\n",
70
+ "\n",
71
+ "## 🛠️ Need Help?\n",
72
+ "- Found a bug? Don't panic! Drop by our GitHub or Discord\n",
73
+ "- Questions? We're here for you!\n",
74
+ "- Want to help? Pull requests are like hugs - always welcome!\n",
75
+ "\n",
76
+ "## 🎯 Recent Updates:\n",
77
+ "1. 🌟 Enhanced Colab compatibility\n",
78
+ "2. 🔧 Streamlined file handling\n",
79
+ "3. 🎨 Made everything prettier (because we can!)\n",
80
+ "4. 📝 Clearer instructions (no more confusion!)\n",
81
+ "5. ✨ Added extra sprinkles of magic\n",
82
+ "\n",
83
+ "Remember: We're not pro coders, we're creative problem solvers! Sometimes the best solutions come with a side of chaos and a sprinkle of adventure! 🌈✨\n",
84
+ "\n",
85
+ "Let's make some AI magic happen! Ready to dive in? 🚀"
86
+ ],
87
+ "metadata": {
88
+ "id": "CxgFI41UGzRu"
89
+ }
90
+ },
91
+ {
92
+ "cell_type": "markdown",
93
+ "source": [
94
+ "# Google Drive Mount\n",
95
+ "\n"
96
+ ],
97
+ "metadata": {
98
+ "id": "IZ_JYwvBLrg-"
99
+ }
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "source": [
104
+ "# @title 🚀 Connect Your Google Drive\n",
105
+ "# @markdown ## Let's Get Your Storage Powers Activated! ✨\n",
106
+ "\n",
107
+ "# @markdown ### What's This All About?\n",
108
+ "# @markdown Hey there, fellow creator! Before we dive into the fun stuff, let's talk storage!\n",
109
+ "\n",
110
+ "# @markdown #### 🎯 Your Options:\n",
111
+ "# @markdown 1. **Google Drive** (Recommended!)\n",
112
+ "# @markdown - Perfect for keeping your models safe\n",
113
+ "# @markdown - Easy access to all your files\n",
114
+ "# @markdown - Everything stays organized\n",
115
+ "# @markdown\n",
116
+ "# @markdown 2. **Alternative Routes** (For the adventurous!)\n",
117
+ "# @markdown - Terminal wizardry (if you're comfortable with commands)\n",
118
+ "# @markdown - Direct uploads to Colab\n",
119
+ "# @markdown - Other cloud storage solutions\n",
120
+ "# @markdown\n",
121
+ "# @markdown #### 🌟 Pro Tips:\n",
122
+ "# @markdown - Watch for the popup after clicking \"Connect\"\n",
123
+ "# @markdown - You'll need to authorize access (don't worry, it's safe!)\n",
124
+ "# @markdown - Your drive will appear as `/content/drive`\n",
125
+ "\n",
126
+ "from google.colab import drive\n",
127
+ "from google.colab import output\n",
128
+ "import os\n",
129
+ "\n",
130
+ "def mount_drive():\n",
131
+ " if not os.path.exists('/content/drive'):\n",
132
+ " print(\"🔮 Summoning your Google Drive...\")\n",
133
+ " drive.mount('/content/drive')\n",
134
+ " print(\"\\n✨ Drive mounted successfully! You're ready to rock!\")\n",
135
+ " else:\n",
136
+ " print(\"🎉 Your Drive is already connected and ready to go!\")\n",
137
+ "\n",
138
+ "# Enable our magical widgets\n",
139
+ "output.enable_custom_widget_manager()\n",
140
+ "\n",
141
+ "# Let's get that drive connected!\n",
142
+ "mount_drive()\n",
143
+ "\n",
144
+ "print(\"\"\"\n",
145
+ "📚 Quick Navigation Guide:\n",
146
+ "- Your Drive lives at: /content/drive\n",
147
+ "- Main workspace: /content/drive/MyDrive\n",
148
+ "- Look for the folder icon in the left sidebar\n",
149
+ "\n",
150
+ "Need to upload files?\n",
151
+ "1. Find the folder icon on the left\n",
152
+ "2. Navigate to your drive\n",
153
+ "3. Drag and drop your files\n",
154
+ "4. Magic happens! ✨\n",
155
+ "\n",
156
+ "Having troubles? No worries! You can:\n",
157
+ "1. Try reconnecting (run this cell again)\n",
158
+ "2. Use terminal commands if you're feeling brave\n",
159
+ "3. Direct upload to Colab (look for the folder icon!)\n",
160
+ "\n",
161
+ "Remember: Your creative journey is valid, no matter which path you choose! 🌈\n",
162
+ "\"\"\")\n"
163
+ ],
164
+ "metadata": {
165
+ "id": "cGrPfIjkH-rQ",
166
+ "cellView": "form"
167
+ },
168
+ "execution_count": null,
169
+ "outputs": []
170
+ },
171
+ {
172
+ "cell_type": "markdown",
173
+ "source": [
174
+ "# Installation & Requirements\n",
175
+ "-----------------\n",
176
+ "\n"
177
+ ],
178
+ "metadata": {
179
+ "id": "J_I_G6_i0rIM"
180
+ }
181
+ },
182
+ {
183
+ "cell_type": "code",
184
+ "source": [
185
+ "# @title 🛠️ Installation Wizard\n",
186
+ "# @markdown ## Let's get your workspace ready for some AI magic! ✨\n",
187
+ "\n",
188
+ "# @markdown ### What's in the Box?\n",
189
+ "# @markdown - Hugging Face Hub (for all your model adventures)\n",
190
+ "# @markdown - IPython Widgets (for a prettier interface)\n",
191
+ "# @markdown - Essential file handling tools\n",
192
+ "\n",
193
+ "print(\"🔍 Starting the setup process...\")\n",
194
+ "\n",
195
+ "def check_and_install(package, install_name=None, verbose=False):\n",
196
+ " \"\"\"Checks if a package is installed and installs it if needed.\"\"\"\n",
197
+ " import importlib\n",
198
+ " if install_name is None:\n",
199
+ " install_name = package\n",
200
+ " try:\n",
201
+ " importlib.import_module(package)\n",
202
+ " print(f\"✅ {package} is already installed.\")\n",
203
+ " except ImportError:\n",
204
+ " print(f\"📦 Installing {package}...\")\n",
205
+ " if verbose:\n",
206
+ " !pip install {install_name}\n",
207
+ " else:\n",
208
+ " !pip install -q {install_name}\n",
209
+ " print(f\"✨ {package} installed successfully.\")\n",
210
+ " except Exception as e:\n",
211
+ " print(f\"❌ An error occurred during install of {package}: {e}\")\n",
212
+ "\n",
213
+ "# Packages needed for our project\n",
214
+ "required_packages = {\n",
215
+ " 'huggingface_hub': '--force-reinstall huggingface_hub', #Reinstalls if exists\n",
216
+ " 'ipywidgets': 'ipywidgets',\n",
217
+ " 'glob': 'glob', # Changed to glob, since glob2 is not essential here\n",
218
+ " 'tqdm': 'tqdm' # Install tqdm\n",
219
+ "}\n",
220
+ "\n",
221
+ "# Run installations\n",
222
+ "for package, install_cmd in required_packages.items():\n",
223
+ " check_and_install(package, install_cmd, verbose=True) #Turn verbose output on\n",
224
+ "\n",
225
+ "# Clean up output\n",
226
+ "from IPython.display import clear_output\n",
227
+ "clear_output()\n",
228
+ "\n",
229
+ "print(\"\"\"\n",
230
+ "🎉 All set! Here's a summary of what was installed:\n",
231
+ "\n",
232
+ "🤗 Hugging Face Hub - Your portal to model magic\n",
233
+ "🎨 IPython Widgets - To make things pretty\n",
234
+ "📁 File Handling - Tools to keep things organized\n",
235
+ "📊 Progress Bars - For better tracking of uploads\n",
236
+ "\n",
237
+ "Having issues? Here's a checklist:\n",
238
+ "1. Try running this cell again\n",
239
+ "2. Ensure your Colab runtime is not encountering errors\n",
240
+ "3. If still wonky, drop by our Discord for help!\n",
241
+ "\n",
242
+ "Let's make some AI magic! 🚀\n",
243
+ "\"\"\")"
244
+ ],
245
+ "metadata": {
246
+ "cellView": "form",
247
+ "id": "Nhi-k9j30ssE"
248
+ },
249
+ "execution_count": null,
250
+ "outputs": []
251
+ },
252
+ {
253
+ "cell_type": "code",
254
+ "source": [
255
+ "# @title 🔐 Connect to Hugging Face Hub - Enhanced\n",
256
+ "# @markdown ## Let's get you logged into your Hugging Face account! ✨\n",
257
+ "\n",
258
+ "# @markdown ### Quick Guide:\n",
259
+ "# @markdown 1. **New User?** Head over to [Hugging Face](https://huggingface.co/) and create a free account.\n",
260
+ "# @markdown 2. **Get Your Token:** Visit your [tokens page](https://huggingface.co/settings/tokens).\n",
261
+ "# @markdown 3. **Create a Token:** Click 'New Token' or copy an existing one (ensure it has `Write` access).\n",
262
+ "# @markdown 4. **Paste Below:** Copy and paste your token into the field below.\n",
263
+ "\n",
264
+ "print(\"✨ Checking Hugging Face connection...\")\n",
265
+ "\n",
266
+ "# Check if hub_ok exists, set it if not\n",
267
+ "try:\n",
268
+ " hub_ok\n",
269
+ "except NameError:\n",
270
+ " print(\"📦 Installing huggingface_hub (if needed)...\")\n",
271
+ " !pip install --force-reinstall -q huggingface_hub\n",
272
+ " hub_ok = True\n",
273
+ "\n",
274
+ "from IPython.display import clear_output\n",
275
+ "from huggingface_hub import login\n",
276
+ "clear_output() #clear the output\n",
277
+ "\n",
278
+ "# @markdown ### 🔑 Your Hugging Face Token\n",
279
+ "write_token = \"\" # @param {type:\"string\"}\n",
280
+ "\n",
281
+ "try:\n",
282
+ " if write_token:\n",
283
+ " print(\"🔑 Logging you in with your Hugging Face token...\")\n",
284
+ " login(write_token, add_to_git_credential=True)\n",
285
+ " print(\"🎉 Successfully logged in to Hugging Face! Your powers are activated!\")\n",
286
+ " print(\"💫 You're ready to upload models and files.\")\n",
287
+ " else:\n",
288
+ " print(\"⚠️ No token was provided. Please paste your Hugging Face token above.\")\n",
289
+ "except Exception as e:\n",
290
+ " print(\"❌ Login failed. Please check the following:\")\n",
291
+ " print(f\" 1. Ensure your token is correct and has 'Write' access.\")\n",
292
+ " print(f\" 2. The error is: {e}\")\n",
293
+ " print(\"🤔 If you're still having problems, visit our Discord for help!\")\n",
294
+ " raise"
295
+ ],
296
+ "metadata": {
297
+ "cellView": "form",
298
+ "id": "1B8DZ_p8IcNh"
299
+ },
300
+ "execution_count": null,
301
+ "outputs": []
302
+ },
303
+ {
304
+ "cell_type": "code",
305
+ "source": [
306
+ "# @title 🏗️ Repository Setup Wizard - Enhanced\n",
307
+ "# @markdown ### Let's get your Hugging Face repository ready! ✨\n",
308
+ "\n",
309
+ "from huggingface_hub.utils import validate_repo_id, HfHubHTTPError\n",
310
+ "from huggingface_hub import HfApi\n",
311
+ "import os\n",
312
+ "\n",
313
+ "# @markdown #### 🎨 Customize Your Repository\n",
314
+ "repo_name = \"\" # @param {type:\"string\"}\n",
315
+ "make_private = False # @param {type:\"boolean\"} {description:\"Keep your repo private?\"}\n",
316
+ "clone_repo = True # @param {type:\"boolean\"} {description:\"Download repo to Colab?\"}\n",
317
+ "\n",
318
+ "print(\"🛠️ Setting up your Hugging Face repository...\")\n",
319
+ "\n",
320
+ "try:\n",
321
+ " # Initialize the Hugging Face API\n",
322
+ " api = HfApi()\n",
323
+ " user = api.whoami()\n",
324
+ " model_repo = f\"{user['name']}/{repo_name.strip()}\"\n",
325
+ "\n",
326
+ " # Validate the repository name\n",
327
+ " print(f\"🔍 Validating repository name: '{model_repo}'\")\n",
328
+ " validate_repo_id(model_repo)\n",
329
+ "\n",
330
+ " # Create or check the repository\n",
331
+ " print(\"📦 Creating repository if it doesn't exist...\")\n",
332
+ " api.create_repo(\n",
333
+ " repo_id=model_repo,\n",
334
+ " private=make_private,\n",
335
+ " exist_ok=True\n",
336
+ " )\n",
337
+ " print(f\"🎉 Repository '{model_repo}' is ready for action!\")\n",
338
+ "\n",
339
+ " # Clone the repository if requested\n",
340
+ " if clone_repo:\n",
341
+ " print(\"\\n📦 Cloning your repository (with LFS)...\")\n",
342
+ " clone_path = f\"/content/{repo_name.strip()}\"\n",
343
+ "\n",
344
+ " if os.path.exists(clone_path):\n",
345
+ " print(f\"⚠️ Repository already exists at '{clone_path}'. Skipping clone step.\")\n",
346
+ " else:\n",
347
+ " !git lfs install --skip-smudge\n",
348
+ " !export GIT_LFS_SKIP_SMUDGE=1\n",
349
+ " !git clone https://huggingface.co/{model_repo} {clone_path}\n",
350
+ " print(\"✨ Repository cloned successfully!\")\n",
351
+ "\n",
352
+ "except Exception as e:\n",
353
+ " print(f\"❌ An error occurred during repository setup: {e}\")\n",
354
+ " raise\n",
355
+ "\n",
356
+ "print(\"✅ Repository setup complete!\")"
357
+ ],
358
+ "metadata": {
359
+ "id": "J851eLx6Ii3h"
360
+ },
361
+ "execution_count": null,
362
+ "outputs": []
363
+ },
364
+ {
365
+ "cell_type": "code",
366
+ "source": [
367
+ "# @title 🚀 Hugging Face File Uploader - Interactive\n",
368
+ "# @markdown ## 🌟 Ready to Upload Your Files to Hugging Face?\n",
369
+ "\n",
370
+ "# @markdown ### Quick Guide:\n",
371
+ "# @markdown 1. Fill in your Hugging Face `Organization/Username` and `Repository name`.\n",
372
+ "# @markdown 2. Specify the directory to search in below.\n",
373
+ "# @markdown 3. Select the files you want to upload using the file picker below.\n",
374
+ "# @markdown 4. Click the `Upload` button to begin the upload process.\n",
375
+ "\n",
376
+ "# @markdown ### Pro Tips:\n",
377
+ "# @markdown - If files are missing, ensure they are in the current directory.\n",
378
+ "# @markdown - Use Ctrl/Cmd to select multiple files.\n",
379
+ "# @markdown - Customize the commit message.\n",
380
+ "\n",
381
+ "import os\n",
382
+ "import glob\n",
383
+ "import time\n",
384
+ "from pathlib import Path\n",
385
+ "from huggingface_hub import HfApi\n",
386
+ "from IPython.display import display, HTML, clear_output, Image\n",
387
+ "from tqdm.notebook import tqdm\n",
388
+ "from ipywidgets import *\n",
389
+ "\n",
390
+ "# @markdown ### 📚 Repository Details\n",
391
+ "hfuser = \"\" # @param {type:\"string\"} {description: \"Your Hugging Face Username or Organization\"}\n",
392
+ "hfrepo = \"\" # @param {type:\"string\"} {description: \"Your Hugging Face Repository Name\"}\n",
393
+ "\n",
394
+ "# @markdown ### 🗂️ File Settings\n",
395
+ "file_type = \"mp3\" # @param [\"safetensors\", \"pt\", \"mp3\", \"pth\", \"onnx\", \"pb\", \"h5\", \"ckpt\", \"bin\", \"json\", \"yaml\", \"yml\", \"txt\", \"csv\", \"pkl\", \"png\", \"jpg\", \"jpeg\", \"webp\", \"gif\", \"zip\", \"tar\", \"gz\", \"mp3\", \"wav\", \"ogg\", \"mp4\", \"mov\", \"avi\", \"mkv\"]\n",
396
+ "#sort_by = \"name\" # @param [\"name\", \"date\"]\n",
397
+ "\n",
398
+ "# @markdown ### 📁 File Location\n",
399
+ "file_location = \"\" # @param {type:\"string\"} {description: \"The directory to search for files\"}\n",
400
+ "\n",
401
+ "# @markdown ### 💭 Upload Settings\n",
402
+ "commit_message = \"Upload with Earth & Dusk Huggingface 🤗 Backup\" # @param {type:\"string\"}\n",
403
+ "create_pr = False # @param {type:\"boolean\"}\n",
404
+ "clear_after = True # @param {type:\"boolean\"}\n",
405
+ "\n",
406
+ "\n",
407
+ "def format_size(size):\n",
408
+ " \"\"\"Formats a file size into a human-readable string.\"\"\"\n",
409
+ " for unit in ['B', 'KB', 'MB', 'GB']:\n",
410
+ " if size < 1024:\n",
411
+ " return f\"{size:.2f} {unit}\"\n",
412
+ " size /= 1024\n",
413
+ " return f\"{size:.2f} TB\"\n",
414
+ "\n",
415
+ "def find_files(file_location, file_type):\n",
416
+ " \"\"\"Finds files matching the selected file type in the given directory.\"\"\"\n",
417
+ " try:\n",
418
+ " files = sorted(\n",
419
+ " glob.glob(os.path.join(file_location, f\"*.{file_type}\")),\n",
420
+ " key=os.path.getmtime if sort_by == 'date' else str\n",
421
+ " )\n",
422
+ " return files\n",
423
+ " except Exception as e:\n",
424
+ " print(f\"❌ Error finding files: {e}\")\n",
425
+ " return []\n",
426
+ "\n",
427
+ "# Widget Setup\n",
428
+ "all_ckpts = find_files(file_location, file_type)\n",
429
+ "ckpt_picker = SelectMultiple(options=all_ckpts, layout=Layout(width=\"600px\"), description=\"Select File(s)\")\n",
430
+ "upload_btn = Button(description='Upload')\n",
431
+ "out = Output()\n",
432
+ "\n",
433
+ "def upload_ckpts(_):\n",
434
+ " repo_id = f\"{hfuser}/{hfrepo}\"\n",
435
+ " with out:\n",
436
+ " if not ckpt_picker.value:\n",
437
+ " print(\"Nothing selected for upload, make sure to click one of the files in the list, or verify there are files in the specified directory.\")\n",
438
+ " return\n",
439
+ " for ckpt in ckpt_picker.value:\n",
440
+ " print(f\"Uploading to HF: huggingface.co/{repo_id}/{os.path.basename(ckpt)}\")\n",
441
+ " size = os.path.getsize(ckpt)\n",
442
+ " print(f\"📦 Uploading file: {ckpt} ({format_size(size)})\")\n",
443
+ "\n",
444
+ " try:\n",
445
+ " start_time = time.time()\n",
446
+ " response = api.upload_file(\n",
447
+ " path_or_fileobj=ckpt,\n",
448
+ " path_in_repo=os.path.basename(ckpt),\n",
449
+ " repo_id=repo_id,\n",
450
+ " repo_type=None,\n",
451
+ " create_pr=create_pr,\n",
452
+ " commit_message=commit_message\n",
453
+ " )\n",
454
+ " duration = time.time() - start_time\n",
455
+ " print(f\"✅ Upload completed in {duration:.1f} seconds\")\n",
456
+ " except Exception as e:\n",
457
+ " print(f\"❌ Error uploading {ckpt}: {e}\")\n",
458
+ " print(\"\\n✨ All uploads complete!\")\n",
459
+ " if create_pr:\n",
460
+ " print(\"🎉 Check your repository for the new Pull Request!\")\n",
461
+ " else:\n",
462
+ " print(\"🎉 Files have been uploaded directly to your repository!\")\n",
463
+ " if clear_after:\n",
464
+ " time.sleep(3)\n",
465
+ " clear_output()\n",
466
+ "\n",
467
+ "\n",
468
+ "upload_btn.on_click(upload_ckpts)\n",
469
+ "\n",
470
+ "# Display widgets\n",
471
+ "box = VBox([\n",
472
+ " ckpt_picker,\n",
473
+ " HBox([\n",
474
+ " Label(\"HF User:\"),\n",
475
+ " Text(value = hfuser, placeholder='YourUSERHERE', disabled = True),\n",
476
+ " Label(\"HF Repo:\"),\n",
477
+ " Text(value = hfrepo, placeholder='ModelNameHere', disabled = True),\n",
478
+ " ]),\n",
479
+ " HBox([\n",
480
+ " Label(\"File Directory:\"),\n",
481
+ " Text(value = file_location, placeholder='/content', disabled = True),\n",
482
+ " ]),\n",
483
+ " upload_btn,\n",
484
+ " out,\n",
485
+ "\n",
486
+ "])\n",
487
+ "\n",
488
+ "display(box)\n",
489
+ "\n",
490
+ "# Helper function for updating the displayed file path\n",
491
+ "def update_file_list(event):\n",
492
+ " global all_ckpts\n",
493
+ " all_ckpts = find_files(file_location, file_type)\n",
494
+ " ckpt_picker.options = all_ckpts\n",
495
+ "\n",
496
+ "def on_file_type_change(change):\n",
497
+ " global all_ckpts\n",
498
+ " all_ckpts = find_files(file_location, change.new)\n",
499
+ " ckpt_picker.options = all_ckpts\n",
500
+ "\n",
501
+ "#Observe for file path changes\n",
502
+ "observe_file_path = Text(value=\"/content\")\n",
503
+ "observe_file_path.observe(update_file_list, names='value')\n",
504
+ "\n",
505
+ "#Observe for file type changes\n",
506
+ "observe_file_type = Dropdown(options=[\"safetensors\", \"pt\", \"pth\", \"mp3\", \"onnx\", \"pb\", \"h5\", \"ckpt\", \"bin\", \"json\", \"yaml\", \"yml\", \"txt\", \"csv\", \"pkl\", \"png\", \"jpg\", \"jpeg\", \"webp\", \"gif\", \"zip\", \"tar\", \"gz\", \"mp3\", \"wav\", \"ogg\", \"mp4\", \"mov\", \"avi\", \"mkv\"], value = file_type)\n",
507
+ "observe_file_type.observe(on_file_type_change, names='value')\n",
508
+ "display(HBox([Label(\"File Type:\"), observe_file_type]))"
509
+ ],
510
+ "metadata": {
511
+ "id": "lucnlbQQCBZd"
512
+ },
513
+ "execution_count": null,
514
+ "outputs": []
515
+ }
516
+ ]
517
+ }
HuggingFace_Backup_Jupyter_2025.ipynb ADDED
@@ -0,0 +1,559 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# 🚀 Welcome to the Hugging Face Uploader Notebook!\n",
8
+ "\n",
9
+ "This notebook provides a user-friendly tool for uploading files directly to your Hugging Face repositories. Here's how to get started:\n",
10
+ "\n",
11
+ "**🔑 Initial Setup (One Time Only)**\n",
12
+ "\n",
13
+ "1. **Authenticate:**\n",
14
+ " * Run the `notebook_login()` cell *once* to securely store your Hugging Face API token.\n",
15
+ " * **Important:** For security, avoid sharing your notebook file or system state after you have run `notebook_login()`. Do not commit your notebook file to a shared repo, as this could expose your API token.\n",
16
+ "\n",
17
+ "**🗂️ Using the Uploader**\n",
18
+ "\n",
19
+ "1. **Repository Details:**\n",
20
+ " * Enter your Hugging Face Organization or Username in the \"Owner\" field.\n",
21
+ " * Enter your repository name in the \"Repo\" field.\n",
22
+ "\n",
23
+ "2. **Directory Selection:**\n",
24
+ " * Enter a directory path where your files are located.\n",
25
+ " * Select the 'Update Dir' button to set that path.\n",
26
+ "\n",
27
+ "3. **File Selection:**\n",
28
+ " * Select the appropriate file type from the dropdown menu.\n",
29
+ " * Select the files you want to upload from the list. You can sort them by name or date modified.\n",
30
+ "\n",
31
+ "4. **Commit Message (Optional):**\n",
32
+ " * Add a commit message to your upload, or use the default message.\n",
33
+ "\n",
34
+ "5. **Upload Options:**\n",
35
+ " * Choose whether to create a pull request or upload directly to the main branch.\n",
36
+ " * Select whether to clear the output after a successful upload.\n",
37
+ "\n",
38
+ "6. **Start Upload:**\n",
39
+ " * Click the \"⬆️ Upload\" button.\n",
40
+ "\n",
41
+ "**💡 Important Notes**\n",
42
+ "\n",
43
+ "* **Direct Uploads:** This uploader uses the Hugging Face API for direct file uploads, bypassing the need for traditional Git operations for core functionality.\n",
44
+ "* **Git LFS:** Most users will not need to interact with Git or Git LFS. If you need to clone or push changes to a repository *outside this notebook*, you will require a separate Git credential setup (e.g., your operating system's credential manager or SSH keys). This is separate from your Hugging Face API token, and you should not share any git credentials in your notebook.\n",
45
+ "* **Troubleshooting:** If you encounter any issues, please review the steps, or double-check that you have write access to the repository, and that your API token has the correct scope of access.\n",
46
+ "\n",
47
+ "**📣 Updates & Community**\n",
48
+ "\n",
49
+ "* This tool will continue to be updated.\n",
50
+ "* For the latest patches, fixes, and community contributions, visit [https://github.com/duskfallcrew/HuggingFace_Backup](https://github.com/duskfallcrew/HuggingFace_Backup)\n",
51
+ "\n",
52
+ "We hope this notebook makes your Hugging Face uploads easier! If you have any questions or suggestions, please reach out."
53
+ ]
54
+ },
55
+ {
56
+ "cell_type": "code",
57
+ "execution_count": 2,
58
+ "metadata": {},
59
+ "outputs": [],
60
+ "source": [
61
+ "!pip install -q huggingface_hub ipywidgets tqdm"
62
+ ]
63
+ },
64
+ {
65
+ "cell_type": "markdown",
66
+ "metadata": {
67
+ "id": "Xs1mb1VKLuUW"
68
+ },
69
+ "source": [
70
+ "# ✨ Connecting to Hugging Face: Authentication Required\n",
71
+ "\n",
72
+ "To upload files to Hugging Face using this notebook, you'll need to authenticate using your Hugging Face API token. This token acts as your secure access key to the Hugging Face Hub.\n",
73
+ "\n",
74
+ "**🔑 Obtaining Your API Token**\n",
75
+ "\n",
76
+ "1. **Go to Your Settings:** Navigate to your [Hugging Face account settings](https://huggingface.co/settings/tokens).\n",
77
+ "2. **Access Tokens Section:** Find the \"Access Tokens\" section.\n",
78
+ "3. **Create or Copy Token:**\n",
79
+ " * If you don't have one already, create a new access token.\n",
80
+ " * Copy your existing access token.\n",
81
+ "\n",
82
+ "**🔒 Logging In**\n",
83
+ "\n",
84
+ "1. **Run the Cell:** Execute the cell below this section.\n",
85
+ "2. **Paste Token:** When prompted, paste your Hugging Face API token into the input field.\n",
86
+ "3. **Confirm:** Press `Enter` to complete the login process. No characters will be displayed as you type your token.\n",
87
+ " * **Security Note:** This ensures your token is kept private while pasting.\n",
88
+ "\n",
89
+ "**Important Notes**\n",
90
+ "\n",
91
+ "* **Purpose:** This login step authorizes your notebook environment to interact with the Hugging Face Hub. This is required for uploading your models and data.\n",
92
+ "* **Session-Based:** You will need to perform this login procedure each time you restart the notebook or start a new session (the token is stored locally on your computer, but not in the notebook, and it doesn't persist between sessions).\n",
93
+ "* **Security:** After you have logged in using `notebook_login()`, **do not** share your notebook or your system state with untrusted users, and do not commit your notebook to a shared repository, as this could compromise your API token.\n",
94
+ "\n",
95
+ "After completing this step, you'll be ready to use the upload functionality of this notebook."
96
+ ]
97
+ },
98
+ {
99
+ "cell_type": "code",
100
+ "execution_count": 3,
101
+ "metadata": {},
102
+ "outputs": [
103
+ {
104
+ "data": {
105
+ "application/vnd.jupyter.widget-view+json": {
106
+ "model_id": "b8aa868174ad469e86777458ea77c214",
107
+ "version_major": 2,
108
+ "version_minor": 0
109
+ },
110
+ "text/plain": [
111
+ "VBox(children=(HTML(value='<center> <img\\nsrc=https://huggingface.co/front/assets/huggingface_logo-noborder.sv…"
112
+ ]
113
+ },
114
+ "metadata": {},
115
+ "output_type": "display_data"
116
+ }
117
+ ],
118
+ "source": [
119
+ "from huggingface_hub import notebook_login\n",
120
+ "import os\n",
121
+ "notebook_login()"
122
+ ]
123
+ },
124
+ {
125
+ "cell_type": "markdown",
126
+ "metadata": {},
127
+ "source": [
128
+ "# 🚀 Using the Hugging Face File Uploader\n",
129
+ "\n",
130
+ "To upload files to your Hugging Face repository, please follow these steps:\n",
131
+ "\n",
132
+ "**Before you start**: You **must have already completed the following:**\n",
133
+ "\n",
134
+ " * You have authenticated with Hugging Face by running the `notebook_login()` cell located at the start of the notebook.\n",
135
+ " * You have created your repository on the Hugging Face Hub.\n",
136
+ "\n",
137
+ "**Using the Uploader**\n",
138
+ "\n",
139
+ "1. **Repository Details:**\n",
140
+ " * Enter your Hugging Face Organization or Username in the \"Owner\" field.\n",
141
+ " * Enter your repository name in the \"Repo\" field.\n",
142
+ "\n",
143
+ "2. **Directory Selection**\n",
144
+ " * Enter a directory path where your files are located.\n",
145
+ " * Select the 'Update Dir' button to set that path.\n",
146
+ "\n",
147
+ "3. **File Selection:**\n",
148
+ " * Select the appropriate file type from the dropdown menu (e.g., SafeTensors, PyTorch).\n",
149
+ " * Choose how you want to sort your files (by name or date modified).\n",
150
+ " * Select the files you wish to upload from the list.\n",
151
+ "\n",
152
+ "4. **Upload Settings:**\n",
153
+ " * Enable \"Create Pull Request\" if you want to submit your changes through a pull request, otherwise the changes will be made directly to the main branch of your repo.\n",
154
+ " * Click the \"Upload\" button to start the upload process.\n",
155
+ "\n",
156
+ "**Status and Updates**\n",
157
+ "\n",
158
+ "* The uploader will provide progress messages during the upload process.\n",
159
+ "* Any errors will be reported with suggestions on how to fix them.\n",
160
+ "\n",
161
+ "**Reusing the Uploader**\n",
162
+ "\n",
163
+ "* You can repeat these steps to upload additional files to the same repository."
164
+ ]
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "execution_count": 20,
169
+ "metadata": {
170
+ "cellView": "form",
171
+ "id": "J851eLx6Ii3h"
172
+ },
173
+ "outputs": [
174
+ {
175
+ "data": {
176
+ "application/vnd.jupyter.widget-view+json": {
177
+ "model_id": "075b7bb0b71e4f0aaa272bfb20fbcebd",
178
+ "version_major": 2,
179
+ "version_minor": 0
180
+ },
181
+ "text/plain": [
182
+ "VBox(children=(HTML(value='<b>📚 Repository Details</b>'), HBox(children=(Text(value='', description='Owner:', …"
183
+ ]
184
+ },
185
+ "metadata": {},
186
+ "output_type": "display_data"
187
+ }
188
+ ],
189
+ "source": [
190
+ "import glob\n",
191
+ "import os\n",
192
+ "from pathlib import Path\n",
193
+ "from huggingface_hub import HfApi\n",
194
+ "from ipywidgets import Text, Dropdown, Button, SelectMultiple, VBox, HBox, Output, Layout, Checkbox, HTML, Textarea, Label, IntProgress\n",
195
+ "from IPython.display import display, clear_output\n",
196
+ "import time\n",
197
+ "from tqdm import tqdm\n",
198
+ "\n",
199
+ "class HuggingFaceUploader:\n",
200
+ " def __init__(self):\n",
201
+ " self.api = HfApi()\n",
202
+ " self.file_types = [\n",
203
+ " # AI Model Files 🤖\n",
204
+ " ('SafeTensors', 'safetensors'),\n",
205
+ " ('PyTorch Models', 'pt'),\n",
206
+ " ('PyTorch Legacy', 'pth'),\n",
207
+ " ('ONNX Models', 'onnx'),\n",
208
+ " ('TensorFlow Models', 'pb'),\n",
209
+ " ('Keras Models', 'h5'),\n",
210
+ "\n",
211
+ " # Checkpoint Files 🎯\n",
212
+ " ('Checkpoints', 'ckpt'),\n",
213
+ " ('Binary Files', 'bin'),\n",
214
+ "\n",
215
+ " # Config & Data Files 📝\n",
216
+ " ('JSON Files', 'json'),\n",
217
+ " ('YAML Files', 'yaml'),\n",
218
+ " ('YAML Alt', 'yml'),\n",
219
+ " ('Text Files', 'txt'),\n",
220
+ " ('CSV Files', 'csv'),\n",
221
+ " ('Pickle Files', 'pkl'),\n",
222
+ "\n",
223
+ " # Image Files 🎨\n",
224
+ " ('PNG Images', 'png'),\n",
225
+ " ('JPEG Images', 'jpg'),\n",
226
+ " ('JPEG Alt', 'jpeg'),\n",
227
+ " ('WebP Images', 'webp'),\n",
228
+ " ('GIF Images', 'gif'),\n",
229
+ "\n",
230
+ " # Archive Files 📦\n",
231
+ " ('ZIP Archives', 'zip'),\n",
232
+ " ('TAR Files', 'tar'),\n",
233
+ " ('GZ Archives', 'gz')\n",
234
+ " ]\n",
235
+ " self.current_directory = os.getcwd()\n",
236
+ " self._create_widgets()\n",
237
+ " self._bind_events()\n",
238
+ "\n",
239
+ "\n",
240
+ " def _create_widgets(self):\n",
241
+ " # Repository info section\n",
242
+ " self.repo_info = HTML(value=\"<b>📚 Repository Details</b>\")\n",
243
+ " self.org_name = Text(\n",
244
+ " placeholder='Organization or Username',\n",
245
+ " description='Owner:',\n",
246
+ " style={'description_width': 'initial'}\n",
247
+ " )\n",
248
+ " self.repo_name = Text(\n",
249
+ " placeholder='Repository Name',\n",
250
+ " description='Repo:',\n",
251
+ " style={'description_width': 'initial'}\n",
252
+ " )\n",
253
+ "\n",
254
+ " # File handling section\n",
255
+ " self.file_section = HTML(value=\"<b>🗂️ File Selection</b>\")\n",
256
+ " self.file_type = Dropdown(\n",
257
+ " options=self.file_types,\n",
258
+ " value='safetensors',\n",
259
+ " description='File Type:',\n",
260
+ " style={'description_width': 'initial'}\n",
261
+ " )\n",
262
+ " self.sort_by = Dropdown(\n",
263
+ " options=['name', 'date'],\n",
264
+ " value='name',\n",
265
+ " description='Sort By:'\n",
266
+ " )\n",
267
+ " self.directory_label = Label(value=f\"Current Directory: {self.current_directory}\")\n",
268
+ " self.directory_text = Text(\n",
269
+ " value=self.current_directory,\n",
270
+ " description=\"Path:\",\n",
271
+ " style={'description_width': 'initial'},\n",
272
+ " layout=Layout(width=\"400px\")\n",
273
+ " )\n",
274
+ " self.directory_update_btn = Button(\n",
275
+ " description='🔄 Update Dir',\n",
276
+ " button_style='info',\n",
277
+ " tooltip='Refresh directory'\n",
278
+ " )\n",
279
+ "\n",
280
+ "\n",
281
+ " # Custom commit message\n",
282
+ " self.commit_section = HTML(value=\"<b>💭 Commit Details</b>\")\n",
283
+ " self.commit_msg = Textarea(\n",
284
+ " value=\"Upload with Earth & Dusk Huggingface 🤗 Backup\",\n",
285
+ " placeholder='Enter your commit message (optional)',\n",
286
+ " description='Message:',\n",
287
+ " layout=Layout(width='400px', height='60px')\n",
288
+ " )\n",
289
+ "\n",
290
+ " # Upload options section\n",
291
+ " self.upload_section = HTML(value=\"<b>🚀 Upload Settings</b>\")\n",
292
+ " self.create_pr = Checkbox(\n",
293
+ " value=False,\n",
294
+ " description='Create Pull Request',\n",
295
+ " indent=False,\n",
296
+ " tooltip='When checked, creates a Pull Request instead of direct upload'\n",
297
+ " )\n",
298
+ " self.clear_after = Checkbox(\n",
299
+ " value=True,\n",
300
+ " description='Clear output after upload',\n",
301
+ " indent=False,\n",
302
+ " tooltip='Clears output area after successful upload'\n",
303
+ " )\n",
304
+ "\n",
305
+ " # Progress tracking\n",
306
+ " self.progress_text = HTML(value=\"\")\n",
307
+ "\n",
308
+ " # Action buttons with style\n",
309
+ " self.update_btn = Button(\n",
310
+ " description='🔄 Update Files',\n",
311
+ " button_style='info',\n",
312
+ " tooltip='Refresh file list'\n",
313
+ " )\n",
314
+ " self.upload_btn = Button(\n",
315
+ " description='⬆️ Upload',\n",
316
+ " button_style='success',\n",
317
+ " tooltip='Start upload process',\n",
318
+ " layout=Layout(width='auto', height='auto'),\n",
319
+ " )\n",
320
+ " self.clear_btn = Button(\n",
321
+ " description='🧹 Clear Output',\n",
322
+ " button_style='warning',\n",
323
+ " tooltip='Clear output area'\n",
324
+ " )\n",
325
+ "\n",
326
+ " # File selector and output\n",
327
+ " self.ckpt_picker = SelectMultiple(\n",
328
+ " options=[],\n",
329
+ " layout=Layout(width=\"600px\", height=\"200px\")\n",
330
+ " )\n",
331
+ " self.out = Output(layout=Layout(padding='10px'))\n",
332
+ " \n",
333
+ " # Create debug output:\n",
334
+ " self.debug_output = Output()\n",
335
+ " self.debug_box = VBox([HTML(value=\"<b style='color: #2ecc71;'>Debug Output</b>\"), self.debug_output],\n",
336
+ " layout=Layout(border='2px solid #2ecc71', padding='10px', margin_top='10px'))\n",
337
+ " self.debug_toggle = Checkbox(\n",
338
+ " value=False,\n",
339
+ " description='Show Debug',\n",
340
+ " indent=False,\n",
341
+ " tooltip='Show debug information'\n",
342
+ " )\n",
343
+ " self.debug_box.layout.visibility = 'hidden'\n",
344
+ "\n",
345
+ "\n",
346
+ " def _bind_events(self):\n",
347
+ " self.update_btn.on_click(self._update_files)\n",
348
+ " self.upload_btn.on_click(self._upload_ckpts)\n",
349
+ " self.clear_btn.on_click(lambda _: self.out.clear_output())\n",
350
+ " self.file_type.observe(self._update_files, names='value')\n",
351
+ " self.directory_update_btn.on_click(self._update_directory)\n",
352
+ " self.debug_toggle.observe(self._toggle_debug, names='value')\n",
353
+ "\n",
354
+ " def _toggle_debug(self,_):\n",
355
+ " if self.debug_toggle.value == True:\n",
356
+ " self.debug_box.layout.visibility = 'visible'\n",
357
+ " else:\n",
358
+ " self.debug_box.layout.visibility = 'hidden'\n",
359
+ "\n",
360
+ "\n",
361
+ " def _update_directory(self,_):\n",
362
+ " new_dir = self.directory_text.value\n",
363
+ " if os.path.isdir(new_dir):\n",
364
+ " self.current_directory = new_dir\n",
365
+ " self.directory_label.value = f\"Current Directory: {self.current_directory}\"\n",
366
+ " self._update_files(None)\n",
367
+ " else:\n",
368
+ " with self.out:\n",
369
+ " print(\"❌ Invalid Directory\")\n",
370
+ "\n",
371
+ " def _update_files(self, _):\n",
372
+ " file_extension = self.file_type.value\n",
373
+ " try:\n",
374
+ " # Glob files based on file extension\n",
375
+ " all_files = glob.glob(os.path.join(self.current_directory, f\"*.{file_extension}\"))\n",
376
+ "\n",
377
+ " with self.debug_output:\n",
378
+ " print(f\"DEBUG _update_files: File type is {file_extension}\")\n",
379
+ " print(f\"DEBUG _update_files: All files found by glob: {all_files}\")\n",
380
+ "\n",
381
+ " # Filter out symlinks, old files and ignore patterns\n",
382
+ " filtered_files = []\n",
383
+ " for file_path in all_files:\n",
384
+ " if os.path.islink(file_path):\n",
385
+ " with self.debug_output:\n",
386
+ " print(f\"DEBUG _update_files: Skipping symlink {file_path}\")\n",
387
+ " continue\n",
388
+ " if not os.path.isfile(file_path):\n",
389
+ " with self.debug_output:\n",
390
+ " print(f\"DEBUG _update_files: Skipping non file {file_path}\")\n",
391
+ " continue\n",
392
+ "\n",
393
+ " filtered_files.append(file_path)\n",
394
+ " \n",
395
+ " # Sort the files\n",
396
+ " all_ckpts = sorted(\n",
397
+ " filtered_files,\n",
398
+ " key=os.path.getmtime if self.sort_by.value == 'date' else str\n",
399
+ " )\n",
400
+ "\n",
401
+ " self.ckpt_picker.options = all_ckpts\n",
402
+ "\n",
403
+ " with self.out:\n",
404
+ " print(f\"✨ Found {len(all_ckpts)} {file_extension} files in {self.current_directory}\")\n",
405
+ "\n",
406
+ " except Exception as e:\n",
407
+ " with self.out:\n",
408
+ " print(f\"❌ Error listing files: {str(e)}\")\n",
409
+ "\n",
410
+ "\n",
411
+ " def _format_size(self, size):\n",
412
+ " for unit in ['B', 'KB', 'MB', 'GB']:\n",
413
+ " if size < 1024:\n",
414
+ " return f\"{size:.2f} {unit}\"\n",
415
+ " size /= 1024\n",
416
+ " return f\"{size:.2f} TB\"\n",
417
+ "\n",
418
+ " def _print_file_info(self, file_path, file_size, index, total):\n",
419
+ " with self.out:\n",
420
+ " print(f\"📦 File {index}/{total}: {file_path} ({self._format_size(file_size)})\")\n",
421
+ "\n",
422
+ "\n",
423
+ " def _upload_ckpts(self, _):\n",
424
+ " if not self.org_name.value or not self.repo_name.value:\n",
425
+ " with self.out:\n",
426
+ " print(\"❗ Please fill in both Organization/Username and Repository name\")\n",
427
+ " return\n",
428
+ "\n",
429
+ " repo_id = f\"{self.org_name.value}/{self.repo_name.value}\"\n",
430
+ " selected_files = self.ckpt_picker.value\n",
431
+ " total_files = len(selected_files)\n",
432
+ "\n",
433
+ " with self.out:\n",
434
+ " if not selected_files:\n",
435
+ " print(\"📝 Nothing selected for upload. Please select files from the list.\")\n",
436
+ " return\n",
437
+ "\n",
438
+ " print(f\"🎯 Starting upload to: huggingface.co/{repo_id}\")\n",
439
+ "\n",
440
+ " commit_msg = self.commit_msg.value if self.commit_msg.value else \"Uploaded with Earth & Dusk Huggingface 🤗 Backup\"\n",
441
+ "\n",
442
+ " with self.debug_output:\n",
443
+ " print(f\"DEBUG TQDM: Is TQDM working? This should be above the progress bar.\")\n",
444
+ "\n",
445
+ " progress_bar = IntProgress( # Create a progress bar for this upload\n",
446
+ " value=0,\n",
447
+ " min=0,\n",
448
+ " max=total_files,\n",
449
+ " description='Upload Progress:',\n",
450
+ " style={'description_width': 'initial'},\n",
451
+ " layout=Layout(width=\"400px\"),\n",
452
+ " )\n",
453
+ " display(progress_bar) # Display progress bar\n",
454
+ "\n",
455
+ " for idx, ckpt in enumerate(selected_files, 1):\n",
456
+ " try:\n",
457
+ " file_size = os.path.getsize(ckpt)\n",
458
+ " self._print_file_info(ckpt, file_size, idx, total_files)\n",
459
+ " start_time = time.time()\n",
460
+ " with self.debug_output:\n",
461
+ " print(f\"🚀 Attempting upload of {ckpt}\")\n",
462
+ " response = self.api.upload_file(\n",
463
+ " path_or_fileobj=ckpt,\n",
464
+ " path_in_repo=os.path.basename(ckpt),\n",
465
+ " repo_id=repo_id,\n",
466
+ " repo_type=None,\n",
467
+ " create_pr=self.create_pr.value,\n",
468
+ " commit_message=commit_msg\n",
469
+ " )\n",
470
+ " with self.debug_output:\n",
471
+ " print(f\"✅ Upload Response: {response}\")\n",
472
+ " duration = time.time() - start_time\n",
473
+ " with self.out:\n",
474
+ " print(f\"✅ Upload completed in {duration:.1f} seconds\")\n",
475
+ " display(response)\n",
476
+ "\n",
477
+ "\n",
478
+ " progress_bar.value = idx\n",
479
+ " display(progress_bar) # Force a render of the progress bar\n",
480
+ " except Exception as e:\n",
481
+ " with self.out:\n",
482
+ " print(f\"❌ Error uploading {ckpt}: {str(e)}\")\n",
483
+ " continue\n",
484
+ "\n",
485
+ "\n",
486
+ " with self.out:\n",
487
+ " print(\"\\n✨ All uploads completed! ✨\")\n",
488
+ " if self.create_pr.value:\n",
489
+ " print(\"🎉 Check your repository for the new Pull Request!\")\n",
490
+ " else:\n",
491
+ " print(\"🎉 Files have been uploaded directly to your repository!\")\n",
492
+ "\n",
493
+ " if self.clear_after.value:\n",
494
+ " time.sleep(3)\n",
495
+ " self.out.clear_output()\n",
496
+ "\n",
497
+ " def display(self):\n",
498
+ " box = VBox([\n",
499
+ " self.repo_info,\n",
500
+ " HBox([self.org_name, self.repo_name]),\n",
501
+ " self.file_section,\n",
502
+ " HBox([self.file_type, self.sort_by]),\n",
503
+ " HBox([self.directory_label, self.directory_text, self.directory_update_btn]),\n",
504
+ " self.commit_section,\n",
505
+ " self.commit_msg,\n",
506
+ " self.upload_section,\n",
507
+ " HBox([self.create_pr, self.clear_after]),\n",
508
+ " self.update_btn,\n",
509
+ " self.ckpt_picker,\n",
510
+ " HBox([self.upload_btn, self.clear_btn, self.debug_toggle], layout=Layout(align_items='center')),\n",
511
+ " self.progress_text,\n",
512
+ " self.out,\n",
513
+ " self.debug_box,\n",
514
+ " ])\n",
515
+ " display(box)\n",
516
+ "\n",
517
+ "# Create and display the uploader - just one line to rule them all! ✨\n",
518
+ "uploader = HuggingFaceUploader()\n",
519
+ "uploader.display()"
520
+ ]
521
+ },
522
+ {
523
+ "cell_type": "code",
524
+ "execution_count": null,
525
+ "metadata": {},
526
+ "outputs": [],
527
+ "source": []
528
+ }
529
+ ],
530
+ "metadata": {
531
+ "colab": {
532
+ "collapsed_sections": [
533
+ "IZ_JYwvBLrg-",
534
+ "PNF2kdyeO3Dn"
535
+ ],
536
+ "private_outputs": true,
537
+ "provenance": []
538
+ },
539
+ "kernelspec": {
540
+ "display_name": "Python 3 (ipykernel)",
541
+ "language": "python",
542
+ "name": "python3"
543
+ },
544
+ "language_info": {
545
+ "codemirror_mode": {
546
+ "name": "ipython",
547
+ "version": 3
548
+ },
549
+ "file_extension": ".py",
550
+ "mimetype": "text/x-python",
551
+ "name": "python",
552
+ "nbconvert_exporter": "python",
553
+ "pygments_lexer": "ipython3",
554
+ "version": "3.10.12"
555
+ }
556
+ },
557
+ "nbformat": 4,
558
+ "nbformat_minor": 4
559
+ }
Screenshot 2024-12-25 at 22.16.11.png ADDED
Screenshot 2024-12-26 at 11.53.48.png ADDED
huggingface_backup_2024_colab.py ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """HuggingFace_Backup_2024_Colab.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/github/duskfallcrew/HuggingFace_Backup/blob/Huggingface_Backup/HuggingFace_Backup_2024_Colab.ipynb
8
+
9
+ # 🌈 HuggingFace Backup - Colab Edition
10
+
11
+ Hey there, fellow adventurers in AI! Welcome to our delightfully unique corner of the universe! ✨
12
+
13
+ ## 💫 What's This All About?
14
+ This is our cozy mashup of Nocrypt's notebook and everyday AI tools, but with our own special twist! Think of it as the Colab-flavored version of our Jupyter notebook - because sometimes you need your AI magic on the go!
15
+
16
+ ### 🎯 Quick Features:
17
+ - Fast uploads to HuggingFace (because waiting is overrated!)
18
+ - Focus on checkpoints (keeping it simple and sweet)
19
+ - Built for Google Colab (our cloud-powered playground)
20
+ - All the same magic as our Jupyter version, just with cloud sprinkles! ✨
21
+
22
+ ## 🔍 Lost & Found
23
+ - Repo doing a disappearing act? [Find us on GitHub!](https://github.com/duskfallcrew/HuggingFace_Backup)
24
+ - CivitAI friends: Updates drop faster than a cat chasing a laser!
25
+
26
+ ## ☕ Support the Magic
27
+ [![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/Z8Z8L4EO)
28
+
29
+ ## 🎮 Join Our Adventure!
30
+ We're a system of 300+ alters, rocking life with DID, ADHD, Autism, and CPTSD. We believe AI can be a game-changer for mental health and creativity. Come explore with us!
31
+
32
+ ### 🌟 Find Us Here:
33
+ - 🏠 [End Media](https://www.end-media.org/)
34
+ - 🎮 [Discord](https://discord.gg/5t2kYxt7An)
35
+ - 🤗 [HuggingFace](https://huggingface.co/EarthnDusk)
36
+ - 🎵 [YouTube](https://www.youtube.com/channel/UCk7MGP7nrJz5awBSP75xmVw)
37
+ - 🎪 [Reddit](https://www.reddit.com/r/earthndusk/)
38
+ - 🎨 [DeviantArt](https://www.deviantart.com/diffusionai)
39
+
40
+ ### 🏴‍☠️ Special Thanks To:
41
+ - [Pirate Diffusion](https://www.piratediffusion.com/)
42
+ - [Yodayo](https://yodayo.com/)
43
+
44
+ ## 💝 Credits & Cool People
45
+ Huge thanks to our code ancestors:
46
+ - EVERYDREAM2 TRAINER
47
+ - LINAQRUF
48
+ - NOCRYPT [![](https://dcbadge.vercel.app/api/shield/442099748669751297?style=flat)](https://lookup.guru/442099748669751297)
49
+
50
+ Want more AI adventures? Check out the original SD Colab:
51
+ <a target="_blank" href="https://colab.research.google.com/drive/1wEa-tS10h4LlDykd87TF5zzpXIIQoCmq">
52
+ <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
53
+ </a>
54
+
55
+ ## 🛠️ Need Help?
56
+ - Found a bug? Don't panic! Drop by our GitHub or Discord
57
+ - Questions? We're here for you!
58
+ - Want to help? Pull requests are like hugs - always welcome!
59
+
60
+ ## 🎯 Recent Updates:
61
+ 1. 🌟 Enhanced Colab compatibility
62
+ 2. 🔧 Streamlined file handling
63
+ 3. 🎨 Made everything prettier (because we can!)
64
+ 4. 📝 Clearer instructions (no more confusion!)
65
+ 5. ✨ Added extra sprinkles of magic
66
+
67
+ Remember: We're not pro coders, we're creative problem solvers! Sometimes the best solutions come with a side of chaos and a sprinkle of adventure! 🌈✨
68
+
69
+ Let's make some AI magic happen! Ready to dive in? 🚀
70
+
71
+ # Google Drive Mount
72
+ """
73
+
74
+ # @title 🚀 Connect Your Google Drive
75
+ # @markdown ## Let's Get Your Storage Powers Activated! ✨
76
+
77
+ # @markdown ### What's This All About?
78
+ # @markdown Hey there, fellow creator! Before we dive into the fun stuff, let's talk storage!
79
+
80
+ # @markdown #### 🎯 Your Options:
81
+ # @markdown 1. **Google Drive** (Recommended!)
82
+ # @markdown - Perfect for keeping your models safe
83
+ # @markdown - Easy access to all your files
84
+ # @markdown - Everything stays organized
85
+ # @markdown
86
+ # @markdown 2. **Alternative Routes** (For the adventurous!)
87
+ # @markdown - Terminal wizardry (if you're comfortable with commands)
88
+ # @markdown - Direct uploads to Colab
89
+ # @markdown - Other cloud storage solutions
90
+ # @markdown
91
+ # @markdown #### 🌟 Pro Tips:
92
+ # @markdown - Watch for the popup after clicking "Connect"
93
+ # @markdown - You'll need to authorize access (don't worry, it's safe!)
94
+ # @markdown - Your drive will appear as `/content/drive`
95
+
96
+ from google.colab import drive
97
+ from google.colab import output
98
+ import os
99
+
100
+ def mount_drive():
101
+ if not os.path.exists('/content/drive'):
102
+ print("🔮 Summoning your Google Drive...")
103
+ drive.mount('/content/drive')
104
+ print("\n✨ Drive mounted successfully! You're ready to rock!")
105
+ else:
106
+ print("🎉 Your Drive is already connected and ready to go!")
107
+
108
+ # Enable our magical widgets
109
+ output.enable_custom_widget_manager()
110
+
111
+ # Let's get that drive connected!
112
+ mount_drive()
113
+
114
+ print("""
115
+ 📚 Quick Navigation Guide:
116
+ - Your Drive lives at: /content/drive
117
+ - Main workspace: /content/drive/MyDrive
118
+ - Look for the folder icon in the left sidebar
119
+
120
+ Need to upload files?
121
+ 1. Find the folder icon on the left
122
+ 2. Navigate to your drive
123
+ 3. Drag and drop your files
124
+ 4. Magic happens! ✨
125
+
126
+ Having troubles? No worries! You can:
127
+ 1. Try reconnecting (run this cell again)
128
+ 2. Use terminal commands if you're feeling brave
129
+ 3. Direct upload to Colab (look for the folder icon!)
130
+
131
+ Remember: Your creative journey is valid, no matter which path you choose! 🌈
132
+ """)
133
+
134
+ """# Installation & Requirements
135
+ -----------------
136
+
137
+
138
+ """
139
+
140
+ # @title 🛠️ Installation Wizard
141
+ # @markdown ## Let's get your workspace ready for some AI magic! ✨
142
+
143
+ # @markdown ### What's in the Box?
144
+ # @markdown - Hugging Face Hub (for all your model adventures)
145
+ # @markdown - IPython Widgets (for a prettier interface)
146
+ # @markdown - Essential file handling tools
147
+
148
+ print("🔍 Starting the setup process...")
149
+
150
+ def check_and_install(package, install_name=None, verbose=False):
151
+ """Checks if a package is installed and installs it if needed."""
152
+ import importlib
153
+ if install_name is None:
154
+ install_name = package
155
+ try:
156
+ importlib.import_module(package)
157
+ print(f"✅ {package} is already installed.")
158
+ except ImportError:
159
+ print(f"📦 Installing {package}...")
160
+ if verbose:
161
+ !pip install {install_name}
162
+ else:
163
+ !pip install -q {install_name}
164
+ print(f"✨ {package} installed successfully.")
165
+ except Exception as e:
166
+ print(f"❌ An error occurred during install of {package}: {e}")
167
+
168
+ # Packages needed for our project
169
+ required_packages = {
170
+ 'huggingface_hub': '--force-reinstall huggingface_hub', #Reinstalls if exists
171
+ 'ipywidgets': 'ipywidgets',
172
+ 'glob': 'glob', # Changed to glob, since glob2 is not essential here
173
+ 'tqdm': 'tqdm' # Install tqdm
174
+ }
175
+
176
+ # Run installations
177
+ for package, install_cmd in required_packages.items():
178
+ check_and_install(package, install_cmd, verbose=True) #Turn verbose output on
179
+
180
+ # Clean up output
181
+ from IPython.display import clear_output
182
+ clear_output()
183
+
184
+ print("""
185
+ 🎉 All set! Here's a summary of what was installed:
186
+
187
+ 🤗 Hugging Face Hub - Your portal to model magic
188
+ 🎨 IPython Widgets - To make things pretty
189
+ 📁 File Handling - Tools to keep things organized
190
+ 📊 Progress Bars - For better tracking of uploads
191
+
192
+ Having issues? Here's a checklist:
193
+ 1. Try running this cell again
194
+ 2. Ensure your Colab runtime is not encountering errors
195
+ 3. If still wonky, drop by our Discord for help!
196
+
197
+ Let's make some AI magic! 🚀
198
+ """)
199
+
200
+ # @title 🔐 Connect to Hugging Face Hub - Enhanced
201
+ # @markdown ## Let's get you logged into your Hugging Face account! ✨
202
+
203
+ # @markdown ### Quick Guide:
204
+ # @markdown 1. **New User?** Head over to [Hugging Face](https://huggingface.co/) and create a free account.
205
+ # @markdown 2. **Get Your Token:** Visit your [tokens page](https://huggingface.co/settings/tokens).
206
+ # @markdown 3. **Create a Token:** Click 'New Token' or copy an existing one (ensure it has `Write` access).
207
+ # @markdown 4. **Paste Below:** Copy and paste your token into the field below.
208
+
209
+ print("✨ Checking Hugging Face connection...")
210
+
211
+ # Check if hub_ok exists, set it if not
212
+ try:
213
+ hub_ok
214
+ except NameError:
215
+ print("📦 Installing huggingface_hub (if needed)...")
216
+ !pip install --force-reinstall -q huggingface_hub
217
+ hub_ok = True
218
+
219
+ from IPython.display import clear_output
220
+ from huggingface_hub import login
221
+ clear_output() #clear the output
222
+
223
+ # @markdown ### 🔑 Your Hugging Face Token
224
+ write_token = "" # @param {type:"string"}
225
+
226
+ try:
227
+ if write_token:
228
+ print("🔑 Logging you in with your Hugging Face token...")
229
+ login(write_token, add_to_git_credential=True)
230
+ print("🎉 Successfully logged in to Hugging Face! Your powers are activated!")
231
+ print("💫 You're ready to upload models and files.")
232
+ else:
233
+ print("⚠️ No token was provided. Please paste your Hugging Face token above.")
234
+ except Exception as e:
235
+ print("❌ Login failed. Please check the following:")
236
+ print(f" 1. Ensure your token is correct and has 'Write' access.")
237
+ print(f" 2. The error is: {e}")
238
+ print("🤔 If you're still having problems, visit our Discord for help!")
239
+ raise
240
+
241
+ # @title 🏗️ Repository Setup Wizard - Enhanced
242
+ # @markdown ### Let's get your Hugging Face repository ready! ✨
243
+
244
+ from huggingface_hub.utils import validate_repo_id, HfHubHTTPError
245
+ from huggingface_hub import HfApi
246
+ import os
247
+
248
+ # @markdown #### 🎨 Customize Your Repository
249
+ repo_name = "" # @param {type:"string"}
250
+ make_private = False # @param {type:"boolean"} {description:"Keep your repo private?"}
251
+ clone_repo = True # @param {type:"boolean"} {description:"Download repo to Colab?"}
252
+
253
+ print("🛠️ Setting up your Hugging Face repository...")
254
+
255
+ try:
256
+ # Initialize the Hugging Face API
257
+ api = HfApi()
258
+ user = api.whoami()
259
+ model_repo = f"{user['name']}/{repo_name.strip()}"
260
+
261
+ # Validate the repository name
262
+ print(f"🔍 Validating repository name: '{model_repo}'")
263
+ validate_repo_id(model_repo)
264
+
265
+ # Create or check the repository
266
+ print("📦 Creating repository if it doesn't exist...")
267
+ api.create_repo(
268
+ repo_id=model_repo,
269
+ private=make_private,
270
+ exist_ok=True
271
+ )
272
+ print(f"🎉 Repository '{model_repo}' is ready for action!")
273
+
274
+ # Clone the repository if requested
275
+ if clone_repo:
276
+ print("\n📦 Cloning your repository (with LFS)...")
277
+ clone_path = f"/content/{repo_name.strip()}"
278
+
279
+ if os.path.exists(clone_path):
280
+ print(f"⚠️ Repository already exists at '{clone_path}'. Skipping clone step.")
281
+ else:
282
+ !git lfs install --skip-smudge
283
+ !export GIT_LFS_SKIP_SMUDGE=1
284
+ !git clone https://huggingface.co/{model_repo} {clone_path}
285
+ print("✨ Repository cloned successfully!")
286
+
287
+ except Exception as e:
288
+ print(f"❌ An error occurred during repository setup: {e}")
289
+ raise
290
+
291
+ print("✅ Repository setup complete!")
292
+
293
+ # @title 🚀 Hugging Face File Uploader - Interactive
294
+ # @markdown ## 🌟 Ready to Upload Your Files to Hugging Face?
295
+
296
+ # @markdown ### Quick Guide:
297
+ # @markdown 1. Fill in your Hugging Face `Organization/Username` and `Repository name`.
298
+ # @markdown 2. Specify the directory to search in below.
299
+ # @markdown 3. Select the files you want to upload using the file picker below.
300
+ # @markdown 4. Click the `Upload` button to begin the upload process.
301
+
302
+ # @markdown ### Pro Tips:
303
+ # @markdown - If files are missing, ensure they are in the current directory.
304
+ # @markdown - Use Ctrl/Cmd to select multiple files.
305
+ # @markdown - Customize the commit message.
306
+
307
+ import os
308
+ import glob
309
+ import time
310
+ from pathlib import Path
311
+ from huggingface_hub import HfApi
312
+ from IPython.display import display, HTML, clear_output, Image
313
+ from tqdm.notebook import tqdm
314
+ from ipywidgets import *
315
+
316
+ # @markdown ### 📚 Repository Details
317
+ hfuser = "" # @param {type:"string"} {description: "Your Hugging Face Username or Organization"}
318
+ hfrepo = "" # @param {type:"string"} {description: "Your Hugging Face Repository Name"}
319
+
320
+ # @markdown ### 🗂️ File Settings
321
+ file_type = "mp3" # @param ["safetensors", "pt", "mp3", "pth", "onnx", "pb", "h5", "ckpt", "bin", "json", "yaml", "yml", "txt", "csv", "pkl", "png", "jpg", "jpeg", "webp", "gif", "zip", "tar", "gz", "mp3", "wav", "ogg", "mp4", "mov", "avi", "mkv"]
322
+ #sort_by = "name" # @param ["name", "date"]
323
+
324
+ # @markdown ### 📁 File Location
325
+ file_location = "" # @param {type:"string"} {description: "The directory to search for files"}
326
+
327
+ # @markdown ### 💭 Upload Settings
328
+ commit_message = "Upload with Earth & Dusk Huggingface 🤗 Backup" # @param {type:"string"}
329
+ create_pr = False # @param {type:"boolean"}
330
+ clear_after = True # @param {type:"boolean"}
331
+
332
+
333
+ def format_size(size):
334
+ """Formats a file size into a human-readable string."""
335
+ for unit in ['B', 'KB', 'MB', 'GB']:
336
+ if size < 1024:
337
+ return f"{size:.2f} {unit}"
338
+ size /= 1024
339
+ return f"{size:.2f} TB"
340
+
341
+ def find_files(file_location, file_type):
342
+ """Finds files matching the selected file type in the given directory."""
343
+ try:
344
+ files = sorted(
345
+ glob.glob(os.path.join(file_location, f"*.{file_type}")),
346
+ key=os.path.getmtime if sort_by == 'date' else str
347
+ )
348
+ return files
349
+ except Exception as e:
350
+ print(f"❌ Error finding files: {e}")
351
+ return []
352
+
353
+ # Widget Setup
354
+ all_ckpts = find_files(file_location, file_type)
355
+ ckpt_picker = SelectMultiple(options=all_ckpts, layout=Layout(width="600px"), description="Select File(s)")
356
+ upload_btn = Button(description='Upload')
357
+ out = Output()
358
+
359
+ def upload_ckpts(_):
360
+ repo_id = f"{hfuser}/{hfrepo}"
361
+ with out:
362
+ if not ckpt_picker.value:
363
+ print("Nothing selected for upload, make sure to click one of the files in the list, or verify there are files in the specified directory.")
364
+ return
365
+ for ckpt in ckpt_picker.value:
366
+ print(f"Uploading to HF: huggingface.co/{repo_id}/{os.path.basename(ckpt)}")
367
+ size = os.path.getsize(ckpt)
368
+ print(f"📦 Uploading file: {ckpt} ({format_size(size)})")
369
+
370
+ try:
371
+ start_time = time.time()
372
+ response = api.upload_file(
373
+ path_or_fileobj=ckpt,
374
+ path_in_repo=os.path.basename(ckpt),
375
+ repo_id=repo_id,
376
+ repo_type=None,
377
+ create_pr=create_pr,
378
+ commit_message=commit_message
379
+ )
380
+ duration = time.time() - start_time
381
+ print(f"✅ Upload completed in {duration:.1f} seconds")
382
+ except Exception as e:
383
+ print(f"❌ Error uploading {ckpt}: {e}")
384
+ print("\n✨ All uploads complete!")
385
+ if create_pr:
386
+ print("🎉 Check your repository for the new Pull Request!")
387
+ else:
388
+ print("🎉 Files have been uploaded directly to your repository!")
389
+ if clear_after:
390
+ time.sleep(3)
391
+ clear_output()
392
+
393
+
394
+ upload_btn.on_click(upload_ckpts)
395
+
396
+ # Display widgets
397
+ box = VBox([
398
+ ckpt_picker,
399
+ HBox([
400
+ Label("HF User:"),
401
+ Text(value = hfuser, placeholder='YourUSERHERE', disabled = True),
402
+ Label("HF Repo:"),
403
+ Text(value = hfrepo, placeholder='ModelNameHere', disabled = True),
404
+ ]),
405
+ HBox([
406
+ Label("File Directory:"),
407
+ Text(value = file_location, placeholder='/content', disabled = True),
408
+ ]),
409
+ upload_btn,
410
+ out,
411
+
412
+ ])
413
+
414
+ display(box)
415
+
416
+ # Helper function for updating the displayed file path
417
+ def update_file_list(event):
418
+ global all_ckpts
419
+ all_ckpts = find_files(file_location, file_type)
420
+ ckpt_picker.options = all_ckpts
421
+
422
+ def on_file_type_change(change):
423
+ global all_ckpts
424
+ all_ckpts = find_files(file_location, change.new)
425
+ ckpt_picker.options = all_ckpts
426
+
427
+ #Observe for file path changes
428
+ observe_file_path = Text(value="/content")
429
+ observe_file_path.observe(update_file_list, names='value')
430
+
431
+ #Observe for file type changes
432
+ observe_file_type = Dropdown(options=["safetensors", "pt", "pth", "mp3", "onnx", "pb", "h5", "ckpt", "bin", "json", "yaml", "yml", "txt", "csv", "pkl", "png", "jpg", "jpeg", "webp", "gif", "zip", "tar", "gz", "mp3", "wav", "ogg", "mp4", "mov", "avi", "mkv"], value = file_type)
433
+ observe_file_type.observe(on_file_type_change, names='value')
434
+ display(HBox([Label("File Type:"), observe_file_type]))