Huggingface_Backup / huggingface_backup_2024_colab.py
Duskfallcrew's picture
Upload 7 files
3d65c27 verified
# -*- coding: utf-8 -*-
"""HuggingFace_Backup_2024_Colab.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/github/duskfallcrew/HuggingFace_Backup/blob/Huggingface_Backup/HuggingFace_Backup_2024_Colab.ipynb
# ๐ŸŒˆ HuggingFace Backup - Colab Edition
Hey there, fellow adventurers in AI! Welcome to our delightfully unique corner of the universe! โœจ
## ๐Ÿ’ซ What's This All About?
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!
### ๐ŸŽฏ Quick Features:
- Fast uploads to HuggingFace (because waiting is overrated!)
- Focus on checkpoints (keeping it simple and sweet)
- Built for Google Colab (our cloud-powered playground)
- All the same magic as our Jupyter version, just with cloud sprinkles! โœจ
## ๐Ÿ” Lost & Found
- Repo doing a disappearing act? [Find us on GitHub!](https://github.com/duskfallcrew/HuggingFace_Backup)
- CivitAI friends: Updates drop faster than a cat chasing a laser!
## โ˜• Support the Magic
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/Z8Z8L4EO)
## ๐ŸŽฎ Join Our Adventure!
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!
### ๐ŸŒŸ Find Us Here:
- ๐Ÿ  [End Media](https://www.end-media.org/)
- ๐ŸŽฎ [Discord](https://discord.gg/5t2kYxt7An)
- ๐Ÿค— [HuggingFace](https://huggingface.co/EarthnDusk)
- ๐ŸŽต [YouTube](https://www.youtube.com/channel/UCk7MGP7nrJz5awBSP75xmVw)
- ๐ŸŽช [Reddit](https://www.reddit.com/r/earthndusk/)
- ๐ŸŽจ [DeviantArt](https://www.deviantart.com/diffusionai)
### ๐Ÿดโ€โ˜ ๏ธ Special Thanks To:
- [Pirate Diffusion](https://www.piratediffusion.com/)
- [Yodayo](https://yodayo.com/)
## ๐Ÿ’ Credits & Cool People
Huge thanks to our code ancestors:
- EVERYDREAM2 TRAINER
- LINAQRUF
- NOCRYPT [![](https://dcbadge.vercel.app/api/shield/442099748669751297?style=flat)](https://lookup.guru/442099748669751297)
Want more AI adventures? Check out the original SD Colab:
<a target="_blank" href="https://colab.research.google.com/drive/1wEa-tS10h4LlDykd87TF5zzpXIIQoCmq">
<img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
</a>
## ๐Ÿ› ๏ธ Need Help?
- Found a bug? Don't panic! Drop by our GitHub or Discord
- Questions? We're here for you!
- Want to help? Pull requests are like hugs - always welcome!
## ๐ŸŽฏ Recent Updates:
1. ๐ŸŒŸ Enhanced Colab compatibility
2. ๐Ÿ”ง Streamlined file handling
3. ๐ŸŽจ Made everything prettier (because we can!)
4. ๐Ÿ“ Clearer instructions (no more confusion!)
5. โœจ Added extra sprinkles of magic
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! ๐ŸŒˆโœจ
Let's make some AI magic happen! Ready to dive in? ๐Ÿš€
# Google Drive Mount
"""
# @title ๐Ÿš€ Connect Your Google Drive
# @markdown ## Let's Get Your Storage Powers Activated! โœจ
# @markdown ### What's This All About?
# @markdown Hey there, fellow creator! Before we dive into the fun stuff, let's talk storage!
# @markdown #### ๐ŸŽฏ Your Options:
# @markdown 1. **Google Drive** (Recommended!)
# @markdown - Perfect for keeping your models safe
# @markdown - Easy access to all your files
# @markdown - Everything stays organized
# @markdown
# @markdown 2. **Alternative Routes** (For the adventurous!)
# @markdown - Terminal wizardry (if you're comfortable with commands)
# @markdown - Direct uploads to Colab
# @markdown - Other cloud storage solutions
# @markdown
# @markdown #### ๐ŸŒŸ Pro Tips:
# @markdown - Watch for the popup after clicking "Connect"
# @markdown - You'll need to authorize access (don't worry, it's safe!)
# @markdown - Your drive will appear as `/content/drive`
from google.colab import drive
from google.colab import output
import os
def mount_drive():
if not os.path.exists('/content/drive'):
print("๐Ÿ”ฎ Summoning your Google Drive...")
drive.mount('/content/drive')
print("\nโœจ Drive mounted successfully! You're ready to rock!")
else:
print("๐ŸŽ‰ Your Drive is already connected and ready to go!")
# Enable our magical widgets
output.enable_custom_widget_manager()
# Let's get that drive connected!
mount_drive()
print("""
๐Ÿ“š Quick Navigation Guide:
- Your Drive lives at: /content/drive
- Main workspace: /content/drive/MyDrive
- Look for the folder icon in the left sidebar
Need to upload files?
1. Find the folder icon on the left
2. Navigate to your drive
3. Drag and drop your files
4. Magic happens! โœจ
Having troubles? No worries! You can:
1. Try reconnecting (run this cell again)
2. Use terminal commands if you're feeling brave
3. Direct upload to Colab (look for the folder icon!)
Remember: Your creative journey is valid, no matter which path you choose! ๐ŸŒˆ
""")
"""# Installation & Requirements
-----------------
"""
# @title ๐Ÿ› ๏ธ Installation Wizard
# @markdown ## Let's get your workspace ready for some AI magic! โœจ
# @markdown ### What's in the Box?
# @markdown - Hugging Face Hub (for all your model adventures)
# @markdown - IPython Widgets (for a prettier interface)
# @markdown - Essential file handling tools
print("๐Ÿ” Starting the setup process...")
def check_and_install(package, install_name=None, verbose=False):
"""Checks if a package is installed and installs it if needed."""
import importlib
if install_name is None:
install_name = package
try:
importlib.import_module(package)
print(f"โœ… {package} is already installed.")
except ImportError:
print(f"๐Ÿ“ฆ Installing {package}...")
if verbose:
!pip install {install_name}
else:
!pip install -q {install_name}
print(f"โœจ {package} installed successfully.")
except Exception as e:
print(f"โŒ An error occurred during install of {package}: {e}")
# Packages needed for our project
required_packages = {
'huggingface_hub': '--force-reinstall huggingface_hub', #Reinstalls if exists
'ipywidgets': 'ipywidgets',
'glob': 'glob', # Changed to glob, since glob2 is not essential here
'tqdm': 'tqdm' # Install tqdm
}
# Run installations
for package, install_cmd in required_packages.items():
check_and_install(package, install_cmd, verbose=True) #Turn verbose output on
# Clean up output
from IPython.display import clear_output
clear_output()
print("""
๐ŸŽ‰ All set! Here's a summary of what was installed:
๐Ÿค— Hugging Face Hub - Your portal to model magic
๐ŸŽจ IPython Widgets - To make things pretty
๐Ÿ“ File Handling - Tools to keep things organized
๐Ÿ“Š Progress Bars - For better tracking of uploads
Having issues? Here's a checklist:
1. Try running this cell again
2. Ensure your Colab runtime is not encountering errors
3. If still wonky, drop by our Discord for help!
Let's make some AI magic! ๐Ÿš€
""")
# @title ๐Ÿ” Connect to Hugging Face Hub - Enhanced
# @markdown ## Let's get you logged into your Hugging Face account! โœจ
# @markdown ### Quick Guide:
# @markdown 1. **New User?** Head over to [Hugging Face](https://huggingface.co/) and create a free account.
# @markdown 2. **Get Your Token:** Visit your [tokens page](https://huggingface.co/settings/tokens).
# @markdown 3. **Create a Token:** Click 'New Token' or copy an existing one (ensure it has `Write` access).
# @markdown 4. **Paste Below:** Copy and paste your token into the field below.
print("โœจ Checking Hugging Face connection...")
# Check if hub_ok exists, set it if not
try:
hub_ok
except NameError:
print("๐Ÿ“ฆ Installing huggingface_hub (if needed)...")
!pip install --force-reinstall -q huggingface_hub
hub_ok = True
from IPython.display import clear_output
from huggingface_hub import login
clear_output() #clear the output
# @markdown ### ๐Ÿ”‘ Your Hugging Face Token
write_token = "" # @param {type:"string"}
try:
if write_token:
print("๐Ÿ”‘ Logging you in with your Hugging Face token...")
login(write_token, add_to_git_credential=True)
print("๐ŸŽ‰ Successfully logged in to Hugging Face! Your powers are activated!")
print("๐Ÿ’ซ You're ready to upload models and files.")
else:
print("โš ๏ธ No token was provided. Please paste your Hugging Face token above.")
except Exception as e:
print("โŒ Login failed. Please check the following:")
print(f" 1. Ensure your token is correct and has 'Write' access.")
print(f" 2. The error is: {e}")
print("๐Ÿค” If you're still having problems, visit our Discord for help!")
raise
# @title ๐Ÿ—๏ธ Repository Setup Wizard - Enhanced
# @markdown ### Let's get your Hugging Face repository ready! โœจ
from huggingface_hub.utils import validate_repo_id, HfHubHTTPError
from huggingface_hub import HfApi
import os
# @markdown #### ๐ŸŽจ Customize Your Repository
repo_name = "" # @param {type:"string"}
make_private = False # @param {type:"boolean"} {description:"Keep your repo private?"}
clone_repo = True # @param {type:"boolean"} {description:"Download repo to Colab?"}
print("๐Ÿ› ๏ธ Setting up your Hugging Face repository...")
try:
# Initialize the Hugging Face API
api = HfApi()
user = api.whoami()
model_repo = f"{user['name']}/{repo_name.strip()}"
# Validate the repository name
print(f"๐Ÿ” Validating repository name: '{model_repo}'")
validate_repo_id(model_repo)
# Create or check the repository
print("๐Ÿ“ฆ Creating repository if it doesn't exist...")
api.create_repo(
repo_id=model_repo,
private=make_private,
exist_ok=True
)
print(f"๐ŸŽ‰ Repository '{model_repo}' is ready for action!")
# Clone the repository if requested
if clone_repo:
print("\n๐Ÿ“ฆ Cloning your repository (with LFS)...")
clone_path = f"/content/{repo_name.strip()}"
if os.path.exists(clone_path):
print(f"โš ๏ธ Repository already exists at '{clone_path}'. Skipping clone step.")
else:
!git lfs install --skip-smudge
!export GIT_LFS_SKIP_SMUDGE=1
!git clone https://huggingface.co/{model_repo} {clone_path}
print("โœจ Repository cloned successfully!")
except Exception as e:
print(f"โŒ An error occurred during repository setup: {e}")
raise
print("โœ… Repository setup complete!")
# @title ๐Ÿš€ Hugging Face File Uploader - Interactive
# @markdown ## ๐ŸŒŸ Ready to Upload Your Files to Hugging Face?
# @markdown ### Quick Guide:
# @markdown 1. Fill in your Hugging Face `Organization/Username` and `Repository name`.
# @markdown 2. Specify the directory to search in below.
# @markdown 3. Select the files you want to upload using the file picker below.
# @markdown 4. Click the `Upload` button to begin the upload process.
# @markdown ### Pro Tips:
# @markdown - If files are missing, ensure they are in the current directory.
# @markdown - Use Ctrl/Cmd to select multiple files.
# @markdown - Customize the commit message.
import os
import glob
import time
from pathlib import Path
from huggingface_hub import HfApi
from IPython.display import display, HTML, clear_output, Image
from tqdm.notebook import tqdm
from ipywidgets import *
# @markdown ### ๐Ÿ“š Repository Details
hfuser = "" # @param {type:"string"} {description: "Your Hugging Face Username or Organization"}
hfrepo = "" # @param {type:"string"} {description: "Your Hugging Face Repository Name"}
# @markdown ### ๐Ÿ—‚๏ธ File Settings
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"]
#sort_by = "name" # @param ["name", "date"]
# @markdown ### ๐Ÿ“ File Location
file_location = "" # @param {type:"string"} {description: "The directory to search for files"}
# @markdown ### ๐Ÿ’ญ Upload Settings
commit_message = "Upload with Earth & Dusk Huggingface ๐Ÿค— Backup" # @param {type:"string"}
create_pr = False # @param {type:"boolean"}
clear_after = True # @param {type:"boolean"}
def format_size(size):
"""Formats a file size into a human-readable string."""
for unit in ['B', 'KB', 'MB', 'GB']:
if size < 1024:
return f"{size:.2f} {unit}"
size /= 1024
return f"{size:.2f} TB"
def find_files(file_location, file_type):
"""Finds files matching the selected file type in the given directory."""
try:
files = sorted(
glob.glob(os.path.join(file_location, f"*.{file_type}")),
key=os.path.getmtime if sort_by == 'date' else str
)
return files
except Exception as e:
print(f"โŒ Error finding files: {e}")
return []
# Widget Setup
all_ckpts = find_files(file_location, file_type)
ckpt_picker = SelectMultiple(options=all_ckpts, layout=Layout(width="600px"), description="Select File(s)")
upload_btn = Button(description='Upload')
out = Output()
def upload_ckpts(_):
repo_id = f"{hfuser}/{hfrepo}"
with out:
if not ckpt_picker.value:
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.")
return
for ckpt in ckpt_picker.value:
print(f"Uploading to HF: huggingface.co/{repo_id}/{os.path.basename(ckpt)}")
size = os.path.getsize(ckpt)
print(f"๐Ÿ“ฆ Uploading file: {ckpt} ({format_size(size)})")
try:
start_time = time.time()
response = api.upload_file(
path_or_fileobj=ckpt,
path_in_repo=os.path.basename(ckpt),
repo_id=repo_id,
repo_type=None,
create_pr=create_pr,
commit_message=commit_message
)
duration = time.time() - start_time
print(f"โœ… Upload completed in {duration:.1f} seconds")
except Exception as e:
print(f"โŒ Error uploading {ckpt}: {e}")
print("\nโœจ All uploads complete!")
if create_pr:
print("๐ŸŽ‰ Check your repository for the new Pull Request!")
else:
print("๐ŸŽ‰ Files have been uploaded directly to your repository!")
if clear_after:
time.sleep(3)
clear_output()
upload_btn.on_click(upload_ckpts)
# Display widgets
box = VBox([
ckpt_picker,
HBox([
Label("HF User:"),
Text(value = hfuser, placeholder='YourUSERHERE', disabled = True),
Label("HF Repo:"),
Text(value = hfrepo, placeholder='ModelNameHere', disabled = True),
]),
HBox([
Label("File Directory:"),
Text(value = file_location, placeholder='/content', disabled = True),
]),
upload_btn,
out,
])
display(box)
# Helper function for updating the displayed file path
def update_file_list(event):
global all_ckpts
all_ckpts = find_files(file_location, file_type)
ckpt_picker.options = all_ckpts
def on_file_type_change(change):
global all_ckpts
all_ckpts = find_files(file_location, change.new)
ckpt_picker.options = all_ckpts
#Observe for file path changes
observe_file_path = Text(value="/content")
observe_file_path.observe(update_file_list, names='value')
#Observe for file type changes
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)
observe_file_type.observe(on_file_type_change, names='value')
display(HBox([Label("File Type:"), observe_file_type]))