Will commited on
Upload 16 files
Browse filesFiles changed (16)
- .gitattributes+54-59
- Notebooks.txtAdded+5
- Notebooks/PPS-A1111.ipynbAdded+184
- Notebooks/PPS-Dreambooth-v1.ipynbAdded+400
- Notebooks/PPS-Dreambooth-v2.ipynbAdded+409
- README.md+1-1
- Scripts/mainpaperspaceA1111.pyAdded+478
- Scripts/mainpaperspaceA1111_311.pyAdded+471
- Scripts/mainpaperspacev1.pyAdded+1337
- Scripts/mainpaperspacev1_311.pyAdded+1330
- Scripts/mainpaperspacev2.pyAdded+1354
- Scripts/mainpaperspacev2_311.pyAdded+1347
- Scripts/mainppsComfy.pyAdded+415
- Scripts/mainppsComfy_311.pyAdded+415
- Scripts/sdxllorapps.pyAdded+1152
- Scripts/sdxllorapps_311.pyAdded+1147
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.lz4 filter=lfs diff=lfs merge=lfs -text*.mds filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text# Audio files - uncompressed*.pcm filter=lfs diff=lfs merge=lfs -text*.sam filter=lfs diff=lfs merge=lfs -text*.raw filter=lfs diff=lfs merge=lfs -text# Audio files - compressed*.aac filter=lfs diff=lfs merge=lfs -text*.flac filter=lfs diff=lfs merge=lfs -text*.mp3 filter=lfs diff=lfs merge=lfs -text*.ogg filter=lfs diff=lfs merge=lfs -text*.wav filter=lfs diff=lfs merge=lfs -text# Image files - uncompressed*.bmp filter=lfs diff=lfs merge=lfs -text*.gif filter=lfs diff=lfs merge=lfs -text*.png filter=lfs diff=lfs merge=lfs -text*.tiff filter=lfs diff=lfs merge=lfs -text# Image files - compressed*.jpg filter=lfs diff=lfs merge=lfs -text*.jpeg filter=lfs diff=lfs merge=lfs -text*.webp filter=lfs diff=lfs merge=lfs -text# Video files - compressed*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.lz4 filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text# Audio files - uncompressed*.pcm filter=lfs diff=lfs merge=lfs -text*.sam filter=lfs diff=lfs merge=lfs -text*.raw filter=lfs diff=lfs merge=lfs -text# Audio files - compressed*.aac filter=lfs diff=lfs merge=lfs -text*.flac filter=lfs diff=lfs merge=lfs -text*.mp3 filter=lfs diff=lfs merge=lfs -text*.ogg filter=lfs diff=lfs merge=lfs -text*.wav filter=lfs diff=lfs merge=lfs -text# Image files - uncompressed*.bmp filter=lfs diff=lfs merge=lfs -text*.gif filter=lfs diff=lfs merge=lfs -text*.png filter=lfs diff=lfs merge=lfs -text*.tiff filter=lfs diff=lfs merge=lfs -text# Image files - compressed*.jpg filter=lfs diff=lfs merge=lfs -text*.jpeg filter=lfs diff=lfs merge=lfs -text*.webp filter=lfs diff=lfs merge=lfs -text
12345https://github.com/TheLastBen/PPS/raw/main/PPS-Dreambooth-v1.ipynb
https://github.com/TheLastBen/PPS/raw/main/PPS-Dreambooth-v2.ipynb
https://github.com/TheLastBen/PPS/raw/main/PPS-A1111.ipynb
https://github.com/TheLastBen/PPS/raw/main/SDXL-LoRA-PPS.ipynb
https://github.com/TheLastBen/PPS/raw/main/PPS-ComfyUI.ipynb123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184{
"cells": [
{
"cell_type": "markdown",
"id": "6441563f-5e6b-4987-abe3-2a1b8c25a789",
"metadata": {},
"source": [
"## A1111 Paperspace Notebook From https://github.com/TheLastBen/fast-stable-diffusion, if you encounter any issues, feel free to discuss them."
]
},
{
"cell_type": "markdown",
"id": "840f2f6a-41d1-4938-a846-d51f76682b76",
"metadata": {},
"source": [
"# Dependencies"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "62e22de7-f054-45a7-b7e3-b63b9a0188a1",
"metadata": {},
"outputs": [],
"source": [
"# Install the dependencies\n",
"\n",
"force_reinstall= False\n",
"\n",
"# Set to true only if you want to install the dependencies again.\n",
"\n",
"\n",
"#--------------------\n",
"with open('/dev/null', 'w') as devnull:import requests, os, time, importlib;open('/notebooks/mainpaperspaceA1111.py', 'wb').write(requests.get('https://huggingface.co/datasets/TheLastBen/PPS/raw/main/Scripts/mainpaperspaceA1111.py').content);os.chdir('/notebooks');time.sleep(3);import mainpaperspaceA1111;importlib.reload(mainpaperspaceA1111);from mainpaperspaceA1111 import *;Deps(force_reinstall)"
]
},
{
"cell_type": "markdown",
"id": "e21f3583-2d0f-4218-9da2-303f9e202820",
"metadata": {
"tags": []
},
"source": [
"# Install/Update AUTOMATIC1111 repo"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ed6cebed-8a4f-4a35-b5c3-36126be008b9",
"metadata": {},
"outputs": [],
"source": [
"# Don't skip this cell to make sure the repo is up to date and functioning correctly\n",
"\n",
"#--------------------\n",
"repo()"
]
},
{
"cell_type": "markdown",
"id": "ab0521c7-8c68-4ea2-915a-bc3f4b67f6e7",
"metadata": {},
"source": [
"# Model Download/Load"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a6f367e0-df08-41fd-91b5-e2afbcbd42e4",
"metadata": {},
"outputs": [],
"source": [
"Original_Model_Version = \"v1.5\"\n",
"\n",
"# Choices are \"v1.5\", \"v2-512\", \"v2-768\"\n",
"\n",
"\n",
"Path_to_MODEL = \"\"\n",
"\n",
"# Insert the full path of your trained model or to a folder containing multiple models.\n",
"\n",
"\n",
"MODEL_LINK = \"\"\n",
"\n",
"# A direct link to a Model or a shared gdrive link.\n",
"\n",
"safetensors= False\n",
"\n",
"# Set to True if the model from the link is in safetensors format.\n",
"\n",
"Temporary_Storage = True\n",
"\n",
"# Download the model to a temporary storage, bigger capacity but will be removed at session shutdown.\n",
"\n",
"\n",
"#--------------------\n",
"model=mdl(Original_Model_Version, Path_to_MODEL, MODEL_LINK, safetensors, Temporary_Storage)"
]
},
{
"cell_type": "markdown",
"id": "2f9228f8-3d2b-4964-a848-f75ae1618d9f",
"metadata": {},
"source": [
"# ControlNet"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "90c5d7c8-d0dc-43dc-9232-1351e8f80b5e",
"metadata": {},
"outputs": [],
"source": [
"# Download/update ControlNet extension and its models.\n",
"\n",
"ControlNet_Model = \"all\"\n",
"\n",
"# Choices are : none; all; 1: Canny; 2: Depth; 3: HED; 4: MLSD; 5: Normal; 6: OpenPose; 7: Scribble; 8: Seg; 9: T2iadapter_Models\n",
"\n",
"ControlNet_v2_Model = \"none\"\n",
"\n",
"# Choices are : none; all; 1: Canny; 2: Depth; 3: HED; 4: OpenPose; 5: Scribble\n",
"\n",
"#--------------------\n",
"CN(ControlNet_Model, ControlNet_v2_Model)"
]
},
{
"cell_type": "markdown",
"id": "e0baf0c4-a410-432f-891b-975c7250c77d",
"metadata": {},
"source": [
"# Start Stable-Diffusion"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0121ea1d-1aa0-4961-b916-c5dbb900e05f",
"metadata": {},
"outputs": [],
"source": [
"User = \"\"\n",
"\n",
"Password= \"\"\n",
"\n",
"# Add credentials to your Gradio interface (optional).\n",
"\n",
"Use_localtunnel = False\n",
"\n",
"# If you have trouble using Gradio server, use this one.\n",
"\n",
"\n",
"#-----------------\n",
"configf=sd(User, Password, Use_localtunnel, model)\n",
"!python /notebooks/sd/stable-diffusion-webui/webui.py $configf"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
}
},
"nbformat": 4,
"nbformat_minor": 5
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400{
"cells": [
{
"cell_type": "markdown",
"id": "494d5ce4-5843-4d70-ae96-c1983e21b6e8",
"metadata": {},
"source": [
"## Dreambooth v1.5 Paperspace Notebook From https://github.com/TheLastBen/fast-stable-diffusion, if you encounter any issues, feel free to discuss them. [Support](https://ko-fi.com/thelastben)"
]
},
{
"cell_type": "markdown",
"id": "8afdca63-eff3-4a9d-b4d9-127c0f028033",
"metadata": {
"tags": []
},
"source": [
"# Dependencies"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "be74b2d5-da96-4bf4-ae82-4fe4b8abc04c",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"# Install the dependencies\n",
"\n",
"force_reinstall= False\n",
"\n",
"# Set to true only if you want to install the dependencies again.\n",
"\n",
"\n",
"#--------------------\n",
"with open('/dev/null', 'w') as devnull:import requests, os, time, importlib;open('/notebooks/mainpaperspacev1.py', 'wb').write(requests.get('https://huggingface.co/datasets/TheLastBen/PPS/raw/main/Scripts/mainpaperspacev1.py').content); os.chdir('/notebooks');time.sleep(3);import mainpaperspacev1;importlib.reload(mainpaperspacev1);from mainpaperspacev1 import *;Deps(force_reinstall)"
]
},
{
"cell_type": "markdown",
"id": "7a4ef4a2-6863-4603-9254-a1e2a547ee38",
"metadata": {
"tags": []
},
"source": [
"# Download the model"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a1ba734e-515b-4761-8c88-ef7f165d7971",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"#Leave everything EMPTY to use the original model\n",
"\n",
"Path_to_HuggingFace= \"\"\n",
"\n",
"# Load and finetune a model from Hugging Face, use the format \"profile/model\" like : runwayml/stable-diffusion-v1-5\n",
"\n",
"\n",
"Model_Path = \"\"\n",
"\n",
"# Load a CKPT model from the storage.\n",
"\n",
"\n",
"Model_Link = \"\"\n",
"\n",
"# A CKPT direct link, huggingface CKPT link or a shared CKPT from gdrive.\n",
"\n",
"\n",
"safetensors= False\n",
"\n",
"# Set to True if the model from the link/path is in safetensors format.\n",
"\n",
"\n",
"#----------------\n",
"MODEL_NAME=dl(Path_to_HuggingFace, Model_Path, Model_Link, safetensors)"
]
},
{
"cell_type": "markdown",
"id": "4c6c4932-e614-4f5e-8d4a-4feca5ce54f5",
"metadata": {},
"source": [
"# Create/Load a Session"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b6595c37-8ad2-45ff-a055-fe58c6663d2f",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"Session_Name = \"sd-session\"\n",
"\n",
"# Enter the session name, it if it exists, it will load it, otherwise it'll create an new session.\n",
"\n",
"\n",
"Session_Link_optional = \"\"\n",
"\n",
"# Import a session from another gdrive, the shared gdrive link must point to the specific session's folder that contains the trained CKPT, remove any intermediary CKPT if any.\n",
"\n",
"\n",
"#-----------------\n",
"[PT, WORKSPACE, Session_Name, INSTANCE_NAME, OUTPUT_DIR, SESSION_DIR, CONCEPT_DIR, INSTANCE_DIR, CAPTIONS_DIR, MDLPTH, MODEL_NAME, resume]=sess(Session_Name, Session_Link_optional, MODEL_NAME if 'MODEL_NAME' in locals() else \"\")"
]
},
{
"cell_type": "markdown",
"id": "5698de61-08d3-4d90-83ef-f882ed956d01",
"metadata": {},
"source": [
"# Instance Images"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bc2f8f28-226e-45b8-8257-804bbb711f56",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"Remove_existing_instance_images= True\n",
"\n",
"# Set to False to keep the existing instance images if any.\n",
"\n",
"\n",
"IMAGES_FOLDER_OPTIONAL=\"\"\n",
"\n",
"# If you prefer to specify directly the folder of the pictures instead of uploading, this will add the pictures to the existing (if any) instance images. Leave EMPTY to upload.\n",
"\n",
"\n",
"Smart_crop_images= True\n",
"\n",
"# Automatically crop your input images.\n",
"\n",
"\n",
"Crop_size = 512\n",
"\n",
"# Choices: \"512\", \"576\", \"640\", \"704\", \"768\", \"832\", \"896\", \"960\", \"1024\"\n",
"\n",
"# Check out this example for naming : https://i.imgur.com/d2lD3rz.jpeg\n",
"\n",
"\n",
"#-----------------\n",
"uplder(Remove_existing_instance_images, Smart_crop_images, Crop_size, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR, False)"
]
},
{
"cell_type": "markdown",
"id": "0e93924f-a6bf-45d5-aa77-915ad7385dcd",
"metadata": {},
"source": [
"# Manual Captioning"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c5dbcb29-b42f-4cfc-9be8-83355838d5a2",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"# Open a tool to manually caption the instance images.\n",
"\n",
"#-----------------\n",
"caption(CAPTIONS_DIR, INSTANCE_DIR)"
]
},
{
"cell_type": "markdown",
"id": "c90140c1-6c91-4cae-a222-e1a746957f95",
"metadata": {},
"source": [
"# Concept Images"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "55c27688-8601-4943-b61d-fc48b9ded067",
"metadata": {},
"outputs": [],
"source": [
"Remove_existing_concept_images= True\n",
"\n",
"# Set to False to keep the existing concept images if any.\n",
"\n",
"\n",
"IMAGES_FOLDER_OPTIONAL=\"\"\n",
"\n",
"# If you prefer to specify directly the folder of the pictures instead of uploading, this will add the pictures to the existing (if any) concept images. Leave EMPTY to upload.\n",
"\n",
"\n",
"#-----------------\n",
"uplder(Remove_existing_concept_images, True, 512, IMAGES_FOLDER_OPTIONAL, CONCEPT_DIR, CAPTIONS_DIR, True)"
]
},
{
"cell_type": "markdown",
"id": "2a4aa42a-fd68-41ad-9ba7-da99f834e2c1",
"metadata": {},
"source": [
"# Dreambooth"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "612d8335-b984-4f34-911d-5457ff98e507",
"metadata": {},
"outputs": [],
"source": [
"Resume_Training = False\n",
"\n",
"# If you're not satisfied with the result, Set to True, run again the cell and it will continue training the current model.\n",
"\n",
"\n",
"UNet_Training_Steps= 1500\n",
"\n",
"UNet_Learning_Rate= \"2e-6\"\n",
"\n",
"# If you use 10 images, use 650 steps, if you're not satisfied with the result, resume training for another 200 steps with a lower learning rate (8e-6), and so on ...\n",
"\n",
"\n",
"Text_Encoder_Training_Steps= 350\n",
"\n",
"Text_Encoder_Learning_Rate= \"1e-6\"\n",
"\n",
"# 350-600 steps is enough for a small dataset, keep this number small to avoid overfitting, set to 0 to disable, set it to 0 before resuming training if it is already trained.\n",
"\n",
"\n",
"Text_Encoder_Concept_Training_Steps= 0\n",
"\n",
"# Suitable for training a style/concept as it acts as regularization, with a minimum of 300 steps, 1 step/image is enough to train the concept(s), set to 0 to disable, set both the settings above to 0 to fintune only the text_encoder on the concept, set it to 0 before resuming training if it is already trained.\n",
"\n",
"\n",
"External_Captions= False\n",
"\n",
"# Get the captions from a text file for each instance image.\n",
"\n",
"\n",
"Offset_Noise= False\n",
"\n",
"# Always use it for style training.\n",
"\n",
"\n",
"Resolution = 512\n",
"\n",
"# Choices : \"512\", \"576\", \"640\", \"704\", \"768\", \"832\", \"896\", \"960\", \"1024\"\n",
"# Higher resolution = Higher quality, make sure the instance images are cropped to this selected size (or larger).\n",
"\n",
"#---------------------------------------------------------------\n",
"\n",
"Save_Checkpoint_Every_n_Steps= False\n",
"\n",
"Save_Checkpoint_Every= 500\n",
"\n",
"# Minimum 200 steps between each save.\n",
"\n",
"\n",
"Start_saving_from_the_step= 500\n",
"\n",
"# Start saving intermediary checkpoints from this step.\n",
"\n",
"\n",
"#-----------------\n",
"resume=dbtrain(Resume_Training, UNet_Training_Steps, UNet_Learning_Rate, Text_Encoder_Training_Steps, Text_Encoder_Concept_Training_Steps, Text_Encoder_Learning_Rate, Offset_Noise, Resolution, MODEL_NAME, SESSION_DIR, INSTANCE_DIR, CONCEPT_DIR, CAPTIONS_DIR, External_Captions, INSTANCE_NAME, Session_Name, OUTPUT_DIR, PT, resume, Save_Checkpoint_Every_n_Steps, Start_saving_from_the_step, Save_Checkpoint_Every)"
]
},
{
"cell_type": "markdown",
"id": "bf6f2232-60b3-41c5-bea6-b0dcc4aef937",
"metadata": {},
"source": [
"# Test the Trained Model"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1263a084-b142-4e63-a0aa-2706673a4355",
"metadata": {},
"outputs": [],
"source": [
"Previous_Session_Name=\"\"\n",
"\n",
"# Leave empty if you want to use the current trained model.\n",
"\n",
"\n",
"Custom_Path = \"\"\n",
"\n",
"# Input the full path to a desired model.\n",
"\n",
"\n",
"User = \"\"\n",
"\n",
"Password= \"\"\n",
"\n",
"# Add credentials to your Gradio interface (optional).\n",
"\n",
"\n",
"Use_localtunnel = False\n",
"\n",
"# If you have trouble using Gradio server, use this one.\n",
"\n",
"\n",
"#-----------------\n",
"configf=test(Custom_Path, Previous_Session_Name, Session_Name, User, Password, Use_localtunnel) if 'Session_Name' in locals() else test(Custom_Path, Previous_Session_Name, \"\", User, Password, Use_localtunnel)\n",
"!python /notebooks/sd/stable-diffusion-webui/webui.py $configf"
]
},
{
"cell_type": "markdown",
"id": "53ccbcaf-3319-44f5-967b-ecbdfa9d0e78",
"metadata": {},
"source": [
"# Upload The Trained Model to Hugging Face"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2c9cb205-d828-4e51-9943-f337bd410ea8",
"metadata": {},
"outputs": [],
"source": [
"#Save it to your personal profile or collaborate to the public [library of concepts](https://huggingface.co/sd-dreambooth-library)\n",
"\n",
"Name_of_your_concept = \"\"\n",
"\n",
"# Leave empty if you want to name your concept the same as the current session.\n",
"\n",
"\n",
"hf_token_write = \"\"\n",
"\n",
"# Create a write access token here : https://huggingface.co/settings/tokens, go to \"New token\" -> Role : Write, a regular read token won't work here.\n",
"\n",
"\n",
"#---------------------------------\n",
"hf(Name_of_your_concept, Save_concept_to, hf_token_write, INSTANCE_NAME, OUTPUT_DIR, Session_Name, MDLPTH)"
]
},
{
"cell_type": "markdown",
"id": "881d80a3-4ebf-41bc-b68f-ac1cacb080f3",
"metadata": {},
"source": [
"# Free up space"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7403744d-cc45-419f-88ac-5475fa0f7f45",
"metadata": {},
"outputs": [],
"source": [
"# Display a list of sessions from which you can remove any session you don't need anymore\n",
"\n",
"#-------------------------\n",
"clean()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
}
},
"nbformat": 4,
"nbformat_minor": 5
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409{
"cells": [
{
"cell_type": "markdown",
"id": "494d5ce4-5843-4d70-ae96-c1983e21b6e8",
"metadata": {},
"source": [
"## Dreambooth v2 Paperspace Notebook From https://github.com/TheLastBen/fast-stable-diffusion, if you encounter any issues, feel free to discuss them. [Support](https://ko-fi.com/thelastben)"
]
},
{
"cell_type": "markdown",
"id": "8afdca63-eff3-4a9d-b4d9-127c0f028033",
"metadata": {
"tags": []
},
"source": [
"# Dependencies"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "be74b2d5-da96-4bf4-ae82-4fe4b8abc04c",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"# Install the dependencies\n",
"\n",
"force_reinstall= False\n",
"\n",
"# Set to true only if you want to install the dependencies again.\n",
"\n",
"\n",
"#--------------------\n",
"with open('/dev/null', 'w') as devnull:import requests, os, time, importlib;open('/notebooks/mainpaperspacev2.py', 'wb').write(requests.get('https://huggingface.co/datasets/TheLastBen/PPS/raw/main/Scripts/mainpaperspacev2.py').content);os.chdir('/notebooks');time.sleep(3);import mainpaperspacev2;importlib.reload(mainpaperspacev2);from mainpaperspacev2 import *;Deps(force_reinstall)"
]
},
{
"cell_type": "markdown",
"id": "7a4ef4a2-6863-4603-9254-a1e2a547ee38",
"metadata": {
"tags": []
},
"source": [
"# Download the model"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a1ba734e-515b-4761-8c88-ef7f165d7971",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"Model_Version = \"768\"\n",
"\n",
"# Choices are : \"512\", \"768\"\n",
"\n",
"#-----------------------------------------------------------------------------------------------------------------------------------\n",
"\n",
"Custom_Model_Version = \"768\"\n",
"\n",
"# Choices are : \"512\", \"768\"\n",
"\n",
"Path_to_HuggingFace= \"\"\n",
"\n",
"# Load and finetune a model from Hugging Face, use the format \"profile/model\" like : runwayml/stable-diffusion-v1-5.\n",
"\n",
"Model_Path = \"\"\n",
"\n",
"# Load a CKPT model from the storage.\n",
"\n",
"Model_Link = \"\"\n",
"\n",
"# A CKPT direct link, huggingface CKPT link or a shared CKPT from gdrive.\n",
"\n",
"\n",
"safetensors= False\n",
"\n",
"# Set to True if the model from the link/path is in safetensors format.\n",
"\n",
"\n",
"#-------------\n",
"MODEL_NAMEv2=dlv2(Path_to_HuggingFace, Model_Path, Model_Link, Model_Version, Custom_Model_Version, safetensors)"
]
},
{
"cell_type": "markdown",
"id": "4c6c4932-e614-4f5e-8d4a-4feca5ce54f5",
"metadata": {},
"source": [
"# Create/Load a Session"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b6595c37-8ad2-45ff-a055-fe58c6663d2f",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"Session_Name = \"sd-session\"\n",
"\n",
"# Enter the session name, it if it exists, it will load it, otherwise it'll create an new session.\n",
"\n",
"Session_Link_optional = \"\"\n",
"\n",
"# Import a session from another gdrive, the shared gdrive link must point to the specific session's folder that contains the trained CKPT, remove any intermediary CKPT if any.\n",
"\n",
"Model_Version = \"768\"\n",
"\n",
"# Ignore this if you're not loading a previous session that contains a trained model, choices are : \"512\", \"768\"\n",
"\n",
"\n",
"#-----------------\n",
"[PT, WORKSPACE, Session_Name, INSTANCE_NAME, OUTPUT_DIR, SESSION_DIR, CONCEPT_DIR, INSTANCE_DIR, CAPTIONS_DIR, MDLPTH, MODEL_NAMEv2, resumev2]=sessv2(Session_Name, Session_Link_optional, Model_Version, MODEL_NAMEv2 if 'MODEL_NAMEv2' in locals() else \"\")"
]
},
{
"cell_type": "markdown",
"id": "5698de61-08d3-4d90-83ef-f882ed956d01",
"metadata": {},
"source": [
"# Instance Images"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bc2f8f28-226e-45b8-8257-804bbb711f56",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"Remove_existing_instance_images= True\n",
"\n",
"# Set to False to keep the existing instance images if any.\n",
"\n",
"\n",
"IMAGES_FOLDER_OPTIONAL=\"\"\n",
"\n",
"# If you prefer to specify directly the folder of the pictures instead of uploading, this will add the pictures to the existing (if any) instance images. Leave EMPTY to upload.\n",
"\n",
"\n",
"Smart_crop_images= True\n",
"\n",
"# Automatically crop your input images.\n",
"\n",
"\n",
"Crop_size = 768\n",
"\n",
"# Choices: \"512\", \"576\", \"640\", \"704\", \"768\", \"832\", \"896\", \"960\", \"1024\"\n",
"\n",
"# Check out this example for naming : https://i.imgur.com/d2lD3rz.jpeg\n",
"\n",
"\n",
"#-----------------\n",
"uplder(Remove_existing_instance_images, Smart_crop_images, Crop_size, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR, False)"
]
},
{
"cell_type": "markdown",
"id": "0e93924f-a6bf-45d5-aa77-915ad7385dcd",
"metadata": {},
"source": [
"# Manual Captioning"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c5dbcb29-b42f-4cfc-9be8-83355838d5a2",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"# Open a tool to manually caption the instance images.\n",
"\n",
"#-----------------\n",
"caption(CAPTIONS_DIR, INSTANCE_DIR)"
]
},
{
"cell_type": "markdown",
"id": "c90140c1-6c91-4cae-a222-e1a746957f95",
"metadata": {},
"source": [
"# Concept Images"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "55c27688-8601-4943-b61d-fc48b9ded067",
"metadata": {},
"outputs": [],
"source": [
"Remove_existing_concept_images= True\n",
"\n",
"# Set to False to keep the existing concept images if any.\n",
"\n",
"\n",
"IMAGES_FOLDER_OPTIONAL=\"\"\n",
"\n",
"# If you prefer to specify directly the folder of the pictures instead of uploading, this will add the pictures to the existing (if any) concept images. Leave EMPTY to upload.\n",
"\n",
"\n",
"#-----------------\n",
"uplder(Remove_existing_concept_images, True, 512, IMAGES_FOLDER_OPTIONAL, CONCEPT_DIR, CAPTIONS_DIR, True)"
]
},
{
"cell_type": "markdown",
"id": "2a4aa42a-fd68-41ad-9ba7-da99f834e2c1",
"metadata": {},
"source": [
"# Dreambooth"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "612d8335-b984-4f34-911d-5457ff98e507",
"metadata": {},
"outputs": [],
"source": [
"Resume_Training = False\n",
"\n",
"# If you're not satisfied with the result, Set to True, run again the cell and it will continue training the current model.\n",
"\n",
"\n",
"UNet_Training_Steps= 1500\n",
"\n",
"UNet_Learning_Rate= \"2e-6\"\n",
"\n",
"# If you use 10 images, use 650 steps, if you're not satisfied with the result, resume training for another 200 steps with a lower learning rate (8e-6), and so on ...\n",
"\n",
"\n",
"Text_Encoder_Training_Steps= 350\n",
"\n",
"Text_Encoder_Learning_Rate= \"1e-6\"\n",
"\n",
"# 350-600 steps is enough for a small dataset, keep this number small to avoid overfitting, set to 0 to disable, set it to 0 before resuming training if it is already trained.\n",
"\n",
"\n",
"Text_Encoder_Concept_Training_Steps= 0\n",
"\n",
"# Suitable for training a style/concept as it acts as regularization, with a minimum of 300 steps, 1 step/image is enough to train the concept(s), set to 0 to disable, set both the settings above to 0 to fintune only the text_encoder on the concept, set it to 0 before resuming training if it is already trained.\n",
"\n",
"\n",
"External_Captions= False\n",
"\n",
"# Get the captions from a text file for each instance image.\n",
"\n",
"\n",
"Offset_Noise= False\n",
"\n",
"# Always use it for style training.\n",
"\n",
"\n",
"Resolution = 768\n",
"\n",
"# Choices : \"512\", \"576\", \"640\", \"704\", \"768\", \"832\", \"896\", \"960\", \"1024\"\n",
"# Higher resolution = Higher quality, make sure the instance images are cropped to this selected size (or larger).\n",
"\n",
"#---------------------------------------------------------------\n",
"\n",
"Save_Checkpoint_Every_n_Steps= False\n",
"\n",
"Save_Checkpoint_Every= 500\n",
"\n",
"# Minimum 200 steps between each save.\n",
"\n",
"\n",
"Start_saving_from_the_step= 500\n",
"\n",
"# Start saving intermediary checkpoints from this step.\n",
"\n",
"\n",
"#-----------------\n",
"resumev2=dbtrainv2(Resume_Training, UNet_Training_Steps, UNet_Learning_Rate, Text_Encoder_Training_Steps, Text_Encoder_Concept_Training_Steps, Text_Encoder_Learning_Rate, Offset_Noise, Resolution, MODEL_NAMEv2, SESSION_DIR, INSTANCE_DIR, CONCEPT_DIR, CAPTIONS_DIR, External_Captions, INSTANCE_NAME, Session_Name, OUTPUT_DIR, PT, resumev2, Save_Checkpoint_Every_n_Steps, Start_saving_from_the_step, Save_Checkpoint_Every)"
]
},
{
"cell_type": "markdown",
"id": "bf6f2232-60b3-41c5-bea6-b0dcc4aef937",
"metadata": {},
"source": [
"# Test the Trained Model"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1263a084-b142-4e63-a0aa-2706673a4355",
"metadata": {},
"outputs": [],
"source": [
"Previous_Session_Name=\"\"\n",
"\n",
"# Leave empty if you want to use the current trained model.\n",
"\n",
"\n",
"Custom_Path = \"\"\n",
"\n",
"# Input the full path to a desired model.\n",
"\n",
"\n",
"User = \"\" \n",
"\n",
"Password= \"\"\n",
"\n",
"# Add credentials to your Gradio interface (optional).\n",
"\n",
"\n",
"Use_localtunnel = False\n",
"\n",
"# If you have trouble using Gradio server, use this one.\n",
"\n",
"\n",
"#-----------------\n",
"configf=test(Custom_Path, Previous_Session_Name, Session_Name, User, Password, Use_localtunnel) if 'Session_Name' in locals() else test(Custom_Path, Previous_Session_Name, \"\", User, Password, Use_localtunnel)\n",
"!python /notebooks/sd/stable-diffusion-webui/webui.py $configf"
]
},
{
"cell_type": "markdown",
"id": "53ccbcaf-3319-44f5-967b-ecbdfa9d0e78",
"metadata": {},
"source": [
"# Upload The Trained Model to Hugging Face"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2c9cb205-d828-4e51-9943-f337bd410ea8",
"metadata": {},
"outputs": [],
"source": [
"#Save it to your personal profile or collaborate to the public [library of concepts](https://huggingface.co/sd-dreambooth-library)\n",
"\n",
"Name_of_your_concept = \"\"\n",
"\n",
"# Leave empty if you want to name your concept the same as the current session.\n",
"\n",
"\n",
"hf_token_write = \"\"\n",
"\n",
"# Create a write access token here : https://huggingface.co/settings/tokens, go to \"New token\" -> Role : Write, a regular read token won't work here.\n",
"\n",
"\n",
"#---------------------------------\n",
"hfv2(Name_of_your_concept, Save_concept_to, hf_token_write, INSTANCE_NAME, OUTPUT_DIR, Session_Name, MDLPTH)"
]
},
{
"cell_type": "markdown",
"id": "881d80a3-4ebf-41bc-b68f-ac1cacb080f3",
"metadata": {},
"source": [
"# Free up space"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7403744d-cc45-419f-88ac-5475fa0f7f45",
"metadata": {},
"outputs": [],
"source": [
"# Display a list of sessions from which you can remove any session you don't need anymore\n",
"\n",
"#-------------------------\n",
"clean()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
}
},
"nbformat": 4,
"nbformat_minor": 5
}123---license: apache-2.0---123---license: cc-by-nc-4.0---
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478import os
from IPython.display import clear_output
from subprocess import call, getoutput, run
import time
import sys
import fileinput
import ipywidgets as widgets
from torch.hub import download_url_to_file
from urllib.parse import urlparse, parse_qs, unquote
import re
import requests
import six
from urllib.request import urlopen, Request
import tempfile
from tqdm import tqdm
def Deps(force_reinstall):
if not force_reinstall and os.path.exists('/usr/local/lib/python3.9/dist-packages/safetensors'):
ntbk()
os.environ['TORCH_HOME'] = '/notebooks/cache/torch'
os.environ['PYTHONWARNINGS'] = 'ignore'
print('[1;32mModules and notebooks updated, dependencies already installed')
else:
call("pip install --root-user-action=ignore --no-deps -q accelerate==0.12.0", shell=True, stdout=open('/dev/null', 'w'))
if not os.path.exists('/usr/local/lib/python3.9/dist-packages/safetensors'):
os.chdir('/usr/local/lib/python3.9/dist-packages')
call("rm -r torch torch-1.12.1+cu116.dist-info torchaudio* torchvision* PIL Pillow* transformers* numpy* gdown*", shell=True, stdout=open('/dev/null', 'w'))
ntbk()
if not os.path.exists('/models'):
call('mkdir /models', shell=True)
if not os.path.exists('/notebooks/models'):
call('ln -s /models /notebooks', shell=True)
if os.path.exists('/deps'):
call("rm -r /deps", shell=True)
call('mkdir /deps', shell=True)
if not os.path.exists('cache'):
call('mkdir cache', shell=True)
os.chdir('/deps')
call('wget -q -i https://raw.githubusercontent.com/TheLastBen/fast-stable-diffusion/main/Dependencies/aptdeps.txt', shell=True)
call('dpkg -i *.deb', shell=True, stdout=open('/dev/null', 'w'))
depsinst("https://huggingface.co/TheLastBen/dependencies/resolve/main/ppsdeps.tar.zst", "/deps/ppsdeps.tar.zst")
call('tar -C / --zstd -xf ppsdeps.tar.zst', shell=True, stdout=open('/dev/null', 'w'))
call("sed -i 's@~/.cache@/notebooks/cache@' /usr/local/lib/python3.9/dist-packages/transformers/utils/hub.py", shell=True)
os.chdir('/notebooks')
call("git clone --depth 1 -q --branch main https://github.com/TheLastBen/diffusers /diffusers", shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
os.environ['TORCH_HOME'] = '/notebooks/cache/torch'
os.environ['PYTHONWARNINGS'] = 'ignore'
call("sed -i 's@text = _formatwarnmsg(msg)@text =\"\"@g' /usr/lib/python3.9/warnings.py", shell=True)
if not os.path.exists('/notebooks/diffusers'):
call('ln -s /diffusers /notebooks', shell=True)
call("rm -r /deps", shell=True)
os.chdir('/notebooks')
clear_output()
done()
def depsinst(url, dst):
file_size = None
req = Request(url, headers={"User-Agent": "torch.hub"})
u = urlopen(req)
meta = u.info()
if hasattr(meta, 'getheaders'):
content_length = meta.getheaders("Content-Length")
else:
content_length = meta.get_all("Content-Length")
if content_length is not None and len(content_length) > 0:
file_size = int(content_length[0])
with tqdm(total=file_size, disable=False, mininterval=0.5,
bar_format='Installing dependencies |{bar:20}| {percentage:3.0f}%') as pbar:
with open(dst, "wb") as f:
while True:
buffer = u.read(8192)
if len(buffer) == 0:
break
f.write(buffer)
pbar.update(len(buffer))
f.close()
def dwn(url, dst, msg):
file_size = None
req = Request(url, headers={"User-Agent": "torch.hub"})
u = urlopen(req)
meta = u.info()
if hasattr(meta, 'getheaders'):
content_length = meta.getheaders("Content-Length")
else:
content_length = meta.get_all("Content-Length")
if content_length is not None and len(content_length) > 0:
file_size = int(content_length[0])
with tqdm(total=file_size, disable=False, mininterval=0.5,
bar_format=msg+' |{bar:20}| {percentage:3.0f}%') as pbar:
with open(dst, "wb") as f:
while True:
buffer = u.read(8192)
if len(buffer) == 0:
break
f.write(buffer)
pbar.update(len(buffer))
f.close()
def ntbk():
os.chdir('/notebooks')
if not os.path.exists('Latest_Notebooks'):
call('mkdir Latest_Notebooks', shell=True)
else:
call('rm -r Latest_Notebooks', shell=True)
call('mkdir Latest_Notebooks', shell=True)
os.chdir('/notebooks/Latest_Notebooks')
call('wget -q -i https://huggingface.co/datasets/TheLastBen/PPS/raw/main/Notebooks.txt', shell=True)
call('rm Notebooks.txt', shell=True)
os.chdir('/notebooks')
def repo():
print('[1;32mInstalling/Updating the repo...')
os.chdir('/notebooks')
if not os.path.exists('/notebooks/sd/stablediffusiond'): #reset later
call('wget -q -O sd_mrep.tar.zst https://huggingface.co/TheLastBen/dependencies/resolve/main/sd_mrep.tar.zst', shell=True)
call('tar --zstd -xf sd_mrep.tar.zst', shell=True)
call('rm sd_mrep.tar.zst', shell=True)
os.chdir('/notebooks/sd')
if not os.path.exists('stable-diffusion-webui'):
call('git clone -q --depth 1 --branch master https://github.com/AUTOMATIC1111/stable-diffusion-webui', shell=True)
os.chdir('/notebooks/sd/stable-diffusion-webui/')
call('git reset --hard', shell=True, stdout=open('/dev/null', 'w'))
print('[1;32m')
call('git checkout master', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('git pull', shell=True, stdout=open('/dev/null', 'w'))
os.makedirs('/notebooks/sd/stable-diffusion-webui/repositories', exist_ok=True)
call('git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui-assets /notebooks/sd/stable-diffusion-webui/repositories/stable-diffusion-webui-assets', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
os.chdir('/notebooks')
clear_output()
done()
def mdls(Original_Model_Version, Path_to_MODEL, MODEL_LINK, Temporary_Storage):
import gdown
src=getsrc(MODEL_LINK)
call('ln -s /datasets/stable-diffusion-classic/SDv1.5.ckpt /notebooks/sd/stable-diffusion-webui/models/Stable-diffusion', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('ln -s /datasets/stable-diffusion-v2-1-base-diffusers/stable-diffusion-2-1-base/v2-1_512-nonema-pruned.safetensors /notebooks/sd/stable-diffusion-webui/models/Stable-diffusion', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('ln -s /datasets/stable-diffusion-v2-1/stable-diffusion-2-1/v2-1_768-nonema-pruned.safetensors /notebooks/sd/stable-diffusion-webui/models/Stable-diffusion', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('ln -s /datasets/stable-diffusion-xl/sd_xl_base_1.0.safetensors /notebooks/sd/stable-diffusion-webui/models/Stable-diffusion', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
if Path_to_MODEL !='':
if os.path.exists(str(Path_to_MODEL)):
print('[1;32mUsing the custom model.')
model=Path_to_MODEL
else:
print('[1;31mWrong path, check that the path to the model is correct')
elif MODEL_LINK !="":
if src=='civitai':
modelname=get_name(MODEL_LINK, False)
if Temporary_Storage:
model=f'/models/{modelname}'
else:
model=f'/notebooks/sd/stable-diffusion-webui/models/Stable-diffusion/{modelname}'
if not os.path.exists(model):
dwn(MODEL_LINK, model, 'Downloading the custom model')
clear_output()
else:
print('[1;33mModel already exists')
elif src=='gdrive':
modelname=get_name(MODEL_LINK, True)
if Temporary_Storage:
model=f'/models/{modelname}'
else:
model=f'/notebooks/sd/stable-diffusion-webui/models/Stable-diffusion/{modelname}'
if not os.path.exists(model):
gdown.download(url=MODEL_LINK, output=model, quiet=False, fuzzy=True)
clear_output()
else:
print('[1;33mModel already exists')
else:
modelname=os.path.basename(MODEL_LINK)
if Temporary_Storage:
model=f'/models/{modelname}'
else:
model=f'/notebooks/sd/stable-diffusion-webui/models/Stable-diffusion/{modelname}'
if not os.path.exists(model):
gdown.download(url=MODEL_LINK, output=model, quiet=False, fuzzy=True)
clear_output()
else:
print('[1;33mModel already exists')
if os.path.exists(model) and os.path.getsize(model) > 1810671599:
print('[1;32mModel downloaded, using the custom model.')
else:
call('rm '+model, shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
print('[1;31mWrong link, check that the link is valid')
else:
if Original_Model_Version == "v1.5":
model="/notebooks/sd/stable-diffusion-webui/models/Stable-diffusion/SDv1.5.ckpt"
print('[1;32mUsing the original V1.5 model')
elif Original_Model_Version == "v2-512":
model="/notebooks/sd/stable-diffusion-webui/models/Stable-diffusion/v2-1_512-nonema-pruned.safetensors"
print('[1;32mUsing the original V2-512 model')
elif Original_Model_Version == "v2-768":
model="/notebooks/sd/stable-diffusion-webui/models/Stable-diffusion/v2-1_768-nonema-pruned.safetensors"
print('[1;32mUsing the original V2-768 model')
elif Original_Model_Version == "SDXL":
model="/notebooks/sd/stable-diffusion-webui/models/Stable-diffusion/sd_xl_base_1.0.safetensors"
print('[1;32mUsing the original SDXL model')
else:
model="/notebooks/sd/stable-diffusion-webui/models/Stable-diffusion"
print('[1;31mWrong model version, try again')
try:
model
except:
model="/notebooks/sd/stable-diffusion-webui/models/Stable-diffusion"
return model
def loradwn(LoRA_LINK):
import gdown
if LoRA_LINK=='':
print('[1;33mNothing to do')
else:
os.makedirs('/notebooks/sd/stable-diffusion-webui/models/Lora', exist_ok=True)
src=getsrc(LoRA_LINK)
if src=='civitai':
modelname=get_name(LoRA_LINK, False)
loramodel=f'/notebooks/sd/stable-diffusion-webui/models/Lora/{modelname}'
if not os.path.exists(loramodel):
dwn(LoRA_LINK, loramodel, 'Downloading the LoRA model')
clear_output()
else:
print('[1;33mModel already exists')
elif src=='gdrive':
modelname=get_name(LoRA_LINK, True)
loramodel=f'/notebooks/sd/stable-diffusion-webui/models/Lora/{modelname}'
if not os.path.exists(loramodel):
gdown.download(url=LoRA_LINK, output=loramodel, quiet=False, fuzzy=True)
clear_output()
else:
print('[1;33mModel already exists')
else:
modelname=os.path.basename(LoRA_LINK)
loramodel=f'/notebooks/sd/stable-diffusion-webui/models/Lora/{modelname}'
if not os.path.exists(loramodel):
gdown.download(url=LoRA_LINK, output=loramodel, quiet=False, fuzzy=True)
clear_output()
else:
print('[1;33mModel already exists')
if os.path.exists(loramodel) :
print('[1;32mLoRA downloaded')
else:
print('[1;31mWrong link, check that the link is valid')
def CN(ControlNet_Model, ControlNet_XL_Model):
def download(url, model_dir):
filename = os.path.basename(urlparse(url).path)
pth = os.path.abspath(os.path.join(model_dir, filename))
if not os.path.exists(pth):
print('Downloading: '+os.path.basename(url))
download_url_to_file(url, pth, hash_prefix=None, progress=True)
else:
print(f"[1;32mThe model {filename} already exists[0m")
wrngv1=False
os.chdir('/notebooks/sd/stable-diffusion-webui/extensions')
if not os.path.exists("sd-webui-controlnet"):
call('git clone https://github.com/Mikubill/sd-webui-controlnet.git', shell=True)
os.chdir('/notebooks')
else:
os.chdir('sd-webui-controlnet')
call('git reset --hard', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('git pull', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
os.chdir('/notebooks')
mdldir="/notebooks/sd/stable-diffusion-webui/extensions/sd-webui-controlnet/models"
for filename in os.listdir(mdldir):
if "_sd14v1" in filename:
renamed = re.sub("_sd14v1", "-fp16", filename)
os.rename(os.path.join(mdldir, filename), os.path.join(mdldir, renamed))
call('wget -q -O CN_models.txt https://github.com/TheLastBen/fast-stable-diffusion/raw/main/AUTOMATIC1111_files/CN_models.txt', shell=True)
call('wget -q -O CN_models_XL.txt https://github.com/TheLastBen/fast-stable-diffusion/raw/main/AUTOMATIC1111_files/CN_models_XL.txt', shell=True)
with open("CN_models.txt", 'r') as f:
mdllnk = f.read().splitlines()
with open("CN_models_XL.txt", 'r') as d:
mdllnk_XL = d.read().splitlines()
call('rm CN_models.txt CN_models_XL.txt', shell=True)
os.chdir('/notebooks')
if ControlNet_Model == "All" or ControlNet_Model == "all" :
for lnk in mdllnk:
download(lnk, mdldir)
clear_output()
elif ControlNet_Model == "15":
mdllnk=list(filter(lambda x: 't2i' in x, mdllnk))
for lnk in mdllnk:
download(lnk, mdldir)
clear_output()
elif ControlNet_Model.isdigit() and int(ControlNet_Model)-1<14 and int(ControlNet_Model)>0:
download(mdllnk[int(ControlNet_Model)-1], mdldir)
clear_output()
elif ControlNet_Model == "none":
pass
clear_output()
else:
print('[1;31mWrong ControlNet V1 choice, try again')
wrngv1=True
if ControlNet_XL_Model == "All" or ControlNet_XL_Model == "all" :
for lnk_XL in mdllnk_XL:
download(lnk_XL, mdldir)
if not wrngv1:
clear_output()
done()
elif ControlNet_XL_Model.isdigit() and int(ControlNet_XL_Model)-1<5:
download(mdllnk_XL[int(ControlNet_XL_Model)-1], mdldir)
if not wrngv1:
clear_output()
done()
elif ControlNet_XL_Model == "none":
pass
if not wrngv1:
clear_output()
done()
else:
print('[1;31mWrong ControlNet XL choice, try again')
def sdui(User, Password, model):
auth=f"--gradio-auth {User}:{Password}"
if User =="" or Password=="":
auth=""
call('wget -q -O /notebooks/sd/stable-diffusion-webui/modules/styles.py https://github.com/TheLastBen/fast-stable-diffusion/raw/main/AUTOMATIC1111_files/styles.py', shell=True)
call('wget -q -O /usr/local/lib/python3.9/dist-packages/gradio/blocks.py https://raw.githubusercontent.com/TheLastBen/fast-stable-diffusion/main/AUTOMATIC1111_files/blocks.py', shell=True)
localurl="tensorboard-"+os.environ.get('PAPERSPACE_FQDN')
for line in fileinput.input('/usr/local/lib/python3.9/dist-packages/gradio/blocks.py', inplace=True):
if line.strip().startswith('self.server_name ='):
line = f' self.server_name = "{localurl}"\n'
if line.strip().startswith('self.protocol = "https"'):
line = ' self.protocol = "https"\n'
if line.strip().startswith('if self.local_url.startswith("https") or self.is_colab'):
line = ''
if line.strip().startswith('else "http"'):
line = ''
sys.stdout.write(line)
os.chdir('/notebooks/sd/stable-diffusion-webui/modules')
call("sed -i 's@possible_sd_paths =.*@possible_sd_paths = [\"/notebooks/sd/stablediffusion\"]@' /notebooks/sd/stable-diffusion-webui/modules/paths.py", shell=True)
call("sed -i 's@\.\.\/@src/@g' /notebooks/sd/stable-diffusion-webui/modules/paths.py", shell=True)
call("sed -i 's@src\/generative-models@generative-models@g' /notebooks/sd/stable-diffusion-webui/modules/paths.py", shell=True)
call("sed -i 's@-> Network | None@@g' /notebooks/sd/stable-diffusion-webui/extensions-builtin/Lora/network.py", shell=True)
call("sed -i 's@|@or@' /notebooks/sd/stable-diffusion-webui/extensions/adetailer/aaaaaa/helper.py", shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call("sed -i 's@\"quicksettings\": OptionInfo(.*@\"quicksettings\": OptionInfo(\"sd_model_checkpoint, sd_vae, CLIP_stop_at_last_layers, inpainting_mask_weight, initial_noise_multiplier\", \"Quicksettings list\"),@' /notebooks/sd/stable-diffusion-webui/modules/shared.py", shell=True)
os.chdir('/notebooks/sd/stable-diffusion-webui')
clear_output()
if model=="":
mdlpth=""
else:
if os.path.isfile(model):
mdlpth="--ckpt "+model
else:
mdlpth="--ckpt-dir "+model
configf="--disable-console-progressbars --no-gradio-queue --no-hashing --no-half-vae --disable-safe-unpickle --api --no-download-sd-model --xformers --enable-insecure-extension-access --port 6006 --listen --skip-version-check --ckpt-dir /models "+auth+" "+mdlpth
return configf
def getsrc(url):
parsed_url = urlparse(url)
if parsed_url.netloc == 'civitai.com':
src='civitai'
elif parsed_url.netloc == 'drive.google.com':
src='gdrive'
elif parsed_url.netloc == 'huggingface.co':
src='huggingface'
else:
src='others'
return src
def get_name(url, gdrive):
from gdown.download import get_url_from_gdrive_confirmation
if not gdrive:
response = requests.get(url, allow_redirects=False)
if "Location" in response.headers:
redirected_url = response.headers["Location"]
quer = parse_qs(urlparse(redirected_url).query)
if "response-content-disposition" in quer:
disp_val = quer["response-content-disposition"][0].split(";")
for vals in disp_val:
if vals.strip().startswith("filename="):
filenm=unquote(vals.split("=", 1)[1].strip())
return filenm.replace("\"","")
else:
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"}
lnk="https://drive.google.com/uc?id={id}&export=download".format(id=url[url.find("/d/")+3:url.find("/view")])
res = requests.session().get(lnk, headers=headers, stream=True, verify=True)
res = requests.session().get(get_url_from_gdrive_confirmation(res.text), headers=headers, stream=True, verify=True)
content_disposition = six.moves.urllib_parse.unquote(res.headers["Content-Disposition"])
filenm = re.search(r"filename\*=UTF-8''(.*)", content_disposition).groups()[0].replace(os.path.sep, "_")
return filenm
def done():
done = widgets.Button(
description='Done!',
disabled=True,
button_style='success',
tooltip='',
icon='check'
)
display(done)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471import os
from IPython.display import clear_output
from subprocess import call, getoutput, run
import time
import sys
import fileinput
import ipywidgets as widgets
from torch.hub import download_url_to_file
from urllib.parse import urlparse, parse_qs, unquote
import re
import requests
import six
from urllib.request import urlopen, Request
import tempfile
from tqdm import tqdm
def Deps(force_reinstall):
if not force_reinstall and os.path.exists('/usr/local/lib/python3.11/dist-packages/gradio'):
ntbk()
os.environ['TORCH_HOME'] = '/notebooks/cache/torch'
os.environ['PYTHONWARNINGS'] = 'ignore'
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
print('[1;32mModules and notebooks updated, dependencies already installed')
else:
call("pip install --root-user-action=ignore --no-deps -q accelerate==0.12.0", shell=True, stdout=open('/dev/null', 'w'))
call("pip uninstall -qq deepspeed -y", shell=True, stdout=open('/dev/null', 'w'))
ntbk()
if not os.path.exists('/models'):
call('mkdir /models', shell=True)
if not os.path.exists('/notebooks/models'):
call('ln -s /models /notebooks', shell=True)
if os.path.exists('/deps'):
call("rm -r /deps", shell=True)
call('mkdir /deps', shell=True)
if not os.path.exists('cache'):
call('mkdir cache', shell=True)
os.chdir('/deps')
call('wget -q -i https://raw.githubusercontent.com/TheLastBen/fast-stable-diffusion/main/Dependencies/aptdeps_311.txt', shell=True)
call('dpkg -i *.deb', shell=True, stdout=open('/dev/null', 'w'))
depsinst("https://huggingface.co/TheLastBen/dependencies/resolve/main/ppsdeps_311.tar.zst", "/deps/ppsdeps_311.tar.zst")
call('tar -C / --zstd -xf ppsdeps_311.tar.zst', shell=True, stdout=open('/dev/null', 'w'))
os.chdir('/notebooks')
call("git clone --depth 1 -q --branch main https://github.com/TheLastBen/diffusers /diffusers", shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
os.environ['TORCH_HOME'] = '/notebooks/cache/torch'
os.environ['PYTHONWARNINGS'] = 'ignore'
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
call("sed -i 's@text = _formatwarnmsg(msg)@text =\"\"@g' /usr/lib/python3.11/warnings.py", shell=True)
if not os.path.exists('/notebooks/diffusers'):
call('ln -s /diffusers /notebooks', shell=True)
call("rm -r /deps", shell=True)
os.chdir('/notebooks')
clear_output()
done()
def depsinst(url, dst):
file_size = None
req = Request(url, headers={"User-Agent": "torch.hub"})
u = urlopen(req)
meta = u.info()
if hasattr(meta, 'getheaders'):
content_length = meta.getheaders("Content-Length")
else:
content_length = meta.get_all("Content-Length")
if content_length is not None and len(content_length) > 0:
file_size = int(content_length[0])
with tqdm(total=file_size, disable=False, mininterval=0.5,
bar_format='(fast-stable-diffusion will soon stop supporting Paperspace) Installing dependencies |{bar:20}| {percentage:3.0f}%') as pbar:
with open(dst, "wb") as f:
while True:
buffer = u.read(8192)
if len(buffer) == 0:
break
f.write(buffer)
pbar.update(len(buffer))
f.close()
def dwn(url, dst, msg):
file_size = None
req = Request(url, headers={"User-Agent": "torch.hub"})
u = urlopen(req)
meta = u.info()
if hasattr(meta, 'getheaders'):
content_length = meta.getheaders("Content-Length")
else:
content_length = meta.get_all("Content-Length")
if content_length is not None and len(content_length) > 0:
file_size = int(content_length[0])
with tqdm(total=file_size, disable=False, mininterval=0.5,
bar_format=msg+' |{bar:20}| {percentage:3.0f}%') as pbar:
with open(dst, "wb") as f:
while True:
buffer = u.read(8192)
if len(buffer) == 0:
break
f.write(buffer)
pbar.update(len(buffer))
f.close()
def ntbk():
os.chdir('/notebooks')
if not os.path.exists('Latest_Notebooks'):
call('mkdir Latest_Notebooks', shell=True)
else:
call('rm -r Latest_Notebooks', shell=True)
call('mkdir Latest_Notebooks', shell=True)
os.chdir('/notebooks/Latest_Notebooks')
call('wget -q -i https://huggingface.co/datasets/TheLastBen/PPS/raw/main/Notebooks.txt', shell=True)
call('rm Notebooks.txt', shell=True)
os.chdir('/notebooks')
def repo():
print('[1;32mInstalling/Updating the repo...')
os.chdir('/notebooks')
if not os.path.exists('/notebooks/sd/stablediffusion'):
call('wget -q -O sd_mrep.tar.zst https://huggingface.co/TheLastBen/dependencies/resolve/main/sd_mrep.tar.zst', shell=True)
call('tar --zstd -xf sd_mrep.tar.zst', shell=True)
call('rm sd_mrep.tar.zst', shell=True)
os.chdir('/notebooks/sd')
if not os.path.exists('stable-diffusion-webui'):
call('git clone -q --depth 1 --branch master https://github.com/AUTOMATIC1111/stable-diffusion-webui', shell=True)
os.chdir('/notebooks/sd/stable-diffusion-webui/')
call('git reset --hard', shell=True, stdout=open('/dev/null', 'w'))
print('[1;32m')
call('git checkout master', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('git pull', shell=True, stdout=open('/dev/null', 'w'))
os.makedirs('/notebooks/sd/stable-diffusion-webui/repositories', exist_ok=True)
call('git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui-assets /notebooks/sd/stable-diffusion-webui/repositories/stable-diffusion-webui-assets', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
os.chdir('/notebooks')
clear_output()
done()
def mdls(Original_Model_Version, Path_to_MODEL, MODEL_LINK, Temporary_Storage):
import gdown
src=getsrc(MODEL_LINK)
call('ln -s /datasets/stable-diffusion-classic/SDv1.5.ckpt /notebooks/sd/stable-diffusion-webui/models/Stable-diffusion', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('ln -s /datasets/stable-diffusion-v2-1-base-diffusers/stable-diffusion-2-1-base/v2-1_512-nonema-pruned.safetensors /notebooks/sd/stable-diffusion-webui/models/Stable-diffusion', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('ln -s /datasets/stable-diffusion-v2-1/stable-diffusion-2-1/v2-1_768-nonema-pruned.safetensors /notebooks/sd/stable-diffusion-webui/models/Stable-diffusion', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('ln -s /datasets/stable-diffusion-xl/sd_xl_base_1.0.safetensors /notebooks/sd/stable-diffusion-webui/models/Stable-diffusion', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
if Path_to_MODEL !='':
if os.path.exists(str(Path_to_MODEL)):
print('[1;32mUsing the custom model.')
model=Path_to_MODEL
else:
print('[1;31mWrong path, check that the path to the model is correct')
elif MODEL_LINK !="":
if src=='civitai':
modelname=get_name(MODEL_LINK, False)
if Temporary_Storage:
model=f'/models/{modelname}'
else:
model=f'/notebooks/sd/stable-diffusion-webui/models/Stable-diffusion/{modelname}'
if not os.path.exists(model):
dwn(MODEL_LINK, model, 'Downloading the custom model')
clear_output()
else:
print('[1;33mModel already exists')
elif src=='gdrive':
modelname=get_name(MODEL_LINK, True)
if Temporary_Storage:
model=f'/models/{modelname}'
else:
model=f'/notebooks/sd/stable-diffusion-webui/models/Stable-diffusion/{modelname}'
if not os.path.exists(model):
gdown.download(url=MODEL_LINK, output=model, quiet=False, fuzzy=True)
clear_output()
else:
print('[1;33mModel already exists')
else:
modelname=os.path.basename(MODEL_LINK)
if Temporary_Storage:
model=f'/models/{modelname}'
else:
model=f'/notebooks/sd/stable-diffusion-webui/models/Stable-diffusion/{modelname}'
if not os.path.exists(model):
gdown.download(url=MODEL_LINK, output=model, quiet=False, fuzzy=True)
clear_output()
else:
print('[1;33mModel already exists')
if os.path.exists(model) and os.path.getsize(model) > 1810671599:
print('[1;32mModel downloaded, using the custom model.')
else:
call('rm '+model, shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
print('[1;31mWrong link, check that the link is valid')
else:
if Original_Model_Version == "v1.5":
model="/notebooks/sd/stable-diffusion-webui/models/Stable-diffusion/SDv1.5.ckpt"
print('[1;32mUsing the original V1.5 model')
elif Original_Model_Version == "v2-512":
model="/notebooks/sd/stable-diffusion-webui/models/Stable-diffusion/v2-1_512-nonema-pruned.safetensors"
print('[1;32mUsing the original V2-512 model')
elif Original_Model_Version == "v2-768":
model="/notebooks/sd/stable-diffusion-webui/models/Stable-diffusion/v2-1_768-nonema-pruned.safetensors"
print('[1;32mUsing the original V2-768 model')
elif Original_Model_Version == "SDXL":
model="/notebooks/sd/stable-diffusion-webui/models/Stable-diffusion/sd_xl_base_1.0.safetensors"
print('[1;32mUsing the original SDXL model')
else:
model="/notebooks/sd/stable-diffusion-webui/models/Stable-diffusion"
print('[1;31mWrong model version, try again')
try:
model
except:
model="/notebooks/sd/stable-diffusion-webui/models/Stable-diffusion"
return model
def loradwn(LoRA_LINK):
import gdown
if LoRA_LINK=='':
print('[1;33mNothing to do')
else:
os.makedirs('/notebooks/sd/stable-diffusion-webui/models/Lora', exist_ok=True)
src=getsrc(LoRA_LINK)
if src=='civitai':
modelname=get_name(LoRA_LINK, False)
loramodel=f'/notebooks/sd/stable-diffusion-webui/models/Lora/{modelname}'
if not os.path.exists(loramodel):
dwn(LoRA_LINK, loramodel, 'Downloading the LoRA model')
clear_output()
else:
print('[1;33mModel already exists')
elif src=='gdrive':
modelname=get_name(LoRA_LINK, True)
loramodel=f'/notebooks/sd/stable-diffusion-webui/models/Lora/{modelname}'
if not os.path.exists(loramodel):
gdown.download(url=LoRA_LINK, output=loramodel, quiet=False, fuzzy=True)
clear_output()
else:
print('[1;33mModel already exists')
else:
modelname=os.path.basename(LoRA_LINK)
loramodel=f'/notebooks/sd/stable-diffusion-webui/models/Lora/{modelname}'
if not os.path.exists(loramodel):
gdown.download(url=LoRA_LINK, output=loramodel, quiet=False, fuzzy=True)
clear_output()
else:
print('[1;33mModel already exists')
if os.path.exists(loramodel) :
print('[1;32mLoRA downloaded')
else:
print('[1;31mWrong link, check that the link is valid')
def CN(ControlNet_Model, ControlNet_XL_Model):
def download(url, model_dir):
filename = os.path.basename(urlparse(url).path)
pth = os.path.abspath(os.path.join(model_dir, filename))
if not os.path.exists(pth):
print('Downloading: '+os.path.basename(url))
download_url_to_file(url, pth, hash_prefix=None, progress=True)
else:
print(f"[1;32mThe model {filename} already exists[0m")
wrngv1=False
os.chdir('/notebooks/sd/stable-diffusion-webui/extensions')
if not os.path.exists("sd-webui-controlnet"):
call('git clone https://github.com/Mikubill/sd-webui-controlnet.git', shell=True)
os.chdir('/notebooks')
else:
os.chdir('sd-webui-controlnet')
call('git reset --hard', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('git pull', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
os.chdir('/notebooks')
mdldir="/notebooks/sd/stable-diffusion-webui/extensions/sd-webui-controlnet/models"
for filename in os.listdir(mdldir):
if "_sd14v1" in filename:
renamed = re.sub("_sd14v1", "-fp16", filename)
os.rename(os.path.join(mdldir, filename), os.path.join(mdldir, renamed))
call('wget -q -O CN_models.txt https://github.com/TheLastBen/fast-stable-diffusion/raw/main/AUTOMATIC1111_files/CN_models.txt', shell=True)
call('wget -q -O CN_models_XL.txt https://github.com/TheLastBen/fast-stable-diffusion/raw/main/AUTOMATIC1111_files/CN_models_XL.txt', shell=True)
with open("CN_models.txt", 'r') as f:
mdllnk = f.read().splitlines()
with open("CN_models_XL.txt", 'r') as d:
mdllnk_XL = d.read().splitlines()
call('rm CN_models.txt CN_models_XL.txt', shell=True)
os.chdir('/notebooks')
if ControlNet_Model == "All" or ControlNet_Model == "all" :
for lnk in mdllnk:
download(lnk, mdldir)
clear_output()
elif ControlNet_Model == "15":
mdllnk=list(filter(lambda x: 't2i' in x, mdllnk))
for lnk in mdllnk:
download(lnk, mdldir)
clear_output()
elif ControlNet_Model.isdigit() and int(ControlNet_Model)-1<14 and int(ControlNet_Model)>0:
download(mdllnk[int(ControlNet_Model)-1], mdldir)
clear_output()
elif ControlNet_Model == "none":
pass
clear_output()
else:
print('[1;31mWrong ControlNet V1 choice, try again')
wrngv1=True
if ControlNet_XL_Model == "All" or ControlNet_XL_Model == "all" :
for lnk_XL in mdllnk_XL:
download(lnk_XL, mdldir)
if not wrngv1:
clear_output()
done()
elif ControlNet_XL_Model.isdigit() and int(ControlNet_XL_Model)-1<5:
download(mdllnk_XL[int(ControlNet_XL_Model)-1], mdldir)
if not wrngv1:
clear_output()
done()
elif ControlNet_XL_Model == "none":
pass
if not wrngv1:
clear_output()
done()
else:
print('[1;31mWrong ControlNet XL choice, try again')
def sdui(User, Password, model):
auth=f"--gradio-auth {User}:{Password}"
if User =="" or Password=="":
auth=""
call('wget -q -O /usr/local/lib/python3.11/dist-packages/gradio/blocks.py https://raw.githubusercontent.com/TheLastBen/fast-stable-diffusion/main/AUTOMATIC1111_files/blocks.py', shell=True)
localurl="tensorboard-"+os.environ.get('PAPERSPACE_FQDN')
for line in fileinput.input('/usr/local/lib/python3.11/dist-packages/gradio/blocks.py', inplace=True):
if line.strip().startswith('self.server_name ='):
line = f' self.server_name = "{localurl}"\n'
if line.strip().startswith('self.protocol = "https"'):
line = ' self.protocol = "https"\n'
if line.strip().startswith('if self.local_url.startswith("https") or self.is_colab'):
line = ''
if line.strip().startswith('else "http"'):
line = ''
sys.stdout.write(line)
os.chdir('/notebooks/sd/stable-diffusion-webui/modules')
call("sed -i 's@possible_sd_paths =.*@possible_sd_paths = [\"/notebooks/sd/stablediffusion\"]@' /notebooks/sd/stable-diffusion-webui/modules/paths.py", shell=True)
call("sed -i 's@\.\.\/@src/@g' /notebooks/sd/stable-diffusion-webui/modules/paths.py", shell=True)
call("sed -i 's@src\/generative-models@generative-models@g' /notebooks/sd/stable-diffusion-webui/modules/paths.py", shell=True)
os.chdir('/notebooks/sd/stable-diffusion-webui')
clear_output()
if model=="":
mdlpth=""
else:
if os.path.isfile(model):
mdlpth="--ckpt "+model
else:
mdlpth="--ckpt-dir "+model
configf="--disable-console-progressbars --no-gradio-queue --no-hashing --no-half-vae --disable-safe-unpickle --api --no-download-sd-model --xformers --enable-insecure-extension-access --port 6006 --listen --skip-version-check --ckpt-dir /models "+auth+" "+mdlpth
return configf
def getsrc(url):
parsed_url = urlparse(url)
if parsed_url.netloc == 'civitai.com':
src='civitai'
elif parsed_url.netloc == 'drive.google.com':
src='gdrive'
elif parsed_url.netloc == 'huggingface.co':
src='huggingface'
else:
src='others'
return src
def get_name(url, gdrive):
from gdown.download import get_url_from_gdrive_confirmation
if not gdrive:
response = requests.get(url, allow_redirects=False)
if "Location" in response.headers:
redirected_url = response.headers["Location"]
quer = parse_qs(urlparse(redirected_url).query)
if "response-content-disposition" in quer:
disp_val = quer["response-content-disposition"][0].split(";")
for vals in disp_val:
if vals.strip().startswith("filename="):
filenm=unquote(vals.split("=", 1)[1].strip())
return filenm.replace("\"","")
else:
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"}
lnk="https://drive.google.com/uc?id={id}&export=download".format(id=url[url.find("/d/")+3:url.find("/view")])
res = requests.session().get(lnk, headers=headers, stream=True, verify=True)
res = requests.session().get(get_url_from_gdrive_confirmation(res.text), headers=headers, stream=True, verify=True)
content_disposition = six.moves.urllib_parse.unquote(res.headers["Content-Disposition"])
filenm = re.search(r"filename\*=UTF-8''(.*)", content_disposition).groups()[0].replace(os.path.sep, "_")
return filenm
def done():
done = widgets.Button(
description='Done!',
disabled=True,
button_style='success',
tooltip='',
icon='check'
)
display(done)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337from IPython.display import clear_output
from subprocess import call, getoutput
from IPython.display import display
import ipywidgets as widgets
import io
from PIL import Image, ImageDraw, ImageOps
import fileinput
import time
import os
from os import listdir
from os.path import isfile
from tqdm import tqdm
import gdown
import random
import sys
import cv2
from io import BytesIO
import requests
from collections import defaultdict
from math import log, sqrt
import numpy as np
import six
import re
from urllib.parse import urlparse, parse_qs, unquote
from urllib.request import urlopen, Request
import tempfile
from tqdm import tqdm
def Deps(force_reinstall):
if not force_reinstall and os.path.exists('/usr/local/lib/python3.9/dist-packages/safetensors'):
ntbk()
call('pip install --root-user-action=ignore --disable-pip-version-check -qq ./diffusers', shell=True, stdout=open('/dev/null', 'w'))
os.environ['TORCH_HOME'] = '/notebooks/cache/torch'
os.environ['PYTHONWARNINGS'] = 'ignore'
print('[1;32mModules and notebooks updated, dependencies already installed')
else:
call("pip install --root-user-action=ignore --no-deps -q accelerate==0.12.0", shell=True, stdout=open('/dev/null', 'w'))
if not os.path.exists('/usr/local/lib/python3.9/dist-packages/safetensors'):
os.chdir('/usr/local/lib/python3.9/dist-packages')
call("rm -r torch torch-1.12.1+cu116.dist-info torchaudio* torchvision* PIL Pillow* transformers* numpy* gdown*", shell=True, stdout=open('/dev/null', 'w'))
ntbk()
if not os.path.exists('/models'):
call('mkdir /models', shell=True)
if not os.path.exists('/notebooks/models'):
call('ln -s /models /notebooks', shell=True)
if os.path.exists('/deps'):
call("rm -r /deps", shell=True)
call('mkdir /deps', shell=True)
if not os.path.exists('cache'):
call('mkdir cache', shell=True)
os.chdir('/deps')
call('wget -q -i https://raw.githubusercontent.com/TheLastBen/fast-stable-diffusion/main/Dependencies/aptdeps.txt', shell=True)
call('dpkg -i *.deb', shell=True, stdout=open('/dev/null', 'w'))
depsinst("https://huggingface.co/TheLastBen/dependencies/resolve/main/ppsdeps.tar.zst", "/deps/ppsdeps.tar.zst")
call('tar -C / --zstd -xf ppsdeps.tar.zst', shell=True, stdout=open('/dev/null', 'w'))
call("sed -i 's@~/.cache@/notebooks/cache@' /usr/local/lib/python3.9/dist-packages/transformers/utils/hub.py", shell=True)
os.chdir('/notebooks')
call("git clone --depth 1 -q --branch main https://github.com/TheLastBen/diffusers /diffusers", shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
os.environ['TORCH_HOME'] = '/notebooks/cache/torch'
os.environ['PYTHONWARNINGS'] = 'ignore'
call("sed -i 's@text = _formatwarnmsg(msg)@text =\"\"@g' /usr/lib/python3.9/warnings.py", shell=True)
if not os.path.exists('/notebooks/diffusers'):
call('ln -s /diffusers /notebooks', shell=True)
call("rm -r /deps", shell=True)
os.chdir('/notebooks')
clear_output()
done()
def depsinst(url, dst):
file_size = None
req = Request(url, headers={"User-Agent": "torch.hub"})
u = urlopen(req)
meta = u.info()
if hasattr(meta, 'getheaders'):
content_length = meta.getheaders("Content-Length")
else:
content_length = meta.get_all("Content-Length")
if content_length is not None and len(content_length) > 0:
file_size = int(content_length[0])
with tqdm(total=file_size, disable=False, mininterval=0.5,
bar_format='Installing dependencies |{bar:20}| {percentage:3.0f}%') as pbar:
with open(dst, "wb") as f:
while True:
buffer = u.read(8192)
if len(buffer) == 0:
break
f.write(buffer)
pbar.update(len(buffer))
f.close()
def ntbk():
os.chdir('/notebooks')
if not os.path.exists('Latest_Notebooks'):
call('mkdir Latest_Notebooks', shell=True)
else:
call('rm -r Latest_Notebooks', shell=True)
call('mkdir Latest_Notebooks', shell=True)
os.chdir('/notebooks/Latest_Notebooks')
call('wget -q -i https://huggingface.co/datasets/TheLastBen/PPS/raw/main/Notebooks.txt', shell=True)
call('rm Notebooks.txt', shell=True)
os.chdir('/notebooks')
def downloadmodel_hf(Path_to_HuggingFace):
import wget
if os.path.exists('/models/stable-diffusion-custom'):
call("rm -r /models/stable-diffusion-custom", shell=True)
clear_output()
if os.path.exists('/notebooks/Fast-Dreambooth/token.txt'):
with open("/notebooks/Fast-Dreambooth/token.txt") as f:
token = f.read()
authe=f'https://USER:{token}@'
else:
authe="https://"
clear_output()
call("mkdir /models/stable-diffusion-custom", shell=True)
os.chdir("/models/stable-diffusion-custom")
call("git init", shell=True)
call("git lfs install --system --skip-repo", shell=True)
call('git remote add -f origin '+authe+'huggingface.co/'+Path_to_HuggingFace, shell=True)
call("git config core.sparsecheckout true", shell=True)
call('echo -e "\nscheduler\ntext_encoder\ntokenizer\nunet\nvae\nmodel_index.json\n!*.safetensors" > .git/info/sparse-checkout', shell=True)
call("git pull origin main", shell=True)
if os.path.exists('unet/diffusion_pytorch_model.bin'):
call("rm -r .git", shell=True)
call("rm model_index.json", shell=True)
wget.download('https://raw.githubusercontent.com/TheLastBen/fast-stable-diffusion/main/Dreambooth/model_index.json')
os.chdir('/notebooks')
clear_output()
done()
while not os.path.exists('/models/stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
print('[1;31mCheck the link you provided')
os.chdir('/notebooks')
time.sleep(5)
def downloadmodel_path(MODEL_PATH):
modelname=os.path.basename(MODEL_PATH)
sftnsr=""
if modelname.split('.')[-1]=='safetensors':
sftnsr="--from_safetensors"
import wget
os.chdir('/notebooks')
clear_output()
if os.path.exists(str(MODEL_PATH)):
call('wget -q -O config.yaml https://github.com/CompVis/stable-diffusion/raw/main/configs/stable-diffusion/v1-inference.yaml', shell=True)
call('python /diffusers/scripts/convert_original_stable_diffusion_to_diffusers.py --checkpoint_path '+MODEL_PATH+' --dump_path /models/stable-diffusion-custom --original_config_file config.yaml '+sftnsr, shell=True)
clear_output()
call('rm config.yaml', shell=True)
if os.path.exists('/models/stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
clear_output()
done()
while not os.path.exists('/models/stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
print('[1;31mConversion error')
time.sleep(5)
else:
while not os.path.exists(str(MODEL_PATH)):
print('[1;31mWrong path, use the file explorer to copy the path')
time.sleep(5)
def downloadmodel_link(MODEL_LINK):
import wget
import gdown
from gdown.download import get_url_from_gdrive_confirmation
def getsrc(url):
parsed_url = urlparse(url)
if parsed_url.netloc == 'civitai.com':
src='civitai'
elif parsed_url.netloc == 'drive.google.com':
src='gdrive'
elif parsed_url.netloc == 'huggingface.co':
src='huggingface'
else:
src='others'
return src
src=getsrc(MODEL_LINK)
def get_name(url, gdrive):
if not gdrive:
response = requests.get(url, allow_redirects=False)
if "Location" in response.headers:
redirected_url = response.headers["Location"]
quer = parse_qs(urlparse(redirected_url).query)
if "response-content-disposition" in quer:
disp_val = quer["response-content-disposition"][0].split(";")
for vals in disp_val:
if vals.strip().startswith("filename="):
filenm=unquote(vals.split("=", 1)[1].strip())
return filenm.replace("\"","")
else:
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"}
lnk="https://drive.google.com/uc?id={id}&export=download".format(id=url[url.find("/d/")+3:url.find("/view")])
res = requests.session().get(lnk, headers=headers, stream=True, verify=True)
res = requests.session().get(get_url_from_gdrive_confirmation(res.text), headers=headers, stream=True, verify=True)
content_disposition = six.moves.urllib_parse.unquote(res.headers["Content-Disposition"])
filenm = re.search(r"filename\*=UTF-8''(.*)", content_disposition).groups()[0].replace(os.path.sep, "_")
return filenm
if src=='civitai':
modelname=get_name(MODEL_LINK, False)
elif src=='gdrive':
modelname=get_name(MODEL_LINK, True)
else:
modelname=os.path.basename(MODEL_LINK)
sftnsr=""
if modelname.split('.')[-1]!='safetensors':
modelnm="model.ckpt"
else:
modelnm="model.safetensors"
sftnsr="--from_safetensors"
os.chdir('/notebooks')
call("gdown --fuzzy " +MODEL_LINK+ " -O "+modelnm, shell=True)
if os.path.exists(modelnm):
if os.path.getsize(modelnm) > 1810671599:
call('wget -q -O config.yaml https://github.com/CompVis/stable-diffusion/raw/main/configs/stable-diffusion/v1-inference.yaml', shell=True)
call('python /diffusers/scripts/convert_original_stable_diffusion_to_diffusers.py --checkpoint_path '+modelnm+' --dump_path /models/stable-diffusion-custom --original_config_file config.yaml '+sftnsr, shell=True)
clear_output()
call('rm config.yaml', shell=True)
if os.path.exists('/models/stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
call('rm '+modelnm, shell=True)
clear_output()
done()
else:
while not os.path.exists('/models/stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
print('[1;31mConversion error')
time.sleep(5)
else:
while os.path.getsize(modelnm) < 1810671599:
print('[1;31mWrong link, check that the link is valid')
time.sleep(5)
def dls(Path_to_HuggingFace, Model_Path, Model_Link):
if Path_to_HuggingFace != "":
downloadmodel_hf(Path_to_HuggingFace)
MODEL_NAME="/models/stable-diffusion-custom"
elif Model_Path !="":
downloadmodel_path(Model_Path)
MODEL_NAME="/models/stable-diffusion-custom"
elif Model_Link !="":
downloadmodel_link(Model_Link)
MODEL_NAME="/models/stable-diffusion-custom"
else:
MODEL_NAME="/datasets/stable-diffusion-diffusers/stable-diffusion-v1-5"
print('[1;32mUsing the original V1.5 model')
return MODEL_NAME
def sess(Session_Name, Session_Link_optional, MODEL_NAME):
import wget, gdown
os.chdir('/notebooks')
PT=""
while Session_Name=="":
print('[1;31mInput the Session Name:')
Session_Name=input("")
Session_Name=Session_Name.replace(" ","_")
WORKSPACE='/notebooks/Fast-Dreambooth'
if Session_Link_optional !="":
print('[1;33mDownloading session...')
if Session_Link_optional != "":
if not os.path.exists(str(WORKSPACE+'/Sessions')):
call("mkdir -p " +WORKSPACE+ "/Sessions", shell=True)
time.sleep(1)
os.chdir(WORKSPACE+'/Sessions')
gdown.download_folder(url=Session_Link_optional, output=Session_Name, quiet=True, remaining_ok=True, use_cookies=False)
os.chdir(Session_Name)
call("rm -r " +instance_images, shell=True)
call("unzip " +instance_images.zip, shell=True, stdout=open('/dev/null', 'w'))
call("rm -r " +concept_images, shell=True)
call("unzip " +concept_images.zip, shell=True, stdout=open('/dev/null', 'w'))
call("rm -r " +captions, shell=True)
call("unzip " +captions.zip, shell=True, stdout=open('/dev/null', 'w'))
os.chdir('/notebooks')
clear_output()
INSTANCE_NAME=Session_Name
OUTPUT_DIR="/models/"+Session_Name
SESSION_DIR=WORKSPACE+"/Sessions/"+Session_Name
CONCEPT_DIR=SESSION_DIR+"/concept_images"
INSTANCE_DIR=SESSION_DIR+"/instance_images"
CAPTIONS_DIR=SESSION_DIR+'/captions'
MDLPTH=str(SESSION_DIR+"/"+Session_Name+'.ckpt')
resume=False
if os.path.exists(str(SESSION_DIR)):
mdls=[ckpt for ckpt in listdir(SESSION_DIR) if ckpt.split(".")[-1]=="ckpt"]
if not os.path.exists(MDLPTH) and '.ckpt' in str(mdls):
def f(n):
k=0
for i in mdls:
if k==n:
call('mv '+SESSION_DIR+'/'+i+' '+MDLPTH, shell=True)
k=k+1
k=0
print('[1;33mNo final checkpoint model found, select which intermediary checkpoint to use, enter only the number, (000 to skip):\n[1;34m')
for i in mdls:
print(str(k)+'- '+i)
k=k+1
n=input()
while int(n)>k-1:
n=input()
if n!="000":
f(int(n))
print('[1;32mUsing the model '+ mdls[int(n)]+" ...")
time.sleep(4)
clear_output()
else:
print('[1;32mSkipping the intermediary checkpoints.')
if os.path.exists(str(SESSION_DIR)) and not os.path.exists(MDLPTH):
print('[1;32mLoading session with no previous model, using the original model or the custom downloaded model')
if MODEL_NAME=="":
print('[1;31mNo model found, use the "Model Download" cell to download a model.')
else:
print('[1;32mSession Loaded, proceed to uploading instance images')
elif os.path.exists(MDLPTH):
print('[1;32mSession found, loading the trained model ...')
call('wget -q -O config.yaml https://github.com/CompVis/stable-diffusion/raw/main/configs/stable-diffusion/v1-inference.yaml', shell=True)
call('python /diffusers/scripts/convert_original_stable_diffusion_to_diffusers.py --checkpoint_path '+MDLPTH+' --dump_path '+OUTPUT_DIR+' --original_config_file config.yaml', shell=True)
clear_output()
call('rm config.yaml', shell=True)
if os.path.exists(OUTPUT_DIR+'/unet/diffusion_pytorch_model.bin'):
resume=True
clear_output()
print('[1;32mSession loaded.')
else:
print('[1;31mConversion error, if the error persists, remove the CKPT file from the current session folder')
elif not os.path.exists(str(SESSION_DIR)):
call('mkdir -p '+INSTANCE_DIR, shell=True)
print('[1;32mCreating session...')
if MODEL_NAME=="":
print('[1;31mNo model found, use the "Model Download" cell to download a model.')
else:
print('[1;32mSession created, proceed to uploading instance images')
return PT, WORKSPACE, Session_Name, INSTANCE_NAME, OUTPUT_DIR, SESSION_DIR, CONCEPT_DIR, INSTANCE_DIR, CAPTIONS_DIR, MDLPTH, MODEL_NAME, resume
def done():
done = widgets.Button(
description='Done!',
disabled=True,
button_style='success',
tooltip='',
icon='check'
)
display(done)
def uplder(Remove_existing_instance_images, Crop_images, Crop_size, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR, ren):
if os.path.exists(INSTANCE_DIR+"/.ipynb_checkpoints"):
call('rm -r '+INSTANCE_DIR+'/.ipynb_checkpoints', shell=True)
uploader = widgets.FileUpload(description="Choose images",accept='image/*, .txt', multiple=True)
Upload = widgets.Button(
description='Upload',
disabled=False,
button_style='info',
tooltip='Click to upload the chosen instance images',
icon=''
)
def up(Upload):
with out:
uploader.close()
Upload.close()
upld(Remove_existing_instance_images, Crop_images, Crop_size, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR, uploader, ren)
done()
out=widgets.Output()
if IMAGES_FOLDER_OPTIONAL=="":
Upload.on_click(up)
display(uploader, Upload, out)
else:
upld(Remove_existing_instance_images, Crop_images, Crop_size, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR, uploader, ren)
done()
def upld(Remove_existing_instance_images, Crop_images, Crop_size, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR, uploader, ren):
if Remove_existing_instance_images:
if os.path.exists(str(INSTANCE_DIR)):
call("rm -r " +INSTANCE_DIR, shell=True)
if os.path.exists(str(CAPTIONS_DIR)):
call("rm -r " +CAPTIONS_DIR, shell=True)
if not os.path.exists(str(INSTANCE_DIR)):
call("mkdir -p " +INSTANCE_DIR, shell=True)
if not os.path.exists(str(CAPTIONS_DIR)):
call("mkdir -p " +CAPTIONS_DIR, shell=True)
if IMAGES_FOLDER_OPTIONAL !="":
if os.path.exists(IMAGES_FOLDER_OPTIONAL+"/.ipynb_checkpoints"):
call('rm -r '+IMAGES_FOLDER_OPTIONAL+'/.ipynb_checkpoints', shell=True)
if any(file.endswith('.{}'.format('txt')) for file in os.listdir(IMAGES_FOLDER_OPTIONAL)):
call('mv '+IMAGES_FOLDER_OPTIONAL+'/*.txt '+CAPTIONS_DIR, shell=True)
if Crop_images:
os.chdir(str(IMAGES_FOLDER_OPTIONAL))
call('find . -name "* *" -type f | rename ' "'s/ /-/g'", shell=True)
os.chdir('/notebooks')
for filename in tqdm(os.listdir(IMAGES_FOLDER_OPTIONAL), bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Uploaded'):
extension = filename.split(".")[-1]
identifier=filename.split(".")[0]
new_path_with_file = os.path.join(INSTANCE_DIR, filename)
file = Image.open(IMAGES_FOLDER_OPTIONAL+"/"+filename)
file=file.convert("RGB")
file=ImageOps.exif_transpose(file)
width, height = file.size
if file.size !=(Crop_size, Crop_size):
image=crop_image(file, Crop_size)
if extension.upper()=="JPG" or extension.upper()=="jpg":
image[0].save(new_path_with_file, format="JPEG", quality = 100)
else:
image[0].save(new_path_with_file, format=extension.upper())
else:
call("cp \'"+IMAGES_FOLDER_OPTIONAL+"/"+filename+"\' "+INSTANCE_DIR, shell=True)
else:
for filename in tqdm(os.listdir(IMAGES_FOLDER_OPTIONAL), bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Uploaded'):
call("cp -r " +IMAGES_FOLDER_OPTIONAL+"/. " +INSTANCE_DIR, shell=True)
elif IMAGES_FOLDER_OPTIONAL =="":
up=""
for file in uploader.value:
filename = file['name']
if filename.split(".")[-1]=="txt":
with open(CAPTIONS_DIR+'/'+filename, 'w') as f:
f.write(bytes(file['content']).decode())
up=[file for file in uploader.value if not file['name'].endswith('.txt')]
if Crop_images:
for file in tqdm(up, bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Uploaded'):
filename = file['name']
img = Image.open(io.BytesIO(file['content']))
extension = filename.split(".")[-1]
identifier=filename.split(".")[0]
img=img.convert("RGB")
img=ImageOps.exif_transpose(img)
if extension.upper()=="JPG" or extension.upper()=="jpg":
img.save(INSTANCE_DIR+"/"+filename, format="JPEG", quality = 100)
else:
img.save(INSTANCE_DIR+"/"+filename, format=extension.upper())
new_path_with_file = os.path.join(INSTANCE_DIR, filename)
file = Image.open(new_path_with_file)
width, height = file.size
if file.size !=(Crop_size, Crop_size):
image=crop_image(file, Crop_size)
if extension.upper()=="JPG" or extension.upper()=="jpg":
image[0].save(new_path_with_file, format="JPEG", quality = 100)
else:
image[0].save(new_path_with_file, format=extension.upper())
else:
for file in tqdm(uploader.value, bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Uploaded'):
filename = file['name']
img = Image.open(io.BytesIO(file['content']))
img=img.convert("RGB")
extension = filename.split(".")[-1]
identifier=filename.split(".")[0]
if extension.upper()=="JPG" or extension.upper()=="jpg":
img.save(INSTANCE_DIR+"/"+filename, format="JPEG", quality = 100)
else:
img.save(INSTANCE_DIR+"/"+filename, format=extension.upper())
if ren:
i=0
for filename in tqdm(os.listdir(INSTANCE_DIR), bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Renamed'):
extension = filename.split(".")[-1]
identifier=filename.split(".")[0]
new_path_with_file = os.path.join(INSTANCE_DIR, "conceptimagedb"+str(i)+"."+extension)
call('mv "'+os.path.join(INSTANCE_DIR,filename)+'" "'+new_path_with_file+'"', shell=True)
i=i+1
os.chdir(INSTANCE_DIR)
call('find . -name "* *" -type f | rename ' "'s/ /-/g'", shell=True)
os.chdir(CAPTIONS_DIR)
call('find . -name "* *" -type f | rename ' "'s/ /-/g'", shell=True)
os.chdir('/notebooks')
def caption(CAPTIONS_DIR, INSTANCE_DIR):
paths=""
out=""
widgets_l=""
clear_output()
def Caption(path):
if path!="Select an instance image to caption":
name = os.path.splitext(os.path.basename(path))[0]
ext=os.path.splitext(os.path.basename(path))[-1][1:]
if ext=="jpg" or "JPG":
ext="JPEG"
if os.path.exists(CAPTIONS_DIR+"/"+name + '.txt'):
with open(CAPTIONS_DIR+"/"+name + '.txt', 'r') as f:
text = f.read()
else:
with open(CAPTIONS_DIR+"/"+name + '.txt', 'w') as f:
f.write("")
with open(CAPTIONS_DIR+"/"+name + '.txt', 'r') as f:
text = f.read()
img=Image.open(os.path.join(INSTANCE_DIR,path))
img=img.convert("RGB")
img=img.resize((420, 420))
image_bytes = BytesIO()
img.save(image_bytes, format=ext, qualiy=10)
image_bytes.seek(0)
image_data = image_bytes.read()
img= image_data
image = widgets.Image(
value=img,
width=420,
height=420
)
text_area = widgets.Textarea(value=text, description='', disabled=False, layout={'width': '300px', 'height': '120px'})
def update_text(text):
with open(CAPTIONS_DIR+"/"+name + '.txt', 'w') as f:
f.write(text)
button = widgets.Button(description='Save', button_style='success')
button.on_click(lambda b: update_text(text_area.value))
return widgets.VBox([widgets.HBox([image, text_area, button])])
paths = os.listdir(INSTANCE_DIR)
widgets_l = widgets.Select(options=["Select an instance image to caption"]+paths, rows=25)
out = widgets.Output()
def click(change):
with out:
out.clear_output()
display(Caption(change.new))
widgets_l.observe(click, names='value')
display(widgets.HBox([widgets_l, out]))
def dbtrain(Resume_Training, UNet_Training_Steps, UNet_Learning_Rate, Text_Encoder_Training_Steps, Text_Encoder_Concept_Training_Steps, Text_Encoder_Learning_Rate, Offset_Noise, Resolution, MODEL_NAME, SESSION_DIR, INSTANCE_DIR, CONCEPT_DIR, CAPTIONS_DIR, External_Captions, INSTANCE_NAME, Session_Name, OUTPUT_DIR, PT, resume, Save_Checkpoint_Every_n_Steps, Start_saving_from_the_step, Save_Checkpoint_Every):
if os.path.exists(INSTANCE_DIR+"/.ipynb_checkpoints"):
call('rm -r '+INSTANCE_DIR+'/.ipynb_checkpoints', shell=True)
if os.path.exists(CONCEPT_DIR+"/.ipynb_checkpoints"):
call('rm -r '+CONCEPT_DIR+'/.ipynb_checkpoints', shell=True)
if os.path.exists(CAPTIONS_DIR+"/.ipynb_checkpoints"):
call('rm -r '+CAPTIONS_DIR+'/.ipynb_checkpoints', shell=True)
if resume and not Resume_Training:
print('[1;31mOverwrite your previously trained model ?, answering "yes" will train a new model, answering "no" will resume the training of the previous model? yes or no ?[0m')
while True:
ansres=input('')
if ansres=='no':
Resume_Training = True
resume= False
break
elif ansres=='yes':
Resume_Training = False
resume= False
break
while not Resume_Training and not os.path.exists(MODEL_NAME+'/unet/diffusion_pytorch_model.bin'):
print('[1;31mNo model found, use the "Model Download" cell to download a model.')
time.sleep(5)
MODELT_NAME=MODEL_NAME
Seed=random.randint(1, 999999)
ofstnse=""
if Offset_Noise:
ofstnse="--offset_noise"
extrnlcptn=""
if External_Captions:
extrnlcptn="--external_captions"
precision="fp16"
resuming=""
if Resume_Training and os.path.exists(OUTPUT_DIR+'/unet/diffusion_pytorch_model.bin'):
MODELT_NAME=OUTPUT_DIR
print('[1;32mResuming Training...[0m')
resuming="Yes"
elif Resume_Training and not os.path.exists(OUTPUT_DIR+'/unet/diffusion_pytorch_model.bin'):
print('[1;31mPrevious model not found, training a new model...[0m')
MODELT_NAME=MODEL_NAME
while MODEL_NAME=="":
print('[1;31mNo model found, use the "Model Download" cell to download a model.')
time.sleep(5)
trnonltxt=""
if UNet_Training_Steps==0:
trnonltxt="--train_only_text_encoder"
Enable_text_encoder_training= True
Enable_Text_Encoder_Concept_Training= True
if Text_Encoder_Training_Steps==0:
Enable_text_encoder_training= False
else:
stptxt=Text_Encoder_Training_Steps
if Text_Encoder_Concept_Training_Steps==0:
Enable_Text_Encoder_Concept_Training= False
else:
stptxtc=Text_Encoder_Concept_Training_Steps
if Save_Checkpoint_Every==None:
Save_Checkpoint_Every=1
stp=0
if Start_saving_from_the_step==None:
Start_saving_from_the_step=0
if (Start_saving_from_the_step < 200):
Start_saving_from_the_step=Save_Checkpoint_Every
stpsv=Start_saving_from_the_step
if Save_Checkpoint_Every_n_Steps:
stp=Save_Checkpoint_Every
def dump_only_textenc(trnonltxt, MODELT_NAME, INSTANCE_DIR, OUTPUT_DIR, PT, Seed, precision, Training_Steps):
call('accelerate launch /notebooks/diffusers/examples/dreambooth/train_dreambooth_pps.py \
'+trnonltxt+' \
'+extrnlcptn+' \
'+ofstnse+' \
--train_text_encoder \
--image_captions_filename \
--dump_only_text_encoder \
--pretrained_model_name_or_path='+MODELT_NAME+' \
--instance_data_dir='+INSTANCE_DIR+' \
--output_dir='+OUTPUT_DIR+' \
--captions_dir='+CAPTIONS_DIR+' \
--instance_prompt='+PT+' \
--seed='+str(Seed)+' \
--resolution='+str(Resolution)+' \
--mixed_precision='+str(precision)+' \
--train_batch_size=1 \
--gradient_accumulation_steps=1 --gradient_checkpointing \
--use_8bit_adam \
--learning_rate='+str(Text_Encoder_Learning_Rate)+' \
--lr_scheduler="linear" \
--lr_warmup_steps=0 \
--max_train_steps='+str(Training_Steps), shell=True)
def train_only_unet(stp, stpsv, SESSION_DIR, MODELT_NAME, INSTANCE_DIR, OUTPUT_DIR, Text_Encoder_Training_Steps, PT, Seed, Resolution, extrnlcptn, precision, Training_Steps):
clear_output()
if resuming=="Yes":
print('[1;32mResuming Training...[0m')
print('[1;33mTraining the UNet...[0m')
call('accelerate launch /notebooks/diffusers/examples/dreambooth/train_dreambooth_pps.py \
'+extrnlcptn+' \
'+ofstnse+' \
--image_captions_filename \
--train_only_unet \
--Session_dir='+SESSION_DIR+' \
--save_starting_step='+str(stpsv)+' \
--save_n_steps='+str(stp)+' \
--pretrained_model_name_or_path='+MODELT_NAME+' \
--instance_data_dir='+INSTANCE_DIR+' \
--output_dir='+OUTPUT_DIR+' \
--captions_dir='+CAPTIONS_DIR+' \
--instance_prompt='+PT+' \
--seed='+str(Seed)+' \
--resolution='+str(Resolution)+' \
--mixed_precision='+str(precision)+' \
--train_batch_size=1 \
--gradient_accumulation_steps=1 --gradient_checkpointing \
--use_8bit_adam \
--learning_rate='+str(UNet_Learning_Rate)+' \
--lr_scheduler="linear" \
--lr_warmup_steps=0 \
--max_train_steps='+str(Training_Steps), shell=True)
if Enable_text_encoder_training :
print('[1;33mTraining the text encoder...[0m')
if os.path.exists(OUTPUT_DIR+'/'+'text_encoder_trained'):
call('rm -r '+OUTPUT_DIR+'/text_encoder_trained', shell=True)
dump_only_textenc(trnonltxt, MODELT_NAME, INSTANCE_DIR, OUTPUT_DIR, PT, Seed, precision, Training_Steps=stptxt)
if Enable_Text_Encoder_Concept_Training:
if os.path.exists(CONCEPT_DIR):
if os.listdir(CONCEPT_DIR)!=[]:
clear_output()
if resuming=="Yes":
print('[1;32mResuming Training...[0m')
print('[1;33mTraining the text encoder on the concept...[0m')
dump_only_textenc(trnonltxt, MODELT_NAME, CONCEPT_DIR, OUTPUT_DIR, PT, Seed, precision, Training_Steps=stptxtc)
else:
clear_output()
if resuming=="Yes":
print('[1;32mResuming Training...[0m')
print('[1;31mNo concept images found, skipping concept training...')
Text_Encoder_Concept_Training_Steps=0
time.sleep(8)
else:
clear_output()
if resuming=="Yes":
print('[1;32mResuming Training...[0m')
print('[1;31mNo concept images found, skipping concept training...')
Text_Encoder_Concept_Training_Steps=0
time.sleep(8)
if UNet_Training_Steps!=0:
train_only_unet(stp, stpsv, SESSION_DIR, MODELT_NAME, INSTANCE_DIR, OUTPUT_DIR, Text_Encoder_Training_Steps, PT, Seed, Resolution, extrnlcptn, precision, Training_Steps=UNet_Training_Steps)
if UNet_Training_Steps==0 and Text_Encoder_Concept_Training_Steps==0 and Text_Encoder_Training_Steps==0 :
print('[1;32mNothing to do')
else:
if os.path.exists(OUTPUT_DIR+'/unet/diffusion_pytorch_model.bin'):
call('python /notebooks/diffusers/scripts/convertosdv2.py --fp16 '+OUTPUT_DIR+' '+SESSION_DIR+'/'+Session_Name+'.ckpt', shell=True)
clear_output()
if os.path.exists(SESSION_DIR+"/"+INSTANCE_NAME+'.ckpt'):
clear_output()
print("[1;32mDONE, the CKPT model is in the session's folder")
else:
print("[1;31mSomething went wrong")
else:
print("[1;31mSomething went wrong")
return resume
def testui(Custom_Path, Previous_Session_Name, Session_Name, User, Password):
if Previous_Session_Name!="":
print("[1;32mLoading a previous session model")
mdldir='/notebooks/Fast-Dreambooth/Sessions/'+Previous_Session_Name
path_to_trained_model=mdldir+"/"+Previous_Session_Name+'.ckpt'
while not os.path.exists(path_to_trained_model):
print("[1;31mThere is no trained model in the previous session")
time.sleep(5)
elif Custom_Path!="":
print("[1;32mLoading model from a custom path")
path_to_trained_model=Custom_Path
while not os.path.exists(path_to_trained_model):
print("[1;31mWrong Path")
time.sleep(5)
else:
print("[1;32mLoading the trained model")
mdldir='/notebooks/Fast-Dreambooth/Sessions/'+Session_Name
path_to_trained_model=mdldir+"/"+Session_Name+'.ckpt'
while not os.path.exists(path_to_trained_model):
print("[1;31mThere is no trained model in this session")
time.sleep(5)
auth=f"--gradio-auth {User}:{Password}"
if User =="" or Password=="":
auth=""
os.chdir('/notebooks')
if not os.path.exists('/notebooks/sd/stablediffusiond'): #reset later
call('wget -q -O sd_mrep.tar.zst https://huggingface.co/TheLastBen/dependencies/resolve/main/sd_mrep.tar.zst', shell=True)
call('tar --zstd -xf sd_mrep.tar.zst', shell=True)
call('rm sd_mrep.tar.zst', shell=True)
os.chdir('/notebooks/sd')
if not os.path.exists('stable-diffusion-webui'):
call('git clone -q --depth 1 --branch master https://github.com/AUTOMATIC1111/stable-diffusion-webui', shell=True)
os.chdir('/notebooks/sd/stable-diffusion-webui/')
call('git reset --hard', shell=True, stdout=open('/dev/null', 'w'))
print('[1;32m')
call('git checkout master', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('git pull', shell=True, stdout=open('/dev/null', 'w'))
os.makedirs('/notebooks/sd/stable-diffusion-webui/repositories', exist_ok=True)
call('git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui-assets /notebooks/sd/stable-diffusion-webui/repositories/stable-diffusion-webui-assets', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
os.chdir('/notebooks')
clear_output()
call('wget -q -O /notebooks/sd/stable-diffusion-webui/modules/styles.py https://github.com/TheLastBen/fast-stable-diffusion/raw/main/AUTOMATIC1111_files/styles.py', shell=True)
call('wget -q -O /usr/local/lib/python3.9/dist-packages/gradio/blocks.py https://raw.githubusercontent.com/TheLastBen/fast-stable-diffusion/main/AUTOMATIC1111_files/blocks.py', shell=True)
localurl="tensorboard-"+os.environ.get('PAPERSPACE_FQDN')
for line in fileinput.input('/usr/local/lib/python3.9/dist-packages/gradio/blocks.py', inplace=True):
if line.strip().startswith('self.server_name ='):
line = f' self.server_name = "{localurl}"\n'
if line.strip().startswith('self.protocol = "https"'):
line = ' self.protocol = "https"\n'
if line.strip().startswith('if self.local_url.startswith("https") or self.is_colab'):
line = ''
if line.strip().startswith('else "http"'):
line = ''
sys.stdout.write(line)
os.chdir('/notebooks/sd/stable-diffusion-webui/modules')
call("sed -i 's@possible_sd_paths =.*@possible_sd_paths = [\"/notebooks/sd/stablediffusion\"]@' /notebooks/sd/stable-diffusion-webui/modules/paths.py", shell=True)
call("sed -i 's@\.\.\/@src/@g' /notebooks/sd/stable-diffusion-webui/modules/paths.py", shell=True)
call("sed -i 's@src\/generative-models@generative-models@g' /notebooks/sd/stable-diffusion-webui/modules/paths.py", shell=True)
call("sed -i 's@-> Network | None@@g' /notebooks/sd/stable-diffusion-webui/extensions-builtin/Lora/network.py", shell=True)
call("sed -i 's@|@or@' /notebooks/sd/stable-diffusion-webui/extensions/adetailer/aaaaaa/helper.py", shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call("sed -i 's@\"quicksettings\": OptionInfo(.*@\"quicksettings\": OptionInfo(\"sd_model_checkpoint, sd_vae, CLIP_stop_at_last_layers, inpainting_mask_weight, initial_noise_multiplier\", \"Quicksettings list\"),@' /notebooks/sd/stable-diffusion-webui/modules/shared.py", shell=True)
os.chdir('/notebooks/sd/stable-diffusion-webui')
clear_output()
configf="--disable-console-progressbars --no-gradio-queue --no-hashing --no-half-vae --disable-safe-unpickle --api --no-download-sd-model --xformers --enable-insecure-extension-access --port 6006 --listen --skip-version-check --ckpt "+path_to_trained_model+" "+auth
return configf
def clean():
Sessions=os.listdir("/notebooks/Fast-Dreambooth/Sessions")
s = widgets.Select(
options=Sessions,
rows=5,
description='',
disabled=False
)
out=widgets.Output()
d = widgets.Button(
description='Remove',
disabled=False,
button_style='warning',
tooltip='Removet the selected session',
icon='warning'
)
def rem(d):
with out:
if s.value is not None:
clear_output()
print("[1;33mTHE SESSION [1;31m"+s.value+" [1;33mHAS BEEN REMOVED FROM THE STORAGE")
call('rm -r /notebooks/Fast-Dreambooth/Sessions/'+s.value, shell=True)
if os.path.exists('/notebooks/models/'+s.value):
call('rm -r /notebooks/models/'+s.value, shell=True)
s.options=os.listdir("/notebooks/Fast-Dreambooth/Sessions")
else:
d.close()
s.close()
clear_output()
print("[1;32mNOTHING TO REMOVE")
d.on_click(rem)
if s.value is not None:
display(s,d,out)
else:
print("[1;32mNOTHING TO REMOVE")
def hf(Name_of_your_concept, hf_token_write, INSTANCE_NAME, OUTPUT_DIR, Session_Name, MDLPTH):
from slugify import slugify
from huggingface_hub import HfApi, HfFolder, CommitOperationAdd
from huggingface_hub import create_repo
from IPython.display import display_markdown
if(Name_of_your_concept == ""):
Name_of_your_concept = Session_Name
Name_of_your_concept=Name_of_your_concept.replace(" ","-")
if hf_token_write =="":
print('[1;32mYour Hugging Face write access token : ')
hf_token_write=input()
hf_token = hf_token_write
api = HfApi()
your_username = api.whoami(token=hf_token)["name"]
repo_id = f"{your_username}/{slugify(Name_of_your_concept)}"
output_dir = f'/notebooks/models/'+INSTANCE_NAME
def bar(prg):
clear_output()
br="[1;33mUploading to HuggingFace : " '[0m|'+'█' * prg + ' ' * (25-prg)+'| ' +str(prg*4)+ "%"
return br
print("[1;33mLoading...")
os.chdir(OUTPUT_DIR)
call('rm -r safety_checker feature_extractor .git', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('rm model_index.json', shell=True)
call('git init', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('git lfs install --system --skip-repo', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('git remote add -f origin https://huggingface.co/runwayml/stable-diffusion-v1-5', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('git config core.sparsecheckout true', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('echo -e "\nfeature_extractor\nsafety_checker\nmodel_index.json\n!*.safetensors" > .git/info/sparse-checkout', shell=True)
call('git pull origin main', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('rm -r .git', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
os.chdir('/notebooks')
print(bar(1))
readme_text = f'''---
license: creativeml-openrail-m
tags:
- text-to-image
- stable-diffusion
---
### {Name_of_your_concept} Dreambooth model trained by {api.whoami(token=hf_token)["name"]} with TheLastBen's fast-DreamBooth notebook
'''
#Save the readme to a file
readme_file = open("README.md", "w")
readme_file.write(readme_text)
readme_file.close()
operations = [
CommitOperationAdd(path_in_repo="README.md", path_or_fileobj="README.md"),
CommitOperationAdd(path_in_repo=f"{Session_Name}.ckpt",path_or_fileobj=MDLPTH)
]
create_repo(repo_id,private=True, token=hf_token)
api.create_commit(
repo_id=repo_id,
operations=operations,
commit_message=f"Upload the concept {Name_of_your_concept} embeds and token",
token=hf_token
)
api.upload_folder(
folder_path=OUTPUT_DIR+"/feature_extractor",
path_in_repo="feature_extractor",
repo_id=repo_id,
token=hf_token
)
print(bar(4))
api.upload_folder(
folder_path=OUTPUT_DIR+"/safety_checker",
path_in_repo="safety_checker",
repo_id=repo_id,
token=hf_token
)
print(bar(8))
api.upload_folder(
folder_path=OUTPUT_DIR+"/scheduler",
path_in_repo="scheduler",
repo_id=repo_id,
token=hf_token
)
print(bar(9))
api.upload_folder(
folder_path=OUTPUT_DIR+"/text_encoder",
path_in_repo="text_encoder",
repo_id=repo_id,
token=hf_token
)
print(bar(12))
api.upload_folder(
folder_path=OUTPUT_DIR+"/tokenizer",
path_in_repo="tokenizer",
repo_id=repo_id,
token=hf_token
)
print(bar(13))
api.upload_folder(
folder_path=OUTPUT_DIR+"/unet",
path_in_repo="unet",
repo_id=repo_id,
token=hf_token
)
print(bar(21))
api.upload_folder(
folder_path=OUTPUT_DIR+"/vae",
path_in_repo="vae",
repo_id=repo_id,
token=hf_token
)
print(bar(23))
api.upload_file(
path_or_fileobj=OUTPUT_DIR+"/model_index.json",
path_in_repo="model_index.json",
repo_id=repo_id,
token=hf_token
)
print(bar(25))
print("[1;32mYour concept was saved successfully at https://huggingface.co/"+repo_id)
done()
def crop_image(im, size):
GREEN = "#0F0"
BLUE = "#00F"
RED = "#F00"
def focal_point(im, settings):
corner_points = image_corner_points(im, settings) if settings.corner_points_weight > 0 else []
entropy_points = image_entropy_points(im, settings) if settings.entropy_points_weight > 0 else []
face_points = image_face_points(im, settings) if settings.face_points_weight > 0 else []
pois = []
weight_pref_total = 0
if len(corner_points) > 0:
weight_pref_total += settings.corner_points_weight
if len(entropy_points) > 0:
weight_pref_total += settings.entropy_points_weight
if len(face_points) > 0:
weight_pref_total += settings.face_points_weight
corner_centroid = None
if len(corner_points) > 0:
corner_centroid = centroid(corner_points)
corner_centroid.weight = settings.corner_points_weight / weight_pref_total
pois.append(corner_centroid)
entropy_centroid = None
if len(entropy_points) > 0:
entropy_centroid = centroid(entropy_points)
entropy_centroid.weight = settings.entropy_points_weight / weight_pref_total
pois.append(entropy_centroid)
face_centroid = None
if len(face_points) > 0:
face_centroid = centroid(face_points)
face_centroid.weight = settings.face_points_weight / weight_pref_total
pois.append(face_centroid)
average_point = poi_average(pois, settings)
return average_point
def image_face_points(im, settings):
np_im = np.array(im)
gray = cv2.cvtColor(np_im, cv2.COLOR_BGR2GRAY)
tries = [
[ f'{cv2.data.haarcascades}haarcascade_eye.xml', 0.01 ],
[ f'{cv2.data.haarcascades}haarcascade_frontalface_default.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_profileface.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_frontalface_alt.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_frontalface_alt2.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_frontalface_alt_tree.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_eye_tree_eyeglasses.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_upperbody.xml', 0.05 ]
]
for t in tries:
classifier = cv2.CascadeClassifier(t[0])
minsize = int(min(im.width, im.height) * t[1]) # at least N percent of the smallest side
try:
faces = classifier.detectMultiScale(gray, scaleFactor=1.1,
minNeighbors=7, minSize=(minsize, minsize), flags=cv2.CASCADE_SCALE_IMAGE)
except:
continue
if len(faces) > 0:
rects = [[f[0], f[1], f[0] + f[2], f[1] + f[3]] for f in faces]
return [PointOfInterest((r[0] +r[2]) // 2, (r[1] + r[3]) // 2, size=abs(r[0]-r[2]), weight=1/len(rects)) for r in rects]
return []
def image_corner_points(im, settings):
grayscale = im.convert("L")
# naive attempt at preventing focal points from collecting at watermarks near the bottom
gd = ImageDraw.Draw(grayscale)
gd.rectangle([0, im.height*.9, im.width, im.height], fill="#999")
np_im = np.array(grayscale)
points = cv2.goodFeaturesToTrack(
np_im,
maxCorners=100,
qualityLevel=0.04,
minDistance=min(grayscale.width, grayscale.height)*0.06,
useHarrisDetector=False,
)
if points is None:
return []
focal_points = []
for point in points:
x, y = point.ravel()
focal_points.append(PointOfInterest(x, y, size=4, weight=1/len(points)))
return focal_points
def image_entropy_points(im, settings):
landscape = im.height < im.width
portrait = im.height > im.width
if landscape:
move_idx = [0, 2]
move_max = im.size[0]
elif portrait:
move_idx = [1, 3]
move_max = im.size[1]
else:
return []
e_max = 0
crop_current = [0, 0, settings.crop_width, settings.crop_height]
crop_best = crop_current
while crop_current[move_idx[1]] < move_max:
crop = im.crop(tuple(crop_current))
e = image_entropy(crop)
if (e > e_max):
e_max = e
crop_best = list(crop_current)
crop_current[move_idx[0]] += 4
crop_current[move_idx[1]] += 4
x_mid = int(crop_best[0] + settings.crop_width/2)
y_mid = int(crop_best[1] + settings.crop_height/2)
return [PointOfInterest(x_mid, y_mid, size=25, weight=1.0)]
def image_entropy(im):
# greyscale image entropy
# band = np.asarray(im.convert("L"))
band = np.asarray(im.convert("1"), dtype=np.uint8)
hist, _ = np.histogram(band, bins=range(0, 256))
hist = hist[hist > 0]
return -np.log2(hist / hist.sum()).sum()
def centroid(pois):
x = [poi.x for poi in pois]
y = [poi.y for poi in pois]
return PointOfInterest(sum(x)/len(pois), sum(y)/len(pois))
def poi_average(pois, settings):
weight = 0.0
x = 0.0
y = 0.0
for poi in pois:
weight += poi.weight
x += poi.x * poi.weight
y += poi.y * poi.weight
avg_x = round(weight and x / weight)
avg_y = round(weight and y / weight)
return PointOfInterest(avg_x, avg_y)
def is_landscape(w, h):
return w > h
def is_portrait(w, h):
return h > w
def is_square(w, h):
return w == h
class PointOfInterest:
def __init__(self, x, y, weight=1.0, size=10):
self.x = x
self.y = y
self.weight = weight
self.size = size
def bounding(self, size):
return [
self.x - size//2,
self.y - size//2,
self.x + size//2,
self.y + size//2
]
class Settings:
def __init__(self, crop_width=512, crop_height=512, corner_points_weight=0.5, entropy_points_weight=0.5, face_points_weight=0.5):
self.crop_width = crop_width
self.crop_height = crop_height
self.corner_points_weight = corner_points_weight
self.entropy_points_weight = entropy_points_weight
self.face_points_weight = face_points_weight
settings = Settings(
crop_width = size,
crop_height = size,
face_points_weight = 0.9,
entropy_points_weight = 0.15,
corner_points_weight = 0.5,
)
scale_by = 1
if is_landscape(im.width, im.height):
scale_by = settings.crop_height / im.height
elif is_portrait(im.width, im.height):
scale_by = settings.crop_width / im.width
elif is_square(im.width, im.height):
if is_square(settings.crop_width, settings.crop_height):
scale_by = settings.crop_width / im.width
elif is_landscape(settings.crop_width, settings.crop_height):
scale_by = settings.crop_width / im.width
elif is_portrait(settings.crop_width, settings.crop_height):
scale_by = settings.crop_height / im.height
im = im.resize((int(im.width * scale_by), int(im.height * scale_by)))
im_debug = im.copy()
focus = focal_point(im_debug, settings)
# take the focal point and turn it into crop coordinates that try to center over the focal
# point but then get adjusted back into the frame
y_half = int(settings.crop_height / 2)
x_half = int(settings.crop_width / 2)
x1 = focus.x - x_half
if x1 < 0:
x1 = 0
elif x1 + settings.crop_width > im.width:
x1 = im.width - settings.crop_width
y1 = focus.y - y_half
if y1 < 0:
y1 = 0
elif y1 + settings.crop_height > im.height:
y1 = im.height - settings.crop_height
x2 = x1 + settings.crop_width
y2 = y1 + settings.crop_height
crop = [x1, y1, x2, y2]
results = []
results.append(im.crop(tuple(crop)))
return results1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330from IPython.display import clear_output
from subprocess import call, getoutput
from IPython.display import display
import ipywidgets as widgets
import io
from PIL import Image, ImageDraw, ImageOps
import fileinput
import time
import os
from os import listdir
from os.path import isfile
from tqdm import tqdm
import gdown
import random
import sys
import cv2
from io import BytesIO
import requests
from collections import defaultdict
from math import log, sqrt
import numpy as np
import six
import re
from urllib.parse import urlparse, parse_qs, unquote
from urllib.request import urlopen, Request
import tempfile
from tqdm import tqdm
def Deps(force_reinstall):
if not force_reinstall and os.path.exists('/usr/local/lib/python3.11/dist-packages/gradio'):
ntbk()
os.environ['TORCH_HOME'] = '/notebooks/cache/torch'
os.environ['PYTHONWARNINGS'] = 'ignore'
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
print('[1;32mModules and notebooks updated, dependencies already installed')
else:
call("pip install --root-user-action=ignore --no-deps -q accelerate==0.12.0", shell=True, stdout=open('/dev/null', 'w'))
call("pip uninstall -qq deepspeed -y", shell=True, stdout=open('/dev/null', 'w'))
ntbk()
if not os.path.exists('/models'):
call('mkdir /models', shell=True)
if not os.path.exists('/notebooks/models'):
call('ln -s /models /notebooks', shell=True)
if os.path.exists('/deps'):
call("rm -r /deps", shell=True)
call('mkdir /deps', shell=True)
if not os.path.exists('cache'):
call('mkdir cache', shell=True)
os.chdir('/deps')
call('wget -q -i https://raw.githubusercontent.com/TheLastBen/fast-stable-diffusion/main/Dependencies/aptdeps_311.txt', shell=True)
call('dpkg -i *.deb', shell=True, stdout=open('/dev/null', 'w'))
depsinst("https://huggingface.co/TheLastBen/dependencies/resolve/main/ppsdeps_311.tar.zst", "/deps/ppsdeps_311.tar.zst")
call('tar -C / --zstd -xf ppsdeps_311.tar.zst', shell=True, stdout=open('/dev/null', 'w'))
os.chdir('/notebooks')
call("git clone --depth 1 -q --branch main https://github.com/TheLastBen/diffusers /diffusers", shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
os.environ['TORCH_HOME'] = '/notebooks/cache/torch'
os.environ['PYTHONWARNINGS'] = 'ignore'
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
call("sed -i 's@text = _formatwarnmsg(msg)@text =\"\"@g' /usr/lib/python3.11/warnings.py", shell=True)
if not os.path.exists('/notebooks/diffusers'):
call('ln -s /diffusers /notebooks', shell=True)
call("rm -r /deps", shell=True)
os.chdir('/notebooks')
clear_output()
done()
def depsinst(url, dst):
file_size = None
req = Request(url, headers={"User-Agent": "torch.hub"})
u = urlopen(req)
meta = u.info()
if hasattr(meta, 'getheaders'):
content_length = meta.getheaders("Content-Length")
else:
content_length = meta.get_all("Content-Length")
if content_length is not None and len(content_length) > 0:
file_size = int(content_length[0])
with tqdm(total=file_size, disable=False, mininterval=0.5,
bar_format='(fast-stable-diffusion will soon stop supporting Paperspace) Installing dependencies |{bar:20}| {percentage:3.0f}%') as pbar:
with open(dst, "wb") as f:
while True:
buffer = u.read(8192)
if len(buffer) == 0:
break
f.write(buffer)
pbar.update(len(buffer))
f.close()
def ntbk():
os.chdir('/notebooks')
if not os.path.exists('Latest_Notebooks'):
call('mkdir Latest_Notebooks', shell=True)
else:
call('rm -r Latest_Notebooks', shell=True)
call('mkdir Latest_Notebooks', shell=True)
os.chdir('/notebooks/Latest_Notebooks')
call('wget -q -i https://huggingface.co/datasets/TheLastBen/PPS/raw/main/Notebooks.txt', shell=True)
call('rm Notebooks.txt', shell=True)
os.chdir('/notebooks')
def downloadmodel_hf(Path_to_HuggingFace):
import wget
if os.path.exists('/models/stable-diffusion-custom'):
call("rm -r /models/stable-diffusion-custom", shell=True)
clear_output()
if os.path.exists('/notebooks/Fast-Dreambooth/token.txt'):
with open("/notebooks/Fast-Dreambooth/token.txt") as f:
token = f.read()
authe=f'https://USER:{token}@'
else:
authe="https://"
clear_output()
call("mkdir /models/stable-diffusion-custom", shell=True)
os.chdir("/models/stable-diffusion-custom")
call("git init", shell=True)
call("git lfs install --system --skip-repo", shell=True)
call('git remote add -f origin '+authe+'huggingface.co/'+Path_to_HuggingFace, shell=True)
call("git config core.sparsecheckout true", shell=True)
call('echo -e "\nscheduler\ntext_encoder\ntokenizer\nunet\nvae\nmodel_index.json\n!*.safetensors" > .git/info/sparse-checkout', shell=True)
call("git pull origin main", shell=True)
if os.path.exists('unet/diffusion_pytorch_model.bin'):
call("rm -r .git", shell=True)
call("rm model_index.json", shell=True)
wget.download('https://raw.githubusercontent.com/TheLastBen/fast-stable-diffusion/main/Dreambooth/model_index.json')
os.chdir('/notebooks')
clear_output()
done()
while not os.path.exists('/models/stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
print('[1;31mCheck the link you provided')
os.chdir('/notebooks')
time.sleep(5)
def downloadmodel_path(MODEL_PATH):
modelname=os.path.basename(MODEL_PATH)
sftnsr=""
if modelname.split('.')[-1]=='safetensors':
sftnsr="--from_safetensors"
import wget
os.chdir('/notebooks')
clear_output()
if os.path.exists(str(MODEL_PATH)):
call('wget -q -O config.yaml https://github.com/CompVis/stable-diffusion/raw/main/configs/stable-diffusion/v1-inference.yaml', shell=True)
call('python /diffusers/scripts/convert_original_stable_diffusion_to_diffusers.py --checkpoint_path '+MODEL_PATH+' --dump_path /models/stable-diffusion-custom --original_config_file config.yaml '+sftnsr, shell=True)
clear_output()
call('rm config.yaml', shell=True)
if os.path.exists('/models/stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
clear_output()
done()
while not os.path.exists('/models/stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
print('[1;31mConversion error')
time.sleep(5)
else:
while not os.path.exists(str(MODEL_PATH)):
print('[1;31mWrong path, use the file explorer to copy the path')
time.sleep(5)
def downloadmodel_link(MODEL_LINK):
import wget
import gdown
from gdown.download import get_url_from_gdrive_confirmation
def getsrc(url):
parsed_url = urlparse(url)
if parsed_url.netloc == 'civitai.com':
src='civitai'
elif parsed_url.netloc == 'drive.google.com':
src='gdrive'
elif parsed_url.netloc == 'huggingface.co':
src='huggingface'
else:
src='others'
return src
src=getsrc(MODEL_LINK)
def get_name(url, gdrive):
if not gdrive:
response = requests.get(url, allow_redirects=False)
if "Location" in response.headers:
redirected_url = response.headers["Location"]
quer = parse_qs(urlparse(redirected_url).query)
if "response-content-disposition" in quer:
disp_val = quer["response-content-disposition"][0].split(";")
for vals in disp_val:
if vals.strip().startswith("filename="):
filenm=unquote(vals.split("=", 1)[1].strip())
return filenm.replace("\"","")
else:
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"}
lnk="https://drive.google.com/uc?id={id}&export=download".format(id=url[url.find("/d/")+3:url.find("/view")])
res = requests.session().get(lnk, headers=headers, stream=True, verify=True)
res = requests.session().get(get_url_from_gdrive_confirmation(res.text), headers=headers, stream=True, verify=True)
content_disposition = six.moves.urllib_parse.unquote(res.headers["Content-Disposition"])
filenm = re.search(r"filename\*=UTF-8''(.*)", content_disposition).groups()[0].replace(os.path.sep, "_")
return filenm
if src=='civitai':
modelname=get_name(MODEL_LINK, False)
elif src=='gdrive':
modelname=get_name(MODEL_LINK, True)
else:
modelname=os.path.basename(MODEL_LINK)
sftnsr=""
if modelname.split('.')[-1]!='safetensors':
modelnm="model.ckpt"
else:
modelnm="model.safetensors"
sftnsr="--from_safetensors"
os.chdir('/notebooks')
call("gdown --fuzzy " +MODEL_LINK+ " -O "+modelnm, shell=True)
if os.path.exists(modelnm):
if os.path.getsize(modelnm) > 1810671599:
call('wget -q -O config.yaml https://github.com/CompVis/stable-diffusion/raw/main/configs/stable-diffusion/v1-inference.yaml', shell=True)
call('python /diffusers/scripts/convert_original_stable_diffusion_to_diffusers.py --checkpoint_path '+modelnm+' --dump_path /models/stable-diffusion-custom --original_config_file config.yaml '+sftnsr, shell=True)
clear_output()
call('rm config.yaml', shell=True)
if os.path.exists('/models/stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
call('rm '+modelnm, shell=True)
clear_output()
done()
else:
while not os.path.exists('/models/stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
print('[1;31mConversion error')
time.sleep(5)
else:
while os.path.getsize(modelnm) < 1810671599:
print('[1;31mWrong link, check that the link is valid')
time.sleep(5)
def dls(Path_to_HuggingFace, Model_Path, Model_Link):
if Path_to_HuggingFace != "":
downloadmodel_hf(Path_to_HuggingFace)
MODEL_NAME="/models/stable-diffusion-custom"
elif Model_Path !="":
downloadmodel_path(Model_Path)
MODEL_NAME="/models/stable-diffusion-custom"
elif Model_Link !="":
downloadmodel_link(Model_Link)
MODEL_NAME="/models/stable-diffusion-custom"
else:
MODEL_NAME="/datasets/stable-diffusion-diffusers/stable-diffusion-v1-5"
print('[1;32mUsing the original V1.5 model')
return MODEL_NAME
def sess(Session_Name, Session_Link_optional, MODEL_NAME):
import wget, gdown
os.chdir('/notebooks')
PT=""
while Session_Name=="":
print('[1;31mInput the Session Name:')
Session_Name=input("")
Session_Name=Session_Name.replace(" ","_")
WORKSPACE='/notebooks/Fast-Dreambooth'
if Session_Link_optional !="":
print('[1;33mDownloading session...')
if Session_Link_optional != "":
if not os.path.exists(str(WORKSPACE+'/Sessions')):
call("mkdir -p " +WORKSPACE+ "/Sessions", shell=True)
time.sleep(1)
os.chdir(WORKSPACE+'/Sessions')
gdown.download_folder(url=Session_Link_optional, output=Session_Name, quiet=True, remaining_ok=True, use_cookies=False)
os.chdir(Session_Name)
call("rm -r " +instance_images, shell=True)
call("unzip " +instance_images.zip, shell=True, stdout=open('/dev/null', 'w'))
call("rm -r " +concept_images, shell=True)
call("unzip " +concept_images.zip, shell=True, stdout=open('/dev/null', 'w'))
call("rm -r " +captions, shell=True)
call("unzip " +captions.zip, shell=True, stdout=open('/dev/null', 'w'))
os.chdir('/notebooks')
clear_output()
INSTANCE_NAME=Session_Name
OUTPUT_DIR="/models/"+Session_Name
SESSION_DIR=WORKSPACE+"/Sessions/"+Session_Name
CONCEPT_DIR=SESSION_DIR+"/concept_images"
INSTANCE_DIR=SESSION_DIR+"/instance_images"
CAPTIONS_DIR=SESSION_DIR+'/captions'
MDLPTH=str(SESSION_DIR+"/"+Session_Name+'.ckpt')
resume=False
if os.path.exists(str(SESSION_DIR)):
mdls=[ckpt for ckpt in listdir(SESSION_DIR) if ckpt.split(".")[-1]=="ckpt"]
if not os.path.exists(MDLPTH) and '.ckpt' in str(mdls):
def f(n):
k=0
for i in mdls:
if k==n:
call('mv '+SESSION_DIR+'/'+i+' '+MDLPTH, shell=True)
k=k+1
k=0
print('[1;33mNo final checkpoint model found, select which intermediary checkpoint to use, enter only the number, (000 to skip):\n[1;34m')
for i in mdls:
print(str(k)+'- '+i)
k=k+1
n=input()
while int(n)>k-1:
n=input()
if n!="000":
f(int(n))
print('[1;32mUsing the model '+ mdls[int(n)]+" ...")
time.sleep(4)
clear_output()
else:
print('[1;32mSkipping the intermediary checkpoints.')
if os.path.exists(str(SESSION_DIR)) and not os.path.exists(MDLPTH):
print('[1;32mLoading session with no previous model, using the original model or the custom downloaded model')
if MODEL_NAME=="":
print('[1;31mNo model found, use the "Model Download" cell to download a model.')
else:
print('[1;32mSession Loaded, proceed to uploading instance images')
elif os.path.exists(MDLPTH):
print('[1;32mSession found, loading the trained model ...')
call('wget -q -O config.yaml https://github.com/CompVis/stable-diffusion/raw/main/configs/stable-diffusion/v1-inference.yaml', shell=True)
call('python /diffusers/scripts/convert_original_stable_diffusion_to_diffusers.py --checkpoint_path '+MDLPTH+' --dump_path '+OUTPUT_DIR+' --original_config_file config.yaml', shell=True)
clear_output()
call('rm config.yaml', shell=True)
if os.path.exists(OUTPUT_DIR+'/unet/diffusion_pytorch_model.bin'):
resume=True
clear_output()
print('[1;32mSession loaded.')
else:
print('[1;31mConversion error, if the error persists, remove the CKPT file from the current session folder')
elif not os.path.exists(str(SESSION_DIR)):
call('mkdir -p '+INSTANCE_DIR, shell=True)
print('[1;32mCreating session...')
if MODEL_NAME=="":
print('[1;31mNo model found, use the "Model Download" cell to download a model.')
else:
print('[1;32mSession created, proceed to uploading instance images')
return PT, WORKSPACE, Session_Name, INSTANCE_NAME, OUTPUT_DIR, SESSION_DIR, CONCEPT_DIR, INSTANCE_DIR, CAPTIONS_DIR, MDLPTH, MODEL_NAME, resume
def done():
done = widgets.Button(
description='Done!',
disabled=True,
button_style='success',
tooltip='',
icon='check'
)
display(done)
def uplder(Remove_existing_instance_images, Crop_images, Crop_size, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR, ren):
if os.path.exists(INSTANCE_DIR+"/.ipynb_checkpoints"):
call('rm -r '+INSTANCE_DIR+'/.ipynb_checkpoints', shell=True)
uploader = widgets.FileUpload(description="Choose images",accept='image/*, .txt', multiple=True)
Upload = widgets.Button(
description='Upload',
disabled=False,
button_style='info',
tooltip='Click to upload the chosen instance images',
icon=''
)
def up(Upload):
with out:
uploader.close()
Upload.close()
upld(Remove_existing_instance_images, Crop_images, Crop_size, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR, uploader, ren)
done()
out=widgets.Output()
if IMAGES_FOLDER_OPTIONAL=="":
Upload.on_click(up)
display(uploader, Upload, out)
else:
upld(Remove_existing_instance_images, Crop_images, Crop_size, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR, uploader, ren)
done()
def upld(Remove_existing_instance_images, Crop_images, Crop_size, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR, uploader, ren):
if Remove_existing_instance_images:
if os.path.exists(str(INSTANCE_DIR)):
call("rm -r " +INSTANCE_DIR, shell=True)
if os.path.exists(str(CAPTIONS_DIR)):
call("rm -r " +CAPTIONS_DIR, shell=True)
if not os.path.exists(str(INSTANCE_DIR)):
call("mkdir -p " +INSTANCE_DIR, shell=True)
if not os.path.exists(str(CAPTIONS_DIR)):
call("mkdir -p " +CAPTIONS_DIR, shell=True)
if IMAGES_FOLDER_OPTIONAL !="":
if os.path.exists(IMAGES_FOLDER_OPTIONAL+"/.ipynb_checkpoints"):
call('rm -r '+IMAGES_FOLDER_OPTIONAL+'/.ipynb_checkpoints', shell=True)
if any(file.endswith('.{}'.format('txt')) for file in os.listdir(IMAGES_FOLDER_OPTIONAL)):
call('mv '+IMAGES_FOLDER_OPTIONAL+'/*.txt '+CAPTIONS_DIR, shell=True)
if Crop_images:
os.chdir(str(IMAGES_FOLDER_OPTIONAL))
call('find . -name "* *" -type f | rename ' "'s/ /-/g'", shell=True)
os.chdir('/notebooks')
for filename in tqdm(os.listdir(IMAGES_FOLDER_OPTIONAL), bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Uploaded'):
extension = filename.split(".")[-1]
identifier=filename.split(".")[0]
new_path_with_file = os.path.join(INSTANCE_DIR, filename)
file = Image.open(IMAGES_FOLDER_OPTIONAL+"/"+filename)
file=file.convert("RGB")
file=ImageOps.exif_transpose(file)
width, height = file.size
if file.size !=(Crop_size, Crop_size):
image=crop_image(file, Crop_size)
if extension.upper()=="JPG" or extension.upper()=="jpg":
image[0].save(new_path_with_file, format="JPEG", quality = 100)
else:
image[0].save(new_path_with_file, format=extension.upper())
else:
call("cp \'"+IMAGES_FOLDER_OPTIONAL+"/"+filename+"\' "+INSTANCE_DIR, shell=True)
else:
for filename in tqdm(os.listdir(IMAGES_FOLDER_OPTIONAL), bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Uploaded'):
call("cp -r " +IMAGES_FOLDER_OPTIONAL+"/. " +INSTANCE_DIR, shell=True)
elif IMAGES_FOLDER_OPTIONAL =="":
up=""
for file in uploader.value:
filename = file['name']
if filename.split(".")[-1]=="txt":
with open(CAPTIONS_DIR+'/'+filename, 'w') as f:
f.write(bytes(file['content']).decode())
up=[file for file in uploader.value if not file['name'].endswith('.txt')]
if Crop_images:
for file in tqdm(up, bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Uploaded'):
filename = file['name']
img = Image.open(io.BytesIO(file['content']))
extension = filename.split(".")[-1]
identifier=filename.split(".")[0]
img=img.convert("RGB")
img=ImageOps.exif_transpose(img)
if extension.upper()=="JPG" or extension.upper()=="jpg":
img.save(INSTANCE_DIR+"/"+filename, format="JPEG", quality = 100)
else:
img.save(INSTANCE_DIR+"/"+filename, format=extension.upper())
new_path_with_file = os.path.join(INSTANCE_DIR, filename)
file = Image.open(new_path_with_file)
width, height = file.size
if file.size !=(Crop_size, Crop_size):
image=crop_image(file, Crop_size)
if extension.upper()=="JPG" or extension.upper()=="jpg":
image[0].save(new_path_with_file, format="JPEG", quality = 100)
else:
image[0].save(new_path_with_file, format=extension.upper())
else:
for file in tqdm(uploader.value, bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Uploaded'):
filename = file['name']
img = Image.open(io.BytesIO(file['content']))
img=img.convert("RGB")
extension = filename.split(".")[-1]
identifier=filename.split(".")[0]
if extension.upper()=="JPG" or extension.upper()=="jpg":
img.save(INSTANCE_DIR+"/"+filename, format="JPEG", quality = 100)
else:
img.save(INSTANCE_DIR+"/"+filename, format=extension.upper())
if ren:
i=0
for filename in tqdm(os.listdir(INSTANCE_DIR), bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Renamed'):
extension = filename.split(".")[-1]
identifier=filename.split(".")[0]
new_path_with_file = os.path.join(INSTANCE_DIR, "conceptimagedb"+str(i)+"."+extension)
call('mv "'+os.path.join(INSTANCE_DIR,filename)+'" "'+new_path_with_file+'"', shell=True)
i=i+1
os.chdir(INSTANCE_DIR)
call('find . -name "* *" -type f | rename ' "'s/ /-/g'", shell=True)
os.chdir(CAPTIONS_DIR)
call('find . -name "* *" -type f | rename ' "'s/ /-/g'", shell=True)
os.chdir('/notebooks')
def caption(CAPTIONS_DIR, INSTANCE_DIR):
paths=""
out=""
widgets_l=""
clear_output()
def Caption(path):
if path!="Select an instance image to caption":
name = os.path.splitext(os.path.basename(path))[0]
ext=os.path.splitext(os.path.basename(path))[-1][1:]
if ext=="jpg" or "JPG":
ext="JPEG"
if os.path.exists(CAPTIONS_DIR+"/"+name + '.txt'):
with open(CAPTIONS_DIR+"/"+name + '.txt', 'r') as f:
text = f.read()
else:
with open(CAPTIONS_DIR+"/"+name + '.txt', 'w') as f:
f.write("")
with open(CAPTIONS_DIR+"/"+name + '.txt', 'r') as f:
text = f.read()
img=Image.open(os.path.join(INSTANCE_DIR,path))
img=img.convert("RGB")
img=img.resize((420, 420))
image_bytes = BytesIO()
img.save(image_bytes, format=ext, qualiy=10)
image_bytes.seek(0)
image_data = image_bytes.read()
img= image_data
image = widgets.Image(
value=img,
width=420,
height=420
)
text_area = widgets.Textarea(value=text, description='', disabled=False, layout={'width': '300px', 'height': '120px'})
def update_text(text):
with open(CAPTIONS_DIR+"/"+name + '.txt', 'w') as f:
f.write(text)
button = widgets.Button(description='Save', button_style='success')
button.on_click(lambda b: update_text(text_area.value))
return widgets.VBox([widgets.HBox([image, text_area, button])])
paths = os.listdir(INSTANCE_DIR)
widgets_l = widgets.Select(options=["Select an instance image to caption"]+paths, rows=25)
out = widgets.Output()
def click(change):
with out:
out.clear_output()
display(Caption(change.new))
widgets_l.observe(click, names='value')
display(widgets.HBox([widgets_l, out]))
def dbtrain(Resume_Training, UNet_Training_Steps, UNet_Learning_Rate, Text_Encoder_Training_Steps, Text_Encoder_Concept_Training_Steps, Text_Encoder_Learning_Rate, Offset_Noise, Resolution, MODEL_NAME, SESSION_DIR, INSTANCE_DIR, CONCEPT_DIR, CAPTIONS_DIR, External_Captions, INSTANCE_NAME, Session_Name, OUTPUT_DIR, PT, resume, Save_Checkpoint_Every_n_Steps, Start_saving_from_the_step, Save_Checkpoint_Every):
if os.path.exists(INSTANCE_DIR+"/.ipynb_checkpoints"):
call('rm -r '+INSTANCE_DIR+'/.ipynb_checkpoints', shell=True)
if os.path.exists(CONCEPT_DIR+"/.ipynb_checkpoints"):
call('rm -r '+CONCEPT_DIR+'/.ipynb_checkpoints', shell=True)
if os.path.exists(CAPTIONS_DIR+"/.ipynb_checkpoints"):
call('rm -r '+CAPTIONS_DIR+'/.ipynb_checkpoints', shell=True)
if resume and not Resume_Training:
print('[1;31mOverwrite your previously trained model ?, answering "yes" will train a new model, answering "no" will resume the training of the previous model? yes or no ?[0m')
while True:
ansres=input('')
if ansres=='no':
Resume_Training = True
resume= False
break
elif ansres=='yes':
Resume_Training = False
resume= False
break
while not Resume_Training and not os.path.exists(MODEL_NAME+'/unet/diffusion_pytorch_model.bin'):
print('[1;31mNo model found, use the "Model Download" cell to download a model.')
time.sleep(5)
MODELT_NAME=MODEL_NAME
Seed=random.randint(1, 999999)
ofstnse=""
if Offset_Noise:
ofstnse="--offset_noise"
extrnlcptn=""
if External_Captions:
extrnlcptn="--external_captions"
precision="fp16"
resuming=""
if Resume_Training and os.path.exists(OUTPUT_DIR+'/unet/diffusion_pytorch_model.bin'):
MODELT_NAME=OUTPUT_DIR
print('[1;32mResuming Training...[0m')
resuming="Yes"
elif Resume_Training and not os.path.exists(OUTPUT_DIR+'/unet/diffusion_pytorch_model.bin'):
print('[1;31mPrevious model not found, training a new model...[0m')
MODELT_NAME=MODEL_NAME
while MODEL_NAME=="":
print('[1;31mNo model found, use the "Model Download" cell to download a model.')
time.sleep(5)
trnonltxt=""
if UNet_Training_Steps==0:
trnonltxt="--train_only_text_encoder"
Enable_text_encoder_training= True
Enable_Text_Encoder_Concept_Training= True
if Text_Encoder_Training_Steps==0:
Enable_text_encoder_training= False
else:
stptxt=Text_Encoder_Training_Steps
if Text_Encoder_Concept_Training_Steps==0:
Enable_Text_Encoder_Concept_Training= False
else:
stptxtc=Text_Encoder_Concept_Training_Steps
if Save_Checkpoint_Every==None:
Save_Checkpoint_Every=1
stp=0
if Start_saving_from_the_step==None:
Start_saving_from_the_step=0
if (Start_saving_from_the_step < 200):
Start_saving_from_the_step=Save_Checkpoint_Every
stpsv=Start_saving_from_the_step
if Save_Checkpoint_Every_n_Steps:
stp=Save_Checkpoint_Every
def dump_only_textenc(trnonltxt, MODELT_NAME, INSTANCE_DIR, OUTPUT_DIR, PT, Seed, precision, Training_Steps):
call('accelerate launch /notebooks/diffusers/examples/dreambooth/train_dreambooth_pps.py \
'+trnonltxt+' \
'+extrnlcptn+' \
'+ofstnse+' \
--train_text_encoder \
--image_captions_filename \
--dump_only_text_encoder \
--pretrained_model_name_or_path='+MODELT_NAME+' \
--instance_data_dir='+INSTANCE_DIR+' \
--output_dir='+OUTPUT_DIR+' \
--captions_dir='+CAPTIONS_DIR+' \
--instance_prompt='+PT+' \
--seed='+str(Seed)+' \
--resolution='+str(Resolution)+' \
--mixed_precision='+str(precision)+' \
--train_batch_size=1 \
--gradient_accumulation_steps=1 --gradient_checkpointing \
--use_8bit_adam \
--learning_rate='+str(Text_Encoder_Learning_Rate)+' \
--lr_scheduler="linear" \
--lr_warmup_steps=0 \
--max_train_steps='+str(Training_Steps), shell=True)
def train_only_unet(stp, stpsv, SESSION_DIR, MODELT_NAME, INSTANCE_DIR, OUTPUT_DIR, Text_Encoder_Training_Steps, PT, Seed, Resolution, extrnlcptn, precision, Training_Steps):
clear_output()
if resuming=="Yes":
print('[1;32mResuming Training...[0m')
print('[1;33mTraining the UNet...[0m')
call('accelerate launch /notebooks/diffusers/examples/dreambooth/train_dreambooth_pps.py \
'+extrnlcptn+' \
'+ofstnse+' \
--image_captions_filename \
--train_only_unet \
--Session_dir='+SESSION_DIR+' \
--save_starting_step='+str(stpsv)+' \
--save_n_steps='+str(stp)+' \
--pretrained_model_name_or_path='+MODELT_NAME+' \
--instance_data_dir='+INSTANCE_DIR+' \
--output_dir='+OUTPUT_DIR+' \
--captions_dir='+CAPTIONS_DIR+' \
--instance_prompt='+PT+' \
--seed='+str(Seed)+' \
--resolution='+str(Resolution)+' \
--mixed_precision='+str(precision)+' \
--train_batch_size=1 \
--gradient_accumulation_steps=1 --gradient_checkpointing \
--use_8bit_adam \
--learning_rate='+str(UNet_Learning_Rate)+' \
--lr_scheduler="linear" \
--lr_warmup_steps=0 \
--max_train_steps='+str(Training_Steps), shell=True)
if Enable_text_encoder_training :
print('[1;33mTraining the text encoder...[0m')
if os.path.exists(OUTPUT_DIR+'/'+'text_encoder_trained'):
call('rm -r '+OUTPUT_DIR+'/text_encoder_trained', shell=True)
dump_only_textenc(trnonltxt, MODELT_NAME, INSTANCE_DIR, OUTPUT_DIR, PT, Seed, precision, Training_Steps=stptxt)
if Enable_Text_Encoder_Concept_Training:
if os.path.exists(CONCEPT_DIR):
if os.listdir(CONCEPT_DIR)!=[]:
clear_output()
if resuming=="Yes":
print('[1;32mResuming Training...[0m')
print('[1;33mTraining the text encoder on the concept...[0m')
dump_only_textenc(trnonltxt, MODELT_NAME, CONCEPT_DIR, OUTPUT_DIR, PT, Seed, precision, Training_Steps=stptxtc)
else:
clear_output()
if resuming=="Yes":
print('[1;32mResuming Training...[0m')
print('[1;31mNo concept images found, skipping concept training...')
Text_Encoder_Concept_Training_Steps=0
time.sleep(8)
else:
clear_output()
if resuming=="Yes":
print('[1;32mResuming Training...[0m')
print('[1;31mNo concept images found, skipping concept training...')
Text_Encoder_Concept_Training_Steps=0
time.sleep(8)
if UNet_Training_Steps!=0:
train_only_unet(stp, stpsv, SESSION_DIR, MODELT_NAME, INSTANCE_DIR, OUTPUT_DIR, Text_Encoder_Training_Steps, PT, Seed, Resolution, extrnlcptn, precision, Training_Steps=UNet_Training_Steps)
if UNet_Training_Steps==0 and Text_Encoder_Concept_Training_Steps==0 and Text_Encoder_Training_Steps==0 :
print('[1;32mNothing to do')
else:
if os.path.exists(OUTPUT_DIR+'/unet/diffusion_pytorch_model.bin'):
call('python /notebooks/diffusers/scripts/convertosdv2.py --fp16 '+OUTPUT_DIR+' '+SESSION_DIR+'/'+Session_Name+'.ckpt', shell=True)
clear_output()
if os.path.exists(SESSION_DIR+"/"+INSTANCE_NAME+'.ckpt'):
clear_output()
print("[1;32mDONE, the CKPT model is in the session's folder")
else:
print("[1;31mSomething went wrong")
else:
print("[1;31mSomething went wrong")
return resume
def testui(Custom_Path, Previous_Session_Name, Session_Name, User, Password):
if Previous_Session_Name!="":
print("[1;32mLoading a previous session model")
mdldir='/notebooks/Fast-Dreambooth/Sessions/'+Previous_Session_Name
path_to_trained_model=mdldir+"/"+Previous_Session_Name+'.ckpt'
while not os.path.exists(path_to_trained_model):
print("[1;31mThere is no trained model in the previous session")
time.sleep(5)
elif Custom_Path!="":
print("[1;32mLoading model from a custom path")
path_to_trained_model=Custom_Path
while not os.path.exists(path_to_trained_model):
print("[1;31mWrong Path")
time.sleep(5)
else:
print("[1;32mLoading the trained model")
mdldir='/notebooks/Fast-Dreambooth/Sessions/'+Session_Name
path_to_trained_model=mdldir+"/"+Session_Name+'.ckpt'
while not os.path.exists(path_to_trained_model):
print("[1;31mThere is no trained model in this session")
time.sleep(5)
auth=f"--gradio-auth {User}:{Password}"
if User =="" or Password=="":
auth=""
os.chdir('/notebooks')
if not os.path.exists('/notebooks/sd/stablediffusiond'): #reset later
call('wget -q -O sd_mrep.tar.zst https://huggingface.co/TheLastBen/dependencies/resolve/main/sd_mrep.tar.zst', shell=True)
call('tar --zstd -xf sd_mrep.tar.zst', shell=True)
call('rm sd_mrep.tar.zst', shell=True)
os.chdir('/notebooks/sd')
if not os.path.exists('stable-diffusion-webui'):
call('git clone -q --depth 1 --branch master https://github.com/AUTOMATIC1111/stable-diffusion-webui', shell=True)
os.chdir('/notebooks/sd/stable-diffusion-webui/')
call('git reset --hard', shell=True, stdout=open('/dev/null', 'w'))
print('[1;32m')
call('git checkout master', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('git pull', shell=True, stdout=open('/dev/null', 'w'))
os.makedirs('/notebooks/sd/stable-diffusion-webui/repositories', exist_ok=True)
call('git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui-assets /notebooks/sd/stable-diffusion-webui/repositories/stable-diffusion-webui-assets', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
os.chdir('/notebooks')
clear_output()
call('wget -q -O /usr/local/lib/python3.11/dist-packages/gradio/blocks.py https://raw.githubusercontent.com/TheLastBen/fast-stable-diffusion/main/AUTOMATIC1111_files/blocks.py', shell=True)
localurl="tensorboard-"+os.environ.get('PAPERSPACE_FQDN')
for line in fileinput.input('/usr/local/lib/python3.11/dist-packages/gradio/blocks.py', inplace=True):
if line.strip().startswith('self.server_name ='):
line = f' self.server_name = "{localurl}"\n'
if line.strip().startswith('self.protocol = "https"'):
line = ' self.protocol = "https"\n'
if line.strip().startswith('if self.local_url.startswith("https") or self.is_colab'):
line = ''
if line.strip().startswith('else "http"'):
line = ''
sys.stdout.write(line)
os.chdir('/notebooks/sd/stable-diffusion-webui/modules')
call("sed -i 's@possible_sd_paths =.*@possible_sd_paths = [\"/notebooks/sd/stablediffusion\"]@' /notebooks/sd/stable-diffusion-webui/modules/paths.py", shell=True)
call("sed -i 's@\.\.\/@src/@g' /notebooks/sd/stable-diffusion-webui/modules/paths.py", shell=True)
call("sed -i 's@src\/generative-models@generative-models@g' /notebooks/sd/stable-diffusion-webui/modules/paths.py", shell=True)
os.chdir('/notebooks/sd/stable-diffusion-webui')
clear_output()
configf="--disable-console-progressbars --no-gradio-queue --no-hashing --no-half-vae --disable-safe-unpickle --api --no-download-sd-model --xformers --enable-insecure-extension-access --port 6006 --listen --skip-version-check --ckpt "+path_to_trained_model+" "+auth
return configf
def clean():
Sessions=os.listdir("/notebooks/Fast-Dreambooth/Sessions")
s = widgets.Select(
options=Sessions,
rows=5,
description='',
disabled=False
)
out=widgets.Output()
d = widgets.Button(
description='Remove',
disabled=False,
button_style='warning',
tooltip='Removet the selected session',
icon='warning'
)
def rem(d):
with out:
if s.value is not None:
clear_output()
print("[1;33mTHE SESSION [1;31m"+s.value+" [1;33mHAS BEEN REMOVED FROM THE STORAGE")
call('rm -r /notebooks/Fast-Dreambooth/Sessions/'+s.value, shell=True)
if os.path.exists('/notebooks/models/'+s.value):
call('rm -r /notebooks/models/'+s.value, shell=True)
s.options=os.listdir("/notebooks/Fast-Dreambooth/Sessions")
else:
d.close()
s.close()
clear_output()
print("[1;32mNOTHING TO REMOVE")
d.on_click(rem)
if s.value is not None:
display(s,d,out)
else:
print("[1;32mNOTHING TO REMOVE")
def hf(Name_of_your_concept, hf_token_write, INSTANCE_NAME, OUTPUT_DIR, Session_Name, MDLPTH):
from slugify import slugify
from huggingface_hub import HfApi, HfFolder, CommitOperationAdd
from huggingface_hub import create_repo
from IPython.display import display_markdown
if(Name_of_your_concept == ""):
Name_of_your_concept = Session_Name
Name_of_your_concept=Name_of_your_concept.replace(" ","-")
if hf_token_write =="":
print('[1;32mYour Hugging Face write access token : ')
hf_token_write=input()
hf_token = hf_token_write
api = HfApi()
your_username = api.whoami(token=hf_token)["name"]
repo_id = f"{your_username}/{slugify(Name_of_your_concept)}"
output_dir = f'/notebooks/models/'+INSTANCE_NAME
def bar(prg):
clear_output()
br="[1;33mUploading to HuggingFace : " '[0m|'+'█' * prg + ' ' * (25-prg)+'| ' +str(prg*4)+ "%"
return br
print("[1;33mLoading...")
os.chdir(OUTPUT_DIR)
call('rm -r safety_checker feature_extractor .git', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('rm model_index.json', shell=True)
call('git init', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('git lfs install --system --skip-repo', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('git remote add -f origin https://huggingface.co/runwayml/stable-diffusion-v1-5', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('git config core.sparsecheckout true', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('echo -e "\nfeature_extractor\nsafety_checker\nmodel_index.json\n!*.safetensors" > .git/info/sparse-checkout', shell=True)
call('git pull origin main', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('rm -r .git', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
os.chdir('/notebooks')
print(bar(1))
readme_text = f'''---
license: creativeml-openrail-m
tags:
- text-to-image
- stable-diffusion
---
### {Name_of_your_concept} Dreambooth model trained by {api.whoami(token=hf_token)["name"]} with TheLastBen's fast-DreamBooth notebook
'''
#Save the readme to a file
readme_file = open("README.md", "w")
readme_file.write(readme_text)
readme_file.close()
operations = [
CommitOperationAdd(path_in_repo="README.md", path_or_fileobj="README.md"),
CommitOperationAdd(path_in_repo=f"{Session_Name}.ckpt",path_or_fileobj=MDLPTH)
]
create_repo(repo_id,private=True, token=hf_token)
api.create_commit(
repo_id=repo_id,
operations=operations,
commit_message=f"Upload the concept {Name_of_your_concept} embeds and token",
token=hf_token
)
api.upload_folder(
folder_path=OUTPUT_DIR+"/feature_extractor",
path_in_repo="feature_extractor",
repo_id=repo_id,
token=hf_token
)
print(bar(4))
api.upload_folder(
folder_path=OUTPUT_DIR+"/safety_checker",
path_in_repo="safety_checker",
repo_id=repo_id,
token=hf_token
)
print(bar(8))
api.upload_folder(
folder_path=OUTPUT_DIR+"/scheduler",
path_in_repo="scheduler",
repo_id=repo_id,
token=hf_token
)
print(bar(9))
api.upload_folder(
folder_path=OUTPUT_DIR+"/text_encoder",
path_in_repo="text_encoder",
repo_id=repo_id,
token=hf_token
)
print(bar(12))
api.upload_folder(
folder_path=OUTPUT_DIR+"/tokenizer",
path_in_repo="tokenizer",
repo_id=repo_id,
token=hf_token
)
print(bar(13))
api.upload_folder(
folder_path=OUTPUT_DIR+"/unet",
path_in_repo="unet",
repo_id=repo_id,
token=hf_token
)
print(bar(21))
api.upload_folder(
folder_path=OUTPUT_DIR+"/vae",
path_in_repo="vae",
repo_id=repo_id,
token=hf_token
)
print(bar(23))
api.upload_file(
path_or_fileobj=OUTPUT_DIR+"/model_index.json",
path_in_repo="model_index.json",
repo_id=repo_id,
token=hf_token
)
print(bar(25))
print("[1;32mYour concept was saved successfully at https://huggingface.co/"+repo_id)
done()
def crop_image(im, size):
GREEN = "#0F0"
BLUE = "#00F"
RED = "#F00"
def focal_point(im, settings):
corner_points = image_corner_points(im, settings) if settings.corner_points_weight > 0 else []
entropy_points = image_entropy_points(im, settings) if settings.entropy_points_weight > 0 else []
face_points = image_face_points(im, settings) if settings.face_points_weight > 0 else []
pois = []
weight_pref_total = 0
if len(corner_points) > 0:
weight_pref_total += settings.corner_points_weight
if len(entropy_points) > 0:
weight_pref_total += settings.entropy_points_weight
if len(face_points) > 0:
weight_pref_total += settings.face_points_weight
corner_centroid = None
if len(corner_points) > 0:
corner_centroid = centroid(corner_points)
corner_centroid.weight = settings.corner_points_weight / weight_pref_total
pois.append(corner_centroid)
entropy_centroid = None
if len(entropy_points) > 0:
entropy_centroid = centroid(entropy_points)
entropy_centroid.weight = settings.entropy_points_weight / weight_pref_total
pois.append(entropy_centroid)
face_centroid = None
if len(face_points) > 0:
face_centroid = centroid(face_points)
face_centroid.weight = settings.face_points_weight / weight_pref_total
pois.append(face_centroid)
average_point = poi_average(pois, settings)
return average_point
def image_face_points(im, settings):
np_im = np.array(im)
gray = cv2.cvtColor(np_im, cv2.COLOR_BGR2GRAY)
tries = [
[ f'{cv2.data.haarcascades}haarcascade_eye.xml', 0.01 ],
[ f'{cv2.data.haarcascades}haarcascade_frontalface_default.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_profileface.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_frontalface_alt.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_frontalface_alt2.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_frontalface_alt_tree.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_eye_tree_eyeglasses.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_upperbody.xml', 0.05 ]
]
for t in tries:
classifier = cv2.CascadeClassifier(t[0])
minsize = int(min(im.width, im.height) * t[1]) # at least N percent of the smallest side
try:
faces = classifier.detectMultiScale(gray, scaleFactor=1.1,
minNeighbors=7, minSize=(minsize, minsize), flags=cv2.CASCADE_SCALE_IMAGE)
except:
continue
if len(faces) > 0:
rects = [[f[0], f[1], f[0] + f[2], f[1] + f[3]] for f in faces]
return [PointOfInterest((r[0] +r[2]) // 2, (r[1] + r[3]) // 2, size=abs(r[0]-r[2]), weight=1/len(rects)) for r in rects]
return []
def image_corner_points(im, settings):
grayscale = im.convert("L")
# naive attempt at preventing focal points from collecting at watermarks near the bottom
gd = ImageDraw.Draw(grayscale)
gd.rectangle([0, im.height*.9, im.width, im.height], fill="#999")
np_im = np.array(grayscale)
points = cv2.goodFeaturesToTrack(
np_im,
maxCorners=100,
qualityLevel=0.04,
minDistance=min(grayscale.width, grayscale.height)*0.06,
useHarrisDetector=False,
)
if points is None:
return []
focal_points = []
for point in points:
x, y = point.ravel()
focal_points.append(PointOfInterest(x, y, size=4, weight=1/len(points)))
return focal_points
def image_entropy_points(im, settings):
landscape = im.height < im.width
portrait = im.height > im.width
if landscape:
move_idx = [0, 2]
move_max = im.size[0]
elif portrait:
move_idx = [1, 3]
move_max = im.size[1]
else:
return []
e_max = 0
crop_current = [0, 0, settings.crop_width, settings.crop_height]
crop_best = crop_current
while crop_current[move_idx[1]] < move_max:
crop = im.crop(tuple(crop_current))
e = image_entropy(crop)
if (e > e_max):
e_max = e
crop_best = list(crop_current)
crop_current[move_idx[0]] += 4
crop_current[move_idx[1]] += 4
x_mid = int(crop_best[0] + settings.crop_width/2)
y_mid = int(crop_best[1] + settings.crop_height/2)
return [PointOfInterest(x_mid, y_mid, size=25, weight=1.0)]
def image_entropy(im):
# greyscale image entropy
# band = np.asarray(im.convert("L"))
band = np.asarray(im.convert("1"), dtype=np.uint8)
hist, _ = np.histogram(band, bins=range(0, 256))
hist = hist[hist > 0]
return -np.log2(hist / hist.sum()).sum()
def centroid(pois):
x = [poi.x for poi in pois]
y = [poi.y for poi in pois]
return PointOfInterest(sum(x)/len(pois), sum(y)/len(pois))
def poi_average(pois, settings):
weight = 0.0
x = 0.0
y = 0.0
for poi in pois:
weight += poi.weight
x += poi.x * poi.weight
y += poi.y * poi.weight
avg_x = round(weight and x / weight)
avg_y = round(weight and y / weight)
return PointOfInterest(avg_x, avg_y)
def is_landscape(w, h):
return w > h
def is_portrait(w, h):
return h > w
def is_square(w, h):
return w == h
class PointOfInterest:
def __init__(self, x, y, weight=1.0, size=10):
self.x = x
self.y = y
self.weight = weight
self.size = size
def bounding(self, size):
return [
self.x - size//2,
self.y - size//2,
self.x + size//2,
self.y + size//2
]
class Settings:
def __init__(self, crop_width=512, crop_height=512, corner_points_weight=0.5, entropy_points_weight=0.5, face_points_weight=0.5):
self.crop_width = crop_width
self.crop_height = crop_height
self.corner_points_weight = corner_points_weight
self.entropy_points_weight = entropy_points_weight
self.face_points_weight = face_points_weight
settings = Settings(
crop_width = size,
crop_height = size,
face_points_weight = 0.9,
entropy_points_weight = 0.15,
corner_points_weight = 0.5,
)
scale_by = 1
if is_landscape(im.width, im.height):
scale_by = settings.crop_height / im.height
elif is_portrait(im.width, im.height):
scale_by = settings.crop_width / im.width
elif is_square(im.width, im.height):
if is_square(settings.crop_width, settings.crop_height):
scale_by = settings.crop_width / im.width
elif is_landscape(settings.crop_width, settings.crop_height):
scale_by = settings.crop_width / im.width
elif is_portrait(settings.crop_width, settings.crop_height):
scale_by = settings.crop_height / im.height
im = im.resize((int(im.width * scale_by), int(im.height * scale_by)))
im_debug = im.copy()
focus = focal_point(im_debug, settings)
# take the focal point and turn it into crop coordinates that try to center over the focal
# point but then get adjusted back into the frame
y_half = int(settings.crop_height / 2)
x_half = int(settings.crop_width / 2)
x1 = focus.x - x_half
if x1 < 0:
x1 = 0
elif x1 + settings.crop_width > im.width:
x1 = im.width - settings.crop_width
y1 = focus.y - y_half
if y1 < 0:
y1 = 0
elif y1 + settings.crop_height > im.height:
y1 = im.height - settings.crop_height
x2 = x1 + settings.crop_width
y2 = y1 + settings.crop_height
crop = [x1, y1, x2, y2]
results = []
results.append(im.crop(tuple(crop)))
return results1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354from IPython.display import clear_output
from subprocess import call, getoutput
from IPython.display import display
import ipywidgets as widgets
import io
from PIL import Image, ImageDraw, ImageOps
import fileinput
import time
import os
from os import listdir
from os.path import isfile
from tqdm import tqdm
import gdown
import random
import sys
import cv2
from io import BytesIO
import requests
from collections import defaultdict
from math import log, sqrt
import numpy as np
from subprocess import check_output
import six
import re
from urllib.parse import urlparse, parse_qs, unquote
from urllib.request import urlopen, Request
import tempfile
from tqdm import tqdm
def Deps(force_reinstall):
if not force_reinstall and os.path.exists('/usr/local/lib/python3.9/dist-packages/safetensors'):
ntbk()
call('pip install --root-user-action=ignore --disable-pip-version-check -qq ./diffusers', shell=True, stdout=open('/dev/null', 'w'))
os.environ['TORCH_HOME'] = '/notebooks/cache/torch'
os.environ['PYTHONWARNINGS'] = 'ignore'
print('[1;32mModules and notebooks updated, dependencies already installed')
else:
call("pip install --root-user-action=ignore --no-deps -q accelerate==0.12.0", shell=True, stdout=open('/dev/null', 'w'))
if not os.path.exists('/usr/local/lib/python3.9/dist-packages/safetensors'):
os.chdir('/usr/local/lib/python3.9/dist-packages')
call("rm -r torch torch-1.12.1+cu116.dist-info torchaudio* torchvision* PIL Pillow* transformers* numpy* gdown*", shell=True, stdout=open('/dev/null', 'w'))
ntbk()
if not os.path.exists('/models'):
call('mkdir /models', shell=True)
if not os.path.exists('/notebooks/models'):
call('ln -s /models /notebooks', shell=True)
if os.path.exists('/deps'):
call("rm -r /deps", shell=True)
call('mkdir /deps', shell=True)
if not os.path.exists('cache'):
call('mkdir cache', shell=True)
os.chdir('/deps')
call('wget -q -i https://raw.githubusercontent.com/TheLastBen/fast-stable-diffusion/main/Dependencies/aptdeps.txt', shell=True)
call('dpkg -i *.deb', shell=True, stdout=open('/dev/null', 'w'))
depsinst("https://huggingface.co/TheLastBen/dependencies/resolve/main/ppsdeps.tar.zst", "/deps/ppsdeps.tar.zst")
call('tar -C / --zstd -xf ppsdeps.tar.zst', shell=True, stdout=open('/dev/null', 'w'))
call("sed -i 's@~/.cache@/notebooks/cache@' /usr/local/lib/python3.9/dist-packages/transformers/utils/hub.py", shell=True)
os.chdir('/notebooks')
call("git clone --depth 1 -q --branch main https://github.com/TheLastBen/diffusers /diffusers", shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
os.environ['TORCH_HOME'] = '/notebooks/cache/torch'
os.environ['PYTHONWARNINGS'] = 'ignore'
call("sed -i 's@text = _formatwarnmsg(msg)@text =\"\"@g' /usr/lib/python3.9/warnings.py", shell=True)
if not os.path.exists('/notebooks/diffusers'):
call('ln -s /diffusers /notebooks', shell=True)
call("rm -r /deps", shell=True)
os.chdir('/notebooks')
clear_output()
done()
def depsinst(url, dst):
file_size = None
req = Request(url, headers={"User-Agent": "torch.hub"})
u = urlopen(req)
meta = u.info()
if hasattr(meta, 'getheaders'):
content_length = meta.getheaders("Content-Length")
else:
content_length = meta.get_all("Content-Length")
if content_length is not None and len(content_length) > 0:
file_size = int(content_length[0])
with tqdm(total=file_size, disable=False, mininterval=0.5,
bar_format='Installing dependencies |{bar:20}| {percentage:3.0f}%') as pbar:
with open(dst, "wb") as f:
while True:
buffer = u.read(8192)
if len(buffer) == 0:
break
f.write(buffer)
pbar.update(len(buffer))
f.close()
def ntbk():
os.chdir('/notebooks')
if not os.path.exists('Latest_Notebooks'):
call('mkdir Latest_Notebooks', shell=True)
else:
call('rm -r Latest_Notebooks', shell=True)
call('mkdir Latest_Notebooks', shell=True)
os.chdir('/notebooks/Latest_Notebooks')
call('wget -q -i https://huggingface.co/datasets/TheLastBen/PPS/raw/main/Notebooks.txt', shell=True)
call('rm Notebooks.txt', shell=True)
os.chdir('/notebooks')
def downloadmodel_hfv2(Path_to_HuggingFace):
import wget
if os.path.exists('/models/stable-diffusion-custom'):
call("rm -r /models/stable-diffusion-custom", shell=True)
clear_output()
if os.path.exists('/notebooks/Fast-Dreambooth/token.txt'):
with open("/notebooks/Fast-Dreambooth/token.txt") as f:
token = f.read()
authe=f'https://USER:{token}@'
else:
authe="https://"
clear_output()
call("mkdir /models/stable-diffusion-custom", shell=True)
os.chdir("/models/stable-diffusion-custom")
call("git init", shell=True)
call("git lfs install --system --skip-repo", shell=True)
call('git remote add -f origin '+authe+'huggingface.co/'+Path_to_HuggingFace, shell=True)
call("git config core.sparsecheckout true", shell=True)
call('echo -e "\nscheduler\ntext_encoder\ntokenizer\nunet\nvae\nfeature_extractor\nmodel_index.json\n!*.safetensors" > .git/info/sparse-checkout', shell=True)
call("git pull origin main", shell=True)
if os.path.exists('unet/diffusion_pytorch_model.bin'):
call("rm -r .git", shell=True)
os.chdir('/notebooks')
clear_output()
done()
while not os.path.exists('/models/stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
print('[1;31mCheck the link you provided')
os.chdir('/notebooks')
time.sleep(5)
def downloadmodel_path_v2(MODEL_PATH):
modelname=os.path.basename(MODEL_PATH)
sftnsr=""
if modelname.split('.')[-1]=='safetensors':
sftnsr="--from_safetensors"
import wget
os.chdir('/models')
clear_output()
if os.path.exists(str(MODEL_PATH)):
wget.download('https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dreambooth/det.py')
print('[1;33mDetecting model version...')
Custom_Model_Version=check_output('python det.py '+sftnsr+' --MODEL_PATH '+MODEL_PATH, shell=True).decode('utf-8').replace('\n', '')
clear_output()
print('[1;32m'+Custom_Model_Version+' Detected')
call('rm det.py', shell=True)
if Custom_Model_Version=='V2.1-512px':
call('wget -q -O convertodiffv2.py https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dreambooth/convertodiffv2.py', shell=True)
call('python convertodiffv2.py '+MODEL_PATH+' stable-diffusion-custom --v2 --reference_model stabilityai/stable-diffusion-2-1-base '+sftnsr, shell=True)
elif Custom_Model_Version=='V2.1-768px':
call('wget -q -O convertodiffv2.py https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dreambooth/convertodiffv2-768.py', shell=True)
call('python convertodiffv2.py '+MODEL_PATH+' stable-diffusion-custom --v2 --reference_model stabilityai/stable-diffusion-2-1 '+sftnsr, shell=True)
call('rm convertodiffv2.py', shell=True)
if os.path.exists('/models/stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
clear_output()
done()
while not os.path.exists('/models/stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
print('[1;31mConversion error')
os.chdir('/workspace')
time.sleep(5)
else:
while not os.path.exists(str(MODEL_PATH)):
print('[1;31mWrong path, use the file explorer to copy the path')
os.chdir('/workspace')
time.sleep(5)
def downloadmodel_link_v2(MODEL_LINK):
import wget
import gdown
from gdown.download import get_url_from_gdrive_confirmation
def getsrc(url):
parsed_url = urlparse(url)
if parsed_url.netloc == 'civitai.com':
src='civitai'
elif parsed_url.netloc == 'drive.google.com':
src='gdrive'
elif parsed_url.netloc == 'huggingface.co':
src='huggingface'
else:
src='others'
return src
src=getsrc(MODEL_LINK)
def get_name(url, gdrive):
if not gdrive:
response = requests.get(url, allow_redirects=False)
if "Location" in response.headers:
redirected_url = response.headers["Location"]
quer = parse_qs(urlparse(redirected_url).query)
if "response-content-disposition" in quer:
disp_val = quer["response-content-disposition"][0].split(";")
for vals in disp_val:
if vals.strip().startswith("filename="):
filenm=unquote(vals.split("=", 1)[1].strip())
return filenm.replace("\"","")
else:
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"}
lnk="https://drive.google.com/uc?id={id}&export=download".format(id=url[url.find("/d/")+3:url.find("/view")])
res = requests.session().get(lnk, headers=headers, stream=True, verify=True)
res = requests.session().get(get_url_from_gdrive_confirmation(res.text), headers=headers, stream=True, verify=True)
content_disposition = six.moves.urllib_parse.unquote(res.headers["Content-Disposition"])
filenm = re.search(r"filename\*=UTF-8''(.*)", content_disposition).groups()[0].replace(os.path.sep, "_")
return filenm
if src=='civitai':
modelname=get_name(MODEL_LINK, False)
elif src=='gdrive':
modelname=get_name(MODEL_LINK, True)
else:
modelname=os.path.basename(MODEL_LINK)
sftnsr=""
if modelname.split('.')[-1]!='safetensors':
modelnm="model.ckpt"
else:
modelnm="model.safetensors"
sftnsr="--from_safetensors"
os.chdir('/models')
call("gdown --fuzzy " +MODEL_LINK+ " -O "+modelnm, shell=True)
if os.path.exists(modelnm):
if os.path.getsize(modelnm) > 1810671599:
wget.download('https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dreambooth/det.py')
print('[1;33mDetecting model version...')
Custom_Model_Version=check_output('python det.py '+sftnsr+' --MODEL_PATH '+modelnm, shell=True).decode('utf-8').replace('\n', '')
clear_output()
print('[1;32m'+Custom_Model_Version+' Detected')
call('rm det.py', shell=True)
if Custom_Model_Version=='V2.1-512px':
call('wget -q -O convertodiffv2.py https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dreambooth/convertodiffv2.py', shell=True)
call('python convertodiffv2.py '+modelnm+' stable-diffusion-custom --v2 --reference_model stabilityai/stable-diffusion-2-1-base '+sftnsr, shell=True)
elif Custom_Model_Version=='V2.1-768px':
call('wget -q -O convertodiffv2.py https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dreambooth/convertodiffv2-768.py', shell=True)
call('python convertodiffv2.py '+modelnm+' stable-diffusion-custom --v2 --reference_model stabilityai/stable-diffusion-2-1 '+sftnsr, shell=True)
call('rm convertodiffv2.py', shell=True)
if os.path.exists('/models/stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
call('rm '+modelnm, shell=True)
os.chdir('/workspace')
clear_output()
done()
else:
while not os.path.exists('/models/stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
print('[1;31mConversion error')
os.chdir('/workspace')
time.sleep(5)
else:
while os.path.getsize(modelnm) < 1810671599:
print('[1;31mWrong link, check that the link is valid')
os.chdir('/workspace')
time.sleep(5)
def dlsv2(Path_to_HuggingFace, Model_Path, Model_Link, Model_Version):
if Path_to_HuggingFace != "":
downloadmodel_hfv2(Path_to_HuggingFace)
MODEL_NAMEv2="/models/stable-diffusion-custom"
elif Model_Path !="":
downloadmodel_path_v2(Model_Path)
MODEL_NAMEv2="/models/stable-diffusion-custom"
elif Model_Link !="":
downloadmodel_link_v2(Model_Link)
MODEL_NAMEv2="/models/stable-diffusion-custom"
else:
if Model_Version=="512":
MODEL_NAMEv2="/datasets/stable-diffusion-v2-1-base-diffusers/stable-diffusion-2-1-base"
print('[1;32mUsing the original V2-512 model')
elif Model_Version=="768":
MODEL_NAMEv2="/datasets/stable-diffusion-v2-1/stable-diffusion-2-1"
print('[1;32mUsing the original V2-768 model')
else:
MODEL_NAMEv2=""
print('[1;31mWrong model version')
return MODEL_NAMEv2
def sessv2(Session_Name, Session_Link_optional, MODEL_NAMEv2):
import gdown
import wget
os.chdir('/notebooks')
PT=""
while Session_Name=="":
print('[1;31mInput the Session Name:')
Session_Name=input("")
Session_Name=Session_Name.replace(" ","_")
WORKSPACE='/notebooks/Fast-Dreambooth'
if Session_Link_optional !="":
print('[1;33mDownloading session...')
if Session_Link_optional != "":
if not os.path.exists(str(WORKSPACE+'/Sessions')):
call("mkdir -p " +WORKSPACE+ "/Sessions", shell=True)
time.sleep(1)
os.chdir(WORKSPACE+'/Sessions')
gdown.download_folder(url=Session_Link_optional, output=Session_Name, quiet=True, remaining_ok=True, use_cookies=False)
os.chdir(Session_Name)
call("rm -r " +instance_images, shell=True)
call("unzip " +instance_images.zip, shell=True, stdout=open('/dev/null', 'w'))
call("rm -r " +concept_images, shell=True)
call("unzip " +concept_images.zip, shell=True, stdout=open('/dev/null', 'w'))
call("rm -r " +captions, shell=True)
call("unzip " +captions.zip, shell=True, stdout=open('/dev/null', 'w'))
os.chdir('/notebooks')
clear_output()
INSTANCE_NAME=Session_Name
OUTPUT_DIR="/models/"+Session_Name
SESSION_DIR=WORKSPACE+"/Sessions/"+Session_Name
CONCEPT_DIR=SESSION_DIR+"/concept_images"
INSTANCE_DIR=SESSION_DIR+"/instance_images"
CAPTIONS_DIR=SESSION_DIR+'/captions'
MDLPTH=str(SESSION_DIR+"/"+Session_Name+'.ckpt')
resumev2=False
if os.path.exists(str(SESSION_DIR)):
mdls=[ckpt for ckpt in listdir(SESSION_DIR) if ckpt.split(".")[-1]=="ckpt"]
if not os.path.exists(MDLPTH) and '.ckpt' in str(mdls):
def f(n):
k=0
for i in mdls:
if k==n:
call('mv '+SESSION_DIR+'/'+i+' '+MDLPTH, shell=True)
k=k+1
k=0
print('[1;33mNo final checkpoint model found, select which intermediary checkpoint to use, enter only the number, (000 to skip):\n[1;34m')
for i in mdls:
print(str(k)+'- '+i)
k=k+1
n=input()
while int(n)>k-1:
n=input()
if n!="000":
f(int(n))
print('[1;32mUsing the model '+ mdls[int(n)]+" ...")
time.sleep(4)
else:
print('[1;32mSkipping the intermediary checkpoints.')
if os.path.exists(str(SESSION_DIR)) and not os.path.exists(MDLPTH):
print('[1;32mLoading session with no previous model, using the original model or the custom downloaded model')
if MODEL_NAMEv2=="":
print('[1;31mNo model found, use the "Model Download" cell to download a model.')
else:
print('[1;32mSession Loaded, proceed to uploading instance images')
elif os.path.exists(MDLPTH):
print('[1;32mSession found, loading the trained model ...')
wget.download('https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dreambooth/det.py')
print('[1;33mDetecting model version...')
Model_Version=check_output('python det.py --MODEL_PATH '+MDLPTH, shell=True).decode('utf-8').replace('\n', '')
clear_output()
print('[1;32m'+Model_Version+' Detected')
call('rm det.py', shell=True)
if Model_Version=='V2.1-512px':
call('wget -q -O convertodiff.py https://raw.githubusercontent.com/TheLastBen/fast-stable-diffusion/main/Dreambooth/convertodiffv2.py', shell=True)
call('python convertodiff.py '+MDLPTH+' '+OUTPUT_DIR+' --v2 --reference_model stabilityai/stable-diffusion-2-1-base', shell=True)
elif Model_Version=='V2.1-768px':
call('wget -q -O convertodiff.py https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dreambooth/convertodiffv2-768.py', shell=True)
call('python convertodiff.py '+MDLPTH+' '+OUTPUT_DIR+' --v2 --reference_model stabilityai/stable-diffusion-2-1', shell=True)
clear_output()
call('rm convertodiff.py', shell=True)
if os.path.exists(OUTPUT_DIR+'/unet/diffusion_pytorch_model.bin'):
resumev2=True
clear_output()
print('[1;32mSession loaded.')
else:
print('[1;31mConversion error, if the error persists, remove the CKPT file from the current session folder')
elif not os.path.exists(str(SESSION_DIR)):
call('mkdir -p '+INSTANCE_DIR, shell=True)
print('[1;32mCreating session...')
if MODEL_NAMEv2=="":
print('[1;31mNo model found, use the "Model Download" cell to download a model.')
else:
print('[1;32mSession created, proceed to uploading instance images')
return PT, WORKSPACE, Session_Name, INSTANCE_NAME, OUTPUT_DIR, SESSION_DIR, CONCEPT_DIR, INSTANCE_DIR, CAPTIONS_DIR, MDLPTH, MODEL_NAMEv2, resumev2
def done():
done = widgets.Button(
description='Done!',
disabled=True,
button_style='success',
tooltip='',
icon='check'
)
display(done)
def uplder(Remove_existing_instance_images, Crop_images, Crop_size, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR, ren):
if os.path.exists(INSTANCE_DIR+"/.ipynb_checkpoints"):
call('rm -r '+INSTANCE_DIR+'/.ipynb_checkpoints', shell=True)
uploader = widgets.FileUpload(description="Choose images",accept='image/*, .txt', multiple=True)
Upload = widgets.Button(
description='Upload',
disabled=False,
button_style='info',
tooltip='Click to upload the chosen instance images',
icon=''
)
def up(Upload):
with out:
uploader.close()
Upload.close()
upld(Remove_existing_instance_images, Crop_images, Crop_size, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR, uploader, ren)
done()
out=widgets.Output()
if IMAGES_FOLDER_OPTIONAL=="":
Upload.on_click(up)
display(uploader, Upload, out)
else:
upld(Remove_existing_instance_images, Crop_images, Crop_size, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR, uploader, ren)
done()
def upld(Remove_existing_instance_images, Crop_images, Crop_size, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR, uploader, ren):
if Remove_existing_instance_images:
if os.path.exists(str(INSTANCE_DIR)):
call("rm -r " +INSTANCE_DIR, shell=True)
if os.path.exists(str(CAPTIONS_DIR)):
call("rm -r " +CAPTIONS_DIR, shell=True)
if not os.path.exists(str(INSTANCE_DIR)):
call("mkdir -p " +INSTANCE_DIR, shell=True)
if not os.path.exists(str(CAPTIONS_DIR)):
call("mkdir -p " +CAPTIONS_DIR, shell=True)
if IMAGES_FOLDER_OPTIONAL !="":
if os.path.exists(IMAGES_FOLDER_OPTIONAL+"/.ipynb_checkpoints"):
call('rm -r '+IMAGES_FOLDER_OPTIONAL+'/.ipynb_checkpoints', shell=True)
if any(file.endswith('.{}'.format('txt')) for file in os.listdir(IMAGES_FOLDER_OPTIONAL)):
call('mv '+IMAGES_FOLDER_OPTIONAL+'/*.txt '+CAPTIONS_DIR, shell=True)
if Crop_images:
os.chdir(str(IMAGES_FOLDER_OPTIONAL))
call('find . -name "* *" -type f | rename ' "'s/ /-/g'", shell=True)
os.chdir('/notebooks')
for filename in tqdm(os.listdir(IMAGES_FOLDER_OPTIONAL), bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Uploaded'):
extension = filename.split(".")[-1]
identifier=filename.split(".")[0]
new_path_with_file = os.path.join(INSTANCE_DIR, filename)
file = Image.open(IMAGES_FOLDER_OPTIONAL+"/"+filename)
file=file.convert("RGB")
file=ImageOps.exif_transpose(file)
width, height = file.size
if file.size !=(Crop_size, Crop_size):
image=crop_image(file, Crop_size)
if extension.upper()=="JPG" or extension.upper()=="jpg":
image[0].save(new_path_with_file, format="JPEG", quality = 100)
else:
image[0].save(new_path_with_file, format=extension.upper())
else:
call("cp \'"+IMAGES_FOLDER_OPTIONAL+"/"+filename+"\' "+INSTANCE_DIR, shell=True)
else:
for filename in tqdm(os.listdir(IMAGES_FOLDER_OPTIONAL), bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Uploaded'):
call("cp -r " +IMAGES_FOLDER_OPTIONAL+"/. " +INSTANCE_DIR, shell=True)
elif IMAGES_FOLDER_OPTIONAL =="":
up=""
for file in uploader.value:
filename = file['name']
if filename.split(".")[-1]=="txt":
with open(CAPTIONS_DIR+'/'+filename, 'w') as f:
f.write(bytes(file['content']).decode())
up=[file for file in uploader.value if not file['name'].endswith('.txt')]
if Crop_images:
for file in tqdm(up, bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Uploaded'):
filename = file['name']
img = Image.open(io.BytesIO(file['content']))
extension = filename.split(".")[-1]
identifier=filename.split(".")[0]
img=img.convert("RGB")
img=ImageOps.exif_transpose(img)
if extension.upper()=="JPG" or extension.upper()=="jpg":
img.save(INSTANCE_DIR+"/"+filename, format="JPEG", quality = 100)
else:
img.save(INSTANCE_DIR+"/"+filename, format=extension.upper())
new_path_with_file = os.path.join(INSTANCE_DIR, filename)
file = Image.open(new_path_with_file)
width, height = file.size
if file.size !=(Crop_size, Crop_size):
image=crop_image(file, Crop_size)
if extension.upper()=="JPG" or extension.upper()=="jpg":
image[0].save(new_path_with_file, format="JPEG", quality = 100)
else:
image[0].save(new_path_with_file, format=extension.upper())
else:
for file in tqdm(uploader.value, bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Uploaded'):
filename = file['name']
img = Image.open(io.BytesIO(file['content']))
img=img.convert("RGB")
extension = filename.split(".")[-1]
identifier=filename.split(".")[0]
if extension.upper()=="JPG" or extension.upper()=="jpg":
img.save(INSTANCE_DIR+"/"+filename, format="JPEG", quality = 100)
else:
img.save(INSTANCE_DIR+"/"+filename, format=extension.upper())
if ren:
i=0
for filename in tqdm(os.listdir(INSTANCE_DIR), bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Renamed'):
extension = filename.split(".")[-1]
identifier=filename.split(".")[0]
new_path_with_file = os.path.join(INSTANCE_DIR, "conceptimagedb"+str(i)+"."+extension)
call('mv "'+os.path.join(INSTANCE_DIR,filename)+'" "'+new_path_with_file+'"', shell=True)
i=i+1
os.chdir(INSTANCE_DIR)
call('find . -name "* *" -type f | rename ' "'s/ /-/g'", shell=True)
os.chdir(CAPTIONS_DIR)
call('find . -name "* *" -type f | rename ' "'s/ /-/g'", shell=True)
os.chdir('/notebooks')
def caption(CAPTIONS_DIR, INSTANCE_DIR):
paths=""
out=""
widgets_l=""
clear_output()
def Caption(path):
if path!="Select an instance image to caption":
name = os.path.splitext(os.path.basename(path))[0]
ext=os.path.splitext(os.path.basename(path))[-1][1:]
if ext=="jpg" or "JPG":
ext="JPEG"
if os.path.exists(CAPTIONS_DIR+"/"+name + '.txt'):
with open(CAPTIONS_DIR+"/"+name + '.txt', 'r') as f:
text = f.read()
else:
with open(CAPTIONS_DIR+"/"+name + '.txt', 'w') as f:
f.write("")
with open(CAPTIONS_DIR+"/"+name + '.txt', 'r') as f:
text = f.read()
img=Image.open(os.path.join(INSTANCE_DIR,path))
img=img.convert("RGB")
img=img.resize((420, 420))
image_bytes = BytesIO()
img.save(image_bytes, format=ext, qualiy=10)
image_bytes.seek(0)
image_data = image_bytes.read()
img= image_data
image = widgets.Image(
value=img,
width=420,
height=420
)
text_area = widgets.Textarea(value=text, description='', disabled=False, layout={'width': '300px', 'height': '120px'})
def update_text(text):
with open(CAPTIONS_DIR+"/"+name + '.txt', 'w') as f:
f.write(text)
button = widgets.Button(description='Save', button_style='success')
button.on_click(lambda b: update_text(text_area.value))
return widgets.VBox([widgets.HBox([image, text_area, button])])
paths = os.listdir(INSTANCE_DIR)
widgets_l = widgets.Select(options=["Select an instance image to caption"]+paths, rows=25)
out = widgets.Output()
def click(change):
with out:
out.clear_output()
display(Caption(change.new))
widgets_l.observe(click, names='value')
display(widgets.HBox([widgets_l, out]))
def dbtrainv2(Resume_Training, UNet_Training_Steps, UNet_Learning_Rate, Text_Encoder_Training_Steps, Text_Encoder_Concept_Training_Steps, Text_Encoder_Learning_Rate, Offset_Noise, Resolution, MODEL_NAMEv2, SESSION_DIR, INSTANCE_DIR, CONCEPT_DIR, CAPTIONS_DIR, External_Captions, INSTANCE_NAME, Session_Name, OUTPUT_DIR, PT, resumev2, Save_Checkpoint_Every_n_Steps, Start_saving_from_the_step, Save_Checkpoint_Every):
if os.path.exists(INSTANCE_DIR+"/.ipynb_checkpoints"):
call('rm -r '+INSTANCE_DIR+'/.ipynb_checkpoints', shell=True)
if os.path.exists(CONCEPT_DIR+"/.ipynb_checkpoints"):
call('rm -r '+CONCEPT_DIR+'/.ipynb_checkpoints', shell=True)
if os.path.exists(CAPTIONS_DIR+"/.ipynb_checkpoints"):
call('rm -r '+CAPTIONS_DIR+'/.ipynb_checkpoints', shell=True)
if resumev2 and not Resume_Training:
print('[1;31mOverwrite your previously trained model ?, answering "yes" will train a new model, answering "no" will resumev2 the training of the previous model? yes or no ?[0m')
while True:
ansres=input('')
if ansres=='no':
Resume_Training = True
resumev2= False
break
elif ansres=='yes':
Resume_Training = False
resumev2= False
break
while not Resume_Training and not os.path.exists(MODEL_NAMEv2+'/unet/diffusion_pytorch_model.bin'):
print('[1;31mNo model found, use the "Model Download" cell to download a model.')
time.sleep(5)
MODELT_NAME=MODEL_NAMEv2
Seed=random.randint(1, 999999)
ofstnse=""
if Offset_Noise:
ofstnse="--offset_noise"
extrnlcptn=""
if External_Captions:
extrnlcptn="--external_captions"
precision="fp16"
resuming=""
if Resume_Training and os.path.exists(OUTPUT_DIR+'/unet/diffusion_pytorch_model.bin'):
MODELT_NAME=OUTPUT_DIR
print('[1;32mResuming Training...[0m')
resuming="Yes"
elif Resume_Training and not os.path.exists(OUTPUT_DIR+'/unet/diffusion_pytorch_model.bin'):
print('[1;31mPrevious model not found, training a new model...[0m')
MODELT_NAME=MODEL_NAMEv2
while MODEL_NAMEv2=="":
print('[1;31mNo model found, use the "Model Download" cell to download a model.')
time.sleep(5)
trnonltxt=""
if UNet_Training_Steps==0:
trnonltxt="--train_only_text_encoder"
Enable_text_encoder_training= True
Enable_Text_Encoder_Concept_Training= True
if Text_Encoder_Training_Steps==0:
Enable_text_encoder_training= False
else:
stptxt=Text_Encoder_Training_Steps
if Text_Encoder_Concept_Training_Steps==0:
Enable_Text_Encoder_Concept_Training= False
else:
stptxtc=Text_Encoder_Concept_Training_Steps
if Save_Checkpoint_Every==None:
Save_Checkpoint_Every=1
stp=0
if Start_saving_from_the_step==None:
Start_saving_from_the_step=0
if (Start_saving_from_the_step < 200):
Start_saving_from_the_step=Save_Checkpoint_Every
stpsv=Start_saving_from_the_step
if Save_Checkpoint_Every_n_Steps:
stp=Save_Checkpoint_Every
def dump_only_textenc(trnonltxt, MODELT_NAME, INSTANCE_DIR, OUTPUT_DIR, PT, Seed, precision, Training_Steps):
call('accelerate launch /notebooks/diffusers/examples/dreambooth/train_dreambooth_pps.py \
'+trnonltxt+' \
'+extrnlcptn+' \
'+ofstnse+' \
--train_text_encoder \
--image_captions_filename \
--dump_only_text_encoder \
--pretrained_model_name_or_path='+MODELT_NAME+' \
--instance_data_dir='+INSTANCE_DIR+' \
--output_dir='+OUTPUT_DIR+' \
--captions_dir='+CAPTIONS_DIR+' \
--instance_prompt='+PT+' \
--seed='+str(Seed)+' \
--resolution='+str(Resolution)+' \
--mixed_precision='+str(precision)+' \
--train_batch_size=1 \
--gradient_accumulation_steps=1 --gradient_checkpointing \
--use_8bit_adam \
--learning_rate='+str(Text_Encoder_Learning_Rate)+' \
--lr_scheduler="linear" \
--lr_warmup_steps=0 \
--max_train_steps='+str(Training_Steps), shell=True)
def train_only_unet(stp, stpsv, SESSION_DIR, MODELT_NAME, INSTANCE_DIR, OUTPUT_DIR, Text_Encoder_Training_Steps, PT, Seed, Resolution, extrnlcptn, precision, Training_Steps):
clear_output()
if resuming=="Yes":
print('[1;32mResuming Training...[0m')
print('[1;33mTraining the UNet...[0m')
call('accelerate launch /notebooks/diffusers/examples/dreambooth/train_dreambooth_pps.py \
'+extrnlcptn+' \
'+ofstnse+' \
--image_captions_filename \
--train_only_unet \
--Session_dir='+SESSION_DIR+' \
--save_starting_step='+str(stpsv)+' \
--save_n_steps='+str(stp)+' \
--pretrained_model_name_or_path='+MODELT_NAME+' \
--instance_data_dir='+INSTANCE_DIR+' \
--output_dir='+OUTPUT_DIR+' \
--captions_dir='+CAPTIONS_DIR+' \
--instance_prompt='+PT+' \
--seed='+str(Seed)+' \
--resolution='+str(Resolution)+' \
--mixed_precision='+str(precision)+' \
--train_batch_size=1 \
--gradient_accumulation_steps=1 --gradient_checkpointing \
--use_8bit_adam \
--learning_rate='+str(UNet_Learning_Rate)+' \
--lr_scheduler="linear" \
--lr_warmup_steps=0 \
--max_train_steps='+str(Training_Steps), shell=True)
if Enable_text_encoder_training :
print('[1;33mTraining the text encoder...[0m')
if os.path.exists(OUTPUT_DIR+'/'+'text_encoder_trained'):
call('rm -r '+OUTPUT_DIR+'/text_encoder_trained', shell=True)
dump_only_textenc(trnonltxt, MODELT_NAME, INSTANCE_DIR, OUTPUT_DIR, PT, Seed, precision, Training_Steps=stptxt)
if Enable_Text_Encoder_Concept_Training:
if os.path.exists(CONCEPT_DIR):
if os.listdir(CONCEPT_DIR)!=[]:
clear_output()
if resuming=="Yes":
print('[1;32mResuming Training...[0m')
print('[1;33mTraining the text encoder on the concept...[0m')
dump_only_textenc(trnonltxt, MODELT_NAME, CONCEPT_DIR, OUTPUT_DIR, PT, Seed, precision, Training_Steps=stptxtc)
else:
clear_output()
if resuming=="Yes":
print('[1;32mResuming Training...[0m')
print('[1;31mNo concept images found, skipping concept training...')
Text_Encoder_Concept_Training_Steps=0
time.sleep(8)
else:
clear_output()
if resuming=="Yes":
print('[1;32mResuming Training...[0m')
print('[1;31mNo concept images found, skipping concept training...')
Text_Encoder_Concept_Training_Steps=0
time.sleep(8)
if UNet_Training_Steps!=0:
train_only_unet(stp, stpsv, SESSION_DIR, MODELT_NAME, INSTANCE_DIR, OUTPUT_DIR, Text_Encoder_Training_Steps, PT, Seed, Resolution, extrnlcptn, precision, Training_Steps=UNet_Training_Steps)
if UNet_Training_Steps==0 and Text_Encoder_Concept_Training_Steps==0 and Text_Encoder_Training_Steps==0 :
print('[1;32mNothing to do')
else:
if os.path.exists(OUTPUT_DIR+'/unet/diffusion_pytorch_model.bin'):
call('python /notebooks/diffusers/scripts/convertosdv2.py --fp16 '+OUTPUT_DIR+' '+SESSION_DIR+'/'+Session_Name+'.ckpt', shell=True)
clear_output()
if os.path.exists(SESSION_DIR+"/"+INSTANCE_NAME+'.ckpt'):
clear_output()
print("[1;32mDONE, the CKPT model is in the session's folder")
else:
print("[1;31mSomething went wrong")
else:
print("[1;31mSomething went wrong")
return resumev2
def testui(Custom_Path, Previous_Session_Name, Session_Name, User, Password):
if Previous_Session_Name!="":
print("[1;32mLoading a previous session model")
mdldir='/notebooks/Fast-Dreambooth/Sessions/'+Previous_Session_Name
path_to_trained_model=mdldir+"/"+Previous_Session_Name+'.ckpt'
while not os.path.exists(path_to_trained_model):
print("[1;31mThere is no trained model in the previous session")
time.sleep(5)
elif Custom_Path!="":
print("[1;32mLoading model from a custom path")
path_to_trained_model=Custom_Path
while not os.path.exists(path_to_trained_model):
print("[1;31mWrong Path")
time.sleep(5)
else:
print("[1;32mLoading the trained model")
mdldir='/notebooks/Fast-Dreambooth/Sessions/'+Session_Name
path_to_trained_model=mdldir+"/"+Session_Name+'.ckpt'
while not os.path.exists(path_to_trained_model):
print("[1;31mThere is no trained model in this session")
time.sleep(5)
auth=f"--gradio-auth {User}:{Password}"
if User =="" or Password=="":
auth=""
os.chdir('/notebooks')
if not os.path.exists('/notebooks/sd/stablediffusiond'): #reset later
call('wget -q -O sd_mrep.tar.zst https://huggingface.co/TheLastBen/dependencies/resolve/main/sd_mrep.tar.zst', shell=True)
call('tar --zstd -xf sd_mrep.tar.zst', shell=True)
call('rm sd_mrep.tar.zst', shell=True)
os.chdir('/notebooks/sd')
if not os.path.exists('stable-diffusion-webui'):
call('git clone -q --depth 1 --branch master https://github.com/AUTOMATIC1111/stable-diffusion-webui', shell=True)
os.chdir('/notebooks/sd/stable-diffusion-webui/')
call('git reset --hard', shell=True, stdout=open('/dev/null', 'w'))
print('[1;32m')
call('git checkout master', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('git pull', shell=True, stdout=open('/dev/null', 'w'))
os.makedirs('/notebooks/sd/stable-diffusion-webui/repositories', exist_ok=True)
call('git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui-assets /notebooks/sd/stable-diffusion-webui/repositories/stable-diffusion-webui-assets', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
os.chdir('/notebooks')
clear_output()
call('wget -q -O /notebooks/sd/stable-diffusion-webui/modules/styles.py https://github.com/TheLastBen/fast-stable-diffusion/raw/main/AUTOMATIC1111_files/styles.py', shell=True)
call('wget -q -O /usr/local/lib/python3.9/dist-packages/gradio/blocks.py https://raw.githubusercontent.com/TheLastBen/fast-stable-diffusion/main/AUTOMATIC1111_files/blocks.py', shell=True)
localurl="tensorboard-"+os.environ.get('PAPERSPACE_FQDN')
for line in fileinput.input('/usr/local/lib/python3.9/dist-packages/gradio/blocks.py', inplace=True):
if line.strip().startswith('self.server_name ='):
line = f' self.server_name = "{localurl}"\n'
if line.strip().startswith('self.protocol = "https"'):
line = ' self.protocol = "https"\n'
if line.strip().startswith('if self.local_url.startswith("https") or self.is_colab'):
line = ''
if line.strip().startswith('else "http"'):
line = ''
sys.stdout.write(line)
os.chdir('/notebooks/sd/stable-diffusion-webui/modules')
call("sed -i 's@possible_sd_paths =.*@possible_sd_paths = [\"/notebooks/sd/stablediffusion\"]@' /notebooks/sd/stable-diffusion-webui/modules/paths.py", shell=True)
call("sed -i 's@\.\.\/@src/@g' /notebooks/sd/stable-diffusion-webui/modules/paths.py", shell=True)
call("sed -i 's@src\/generative-models@generative-models@g' /notebooks/sd/stable-diffusion-webui/modules/paths.py", shell=True)
call("sed -i 's@-> Network | None@@g' /notebooks/sd/stable-diffusion-webui/extensions-builtin/Lora/network.py", shell=True)
call("sed -i 's@|@or@' /notebooks/sd/stable-diffusion-webui/extensions/adetailer/aaaaaa/helper.py", shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call("sed -i 's@\"quicksettings\": OptionInfo(.*@\"quicksettings\": OptionInfo(\"sd_model_checkpoint, sd_vae, CLIP_stop_at_last_layers, inpainting_mask_weight, initial_noise_multiplier\", \"Quicksettings list\"),@' /notebooks/sd/stable-diffusion-webui/modules/shared.py", shell=True)
os.chdir('/notebooks/sd/stable-diffusion-webui')
clear_output()
configf="--disable-console-progressbars --no-gradio-queue --no-hashing --no-half-vae --disable-safe-unpickle --api --no-download-sd-model --xformers --enable-insecure-extension-access --port 6006 --listen --skip-version-check --ckpt "+path_to_trained_model+" "+auth
return configf
def clean():
Sessions=os.listdir("/notebooks/Fast-Dreambooth/Sessions")
s = widgets.Select(
options=Sessions,
rows=5,
description='',
disabled=False
)
out=widgets.Output()
d = widgets.Button(
description='Remove',
disabled=False,
button_style='warning',
tooltip='Removet the selected session',
icon='warning'
)
def rem(d):
with out:
if s.value is not None:
clear_output()
print("[1;33mTHE SESSION [1;31m"+s.value+" [1;33mHAS BEEN REMOVED FROM THE STORAGE")
call('rm -r /notebooks/Fast-Dreambooth/Sessions/'+s.value, shell=True)
if os.path.exists('/notebooks/models/'+s.value):
call('rm -r /notebooks/models/'+s.value, shell=True)
s.options=os.listdir("/notebooks/Fast-Dreambooth/Sessions")
else:
d.close()
s.close()
clear_output()
print("[1;32mNOTHING TO REMOVE")
d.on_click(rem)
if s.value is not None:
display(s,d,out)
else:
print("[1;32mNOTHING TO REMOVE")
def hfv2(Name_of_your_concept, Save_concept_to, hf_token_write, INSTANCE_NAME, OUTPUT_DIR, Session_Name, MDLPTH):
from slugify import slugify
from huggingface_hub import HfApi, HfFolder, CommitOperationAdd
from huggingface_hub import create_repo
from IPython.display import display_markdown
if(Name_of_your_concept == ""):
Name_of_your_concept = Session_Name
Name_of_your_concept=Name_of_your_concept.replace(" ","-")
if hf_token_write =="":
print('[1;32mYour Hugging Face write access token : ')
hf_token_write=input()
hf_token = hf_token_write
api = HfApi()
your_username = api.whoami(token=hf_token)["name"]
repo_id = f"{your_username}/{slugify(Name_of_your_concept)}"
output_dir = f'/notebooks/models/'+INSTANCE_NAME
def bar(prg):
clear_output()
br="[1;33mUploading to HuggingFace : " '[0m|'+'█' * prg + ' ' * (25-prg)+'| ' +str(prg*4)+ "%"
return br
print(bar(1))
readme_text = f'''---
license: creativeml-openrail-m
tags:
- text-to-image
- stable-diffusion
---
### {Name_of_your_concept} Dreambooth model trained by {api.whoami(token=hf_token)["name"]} with TheLastBen's fast-DreamBooth notebook
'''
#Save the readme to a file
readme_file = open("README.md", "w")
readme_file.write(readme_text)
readme_file.close()
operations = [
CommitOperationAdd(path_in_repo="README.md", path_or_fileobj="README.md"),
CommitOperationAdd(path_in_repo=f"{Session_Name}.ckpt",path_or_fileobj=MDLPTH)
]
create_repo(repo_id,private=True, token=hf_token)
api.create_commit(
repo_id=repo_id,
operations=operations,
commit_message=f"Upload the concept {Name_of_your_concept} embeds and token",
token=hf_token
)
print(bar(8))
api.upload_folder(
folder_path=OUTPUT_DIR+"/scheduler",
path_in_repo="scheduler",
repo_id=repo_id,
token=hf_token
)
print(bar(9))
api.upload_folder(
folder_path=OUTPUT_DIR+"/text_encoder",
path_in_repo="text_encoder",
repo_id=repo_id,
token=hf_token
)
print(bar(12))
api.upload_folder(
folder_path=OUTPUT_DIR+"/tokenizer",
path_in_repo="tokenizer",
repo_id=repo_id,
token=hf_token
)
print(bar(13))
api.upload_folder(
folder_path=OUTPUT_DIR+"/unet",
path_in_repo="unet",
repo_id=repo_id,
token=hf_token
)
print(bar(21))
api.upload_folder(
folder_path=OUTPUT_DIR+"/vae",
path_in_repo="vae",
repo_id=repo_id,
token=hf_token
)
print(bar(23))
api.upload_file(
path_or_fileobj=OUTPUT_DIR+"/model_index.json",
path_in_repo="model_index.json",
repo_id=repo_id,
token=hf_token
)
print(bar(25))
print("[1;32mYour concept was saved successfully at https://huggingface.co/"+repo_id)
done()
def crop_image(im, size):
GREEN = "#0F0"
BLUE = "#00F"
RED = "#F00"
def focal_point(im, settings):
corner_points = image_corner_points(im, settings) if settings.corner_points_weight > 0 else []
entropy_points = image_entropy_points(im, settings) if settings.entropy_points_weight > 0 else []
face_points = image_face_points(im, settings) if settings.face_points_weight > 0 else []
pois = []
weight_pref_total = 0
if len(corner_points) > 0:
weight_pref_total += settings.corner_points_weight
if len(entropy_points) > 0:
weight_pref_total += settings.entropy_points_weight
if len(face_points) > 0:
weight_pref_total += settings.face_points_weight
corner_centroid = None
if len(corner_points) > 0:
corner_centroid = centroid(corner_points)
corner_centroid.weight = settings.corner_points_weight / weight_pref_total
pois.append(corner_centroid)
entropy_centroid = None
if len(entropy_points) > 0:
entropy_centroid = centroid(entropy_points)
entropy_centroid.weight = settings.entropy_points_weight / weight_pref_total
pois.append(entropy_centroid)
face_centroid = None
if len(face_points) > 0:
face_centroid = centroid(face_points)
face_centroid.weight = settings.face_points_weight / weight_pref_total
pois.append(face_centroid)
average_point = poi_average(pois, settings)
return average_point
def image_face_points(im, settings):
np_im = np.array(im)
gray = cv2.cvtColor(np_im, cv2.COLOR_BGR2GRAY)
tries = [
[ f'{cv2.data.haarcascades}haarcascade_eye.xml', 0.01 ],
[ f'{cv2.data.haarcascades}haarcascade_frontalface_default.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_profileface.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_frontalface_alt.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_frontalface_alt2.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_frontalface_alt_tree.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_eye_tree_eyeglasses.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_upperbody.xml', 0.05 ]
]
for t in tries:
classifier = cv2.CascadeClassifier(t[0])
minsize = int(min(im.width, im.height) * t[1]) # at least N percent of the smallest side
try:
faces = classifier.detectMultiScale(gray, scaleFactor=1.1,
minNeighbors=7, minSize=(minsize, minsize), flags=cv2.CASCADE_SCALE_IMAGE)
except:
continue
if len(faces) > 0:
rects = [[f[0], f[1], f[0] + f[2], f[1] + f[3]] for f in faces]
return [PointOfInterest((r[0] +r[2]) // 2, (r[1] + r[3]) // 2, size=abs(r[0]-r[2]), weight=1/len(rects)) for r in rects]
return []
def image_corner_points(im, settings):
grayscale = im.convert("L")
gd = ImageDraw.Draw(grayscale)
gd.rectangle([0, im.height*.9, im.width, im.height], fill="#999")
np_im = np.array(grayscale)
points = cv2.goodFeaturesToTrack(
np_im,
maxCorners=100,
qualityLevel=0.04,
minDistance=min(grayscale.width, grayscale.height)*0.06,
useHarrisDetector=False,
)
if points is None:
return []
focal_points = []
for point in points:
x, y = point.ravel()
focal_points.append(PointOfInterest(x, y, size=4, weight=1/len(points)))
return focal_points
def image_entropy_points(im, settings):
landscape = im.height < im.width
portrait = im.height > im.width
if landscape:
move_idx = [0, 2]
move_max = im.size[0]
elif portrait:
move_idx = [1, 3]
move_max = im.size[1]
else:
return []
e_max = 0
crop_current = [0, 0, settings.crop_width, settings.crop_height]
crop_best = crop_current
while crop_current[move_idx[1]] < move_max:
crop = im.crop(tuple(crop_current))
e = image_entropy(crop)
if (e > e_max):
e_max = e
crop_best = list(crop_current)
crop_current[move_idx[0]] += 4
crop_current[move_idx[1]] += 4
x_mid = int(crop_best[0] + settings.crop_width/2)
y_mid = int(crop_best[1] + settings.crop_height/2)
return [PointOfInterest(x_mid, y_mid, size=25, weight=1.0)]
def image_entropy(im):
# greyscale image entropy
# band = np.asarray(im.convert("L"))
band = np.asarray(im.convert("1"), dtype=np.uint8)
hist, _ = np.histogram(band, bins=range(0, 256))
hist = hist[hist > 0]
return -np.log2(hist / hist.sum()).sum()
def centroid(pois):
x = [poi.x for poi in pois]
y = [poi.y for poi in pois]
return PointOfInterest(sum(x)/len(pois), sum(y)/len(pois))
def poi_average(pois, settings):
weight = 0.0
x = 0.0
y = 0.0
for poi in pois:
weight += poi.weight
x += poi.x * poi.weight
y += poi.y * poi.weight
avg_x = round(weight and x / weight)
avg_y = round(weight and y / weight)
return PointOfInterest(avg_x, avg_y)
def is_landscape(w, h):
return w > h
def is_portrait(w, h):
return h > w
def is_square(w, h):
return w == h
class PointOfInterest:
def __init__(self, x, y, weight=1.0, size=10):
self.x = x
self.y = y
self.weight = weight
self.size = size
def bounding(self, size):
return [
self.x - size//2,
self.y - size//2,
self.x + size//2,
self.y + size//2
]
class Settings:
def __init__(self, crop_width=512, crop_height=512, corner_points_weight=0.5, entropy_points_weight=0.5, face_points_weight=0.5):
self.crop_width = crop_width
self.crop_height = crop_height
self.corner_points_weight = corner_points_weight
self.entropy_points_weight = entropy_points_weight
self.face_points_weight = face_points_weight
settings = Settings(
crop_width = size,
crop_height = size,
face_points_weight = 0.9,
entropy_points_weight = 0.15,
corner_points_weight = 0.5,
)
scale_by = 1
if is_landscape(im.width, im.height):
scale_by = settings.crop_height / im.height
elif is_portrait(im.width, im.height):
scale_by = settings.crop_width / im.width
elif is_square(im.width, im.height):
if is_square(settings.crop_width, settings.crop_height):
scale_by = settings.crop_width / im.width
elif is_landscape(settings.crop_width, settings.crop_height):
scale_by = settings.crop_width / im.width
elif is_portrait(settings.crop_width, settings.crop_height):
scale_by = settings.crop_height / im.height
im = im.resize((int(im.width * scale_by), int(im.height * scale_by)))
im_debug = im.copy()
focus = focal_point(im_debug, settings)
# take the focal point and turn it into crop coordinates that try to center over the focal
# point but then get adjusted back into the frame
y_half = int(settings.crop_height / 2)
x_half = int(settings.crop_width / 2)
x1 = focus.x - x_half
if x1 < 0:
x1 = 0
elif x1 + settings.crop_width > im.width:
x1 = im.width - settings.crop_width
y1 = focus.y - y_half
if y1 < 0:
y1 = 0
elif y1 + settings.crop_height > im.height:
y1 = im.height - settings.crop_height
x2 = x1 + settings.crop_width
y2 = y1 + settings.crop_height
crop = [x1, y1, x2, y2]
results = []
results.append(im.crop(tuple(crop)))
return results123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347from IPython.display import clear_output
from subprocess import call, getoutput
from IPython.display import display
import ipywidgets as widgets
import io
from PIL import Image, ImageDraw, ImageOps
import fileinput
import time
import os
from os import listdir
from os.path import isfile
from tqdm import tqdm
import gdown
import random
import sys
import cv2
from io import BytesIO
import requests
from collections import defaultdict
from math import log, sqrt
import numpy as np
from subprocess import check_output
import six
import re
from urllib.parse import urlparse, parse_qs, unquote
from urllib.request import urlopen, Request
import tempfile
from tqdm import tqdm
def Deps(force_reinstall):
if not force_reinstall and os.path.exists('/usr/local/lib/python3.11/dist-packages/gradio'):
ntbk()
os.environ['TORCH_HOME'] = '/notebooks/cache/torch'
os.environ['PYTHONWARNINGS'] = 'ignore'
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
print('[1;32mModules and notebooks updated, dependencies already installed')
else:
call("pip install --root-user-action=ignore --no-deps -q accelerate==0.12.0", shell=True, stdout=open('/dev/null', 'w'))
call("pip uninstall -qq deepspeed -y", shell=True, stdout=open('/dev/null', 'w'))
ntbk()
if not os.path.exists('/models'):
call('mkdir /models', shell=True)
if not os.path.exists('/notebooks/models'):
call('ln -s /models /notebooks', shell=True)
if os.path.exists('/deps'):
call("rm -r /deps", shell=True)
call('mkdir /deps', shell=True)
if not os.path.exists('cache'):
call('mkdir cache', shell=True)
os.chdir('/deps')
call('wget -q -i https://raw.githubusercontent.com/TheLastBen/fast-stable-diffusion/main/Dependencies/aptdeps_311.txt', shell=True)
call('dpkg -i *.deb', shell=True, stdout=open('/dev/null', 'w'))
depsinst("https://huggingface.co/TheLastBen/dependencies/resolve/main/ppsdeps_311.tar.zst", "/deps/ppsdeps_311.tar.zst")
call('tar -C / --zstd -xf ppsdeps_311.tar.zst', shell=True, stdout=open('/dev/null', 'w'))
os.chdir('/notebooks')
call("git clone --depth 1 -q --branch main https://github.com/TheLastBen/diffusers /diffusers", shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
os.environ['TORCH_HOME'] = '/notebooks/cache/torch'
os.environ['PYTHONWARNINGS'] = 'ignore'
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
call("sed -i 's@text = _formatwarnmsg(msg)@text =\"\"@g' /usr/lib/python3.11/warnings.py", shell=True)
if not os.path.exists('/notebooks/diffusers'):
call('ln -s /diffusers /notebooks', shell=True)
call("rm -r /deps", shell=True)
os.chdir('/notebooks')
clear_output()
done()
def depsinst(url, dst):
file_size = None
req = Request(url, headers={"User-Agent": "torch.hub"})
u = urlopen(req)
meta = u.info()
if hasattr(meta, 'getheaders'):
content_length = meta.getheaders("Content-Length")
else:
content_length = meta.get_all("Content-Length")
if content_length is not None and len(content_length) > 0:
file_size = int(content_length[0])
with tqdm(total=file_size, disable=False, mininterval=0.5,
bar_format='(fast-stable-diffusion will soon stop supporting Paperspace) Installing dependencies |{bar:20}| {percentage:3.0f}%') as pbar:
with open(dst, "wb") as f:
while True:
buffer = u.read(8192)
if len(buffer) == 0:
break
f.write(buffer)
pbar.update(len(buffer))
f.close()
def ntbk():
os.chdir('/notebooks')
if not os.path.exists('Latest_Notebooks'):
call('mkdir Latest_Notebooks', shell=True)
else:
call('rm -r Latest_Notebooks', shell=True)
call('mkdir Latest_Notebooks', shell=True)
os.chdir('/notebooks/Latest_Notebooks')
call('wget -q -i https://huggingface.co/datasets/TheLastBen/PPS/raw/main/Notebooks.txt', shell=True)
call('rm Notebooks.txt', shell=True)
os.chdir('/notebooks')
def downloadmodel_hfv2(Path_to_HuggingFace):
import wget
if os.path.exists('/models/stable-diffusion-custom'):
call("rm -r /models/stable-diffusion-custom", shell=True)
clear_output()
if os.path.exists('/notebooks/Fast-Dreambooth/token.txt'):
with open("/notebooks/Fast-Dreambooth/token.txt") as f:
token = f.read()
authe=f'https://USER:{token}@'
else:
authe="https://"
clear_output()
call("mkdir /models/stable-diffusion-custom", shell=True)
os.chdir("/models/stable-diffusion-custom")
call("git init", shell=True)
call("git lfs install --system --skip-repo", shell=True)
call('git remote add -f origin '+authe+'huggingface.co/'+Path_to_HuggingFace, shell=True)
call("git config core.sparsecheckout true", shell=True)
call('echo -e "\nscheduler\ntext_encoder\ntokenizer\nunet\nvae\nfeature_extractor\nmodel_index.json\n!*.safetensors" > .git/info/sparse-checkout', shell=True)
call("git pull origin main", shell=True)
if os.path.exists('unet/diffusion_pytorch_model.bin'):
call("rm -r .git", shell=True)
os.chdir('/notebooks')
clear_output()
done()
while not os.path.exists('/models/stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
print('[1;31mCheck the link you provided')
os.chdir('/notebooks')
time.sleep(5)
def downloadmodel_path_v2(MODEL_PATH):
modelname=os.path.basename(MODEL_PATH)
sftnsr=""
if modelname.split('.')[-1]=='safetensors':
sftnsr="--from_safetensors"
import wget
os.chdir('/models')
clear_output()
if os.path.exists(str(MODEL_PATH)):
wget.download('https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dreambooth/det.py')
print('[1;33mDetecting model version...')
Custom_Model_Version=check_output('python det.py '+sftnsr+' --MODEL_PATH '+MODEL_PATH, shell=True).decode('utf-8').replace('\n', '')
clear_output()
print('[1;32m'+Custom_Model_Version+' Detected')
call('rm det.py', shell=True)
if Custom_Model_Version=='V2.1-512px':
call('wget -q -O convertodiffv2.py https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dreambooth/convertodiffv2.py', shell=True)
call('python convertodiffv2.py '+MODEL_PATH+' stable-diffusion-custom --v2 --reference_model stabilityai/stable-diffusion-2-1-base '+sftnsr, shell=True)
elif Custom_Model_Version=='V2.1-768px':
call('wget -q -O convertodiffv2.py https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dreambooth/convertodiffv2-768.py', shell=True)
call('python convertodiffv2.py '+MODEL_PATH+' stable-diffusion-custom --v2 --reference_model stabilityai/stable-diffusion-2-1 '+sftnsr, shell=True)
call('rm convertodiffv2.py', shell=True)
if os.path.exists('/models/stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
clear_output()
done()
while not os.path.exists('/models/stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
print('[1;31mConversion error')
os.chdir('/workspace')
time.sleep(5)
else:
while not os.path.exists(str(MODEL_PATH)):
print('[1;31mWrong path, use the file explorer to copy the path')
os.chdir('/workspace')
time.sleep(5)
def downloadmodel_link_v2(MODEL_LINK):
import wget
import gdown
from gdown.download import get_url_from_gdrive_confirmation
def getsrc(url):
parsed_url = urlparse(url)
if parsed_url.netloc == 'civitai.com':
src='civitai'
elif parsed_url.netloc == 'drive.google.com':
src='gdrive'
elif parsed_url.netloc == 'huggingface.co':
src='huggingface'
else:
src='others'
return src
src=getsrc(MODEL_LINK)
def get_name(url, gdrive):
if not gdrive:
response = requests.get(url, allow_redirects=False)
if "Location" in response.headers:
redirected_url = response.headers["Location"]
quer = parse_qs(urlparse(redirected_url).query)
if "response-content-disposition" in quer:
disp_val = quer["response-content-disposition"][0].split(";")
for vals in disp_val:
if vals.strip().startswith("filename="):
filenm=unquote(vals.split("=", 1)[1].strip())
return filenm.replace("\"","")
else:
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"}
lnk="https://drive.google.com/uc?id={id}&export=download".format(id=url[url.find("/d/")+3:url.find("/view")])
res = requests.session().get(lnk, headers=headers, stream=True, verify=True)
res = requests.session().get(get_url_from_gdrive_confirmation(res.text), headers=headers, stream=True, verify=True)
content_disposition = six.moves.urllib_parse.unquote(res.headers["Content-Disposition"])
filenm = re.search(r"filename\*=UTF-8''(.*)", content_disposition).groups()[0].replace(os.path.sep, "_")
return filenm
if src=='civitai':
modelname=get_name(MODEL_LINK, False)
elif src=='gdrive':
modelname=get_name(MODEL_LINK, True)
else:
modelname=os.path.basename(MODEL_LINK)
sftnsr=""
if modelname.split('.')[-1]!='safetensors':
modelnm="model.ckpt"
else:
modelnm="model.safetensors"
sftnsr="--from_safetensors"
os.chdir('/models')
call("gdown --fuzzy " +MODEL_LINK+ " -O "+modelnm, shell=True)
if os.path.exists(modelnm):
if os.path.getsize(modelnm) > 1810671599:
wget.download('https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dreambooth/det.py')
print('[1;33mDetecting model version...')
Custom_Model_Version=check_output('python det.py '+sftnsr+' --MODEL_PATH '+modelnm, shell=True).decode('utf-8').replace('\n', '')
clear_output()
print('[1;32m'+Custom_Model_Version+' Detected')
call('rm det.py', shell=True)
if Custom_Model_Version=='V2.1-512px':
call('wget -q -O convertodiffv2.py https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dreambooth/convertodiffv2.py', shell=True)
call('python convertodiffv2.py '+modelnm+' stable-diffusion-custom --v2 --reference_model stabilityai/stable-diffusion-2-1-base '+sftnsr, shell=True)
elif Custom_Model_Version=='V2.1-768px':
call('wget -q -O convertodiffv2.py https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dreambooth/convertodiffv2-768.py', shell=True)
call('python convertodiffv2.py '+modelnm+' stable-diffusion-custom --v2 --reference_model stabilityai/stable-diffusion-2-1 '+sftnsr, shell=True)
call('rm convertodiffv2.py', shell=True)
if os.path.exists('/models/stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
call('rm '+modelnm, shell=True)
os.chdir('/workspace')
clear_output()
done()
else:
while not os.path.exists('/models/stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
print('[1;31mConversion error')
os.chdir('/workspace')
time.sleep(5)
else:
while os.path.getsize(modelnm) < 1810671599:
print('[1;31mWrong link, check that the link is valid')
os.chdir('/workspace')
time.sleep(5)
def dlsv2(Path_to_HuggingFace, Model_Path, Model_Link, Model_Version):
if Path_to_HuggingFace != "":
downloadmodel_hfv2(Path_to_HuggingFace)
MODEL_NAMEv2="/models/stable-diffusion-custom"
elif Model_Path !="":
downloadmodel_path_v2(Model_Path)
MODEL_NAMEv2="/models/stable-diffusion-custom"
elif Model_Link !="":
downloadmodel_link_v2(Model_Link)
MODEL_NAMEv2="/models/stable-diffusion-custom"
else:
if Model_Version=="512":
MODEL_NAMEv2="/datasets/stable-diffusion-v2-1-base-diffusers/stable-diffusion-2-1-base"
print('[1;32mUsing the original V2-512 model')
elif Model_Version=="768":
MODEL_NAMEv2="/datasets/stable-diffusion-v2-1/stable-diffusion-2-1"
print('[1;32mUsing the original V2-768 model')
else:
MODEL_NAMEv2=""
print('[1;31mWrong model version')
return MODEL_NAMEv2
def sessv2(Session_Name, Session_Link_optional, MODEL_NAMEv2):
import gdown
import wget
os.chdir('/notebooks')
PT=""
while Session_Name=="":
print('[1;31mInput the Session Name:')
Session_Name=input("")
Session_Name=Session_Name.replace(" ","_")
WORKSPACE='/notebooks/Fast-Dreambooth'
if Session_Link_optional !="":
print('[1;33mDownloading session...')
if Session_Link_optional != "":
if not os.path.exists(str(WORKSPACE+'/Sessions')):
call("mkdir -p " +WORKSPACE+ "/Sessions", shell=True)
time.sleep(1)
os.chdir(WORKSPACE+'/Sessions')
gdown.download_folder(url=Session_Link_optional, output=Session_Name, quiet=True, remaining_ok=True, use_cookies=False)
os.chdir(Session_Name)
call("rm -r " +instance_images, shell=True)
call("unzip " +instance_images.zip, shell=True, stdout=open('/dev/null', 'w'))
call("rm -r " +concept_images, shell=True)
call("unzip " +concept_images.zip, shell=True, stdout=open('/dev/null', 'w'))
call("rm -r " +captions, shell=True)
call("unzip " +captions.zip, shell=True, stdout=open('/dev/null', 'w'))
os.chdir('/notebooks')
clear_output()
INSTANCE_NAME=Session_Name
OUTPUT_DIR="/models/"+Session_Name
SESSION_DIR=WORKSPACE+"/Sessions/"+Session_Name
CONCEPT_DIR=SESSION_DIR+"/concept_images"
INSTANCE_DIR=SESSION_DIR+"/instance_images"
CAPTIONS_DIR=SESSION_DIR+'/captions'
MDLPTH=str(SESSION_DIR+"/"+Session_Name+'.ckpt')
resumev2=False
if os.path.exists(str(SESSION_DIR)):
mdls=[ckpt for ckpt in listdir(SESSION_DIR) if ckpt.split(".")[-1]=="ckpt"]
if not os.path.exists(MDLPTH) and '.ckpt' in str(mdls):
def f(n):
k=0
for i in mdls:
if k==n:
call('mv '+SESSION_DIR+'/'+i+' '+MDLPTH, shell=True)
k=k+1
k=0
print('[1;33mNo final checkpoint model found, select which intermediary checkpoint to use, enter only the number, (000 to skip):\n[1;34m')
for i in mdls:
print(str(k)+'- '+i)
k=k+1
n=input()
while int(n)>k-1:
n=input()
if n!="000":
f(int(n))
print('[1;32mUsing the model '+ mdls[int(n)]+" ...")
time.sleep(4)
else:
print('[1;32mSkipping the intermediary checkpoints.')
if os.path.exists(str(SESSION_DIR)) and not os.path.exists(MDLPTH):
print('[1;32mLoading session with no previous model, using the original model or the custom downloaded model')
if MODEL_NAMEv2=="":
print('[1;31mNo model found, use the "Model Download" cell to download a model.')
else:
print('[1;32mSession Loaded, proceed to uploading instance images')
elif os.path.exists(MDLPTH):
print('[1;32mSession found, loading the trained model ...')
wget.download('https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dreambooth/det.py')
print('[1;33mDetecting model version...')
Model_Version=check_output('python det.py --MODEL_PATH '+MDLPTH, shell=True).decode('utf-8').replace('\n', '')
clear_output()
print('[1;32m'+Model_Version+' Detected')
call('rm det.py', shell=True)
if Model_Version=='V2.1-512px':
call('wget -q -O convertodiff.py https://raw.githubusercontent.com/TheLastBen/fast-stable-diffusion/main/Dreambooth/convertodiffv2.py', shell=True)
call('python convertodiff.py '+MDLPTH+' '+OUTPUT_DIR+' --v2 --reference_model stabilityai/stable-diffusion-2-1-base', shell=True)
elif Model_Version=='V2.1-768px':
call('wget -q -O convertodiff.py https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dreambooth/convertodiffv2-768.py', shell=True)
call('python convertodiff.py '+MDLPTH+' '+OUTPUT_DIR+' --v2 --reference_model stabilityai/stable-diffusion-2-1', shell=True)
clear_output()
call('rm convertodiff.py', shell=True)
if os.path.exists(OUTPUT_DIR+'/unet/diffusion_pytorch_model.bin'):
resumev2=True
clear_output()
print('[1;32mSession loaded.')
else:
print('[1;31mConversion error, if the error persists, remove the CKPT file from the current session folder')
elif not os.path.exists(str(SESSION_DIR)):
call('mkdir -p '+INSTANCE_DIR, shell=True)
print('[1;32mCreating session...')
if MODEL_NAMEv2=="":
print('[1;31mNo model found, use the "Model Download" cell to download a model.')
else:
print('[1;32mSession created, proceed to uploading instance images')
return PT, WORKSPACE, Session_Name, INSTANCE_NAME, OUTPUT_DIR, SESSION_DIR, CONCEPT_DIR, INSTANCE_DIR, CAPTIONS_DIR, MDLPTH, MODEL_NAMEv2, resumev2
def done():
done = widgets.Button(
description='Done!',
disabled=True,
button_style='success',
tooltip='',
icon='check'
)
display(done)
def uplder(Remove_existing_instance_images, Crop_images, Crop_size, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR, ren):
if os.path.exists(INSTANCE_DIR+"/.ipynb_checkpoints"):
call('rm -r '+INSTANCE_DIR+'/.ipynb_checkpoints', shell=True)
uploader = widgets.FileUpload(description="Choose images",accept='image/*, .txt', multiple=True)
Upload = widgets.Button(
description='Upload',
disabled=False,
button_style='info',
tooltip='Click to upload the chosen instance images',
icon=''
)
def up(Upload):
with out:
uploader.close()
Upload.close()
upld(Remove_existing_instance_images, Crop_images, Crop_size, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR, uploader, ren)
done()
out=widgets.Output()
if IMAGES_FOLDER_OPTIONAL=="":
Upload.on_click(up)
display(uploader, Upload, out)
else:
upld(Remove_existing_instance_images, Crop_images, Crop_size, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR, uploader, ren)
done()
def upld(Remove_existing_instance_images, Crop_images, Crop_size, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR, uploader, ren):
if Remove_existing_instance_images:
if os.path.exists(str(INSTANCE_DIR)):
call("rm -r " +INSTANCE_DIR, shell=True)
if os.path.exists(str(CAPTIONS_DIR)):
call("rm -r " +CAPTIONS_DIR, shell=True)
if not os.path.exists(str(INSTANCE_DIR)):
call("mkdir -p " +INSTANCE_DIR, shell=True)
if not os.path.exists(str(CAPTIONS_DIR)):
call("mkdir -p " +CAPTIONS_DIR, shell=True)
if IMAGES_FOLDER_OPTIONAL !="":
if os.path.exists(IMAGES_FOLDER_OPTIONAL+"/.ipynb_checkpoints"):
call('rm -r '+IMAGES_FOLDER_OPTIONAL+'/.ipynb_checkpoints', shell=True)
if any(file.endswith('.{}'.format('txt')) for file in os.listdir(IMAGES_FOLDER_OPTIONAL)):
call('mv '+IMAGES_FOLDER_OPTIONAL+'/*.txt '+CAPTIONS_DIR, shell=True)
if Crop_images:
os.chdir(str(IMAGES_FOLDER_OPTIONAL))
call('find . -name "* *" -type f | rename ' "'s/ /-/g'", shell=True)
os.chdir('/notebooks')
for filename in tqdm(os.listdir(IMAGES_FOLDER_OPTIONAL), bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Uploaded'):
extension = filename.split(".")[-1]
identifier=filename.split(".")[0]
new_path_with_file = os.path.join(INSTANCE_DIR, filename)
file = Image.open(IMAGES_FOLDER_OPTIONAL+"/"+filename)
file=file.convert("RGB")
file=ImageOps.exif_transpose(file)
width, height = file.size
if file.size !=(Crop_size, Crop_size):
image=crop_image(file, Crop_size)
if extension.upper()=="JPG" or extension.upper()=="jpg":
image[0].save(new_path_with_file, format="JPEG", quality = 100)
else:
image[0].save(new_path_with_file, format=extension.upper())
else:
call("cp \'"+IMAGES_FOLDER_OPTIONAL+"/"+filename+"\' "+INSTANCE_DIR, shell=True)
else:
for filename in tqdm(os.listdir(IMAGES_FOLDER_OPTIONAL), bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Uploaded'):
call("cp -r " +IMAGES_FOLDER_OPTIONAL+"/. " +INSTANCE_DIR, shell=True)
elif IMAGES_FOLDER_OPTIONAL =="":
up=""
for file in uploader.value:
filename = file['name']
if filename.split(".")[-1]=="txt":
with open(CAPTIONS_DIR+'/'+filename, 'w') as f:
f.write(bytes(file['content']).decode())
up=[file for file in uploader.value if not file['name'].endswith('.txt')]
if Crop_images:
for file in tqdm(up, bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Uploaded'):
filename = file['name']
img = Image.open(io.BytesIO(file['content']))
extension = filename.split(".")[-1]
identifier=filename.split(".")[0]
img=img.convert("RGB")
img=ImageOps.exif_transpose(img)
if extension.upper()=="JPG" or extension.upper()=="jpg":
img.save(INSTANCE_DIR+"/"+filename, format="JPEG", quality = 100)
else:
img.save(INSTANCE_DIR+"/"+filename, format=extension.upper())
new_path_with_file = os.path.join(INSTANCE_DIR, filename)
file = Image.open(new_path_with_file)
width, height = file.size
if file.size !=(Crop_size, Crop_size):
image=crop_image(file, Crop_size)
if extension.upper()=="JPG" or extension.upper()=="jpg":
image[0].save(new_path_with_file, format="JPEG", quality = 100)
else:
image[0].save(new_path_with_file, format=extension.upper())
else:
for file in tqdm(uploader.value, bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Uploaded'):
filename = file['name']
img = Image.open(io.BytesIO(file['content']))
img=img.convert("RGB")
extension = filename.split(".")[-1]
identifier=filename.split(".")[0]
if extension.upper()=="JPG" or extension.upper()=="jpg":
img.save(INSTANCE_DIR+"/"+filename, format="JPEG", quality = 100)
else:
img.save(INSTANCE_DIR+"/"+filename, format=extension.upper())
if ren:
i=0
for filename in tqdm(os.listdir(INSTANCE_DIR), bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Renamed'):
extension = filename.split(".")[-1]
identifier=filename.split(".")[0]
new_path_with_file = os.path.join(INSTANCE_DIR, "conceptimagedb"+str(i)+"."+extension)
call('mv "'+os.path.join(INSTANCE_DIR,filename)+'" "'+new_path_with_file+'"', shell=True)
i=i+1
os.chdir(INSTANCE_DIR)
call('find . -name "* *" -type f | rename ' "'s/ /-/g'", shell=True)
os.chdir(CAPTIONS_DIR)
call('find . -name "* *" -type f | rename ' "'s/ /-/g'", shell=True)
os.chdir('/notebooks')
def caption(CAPTIONS_DIR, INSTANCE_DIR):
paths=""
out=""
widgets_l=""
clear_output()
def Caption(path):
if path!="Select an instance image to caption":
name = os.path.splitext(os.path.basename(path))[0]
ext=os.path.splitext(os.path.basename(path))[-1][1:]
if ext=="jpg" or "JPG":
ext="JPEG"
if os.path.exists(CAPTIONS_DIR+"/"+name + '.txt'):
with open(CAPTIONS_DIR+"/"+name + '.txt', 'r') as f:
text = f.read()
else:
with open(CAPTIONS_DIR+"/"+name + '.txt', 'w') as f:
f.write("")
with open(CAPTIONS_DIR+"/"+name + '.txt', 'r') as f:
text = f.read()
img=Image.open(os.path.join(INSTANCE_DIR,path))
img=img.convert("RGB")
img=img.resize((420, 420))
image_bytes = BytesIO()
img.save(image_bytes, format=ext, qualiy=10)
image_bytes.seek(0)
image_data = image_bytes.read()
img= image_data
image = widgets.Image(
value=img,
width=420,
height=420
)
text_area = widgets.Textarea(value=text, description='', disabled=False, layout={'width': '300px', 'height': '120px'})
def update_text(text):
with open(CAPTIONS_DIR+"/"+name + '.txt', 'w') as f:
f.write(text)
button = widgets.Button(description='Save', button_style='success')
button.on_click(lambda b: update_text(text_area.value))
return widgets.VBox([widgets.HBox([image, text_area, button])])
paths = os.listdir(INSTANCE_DIR)
widgets_l = widgets.Select(options=["Select an instance image to caption"]+paths, rows=25)
out = widgets.Output()
def click(change):
with out:
out.clear_output()
display(Caption(change.new))
widgets_l.observe(click, names='value')
display(widgets.HBox([widgets_l, out]))
def dbtrainv2(Resume_Training, UNet_Training_Steps, UNet_Learning_Rate, Text_Encoder_Training_Steps, Text_Encoder_Concept_Training_Steps, Text_Encoder_Learning_Rate, Offset_Noise, Resolution, MODEL_NAMEv2, SESSION_DIR, INSTANCE_DIR, CONCEPT_DIR, CAPTIONS_DIR, External_Captions, INSTANCE_NAME, Session_Name, OUTPUT_DIR, PT, resumev2, Save_Checkpoint_Every_n_Steps, Start_saving_from_the_step, Save_Checkpoint_Every):
if os.path.exists(INSTANCE_DIR+"/.ipynb_checkpoints"):
call('rm -r '+INSTANCE_DIR+'/.ipynb_checkpoints', shell=True)
if os.path.exists(CONCEPT_DIR+"/.ipynb_checkpoints"):
call('rm -r '+CONCEPT_DIR+'/.ipynb_checkpoints', shell=True)
if os.path.exists(CAPTIONS_DIR+"/.ipynb_checkpoints"):
call('rm -r '+CAPTIONS_DIR+'/.ipynb_checkpoints', shell=True)
if resumev2 and not Resume_Training:
print('[1;31mOverwrite your previously trained model ?, answering "yes" will train a new model, answering "no" will resumev2 the training of the previous model? yes or no ?[0m')
while True:
ansres=input('')
if ansres=='no':
Resume_Training = True
resumev2= False
break
elif ansres=='yes':
Resume_Training = False
resumev2= False
break
while not Resume_Training and not os.path.exists(MODEL_NAMEv2+'/unet/diffusion_pytorch_model.bin'):
print('[1;31mNo model found, use the "Model Download" cell to download a model.')
time.sleep(5)
MODELT_NAME=MODEL_NAMEv2
Seed=random.randint(1, 999999)
ofstnse=""
if Offset_Noise:
ofstnse="--offset_noise"
extrnlcptn=""
if External_Captions:
extrnlcptn="--external_captions"
precision="fp16"
resuming=""
if Resume_Training and os.path.exists(OUTPUT_DIR+'/unet/diffusion_pytorch_model.bin'):
MODELT_NAME=OUTPUT_DIR
print('[1;32mResuming Training...[0m')
resuming="Yes"
elif Resume_Training and not os.path.exists(OUTPUT_DIR+'/unet/diffusion_pytorch_model.bin'):
print('[1;31mPrevious model not found, training a new model...[0m')
MODELT_NAME=MODEL_NAMEv2
while MODEL_NAMEv2=="":
print('[1;31mNo model found, use the "Model Download" cell to download a model.')
time.sleep(5)
trnonltxt=""
if UNet_Training_Steps==0:
trnonltxt="--train_only_text_encoder"
Enable_text_encoder_training= True
Enable_Text_Encoder_Concept_Training= True
if Text_Encoder_Training_Steps==0:
Enable_text_encoder_training= False
else:
stptxt=Text_Encoder_Training_Steps
if Text_Encoder_Concept_Training_Steps==0:
Enable_Text_Encoder_Concept_Training= False
else:
stptxtc=Text_Encoder_Concept_Training_Steps
if Save_Checkpoint_Every==None:
Save_Checkpoint_Every=1
stp=0
if Start_saving_from_the_step==None:
Start_saving_from_the_step=0
if (Start_saving_from_the_step < 200):
Start_saving_from_the_step=Save_Checkpoint_Every
stpsv=Start_saving_from_the_step
if Save_Checkpoint_Every_n_Steps:
stp=Save_Checkpoint_Every
def dump_only_textenc(trnonltxt, MODELT_NAME, INSTANCE_DIR, OUTPUT_DIR, PT, Seed, precision, Training_Steps):
call('accelerate launch /notebooks/diffusers/examples/dreambooth/train_dreambooth_pps.py \
'+trnonltxt+' \
'+extrnlcptn+' \
'+ofstnse+' \
--train_text_encoder \
--image_captions_filename \
--dump_only_text_encoder \
--pretrained_model_name_or_path='+MODELT_NAME+' \
--instance_data_dir='+INSTANCE_DIR+' \
--output_dir='+OUTPUT_DIR+' \
--captions_dir='+CAPTIONS_DIR+' \
--instance_prompt='+PT+' \
--seed='+str(Seed)+' \
--resolution='+str(Resolution)+' \
--mixed_precision='+str(precision)+' \
--train_batch_size=1 \
--gradient_accumulation_steps=1 --gradient_checkpointing \
--use_8bit_adam \
--learning_rate='+str(Text_Encoder_Learning_Rate)+' \
--lr_scheduler="linear" \
--lr_warmup_steps=0 \
--max_train_steps='+str(Training_Steps), shell=True)
def train_only_unet(stp, stpsv, SESSION_DIR, MODELT_NAME, INSTANCE_DIR, OUTPUT_DIR, Text_Encoder_Training_Steps, PT, Seed, Resolution, extrnlcptn, precision, Training_Steps):
clear_output()
if resuming=="Yes":
print('[1;32mResuming Training...[0m')
print('[1;33mTraining the UNet...[0m')
call('accelerate launch /notebooks/diffusers/examples/dreambooth/train_dreambooth_pps.py \
'+extrnlcptn+' \
'+ofstnse+' \
--image_captions_filename \
--train_only_unet \
--Session_dir='+SESSION_DIR+' \
--save_starting_step='+str(stpsv)+' \
--save_n_steps='+str(stp)+' \
--pretrained_model_name_or_path='+MODELT_NAME+' \
--instance_data_dir='+INSTANCE_DIR+' \
--output_dir='+OUTPUT_DIR+' \
--captions_dir='+CAPTIONS_DIR+' \
--instance_prompt='+PT+' \
--seed='+str(Seed)+' \
--resolution='+str(Resolution)+' \
--mixed_precision='+str(precision)+' \
--train_batch_size=1 \
--gradient_accumulation_steps=1 --gradient_checkpointing \
--use_8bit_adam \
--learning_rate='+str(UNet_Learning_Rate)+' \
--lr_scheduler="linear" \
--lr_warmup_steps=0 \
--max_train_steps='+str(Training_Steps), shell=True)
if Enable_text_encoder_training :
print('[1;33mTraining the text encoder...[0m')
if os.path.exists(OUTPUT_DIR+'/'+'text_encoder_trained'):
call('rm -r '+OUTPUT_DIR+'/text_encoder_trained', shell=True)
dump_only_textenc(trnonltxt, MODELT_NAME, INSTANCE_DIR, OUTPUT_DIR, PT, Seed, precision, Training_Steps=stptxt)
if Enable_Text_Encoder_Concept_Training:
if os.path.exists(CONCEPT_DIR):
if os.listdir(CONCEPT_DIR)!=[]:
clear_output()
if resuming=="Yes":
print('[1;32mResuming Training...[0m')
print('[1;33mTraining the text encoder on the concept...[0m')
dump_only_textenc(trnonltxt, MODELT_NAME, CONCEPT_DIR, OUTPUT_DIR, PT, Seed, precision, Training_Steps=stptxtc)
else:
clear_output()
if resuming=="Yes":
print('[1;32mResuming Training...[0m')
print('[1;31mNo concept images found, skipping concept training...')
Text_Encoder_Concept_Training_Steps=0
time.sleep(8)
else:
clear_output()
if resuming=="Yes":
print('[1;32mResuming Training...[0m')
print('[1;31mNo concept images found, skipping concept training...')
Text_Encoder_Concept_Training_Steps=0
time.sleep(8)
if UNet_Training_Steps!=0:
train_only_unet(stp, stpsv, SESSION_DIR, MODELT_NAME, INSTANCE_DIR, OUTPUT_DIR, Text_Encoder_Training_Steps, PT, Seed, Resolution, extrnlcptn, precision, Training_Steps=UNet_Training_Steps)
if UNet_Training_Steps==0 and Text_Encoder_Concept_Training_Steps==0 and Text_Encoder_Training_Steps==0 :
print('[1;32mNothing to do')
else:
if os.path.exists(OUTPUT_DIR+'/unet/diffusion_pytorch_model.bin'):
call('python /notebooks/diffusers/scripts/convertosdv2.py --fp16 '+OUTPUT_DIR+' '+SESSION_DIR+'/'+Session_Name+'.ckpt', shell=True)
clear_output()
if os.path.exists(SESSION_DIR+"/"+INSTANCE_NAME+'.ckpt'):
clear_output()
print("[1;32mDONE, the CKPT model is in the session's folder")
else:
print("[1;31mSomething went wrong")
else:
print("[1;31mSomething went wrong")
return resumev2
def testui(Custom_Path, Previous_Session_Name, Session_Name, User, Password):
if Previous_Session_Name!="":
print("[1;32mLoading a previous session model")
mdldir='/notebooks/Fast-Dreambooth/Sessions/'+Previous_Session_Name
path_to_trained_model=mdldir+"/"+Previous_Session_Name+'.ckpt'
while not os.path.exists(path_to_trained_model):
print("[1;31mThere is no trained model in the previous session")
time.sleep(5)
elif Custom_Path!="":
print("[1;32mLoading model from a custom path")
path_to_trained_model=Custom_Path
while not os.path.exists(path_to_trained_model):
print("[1;31mWrong Path")
time.sleep(5)
else:
print("[1;32mLoading the trained model")
mdldir='/notebooks/Fast-Dreambooth/Sessions/'+Session_Name
path_to_trained_model=mdldir+"/"+Session_Name+'.ckpt'
while not os.path.exists(path_to_trained_model):
print("[1;31mThere is no trained model in this session")
time.sleep(5)
auth=f"--gradio-auth {User}:{Password}"
if User =="" or Password=="":
auth=""
os.chdir('/notebooks')
if not os.path.exists('/notebooks/sd/stablediffusiond'): #reset later
call('wget -q -O sd_mrep.tar.zst https://huggingface.co/TheLastBen/dependencies/resolve/main/sd_mrep.tar.zst', shell=True)
call('tar --zstd -xf sd_mrep.tar.zst', shell=True)
call('rm sd_mrep.tar.zst', shell=True)
os.chdir('/notebooks/sd')
if not os.path.exists('stable-diffusion-webui'):
call('git clone -q --depth 1 --branch master https://github.com/AUTOMATIC1111/stable-diffusion-webui', shell=True)
os.chdir('/notebooks/sd/stable-diffusion-webui/')
call('git reset --hard', shell=True, stdout=open('/dev/null', 'w'))
print('[1;32m')
call('git checkout master', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('git pull', shell=True, stdout=open('/dev/null', 'w'))
os.makedirs('/notebooks/sd/stable-diffusion-webui/repositories', exist_ok=True)
call('git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui-assets /notebooks/sd/stable-diffusion-webui/repositories/stable-diffusion-webui-assets', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
os.chdir('/notebooks')
clear_output()
call('wget -q -O /usr/local/lib/python3.11/dist-packages/gradio/blocks.py https://raw.githubusercontent.com/TheLastBen/fast-stable-diffusion/main/AUTOMATIC1111_files/blocks.py', shell=True)
localurl="tensorboard-"+os.environ.get('PAPERSPACE_FQDN')
for line in fileinput.input('/usr/local/lib/python3.11/dist-packages/gradio/blocks.py', inplace=True):
if line.strip().startswith('self.server_name ='):
line = f' self.server_name = "{localurl}"\n'
if line.strip().startswith('self.protocol = "https"'):
line = ' self.protocol = "https"\n'
if line.strip().startswith('if self.local_url.startswith("https") or self.is_colab'):
line = ''
if line.strip().startswith('else "http"'):
line = ''
sys.stdout.write(line)
os.chdir('/notebooks/sd/stable-diffusion-webui/modules')
call("sed -i 's@possible_sd_paths =.*@possible_sd_paths = [\"/notebooks/sd/stablediffusion\"]@' /notebooks/sd/stable-diffusion-webui/modules/paths.py", shell=True)
call("sed -i 's@\.\.\/@src/@g' /notebooks/sd/stable-diffusion-webui/modules/paths.py", shell=True)
call("sed -i 's@src\/generative-models@generative-models@g' /notebooks/sd/stable-diffusion-webui/modules/paths.py", shell=True)
os.chdir('/notebooks/sd/stable-diffusion-webui')
clear_output()
configf="--disable-console-progressbars --no-gradio-queue --no-hashing --no-half-vae --disable-safe-unpickle --api --no-download-sd-model --xformers --enable-insecure-extension-access --port 6006 --listen --skip-version-check --ckpt "+path_to_trained_model+" "+auth
return configf
def clean():
Sessions=os.listdir("/notebooks/Fast-Dreambooth/Sessions")
s = widgets.Select(
options=Sessions,
rows=5,
description='',
disabled=False
)
out=widgets.Output()
d = widgets.Button(
description='Remove',
disabled=False,
button_style='warning',
tooltip='Removet the selected session',
icon='warning'
)
def rem(d):
with out:
if s.value is not None:
clear_output()
print("[1;33mTHE SESSION [1;31m"+s.value+" [1;33mHAS BEEN REMOVED FROM THE STORAGE")
call('rm -r /notebooks/Fast-Dreambooth/Sessions/'+s.value, shell=True)
if os.path.exists('/notebooks/models/'+s.value):
call('rm -r /notebooks/models/'+s.value, shell=True)
s.options=os.listdir("/notebooks/Fast-Dreambooth/Sessions")
else:
d.close()
s.close()
clear_output()
print("[1;32mNOTHING TO REMOVE")
d.on_click(rem)
if s.value is not None:
display(s,d,out)
else:
print("[1;32mNOTHING TO REMOVE")
def hfv2(Name_of_your_concept, Save_concept_to, hf_token_write, INSTANCE_NAME, OUTPUT_DIR, Session_Name, MDLPTH):
from slugify import slugify
from huggingface_hub import HfApi, HfFolder, CommitOperationAdd
from huggingface_hub import create_repo
from IPython.display import display_markdown
if(Name_of_your_concept == ""):
Name_of_your_concept = Session_Name
Name_of_your_concept=Name_of_your_concept.replace(" ","-")
if hf_token_write =="":
print('[1;32mYour Hugging Face write access token : ')
hf_token_write=input()
hf_token = hf_token_write
api = HfApi()
your_username = api.whoami(token=hf_token)["name"]
repo_id = f"{your_username}/{slugify(Name_of_your_concept)}"
output_dir = f'/notebooks/models/'+INSTANCE_NAME
def bar(prg):
clear_output()
br="[1;33mUploading to HuggingFace : " '[0m|'+'█' * prg + ' ' * (25-prg)+'| ' +str(prg*4)+ "%"
return br
print(bar(1))
readme_text = f'''---
license: creativeml-openrail-m
tags:
- text-to-image
- stable-diffusion
---
### {Name_of_your_concept} Dreambooth model trained by {api.whoami(token=hf_token)["name"]} with TheLastBen's fast-DreamBooth notebook
'''
#Save the readme to a file
readme_file = open("README.md", "w")
readme_file.write(readme_text)
readme_file.close()
operations = [
CommitOperationAdd(path_in_repo="README.md", path_or_fileobj="README.md"),
CommitOperationAdd(path_in_repo=f"{Session_Name}.ckpt",path_or_fileobj=MDLPTH)
]
create_repo(repo_id,private=True, token=hf_token)
api.create_commit(
repo_id=repo_id,
operations=operations,
commit_message=f"Upload the concept {Name_of_your_concept} embeds and token",
token=hf_token
)
print(bar(8))
api.upload_folder(
folder_path=OUTPUT_DIR+"/scheduler",
path_in_repo="scheduler",
repo_id=repo_id,
token=hf_token
)
print(bar(9))
api.upload_folder(
folder_path=OUTPUT_DIR+"/text_encoder",
path_in_repo="text_encoder",
repo_id=repo_id,
token=hf_token
)
print(bar(12))
api.upload_folder(
folder_path=OUTPUT_DIR+"/tokenizer",
path_in_repo="tokenizer",
repo_id=repo_id,
token=hf_token
)
print(bar(13))
api.upload_folder(
folder_path=OUTPUT_DIR+"/unet",
path_in_repo="unet",
repo_id=repo_id,
token=hf_token
)
print(bar(21))
api.upload_folder(
folder_path=OUTPUT_DIR+"/vae",
path_in_repo="vae",
repo_id=repo_id,
token=hf_token
)
print(bar(23))
api.upload_file(
path_or_fileobj=OUTPUT_DIR+"/model_index.json",
path_in_repo="model_index.json",
repo_id=repo_id,
token=hf_token
)
print(bar(25))
print("[1;32mYour concept was saved successfully at https://huggingface.co/"+repo_id)
done()
def crop_image(im, size):
GREEN = "#0F0"
BLUE = "#00F"
RED = "#F00"
def focal_point(im, settings):
corner_points = image_corner_points(im, settings) if settings.corner_points_weight > 0 else []
entropy_points = image_entropy_points(im, settings) if settings.entropy_points_weight > 0 else []
face_points = image_face_points(im, settings) if settings.face_points_weight > 0 else []
pois = []
weight_pref_total = 0
if len(corner_points) > 0:
weight_pref_total += settings.corner_points_weight
if len(entropy_points) > 0:
weight_pref_total += settings.entropy_points_weight
if len(face_points) > 0:
weight_pref_total += settings.face_points_weight
corner_centroid = None
if len(corner_points) > 0:
corner_centroid = centroid(corner_points)
corner_centroid.weight = settings.corner_points_weight / weight_pref_total
pois.append(corner_centroid)
entropy_centroid = None
if len(entropy_points) > 0:
entropy_centroid = centroid(entropy_points)
entropy_centroid.weight = settings.entropy_points_weight / weight_pref_total
pois.append(entropy_centroid)
face_centroid = None
if len(face_points) > 0:
face_centroid = centroid(face_points)
face_centroid.weight = settings.face_points_weight / weight_pref_total
pois.append(face_centroid)
average_point = poi_average(pois, settings)
return average_point
def image_face_points(im, settings):
np_im = np.array(im)
gray = cv2.cvtColor(np_im, cv2.COLOR_BGR2GRAY)
tries = [
[ f'{cv2.data.haarcascades}haarcascade_eye.xml', 0.01 ],
[ f'{cv2.data.haarcascades}haarcascade_frontalface_default.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_profileface.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_frontalface_alt.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_frontalface_alt2.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_frontalface_alt_tree.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_eye_tree_eyeglasses.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_upperbody.xml', 0.05 ]
]
for t in tries:
classifier = cv2.CascadeClassifier(t[0])
minsize = int(min(im.width, im.height) * t[1]) # at least N percent of the smallest side
try:
faces = classifier.detectMultiScale(gray, scaleFactor=1.1,
minNeighbors=7, minSize=(minsize, minsize), flags=cv2.CASCADE_SCALE_IMAGE)
except:
continue
if len(faces) > 0:
rects = [[f[0], f[1], f[0] + f[2], f[1] + f[3]] for f in faces]
return [PointOfInterest((r[0] +r[2]) // 2, (r[1] + r[3]) // 2, size=abs(r[0]-r[2]), weight=1/len(rects)) for r in rects]
return []
def image_corner_points(im, settings):
grayscale = im.convert("L")
gd = ImageDraw.Draw(grayscale)
gd.rectangle([0, im.height*.9, im.width, im.height], fill="#999")
np_im = np.array(grayscale)
points = cv2.goodFeaturesToTrack(
np_im,
maxCorners=100,
qualityLevel=0.04,
minDistance=min(grayscale.width, grayscale.height)*0.06,
useHarrisDetector=False,
)
if points is None:
return []
focal_points = []
for point in points:
x, y = point.ravel()
focal_points.append(PointOfInterest(x, y, size=4, weight=1/len(points)))
return focal_points
def image_entropy_points(im, settings):
landscape = im.height < im.width
portrait = im.height > im.width
if landscape:
move_idx = [0, 2]
move_max = im.size[0]
elif portrait:
move_idx = [1, 3]
move_max = im.size[1]
else:
return []
e_max = 0
crop_current = [0, 0, settings.crop_width, settings.crop_height]
crop_best = crop_current
while crop_current[move_idx[1]] < move_max:
crop = im.crop(tuple(crop_current))
e = image_entropy(crop)
if (e > e_max):
e_max = e
crop_best = list(crop_current)
crop_current[move_idx[0]] += 4
crop_current[move_idx[1]] += 4
x_mid = int(crop_best[0] + settings.crop_width/2)
y_mid = int(crop_best[1] + settings.crop_height/2)
return [PointOfInterest(x_mid, y_mid, size=25, weight=1.0)]
def image_entropy(im):
# greyscale image entropy
# band = np.asarray(im.convert("L"))
band = np.asarray(im.convert("1"), dtype=np.uint8)
hist, _ = np.histogram(band, bins=range(0, 256))
hist = hist[hist > 0]
return -np.log2(hist / hist.sum()).sum()
def centroid(pois):
x = [poi.x for poi in pois]
y = [poi.y for poi in pois]
return PointOfInterest(sum(x)/len(pois), sum(y)/len(pois))
def poi_average(pois, settings):
weight = 0.0
x = 0.0
y = 0.0
for poi in pois:
weight += poi.weight
x += poi.x * poi.weight
y += poi.y * poi.weight
avg_x = round(weight and x / weight)
avg_y = round(weight and y / weight)
return PointOfInterest(avg_x, avg_y)
def is_landscape(w, h):
return w > h
def is_portrait(w, h):
return h > w
def is_square(w, h):
return w == h
class PointOfInterest:
def __init__(self, x, y, weight=1.0, size=10):
self.x = x
self.y = y
self.weight = weight
self.size = size
def bounding(self, size):
return [
self.x - size//2,
self.y - size//2,
self.x + size//2,
self.y + size//2
]
class Settings:
def __init__(self, crop_width=512, crop_height=512, corner_points_weight=0.5, entropy_points_weight=0.5, face_points_weight=0.5):
self.crop_width = crop_width
self.crop_height = crop_height
self.corner_points_weight = corner_points_weight
self.entropy_points_weight = entropy_points_weight
self.face_points_weight = face_points_weight
settings = Settings(
crop_width = size,
crop_height = size,
face_points_weight = 0.9,
entropy_points_weight = 0.15,
corner_points_weight = 0.5,
)
scale_by = 1
if is_landscape(im.width, im.height):
scale_by = settings.crop_height / im.height
elif is_portrait(im.width, im.height):
scale_by = settings.crop_width / im.width
elif is_square(im.width, im.height):
if is_square(settings.crop_width, settings.crop_height):
scale_by = settings.crop_width / im.width
elif is_landscape(settings.crop_width, settings.crop_height):
scale_by = settings.crop_width / im.width
elif is_portrait(settings.crop_width, settings.crop_height):
scale_by = settings.crop_height / im.height
im = im.resize((int(im.width * scale_by), int(im.height * scale_by)))
im_debug = im.copy()
focus = focal_point(im_debug, settings)
# take the focal point and turn it into crop coordinates that try to center over the focal
# point but then get adjusted back into the frame
y_half = int(settings.crop_height / 2)
x_half = int(settings.crop_width / 2)
x1 = focus.x - x_half
if x1 < 0:
x1 = 0
elif x1 + settings.crop_width > im.width:
x1 = im.width - settings.crop_width
y1 = focus.y - y_half
if y1 < 0:
y1 = 0
elif y1 + settings.crop_height > im.height:
y1 = im.height - settings.crop_height
x2 = x1 + settings.crop_width
y2 = y1 + settings.crop_height
crop = [x1, y1, x2, y2]
results = []
results.append(im.crop(tuple(crop)))
return results123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415import os
from IPython.display import clear_output
from subprocess import call, getoutput, Popen, run
import time
import ipywidgets as widgets
import requests
import sys
import fileinput
from torch.hub import download_url_to_file
from urllib.parse import urlparse, parse_qs, unquote
import re
import six
from urllib.request import urlopen, Request
import tempfile
from tqdm import tqdm
def Deps(force_reinstall):
if not force_reinstall and os.path.exists('/usr/local/lib/python3.9/dist-packages/safetensors'):
ntbk()
call('pip install --root-user-action=ignore --disable-pip-version-check -qq diffusers==0.18.1', shell=True, stdout=open('/dev/null', 'w'))
os.environ['TORCH_HOME'] = '/notebooks/cache/torch'
os.environ['PYTHONWARNINGS'] = 'ignore'
print('[1;32mModules and notebooks updated, dependencies already installed')
else:
call("pip install --root-user-action=ignore --no-deps -q accelerate==0.12.0", shell=True, stdout=open('/dev/null', 'w'))
if not os.path.exists('/usr/local/lib/python3.9/dist-packages/safetensors'):
os.chdir('/usr/local/lib/python3.9/dist-packages')
call("rm -r torch torch-1.12.1+cu116.dist-info torchaudio* torchvision* PIL Pillow* transformers* numpy* gdown*", shell=True, stdout=open('/dev/null', 'w'))
ntbk()
if not os.path.exists('/models'):
call('mkdir /models', shell=True)
if not os.path.exists('/notebooks/models'):
call('ln -s /models /notebooks', shell=True)
if os.path.exists('/deps'):
call("rm -r /deps", shell=True)
call('mkdir /deps', shell=True)
if not os.path.exists('cache'):
call('mkdir cache', shell=True)
os.chdir('/deps')
call('wget -q -i https://raw.githubusercontent.com/TheLastBen/fast-stable-diffusion/main/Dependencies/aptdeps.txt', shell=True)
call('dpkg -i *.deb', shell=True, stdout=open('/dev/null', 'w'))
depsinst("https://huggingface.co/TheLastBen/dependencies/resolve/main/ppsdeps.tar.zst", "/deps/ppsdeps.tar.zst")
call('tar -C / --zstd -xf ppsdeps.tar.zst', shell=True, stdout=open('/dev/null', 'w'))
call("sed -i 's@~/.cache@/notebooks/cache@' /usr/local/lib/python3.9/dist-packages/transformers/utils/hub.py", shell=True)
os.chdir('/notebooks')
call('pip install --root-user-action=ignore --disable-pip-version-check -qq diffusers==0.18.1', shell=True, stdout=open('/dev/null', 'w'))
call("git clone --depth 1 -q --branch main https://github.com/TheLastBen/diffusers /diffusers", shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
os.environ['TORCH_HOME'] = '/notebooks/cache/torch'
os.environ['PYTHONWARNINGS'] = 'ignore'
call("sed -i 's@text = _formatwarnmsg(msg)@text =\"\"@g' /usr/lib/python3.9/warnings.py", shell=True)
if not os.path.exists('/notebooks/diffusers'):
call('ln -s /diffusers /notebooks', shell=True)
call("rm -r /deps", shell=True)
os.chdir('/notebooks')
clear_output()
done()
def depsinst(url, dst):
file_size = None
req = Request(url, headers={"User-Agent": "torch.hub"})
u = urlopen(req)
meta = u.info()
if hasattr(meta, 'getheaders'):
content_length = meta.getheaders("Content-Length")
else:
content_length = meta.get_all("Content-Length")
if content_length is not None and len(content_length) > 0:
file_size = int(content_length[0])
with tqdm(total=file_size, disable=False, mininterval=0.5,
bar_format='Installing dependencies |{bar:20}| {percentage:3.0f}%') as pbar:
with open(dst, "wb") as f:
while True:
buffer = u.read(8192)
if len(buffer) == 0:
break
f.write(buffer)
pbar.update(len(buffer))
f.close()
def dwn(url, dst, msg):
file_size = None
req = Request(url, headers={"User-Agent": "torch.hub"})
u = urlopen(req)
meta = u.info()
if hasattr(meta, 'getheaders'):
content_length = meta.getheaders("Content-Length")
else:
content_length = meta.get_all("Content-Length")
if content_length is not None and len(content_length) > 0:
file_size = int(content_length[0])
with tqdm(total=file_size, disable=False, mininterval=0.5,
bar_format=msg+' |{bar:20}| {percentage:3.0f}%') as pbar:
with open(dst, "wb") as f:
while True:
buffer = u.read(8192)
if len(buffer) == 0:
break
f.write(buffer)
pbar.update(len(buffer))
f.close()
def ntbk():
os.chdir('/notebooks')
if not os.path.exists('Latest_Notebooks'):
call('mkdir Latest_Notebooks', shell=True)
else:
call('rm -r Latest_Notebooks', shell=True)
call('mkdir Latest_Notebooks', shell=True)
os.chdir('/notebooks/Latest_Notebooks')
call('wget -q -i https://huggingface.co/datasets/TheLastBen/PPS/raw/main/Notebooks.txt', shell=True)
call('rm Notebooks.txt', shell=True)
os.chdir('/notebooks')
def repo():
os.chdir('/notebooks')
print('[1;33mInstalling/Updating the repo...')
os.chdir('/notebooks')
if not os.path.exists('ComfyUI'):
call('git clone -q --depth 1 https://github.com/comfyanonymous/ComfyUI', shell=True)
os.chdir('ComfyUI')
call('git reset --hard', shell=True)
print('[1;32m')
call('git pull', shell=True)
os.chdir('/notebooks')
clear_output()
done()
def mdls(Original_Model_Version, Path_to_MODEL, MODEL_LINK, Temporary_Storage=False):
import gdown
src=getsrc(MODEL_LINK)
call('ln -s /datasets/stable-diffusion-classic/SDv1.5.ckpt /notebooks/ComfyUI/models/checkpoints', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('ln -s /datasets/stable-diffusion-v2-1-base-diffusers/stable-diffusion-2-1-base/v2-1_512-nonema-pruned.safetensors /notebooks/ComfyUI/models/checkpoints', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('ln -s /datasets/stable-diffusion-v2-1/stable-diffusion-2-1/v2-1_768-nonema-pruned.safetensors /notebooks/ComfyUI/models/checkpoints', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('ln -s /datasets/stable-diffusion-xl/sd_xl_base_1.0.safetensors /notebooks/ComfyUI/models/checkpoints', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
if Path_to_MODEL !='':
if os.path.exists(str(Path_to_MODEL)):
print('[1;32mUsing the custom model.')
model=Path_to_MODEL
else:
print('[1;31mWrong path, check that the path to the model is correct')
elif MODEL_LINK !="":
if src=='civitai':
modelname=get_name(MODEL_LINK, False)
if Temporary_Storage:
model=f'/models/{modelname}'
else:
model=f'/notebooks/ComfyUI/models/checkpoints/{modelname}'
if not os.path.exists(model):
dwn(MODEL_LINK, model, 'Downloading the custom model')
clear_output()
else:
print('[1;33mModel already exists')
elif src=='gdrive':
modelname=get_name(MODEL_LINK, True)
if Temporary_Storage:
model=f'/models/{modelname}'
else:
model=f'/notebooks/ComfyUI/models/checkpoints/{modelname}'
if not os.path.exists(model):
gdown.download(url=MODEL_LINK, output=model, quiet=False, fuzzy=True)
clear_output()
else:
print('[1;33mModel already exists')
else:
modelname=os.path.basename(MODEL_LINK)
if Temporary_Storage:
model=f'/models/{modelname}'
else:
model=f'/notebooks/ComfyUI/models/checkpoints/{modelname}'
if not os.path.exists(model):
gdown.download(url=MODEL_LINK, output=model, quiet=False, fuzzy=True)
clear_output()
else:
print('[1;33mModel already exists')
if os.path.exists(model) and os.path.getsize(model) > 1810671599:
print('[1;32mModel downloaded, using the custom model.')
else:
call('rm '+model, shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
print('[1;31mWrong link, check that the link is valid')
else:
if Original_Model_Version == "v1.5":
model="/notebooks/ComfyUI/models/checkpoints/SDv1.5.ckpt"
print('[1;32mUsing the original V1.5 model')
elif Original_Model_Version == "v2-512":
model="/notebooks/ComfyUI/models/checkpoints/v2-1_512-nonema-pruned.safetensors"
print('[1;32mUsing the original V2-512 model')
elif Original_Model_Version == "v2-768":
model="/notebooks/ComfyUI/models/checkpoints/v2-1_768-nonema-pruned.safetensors"
print('[1;32mUsing the original V2-768 model')
elif Original_Model_Version == "SDXL":
model="/notebooks/ComfyUI/models/checkpoints/sd_xl_base_1.0.safetensors"
print('[1;32mUsing the original SDXL model')
else:
model="/notebooks/ComfyUI/models/checkpoints"
print('[1;31mWrong model version, try again')
try:
model
except:
model="/notebooks/ComfyUI/models/checkpoints"
return model
def loradwn(LoRA_LINK):
import gdown
if LoRA_LINK=='':
print('[1;33mNothing to do')
else:
src=getsrc(LoRA_LINK)
if src=='civitai':
modelname=get_name(LoRA_LINK, False)
loramodel=f'/notebooks/ComfyUI/models/loras/{modelname}'
if not os.path.exists(loramodel):
dwn(LoRA_LINK, loramodel, 'Downloading the LoRA model')
clear_output()
else:
print('[1;33mModel already exists')
elif src=='gdrive':
modelname=get_name(LoRA_LINK, True)
loramodel=f'/notebooks/ComfyUI/models/loras/{modelname}'
if not os.path.exists(loramodel):
gdown.download(url=LoRA_LINK, output=loramodel, quiet=False, fuzzy=True)
clear_output()
else:
print('[1;33mModel already exists')
else:
modelname=os.path.basename(LoRA_LINK)
loramodel=f'/notebooks/ComfyUI/models/loras/{modelname}'
if not os.path.exists(loramodel):
gdown.download(url=LoRA_LINK, output=loramodel, quiet=False, fuzzy=True)
clear_output()
else:
print('[1;33mModel already exists')
if os.path.exists(loramodel) :
print('[1;32mLoRA downloaded')
else:
print('[1;31mWrong link, check that the link is valid')
def CNet(ControlNet_Model, ControlNet_XL_Model):
def download(url, model_dir):
filename = os.path.basename(urlparse(url).path)
pth = os.path.abspath(os.path.join(model_dir, filename))
if not os.path.exists(pth):
print('Downloading: '+os.path.basename(url))
download_url_to_file(url, pth, hash_prefix=None, progress=True)
else:
print(f"[1;32mThe model {filename} already exists[0m")
wrngv1=False
mdldir="/notebooks/ComfyUI/models/controlnet"
for filename in os.listdir(mdldir):
if "_sd14v1" in filename:
renamed = re.sub("_sd14v1", "-fp16", filename)
os.rename(os.path.join(mdldir, filename), os.path.join(mdldir, renamed))
call('wget -q -O CN_models.txt https://github.com/TheLastBen/fast-stable-diffusion/raw/main/AUTOMATIC1111_files/CN_models.txt', shell=True)
call('wget -q -O CN_models_XL.txt https://github.com/TheLastBen/fast-stable-diffusion/raw/main/AUTOMATIC1111_files/CN_models_XL.txt', shell=True)
with open("CN_models.txt", 'r') as f:
mdllnk = f.read().splitlines()
with open("CN_models_XL.txt", 'r') as d:
mdllnk_XL = d.read().splitlines()
call('rm CN_models.txt CN_models_XL.txt', shell=True)
os.chdir('/notebooks')
if ControlNet_Model == "All" or ControlNet_Model == "all" :
for lnk in mdllnk:
download(lnk, mdldir)
clear_output()
elif ControlNet_Model == "15":
mdllnk=list(filter(lambda x: 't2i' in x, mdllnk))
for lnk in mdllnk:
download(lnk, mdldir)
clear_output()
elif ControlNet_Model.isdigit() and int(ControlNet_Model)-1<14 and int(ControlNet_Model)>0:
download(mdllnk[int(ControlNet_Model)-1], mdldir)
clear_output()
elif ControlNet_Model == "none":
pass
clear_output()
else:
print('[1;31mWrong ControlNet V1 choice, try again')
wrngv1=True
if ControlNet_XL_Model == "All" or ControlNet_XL_Model == "all" :
for lnk_XL in mdllnk_XL:
download(lnk_XL, mdldir)
if not wrngv1:
clear_output()
done()
elif ControlNet_XL_Model.isdigit() and int(ControlNet_XL_Model)-1<5:
download(mdllnk_XL[int(ControlNet_XL_Model)-1], mdldir)
if not wrngv1:
clear_output()
done()
elif ControlNet_XL_Model == "none":
pass
if not wrngv1:
clear_output()
done()
else:
print('[1;31mWrong ControlNet V2 choice, try again')
def sd():
localurl="https://tensorboard-"+os.environ.get('PAPERSPACE_FQDN')
call("sed -i 's@^ logging.info(\"To see the GUI go to: {}://{}:{}\".format(scheme, address_print, port))@ print(\"[32m\u2714 Connected\");print(\"[1;34m"+localurl+"[0m\")@' /notebooks/ComfyUI/server.py", shell=True)
os.chdir('/notebooks')
def getsrc(url):
parsed_url = urlparse(url)
if parsed_url.netloc == 'civitai.com':
src='civitai'
elif parsed_url.netloc == 'drive.google.com':
src='gdrive'
elif parsed_url.netloc == 'huggingface.co':
src='huggingface'
else:
src='others'
return src
def get_name(url, gdrive):
from gdown.download import get_url_from_gdrive_confirmation
if not gdrive:
response = requests.get(url, allow_redirects=False)
if "Location" in response.headers:
redirected_url = response.headers["Location"]
quer = parse_qs(urlparse(redirected_url).query)
if "response-content-disposition" in quer:
disp_val = quer["response-content-disposition"][0].split(";")
for vals in disp_val:
if vals.strip().startswith("filename="):
filenm=unquote(vals.split("=", 1)[1].strip())
return filenm.replace("\"","")
else:
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"}
lnk="https://drive.google.com/uc?id={id}&export=download".format(id=url[url.find("/d/")+3:url.find("/view")])
res = requests.session().get(lnk, headers=headers, stream=True, verify=True)
res = requests.session().get(get_url_from_gdrive_confirmation(res.text), headers=headers, stream=True, verify=True)
content_disposition = six.moves.urllib_parse.unquote(res.headers["Content-Disposition"])
filenm = re.search(r"filename\*=UTF-8''(.*)", content_disposition).groups()[0].replace(os.path.sep, "_")
return filenm
def done():
done = widgets.Button(
description='Done!',
disabled=True,
button_style='success',
tooltip='',
icon='check'
)
display(done)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415import os
from IPython.display import clear_output
from subprocess import call, getoutput, Popen, run
import time
import ipywidgets as widgets
import requests
import sys
import fileinput
from torch.hub import download_url_to_file
from urllib.parse import urlparse, parse_qs, unquote
import re
import six
from urllib.request import urlopen, Request
import tempfile
from tqdm import tqdm
def Deps(force_reinstall):
if not force_reinstall and os.path.exists('/usr/local/lib/python3.11/dist-packages/gradio'):
ntbk()
os.environ['TORCH_HOME'] = '/notebooks/cache/torch'
os.environ['PYTHONWARNINGS'] = 'ignore'
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
print('[1;32mModules and notebooks updated, dependencies already installed')
else:
call("pip install --root-user-action=ignore --no-deps -q accelerate==0.12.0", shell=True, stdout=open('/dev/null', 'w'))
call("pip uninstall -qq deepspeed -y", shell=True, stdout=open('/dev/null', 'w'))
ntbk()
if not os.path.exists('/models'):
call('mkdir /models', shell=True)
if not os.path.exists('/notebooks/models'):
call('ln -s /models /notebooks', shell=True)
if os.path.exists('/deps'):
call("rm -r /deps", shell=True)
call('mkdir /deps', shell=True)
if not os.path.exists('cache'):
call('mkdir cache', shell=True)
os.chdir('/deps')
call('wget -q -i https://raw.githubusercontent.com/TheLastBen/fast-stable-diffusion/main/Dependencies/aptdeps_311.txt', shell=True)
call('dpkg -i *.deb', shell=True, stdout=open('/dev/null', 'w'))
depsinst("https://huggingface.co/TheLastBen/dependencies/resolve/main/ppsdeps_311.tar.zst", "/deps/ppsdeps_311.tar.zst")
call('tar -C / --zstd -xf ppsdeps_311.tar.zst', shell=True, stdout=open('/dev/null', 'w'))
os.chdir('/notebooks')
call("git clone --depth 1 -q --branch main https://github.com/TheLastBen/diffusers /diffusers", shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
os.environ['TORCH_HOME'] = '/notebooks/cache/torch'
os.environ['PYTHONWARNINGS'] = 'ignore'
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
call("sed -i 's@text = _formatwarnmsg(msg)@text =\"\"@g' /usr/lib/python3.11/warnings.py", shell=True)
if not os.path.exists('/notebooks/diffusers'):
call('ln -s /diffusers /notebooks', shell=True)
call("rm -r /deps", shell=True)
os.chdir('/notebooks')
clear_output()
done()
def depsinst(url, dst):
file_size = None
req = Request(url, headers={"User-Agent": "torch.hub"})
u = urlopen(req)
meta = u.info()
if hasattr(meta, 'getheaders'):
content_length = meta.getheaders("Content-Length")
else:
content_length = meta.get_all("Content-Length")
if content_length is not None and len(content_length) > 0:
file_size = int(content_length[0])
with tqdm(total=file_size, disable=False, mininterval=0.5,
bar_format='(fast-stable-diffusion will soon stop supporting Paperspace) Installing dependencies |{bar:20}| {percentage:3.0f}%') as pbar:
with open(dst, "wb") as f:
while True:
buffer = u.read(8192)
if len(buffer) == 0:
break
f.write(buffer)
pbar.update(len(buffer))
f.close()
def dwn(url, dst, msg):
file_size = None
req = Request(url, headers={"User-Agent": "torch.hub"})
u = urlopen(req)
meta = u.info()
if hasattr(meta, 'getheaders'):
content_length = meta.getheaders("Content-Length")
else:
content_length = meta.get_all("Content-Length")
if content_length is not None and len(content_length) > 0:
file_size = int(content_length[0])
with tqdm(total=file_size, disable=False, mininterval=0.5,
bar_format=msg+' |{bar:20}| {percentage:3.0f}%') as pbar:
with open(dst, "wb") as f:
while True:
buffer = u.read(8192)
if len(buffer) == 0:
break
f.write(buffer)
pbar.update(len(buffer))
f.close()
def ntbk():
os.chdir('/notebooks')
if not os.path.exists('Latest_Notebooks'):
call('mkdir Latest_Notebooks', shell=True)
else:
call('rm -r Latest_Notebooks', shell=True)
call('mkdir Latest_Notebooks', shell=True)
os.chdir('/notebooks/Latest_Notebooks')
call('wget -q -i https://huggingface.co/datasets/TheLastBen/PPS/raw/main/Notebooks.txt', shell=True)
call('rm Notebooks.txt', shell=True)
os.chdir('/notebooks')
def repo():
os.chdir('/notebooks')
print('[1;33mInstalling/Updating the repo...')
os.chdir('/notebooks')
if not os.path.exists('ComfyUI'):
call('git clone -q --depth 1 https://github.com/comfyanonymous/ComfyUI', shell=True)
os.chdir('ComfyUI')
call('git reset --hard', shell=True)
print('[1;32m')
call('git pull', shell=True)
os.chdir('/notebooks')
clear_output()
done()
def mdls(Original_Model_Version, Path_to_MODEL, MODEL_LINK, Temporary_Storage=False):
import gdown
src=getsrc(MODEL_LINK)
call('ln -s /datasets/stable-diffusion-classic/SDv1.5.ckpt /notebooks/ComfyUI/models/checkpoints', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('ln -s /datasets/stable-diffusion-v2-1-base-diffusers/stable-diffusion-2-1-base/v2-1_512-nonema-pruned.safetensors /notebooks/ComfyUI/models/checkpoints', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('ln -s /datasets/stable-diffusion-v2-1/stable-diffusion-2-1/v2-1_768-nonema-pruned.safetensors /notebooks/ComfyUI/models/checkpoints', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('ln -s /datasets/stable-diffusion-xl/sd_xl_base_1.0.safetensors /notebooks/ComfyUI/models/checkpoints', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
if Path_to_MODEL !='':
if os.path.exists(str(Path_to_MODEL)):
print('[1;32mUsing the custom model.')
model=Path_to_MODEL
else:
print('[1;31mWrong path, check that the path to the model is correct')
elif MODEL_LINK !="":
if src=='civitai':
modelname=get_name(MODEL_LINK, False)
if Temporary_Storage:
model=f'/models/{modelname}'
else:
model=f'/notebooks/ComfyUI/models/checkpoints/{modelname}'
if not os.path.exists(model):
dwn(MODEL_LINK, model, 'Downloading the custom model')
clear_output()
else:
print('[1;33mModel already exists')
elif src=='gdrive':
modelname=get_name(MODEL_LINK, True)
if Temporary_Storage:
model=f'/models/{modelname}'
else:
model=f'/notebooks/ComfyUI/models/checkpoints/{modelname}'
if not os.path.exists(model):
gdown.download(url=MODEL_LINK, output=model, quiet=False, fuzzy=True)
clear_output()
else:
print('[1;33mModel already exists')
else:
modelname=os.path.basename(MODEL_LINK)
if Temporary_Storage:
model=f'/models/{modelname}'
else:
model=f'/notebooks/ComfyUI/models/checkpoints/{modelname}'
if not os.path.exists(model):
gdown.download(url=MODEL_LINK, output=model, quiet=False, fuzzy=True)
clear_output()
else:
print('[1;33mModel already exists')
if os.path.exists(model) and os.path.getsize(model) > 1810671599:
print('[1;32mModel downloaded, using the custom model.')
else:
call('rm '+model, shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
print('[1;31mWrong link, check that the link is valid')
else:
if Original_Model_Version == "v1.5":
model="/notebooks/ComfyUI/models/checkpoints/SDv1.5.ckpt"
print('[1;32mUsing the original V1.5 model')
elif Original_Model_Version == "v2-512":
model="/notebooks/ComfyUI/models/checkpoints/v2-1_512-nonema-pruned.safetensors"
print('[1;32mUsing the original V2-512 model')
elif Original_Model_Version == "v2-768":
model="/notebooks/ComfyUI/models/checkpoints/v2-1_768-nonema-pruned.safetensors"
print('[1;32mUsing the original V2-768 model')
elif Original_Model_Version == "SDXL":
model="/notebooks/ComfyUI/models/checkpoints/sd_xl_base_1.0.safetensors"
print('[1;32mUsing the original SDXL model')
else:
model="/notebooks/ComfyUI/models/checkpoints"
print('[1;31mWrong model version, try again')
try:
model
except:
model="/notebooks/ComfyUI/models/checkpoints"
return model
def loradwn(LoRA_LINK):
import gdown
if LoRA_LINK=='':
print('[1;33mNothing to do')
else:
src=getsrc(LoRA_LINK)
if src=='civitai':
modelname=get_name(LoRA_LINK, False)
loramodel=f'/notebooks/ComfyUI/models/loras/{modelname}'
if not os.path.exists(loramodel):
dwn(LoRA_LINK, loramodel, 'Downloading the LoRA model')
clear_output()
else:
print('[1;33mModel already exists')
elif src=='gdrive':
modelname=get_name(LoRA_LINK, True)
loramodel=f'/notebooks/ComfyUI/models/loras/{modelname}'
if not os.path.exists(loramodel):
gdown.download(url=LoRA_LINK, output=loramodel, quiet=False, fuzzy=True)
clear_output()
else:
print('[1;33mModel already exists')
else:
modelname=os.path.basename(LoRA_LINK)
loramodel=f'/notebooks/ComfyUI/models/loras/{modelname}'
if not os.path.exists(loramodel):
gdown.download(url=LoRA_LINK, output=loramodel, quiet=False, fuzzy=True)
clear_output()
else:
print('[1;33mModel already exists')
if os.path.exists(loramodel) :
print('[1;32mLoRA downloaded')
else:
print('[1;31mWrong link, check that the link is valid')
def CNet(ControlNet_Model, ControlNet_XL_Model):
def download(url, model_dir):
filename = os.path.basename(urlparse(url).path)
pth = os.path.abspath(os.path.join(model_dir, filename))
if not os.path.exists(pth):
print('Downloading: '+os.path.basename(url))
download_url_to_file(url, pth, hash_prefix=None, progress=True)
else:
print(f"[1;32mThe model {filename} already exists[0m")
wrngv1=False
mdldir="/notebooks/ComfyUI/models/controlnet"
for filename in os.listdir(mdldir):
if "_sd14v1" in filename:
renamed = re.sub("_sd14v1", "-fp16", filename)
os.rename(os.path.join(mdldir, filename), os.path.join(mdldir, renamed))
call('wget -q -O CN_models.txt https://github.com/TheLastBen/fast-stable-diffusion/raw/main/AUTOMATIC1111_files/CN_models.txt', shell=True)
call('wget -q -O CN_models_XL.txt https://github.com/TheLastBen/fast-stable-diffusion/raw/main/AUTOMATIC1111_files/CN_models_XL.txt', shell=True)
with open("CN_models.txt", 'r') as f:
mdllnk = f.read().splitlines()
with open("CN_models_XL.txt", 'r') as d:
mdllnk_XL = d.read().splitlines()
call('rm CN_models.txt CN_models_XL.txt', shell=True)
os.chdir('/notebooks')
if ControlNet_Model == "All" or ControlNet_Model == "all" :
for lnk in mdllnk:
download(lnk, mdldir)
clear_output()
elif ControlNet_Model == "15":
mdllnk=list(filter(lambda x: 't2i' in x, mdllnk))
for lnk in mdllnk:
download(lnk, mdldir)
clear_output()
elif ControlNet_Model.isdigit() and int(ControlNet_Model)-1<14 and int(ControlNet_Model)>0:
download(mdllnk[int(ControlNet_Model)-1], mdldir)
clear_output()
elif ControlNet_Model == "none":
pass
clear_output()
else:
print('[1;31mWrong ControlNet V1 choice, try again')
wrngv1=True
if ControlNet_XL_Model == "All" or ControlNet_XL_Model == "all" :
for lnk_XL in mdllnk_XL:
download(lnk_XL, mdldir)
if not wrngv1:
clear_output()
done()
elif ControlNet_XL_Model.isdigit() and int(ControlNet_XL_Model)-1<5:
download(mdllnk_XL[int(ControlNet_XL_Model)-1], mdldir)
if not wrngv1:
clear_output()
done()
elif ControlNet_XL_Model == "none":
pass
if not wrngv1:
clear_output()
done()
else:
print('[1;31mWrong ControlNet V2 choice, try again')
def sd():
localurl="https://tensorboard-"+os.environ.get('PAPERSPACE_FQDN')
call("sed -i 's@^ if verbose:@@' /notebooks/ComfyUI/server.py", shell=True)
call("sed -i 's@^ logging.info(\"To see the GUI go to: {}://{}:{}\".format(scheme, address_print, port))@ logging.info(\"[32m\u2714 Connected\");logging.info(\"[1;34m"+localurl+"[0m\")@' /notebooks/ComfyUI/server.py", shell=True)
os.chdir('/notebooks')
def getsrc(url):
parsed_url = urlparse(url)
if parsed_url.netloc == 'civitai.com':
src='civitai'
elif parsed_url.netloc == 'drive.google.com':
src='gdrive'
elif parsed_url.netloc == 'huggingface.co':
src='huggingface'
else:
src='others'
return src
def get_name(url, gdrive):
from gdown.download import get_url_from_gdrive_confirmation
if not gdrive:
response = requests.get(url, allow_redirects=False)
if "Location" in response.headers:
redirected_url = response.headers["Location"]
quer = parse_qs(urlparse(redirected_url).query)
if "response-content-disposition" in quer:
disp_val = quer["response-content-disposition"][0].split(";")
for vals in disp_val:
if vals.strip().startswith("filename="):
filenm=unquote(vals.split("=", 1)[1].strip())
return filenm.replace("\"","")
else:
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"}
lnk="https://drive.google.com/uc?id={id}&export=download".format(id=url[url.find("/d/")+3:url.find("/view")])
res = requests.session().get(lnk, headers=headers, stream=True, verify=True)
res = requests.session().get(get_url_from_gdrive_confirmation(res.text), headers=headers, stream=True, verify=True)
content_disposition = six.moves.urllib_parse.unquote(res.headers["Content-Disposition"])
filenm = re.search(r"filename\*=UTF-8''(.*)", content_disposition).groups()[0].replace(os.path.sep, "_")
return filenm
def done():
done = widgets.Button(
description='Done!',
disabled=True,
button_style='success',
tooltip='',
icon='check'
)
display(done)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152from IPython.display import clear_output
from subprocess import call, getoutput, Popen
from IPython.display import display
import ipywidgets as widgets
import io
from PIL import Image, ImageDraw, ImageOps
import fileinput
import time
import os
from os import listdir
from os.path import isfile
import random
import sys
from io import BytesIO
import requests
from collections import defaultdict
from math import log, sqrt
import numpy as np
import sys
import fileinput
import six
import base64
import re
import cv2
from urllib.parse import urlparse, parse_qs, unquote
import urllib.request
from urllib.request import urlopen, Request
import tempfile
from tqdm import tqdm
def Deps(force_reinstall):
if not force_reinstall and os.path.exists('/usr/local/lib/python3.9/dist-packages/safetensors'):
ntbk()
call('pip install --root-user-action=ignore --disable-pip-version-check -qq diffusers==0.18.1', shell=True, stdout=open('/dev/null', 'w'))
os.environ['TORCH_HOME'] = '/notebooks/cache/torch'
os.environ['PYTHONWARNINGS'] = 'ignore'
print('[1;32mModules and notebooks updated, dependencies already installed')
else:
call("pip install --root-user-action=ignore --no-deps -q accelerate==0.12.0", shell=True, stdout=open('/dev/null', 'w'))
if not os.path.exists('/usr/local/lib/python3.9/dist-packages/safetensors'):
os.chdir('/usr/local/lib/python3.9/dist-packages')
call("rm -r torch torch-1.12.1+cu116.dist-info torchaudio* torchvision* PIL Pillow* transformers* numpy* gdown*", shell=True, stdout=open('/dev/null', 'w'))
ntbk()
if not os.path.exists('/models'):
call('mkdir /models', shell=True)
if not os.path.exists('/notebooks/models'):
call('ln -s /models /notebooks', shell=True)
if os.path.exists('/deps'):
call("rm -r /deps", shell=True)
call('mkdir /deps', shell=True)
if not os.path.exists('cache'):
call('mkdir cache', shell=True)
os.chdir('/deps')
call('wget -q -i https://raw.githubusercontent.com/TheLastBen/fast-stable-diffusion/main/Dependencies/aptdeps.txt', shell=True)
call('dpkg -i *.deb', shell=True, stdout=open('/dev/null', 'w'))
depsinst("https://huggingface.co/TheLastBen/dependencies/resolve/main/ppsdeps.tar.zst", "/deps/ppsdeps.tar.zst")
call('tar -C / --zstd -xf ppsdeps.tar.zst', shell=True, stdout=open('/dev/null', 'w'))
call("sed -i 's@~/.cache@/notebooks/cache@' /usr/local/lib/python3.9/dist-packages/transformers/utils/hub.py", shell=True)
os.chdir('/notebooks')
call('pip install --root-user-action=ignore --disable-pip-version-check -qq diffusers==0.18.1', shell=True, stdout=open('/dev/null', 'w'))
call("git clone --depth 1 -q --branch main https://github.com/TheLastBen/diffusers /diffusers", shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
os.environ['TORCH_HOME'] = '/notebooks/cache/torch'
os.environ['PYTHONWARNINGS'] = 'ignore'
call("sed -i 's@text = _formatwarnmsg(msg)@text =\"\"@g' /usr/lib/python3.9/warnings.py", shell=True)
if not os.path.exists('/notebooks/diffusers'):
call('ln -s /diffusers /notebooks', shell=True)
call("rm -r /deps", shell=True)
os.chdir('/notebooks')
clear_output()
done()
def depsinst(url, dst):
file_size = None
req = Request(url, headers={"User-Agent": "torch.hub"})
u = urlopen(req)
meta = u.info()
if hasattr(meta, 'getheaders'):
content_length = meta.getheaders("Content-Length")
else:
content_length = meta.get_all("Content-Length")
if content_length is not None and len(content_length) > 0:
file_size = int(content_length[0])
with tqdm(total=file_size, disable=False, mininterval=0.5,
bar_format='Installing dependencies |{bar:20}| {percentage:3.0f}%') as pbar:
with open(dst, "wb") as f:
while True:
buffer = u.read(8192)
if len(buffer) == 0:
break
f.write(buffer)
pbar.update(len(buffer))
f.close()
def dwn(url, dst, msg):
file_size = None
req = Request(url, headers={"User-Agent": "torch.hub"})
u = urlopen(req)
meta = u.info()
if hasattr(meta, 'getheaders'):
content_length = meta.getheaders("Content-Length")
else:
content_length = meta.get_all("Content-Length")
if content_length is not None and len(content_length) > 0:
file_size = int(content_length[0])
with tqdm(total=file_size, disable=False, mininterval=0.5,
bar_format=msg+' |{bar:20}| {percentage:3.0f}%') as pbar:
with open(dst, "wb") as f:
while True:
buffer = u.read(8192)
if len(buffer) == 0:
break
f.write(buffer)
pbar.update(len(buffer))
f.close()
def ntbk():
os.chdir('/notebooks')
if not os.path.exists('Latest_Notebooks'):
call('mkdir Latest_Notebooks', shell=True)
else:
call('rm -r Latest_Notebooks', shell=True)
call('mkdir Latest_Notebooks', shell=True)
os.chdir('/notebooks/Latest_Notebooks')
call('wget -q -i https://huggingface.co/datasets/TheLastBen/PPS/raw/main/Notebooks.txt', shell=True)
call('rm Notebooks.txt', shell=True)
os.chdir('/notebooks')
def ntbks():
os.chdir('/notebooks')
if not os.path.exists('Latest_Notebooks'):
call('mkdir Latest_Notebooks', shell=True)
else:
call('rm -r Latest_Notebooks', shell=True)
call('mkdir Latest_Notebooks', shell=True)
os.chdir('/notebooks/Latest_Notebooks')
call('wget -q -i https://huggingface.co/datasets/TheLastBen/RNPD/raw/main/Notebooks.txt', shell=True)
call('rm Notebooks.txt', shell=True)
os.chdir('/notebooks')
def done():
done = widgets.Button(
description='Done!',
disabled=True,
button_style='success',
tooltip='',
icon='check'
)
display(done)
def mdlvxl():
os.chdir('/notebooks')
if os.path.exists('stable-diffusion-XL') and not os.path.exists('/notebooks/stable-diffusion-XL/unet/diffusion_pytorch_model.safetensors'):
call('rm -r stable-diffusion-XL', shell=True)
if not os.path.exists('stable-diffusion-XL'):
print('[1;33mDownloading SDXL model...')
call('mkdir stable-diffusion-XL', shell=True)
os.chdir('stable-diffusion-XL')
call('git init', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('git lfs install --system --skip-repo', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('git remote add -f origin https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('git config core.sparsecheckout true', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('echo -e "\nscheduler\ntext_encoder\ntext_encoder_2\ntokenizer\ntokenizer_2\nunet\nvae\nfeature_extractor\nmodel_index.json\n!*.safetensors\n!*.bin\n!*.onnx*\n!*.xml\n!*.msgpack" > .git/info/sparse-checkout', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('git pull origin main', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
dwn('https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/text_encoder/model.safetensors', 'text_encoder/model.safetensors', '1/4')
dwn('https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/text_encoder_2/model.safetensors', 'text_encoder_2/model.safetensors', '2/4')
dwn('https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/vae/diffusion_pytorch_model.safetensors', 'vae/diffusion_pytorch_model.safetensors', '3/4')
dwn('https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/unet/diffusion_pytorch_model.safetensors', 'unet/diffusion_pytorch_model.safetensors', '4/4')
call('rm -r .git', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
os.chdir('/notebooks')
clear_output()
while not os.path.exists('/notebooks/stable-diffusion-XL/unet/diffusion_pytorch_model.safetensors'):
print('[1;31mInvalid HF token, make sure you have access to the model')
time.sleep(8)
if os.path.exists('/notebooks/stable-diffusion-XL/unet/diffusion_pytorch_model.safetensors'):
print('[1;32mUsing SDXL model')
else:
print('[1;32mUsing SDXL model')
call("sed -i 's@\"force_upcast.*@@' /notebooks/stable-diffusion-XL/vae/config.json", shell=True)
def downloadmodel_hfxl(Path_to_HuggingFace):
os.chdir('/notebooks')
if os.path.exists('stable-diffusion-custom'):
call("rm -r stable-diffusion-custom", shell=True)
clear_output()
if os.path.exists('Fast-Dreambooth/token.txt'):
with open("Fast-Dreambooth/token.txt") as f:
token = f.read()
authe=f'https://USER:{token}@'
else:
authe="https://"
clear_output()
call("mkdir stable-diffusion-custom", shell=True)
os.chdir("stable-diffusion-custom")
call("git init", shell=True)
call("git lfs install --system --skip-repo", shell=True)
call('git remote add -f origin '+authe+'huggingface.co/'+Path_to_HuggingFace, shell=True)
call("git config core.sparsecheckout true", shell=True)
call('echo -e "\nscheduler\ntext_encoder\ntokenizer\nunet\nvae\nfeature_extractor\nmodel_index.json\n!*.safetensors\n!*.fp16.bin" > .git/info/sparse-checkout', shell=True)
call("git pull origin main", shell=True)
if os.path.exists('unet/diffusion_pytorch_model.safetensors'):
call("rm -r .git", shell=True)
os.chdir('/notebooks')
clear_output()
done()
while not os.path.exists('/notebooks/stable-diffusion-custom/unet/diffusion_pytorch_model.safetensors'):
print('[1;31mCheck the link you provided')
os.chdir('/notebooks')
time.sleep(5)
def downloadmodel_link_xl(MODEL_LINK):
import wget
import gdown
from gdown.download import get_url_from_gdrive_confirmation
def getsrc(url):
parsed_url = urlparse(url)
if parsed_url.netloc == 'civitai.com':
src='civitai'
elif parsed_url.netloc == 'drive.google.com':
src='gdrive'
elif parsed_url.netloc == 'huggingface.co':
src='huggingface'
else:
src='others'
return src
src=getsrc(MODEL_LINK)
def get_name(url, gdrive):
if not gdrive:
response = requests.get(url, allow_redirects=False)
if "Location" in response.headers:
redirected_url = response.headers["Location"]
quer = parse_qs(urlparse(redirected_url).query)
if "response-content-disposition" in quer:
disp_val = quer["response-content-disposition"][0].split(";")
for vals in disp_val:
if vals.strip().startswith("filename="):
filenm=unquote(vals.split("=", 1)[1].strip())
return filenm.replace("\"","")
else:
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"}
lnk="https://drive.google.com/uc?id={id}&export=download".format(id=url[url.find("/d/")+3:url.find("/view")])
res = requests.session().get(lnk, headers=headers, stream=True, verify=True)
res = requests.session().get(get_url_from_gdrive_confirmation(res.text), headers=headers, stream=True, verify=True)
content_disposition = six.moves.urllib_parse.unquote(res.headers["Content-Disposition"])
filenm = re.search(r"filename\*=UTF-8''(.*)", content_disposition).groups()[0].replace(os.path.sep, "_")
return filenm
if src=='civitai':
modelname=get_name(MODEL_LINK, False)
elif src=='gdrive':
modelname=get_name(MODEL_LINK, True)
else:
modelname=os.path.basename(MODEL_LINK)
os.chdir('/notebooks')
if src=='huggingface':
dwn(MODEL_LINK, modelname,'[1;33mDownloading the Model')
else:
call("gdown --fuzzy " +MODEL_LINK+ " -O "+modelname, shell=True)
if os.path.exists(modelname):
if os.path.getsize(modelname) > 1810671599:
print('[1;32mConverting to diffusers...')
call('python /notebooks/diffusers/scripts/convert_original_stable_diffusion_to_diffusers.py --checkpoint_path '+modelname+' --dump_path stable-diffusion-custom --from_safetensors', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
if os.path.exists('stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
os.chdir('/notebooks')
clear_output()
done()
else:
while not os.path.exists('stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
print('[1;31mConversion error')
os.chdir('/notebooks')
time.sleep(5)
else:
while os.path.getsize(modelname) < 1810671599:
print('[1;31mWrong link, check that the link is valid')
os.chdir('/notebooks')
time.sleep(5)
def downloadmodel_path_xl(MODEL_PATH):
import wget
os.chdir('/notebooks')
clear_output()
if os.path.exists(str(MODEL_PATH)):
print('[1;32mConverting to diffusers...')
call('python /notebooks/diffusers/scripts/convert_original_stable_diffusion_to_diffusers.py --checkpoint_path '+MODEL_PATH+' --dump_path stable-diffusion-custom --from_safetensors', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
if os.path.exists('stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
clear_output()
done()
while not os.path.exists('stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
print('[1;31mConversion error')
os.chdir('/notebooks')
time.sleep(5)
else:
while not os.path.exists(str(MODEL_PATH)):
print('[1;31mWrong path, use the file explorer to copy the path')
os.chdir('/notebooks')
time.sleep(5)
def dls_xl(Path_to_HuggingFace, MODEL_PATH, MODEL_LINK):
os.chdir('/notebooks')
if Path_to_HuggingFace != "":
downloadmodel_hfxl(Path_to_HuggingFace)
MODEL_NAMExl="/notebooks/stable-diffusion-custom"
elif MODEL_PATH !="":
downloadmodel_path_xl(MODEL_PATH)
MODEL_NAMExl="/notebooks/stable-diffusion-custom"
elif MODEL_LINK !="":
downloadmodel_link_xl(MODEL_LINK)
MODEL_NAMExl="/notebooks/stable-diffusion-custom"
else:
mdlvxl()
MODEL_NAMExl="/notebooks/stable-diffusion-XL"
return MODEL_NAMExl
def sess_xl(Session_Name, MODEL_NAMExl):
import gdown
import wget
os.chdir('/notebooks')
PT=""
while Session_Name=="":
print('[1;31mInput the Session Name:')
Session_Name=input("")
Session_Name=Session_Name.replace(" ","_")
WORKSPACE='/notebooks/Fast-Dreambooth'
INSTANCE_NAME=Session_Name
OUTPUT_DIR="/notebooks/models/"+Session_Name
SESSION_DIR=WORKSPACE+"/Sessions/"+Session_Name
INSTANCE_DIR=SESSION_DIR+"/instance_images"
CAPTIONS_DIR=SESSION_DIR+'/captions'
MDLPTH=str(SESSION_DIR+"/"+Session_Name+'.safetensors')
if os.path.exists(str(SESSION_DIR)) and not os.path.exists(MDLPTH):
print('[1;32mLoading session with no previous LoRa model')
if MODEL_NAMExl=="":
print('[1;31mNo model found, use the "Model Download" cell to download a model.')
else:
print('[1;32mSession Loaded, proceed')
elif not os.path.exists(str(SESSION_DIR)):
call('mkdir -p '+INSTANCE_DIR, shell=True)
print('[1;32mCreating session...')
if MODEL_NAMExl=="":
print('[1;31mNo model found, use the "Model Download" cell to download a model.')
else:
print('[1;32mSession created, proceed to uploading instance images')
if MODEL_NAMExl=="":
print('[1;31mNo model found, use the "Model Download" cell to download a model.')
else:
print('[1;32mSession Loaded, proceed')
return WORKSPACE, Session_Name, INSTANCE_NAME, OUTPUT_DIR, SESSION_DIR, INSTANCE_DIR, CAPTIONS_DIR, MDLPTH, MODEL_NAMExl
def uplder(Remove_existing_instance_images, Crop_images, Crop_size, Resize_to_1024_and_keep_aspect_ratio, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR):
if os.path.exists(INSTANCE_DIR+"/.ipynb_checkpoints"):
call('rm -r '+INSTANCE_DIR+'/.ipynb_checkpoints', shell=True)
uploader = widgets.FileUpload(description="Choose images",accept='image/*, .txt', multiple=True)
Upload = widgets.Button(
description='Upload',
disabled=False,
button_style='info',
tooltip='Click to upload the chosen instance images',
icon=''
)
def up(Upload):
with out:
uploader.close()
Upload.close()
upld(Remove_existing_instance_images, Crop_images, Crop_size, Resize_to_1024_and_keep_aspect_ratio, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR, uploader)
done()
out=widgets.Output()
if IMAGES_FOLDER_OPTIONAL=="":
Upload.on_click(up)
display(uploader, Upload, out)
else:
upld(Remove_existing_instance_images, Crop_images, Crop_size, Resize_to_1024_and_keep_aspect_ratio, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR, uploader)
done()
def upld(Remove_existing_instance_images, Crop_images, Crop_size, Resize_to_1024_and_keep_aspect_ratio, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR, uploader):
if Remove_existing_instance_images:
if os.path.exists(str(INSTANCE_DIR)):
call("rm -r " +INSTANCE_DIR, shell=True)
if os.path.exists(str(CAPTIONS_DIR)):
call("rm -r " +CAPTIONS_DIR, shell=True)
if not os.path.exists(str(INSTANCE_DIR)):
call("mkdir -p " +INSTANCE_DIR, shell=True)
if not os.path.exists(str(CAPTIONS_DIR)):
call("mkdir -p " +CAPTIONS_DIR, shell=True)
if IMAGES_FOLDER_OPTIONAL !="":
if os.path.exists(IMAGES_FOLDER_OPTIONAL+"/.ipynb_checkpoints"):
call('rm -r '+IMAGES_FOLDER_OPTIONAL+'/.ipynb_checkpoints', shell=True)
if any(file.endswith('.{}'.format('txt')) for file in os.listdir(IMAGES_FOLDER_OPTIONAL)):
call('mv '+IMAGES_FOLDER_OPTIONAL+'/*.txt '+CAPTIONS_DIR, shell=True)
if Crop_images:
os.chdir(str(IMAGES_FOLDER_OPTIONAL))
call('find . -name "* *" -type f | rename ' "'s/ /-/g'", shell=True)
os.chdir('/notebooks')
for filename in tqdm(os.listdir(IMAGES_FOLDER_OPTIONAL), bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Uploaded'):
extension = filename.split(".")[-1]
identifier=filename.split(".")[0]
new_path_with_file = os.path.join(INSTANCE_DIR, filename)
file = Image.open(IMAGES_FOLDER_OPTIONAL+"/"+filename)
file=file.convert("RGB")
file=ImageOps.exif_transpose(file)
width, height = file.size
if file.size !=(Crop_size, Crop_size):
image=crop_image(file, Crop_size)
if extension.upper()=="JPG" or extension.upper()=="jpg":
image[0].save(new_path_with_file, format="JPEG", quality = 100)
else:
image[0].save(new_path_with_file, format=extension.upper())
else:
call("cp \'"+IMAGES_FOLDER_OPTIONAL+"/"+filename+"\' "+INSTANCE_DIR, shell=True)
else:
for filename in tqdm(os.listdir(IMAGES_FOLDER_OPTIONAL), bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Uploaded'):
call("cp -r " +IMAGES_FOLDER_OPTIONAL+"/. " +INSTANCE_DIR, shell=True)
elif IMAGES_FOLDER_OPTIONAL =="":
up=""
for file in uploader.value:
filename = file['name']
if filename.split(".")[-1]=="txt":
with open(CAPTIONS_DIR+'/'+filename, 'w') as f:
f.write(bytes(file['content']).decode())
up=[file for file in uploader.value if not file['name'].endswith('.txt')]
if Crop_images:
for file in tqdm(up, bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Uploaded'):
filename = file['name']
img = Image.open(io.BytesIO(file['content']))
extension = filename.split(".")[-1]
identifier=filename.split(".")[0]
img=img.convert("RGB")
img=ImageOps.exif_transpose(img)
if extension.upper()=="JPG" or extension.upper()=="jpg":
img.save(INSTANCE_DIR+"/"+filename, format="JPEG", quality = 100)
else:
img.save(INSTANCE_DIR+"/"+filename, format=extension.upper())
new_path_with_file = os.path.join(INSTANCE_DIR, filename)
file = Image.open(new_path_with_file)
width, height = file.size
if file.size !=(Crop_size, Crop_size):
image=crop_image(file, Crop_size)
if extension.upper()=="JPG" or extension.upper()=="jpg":
image[0].save(new_path_with_file, format="JPEG", quality = 100)
else:
image[0].save(new_path_with_file, format=extension.upper())
else:
for file in tqdm(uploader.value, bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Uploaded'):
filename = file['name']
img = Image.open(io.BytesIO(file['content']))
img=img.convert("RGB")
extension = filename.split(".")[-1]
identifier=filename.split(".")[0]
if extension.upper()=="JPG" or extension.upper()=="jpg":
img.save(INSTANCE_DIR+"/"+filename, format="JPEG", quality = 100)
else:
img.save(INSTANCE_DIR+"/"+filename, format=extension.upper())
os.chdir(INSTANCE_DIR)
call('find . -name "* *" -type f | rename ' "'s/ /-/g'", shell=True)
os.chdir(CAPTIONS_DIR)
call('find . -name "* *" -type f | rename ' "'s/ /-/g'", shell=True)
os.chdir('/notebooks')
if Resize_to_1024_and_keep_aspect_ratio and not Crop_images:
resize_keep_aspect(INSTANCE_DIR)
def caption(CAPTIONS_DIR, INSTANCE_DIR):
paths=""
out=""
widgets_l=""
clear_output()
def Caption(path):
if path!="Select an instance image to caption":
name = os.path.splitext(os.path.basename(path))[0]
ext=os.path.splitext(os.path.basename(path))[-1][1:]
if ext=="jpg" or "JPG":
ext="JPEG"
if os.path.exists(CAPTIONS_DIR+"/"+name + '.txt'):
with open(CAPTIONS_DIR+"/"+name + '.txt', 'r') as f:
text = f.read()
else:
with open(CAPTIONS_DIR+"/"+name + '.txt', 'w') as f:
f.write("")
with open(CAPTIONS_DIR+"/"+name + '.txt', 'r') as f:
text = f.read()
img=Image.open(os.path.join(INSTANCE_DIR,path))
img=img.convert("RGB")
img=img.resize((420, 420))
image_bytes = BytesIO()
img.save(image_bytes, format=ext, qualiy=10)
image_bytes.seek(0)
image_data = image_bytes.read()
img= image_data
image = widgets.Image(
value=img,
width=420,
height=420
)
text_area = widgets.Textarea(value=text, description='', disabled=False, layout={'width': '300px', 'height': '120px'})
def update_text(text):
with open(CAPTIONS_DIR+"/"+name + '.txt', 'w') as f:
f.write(text)
button = widgets.Button(description='Save', button_style='success')
button.on_click(lambda b: update_text(text_area.value))
return widgets.VBox([widgets.HBox([image, text_area, button])])
paths = os.listdir(INSTANCE_DIR)
widgets_l = widgets.Select(options=["Select an instance image to caption"]+paths, rows=25)
out = widgets.Output()
def click(change):
with out:
out.clear_output()
display(Caption(change.new))
widgets_l.observe(click, names='value')
display(widgets.HBox([widgets_l, out]))
def dbtrainxl(Unet_Training_Epochs, Text_Encoder_Training_Epochs, Unet_Learning_Rate, Text_Encoder_Learning_Rate, dim, Offset_Noise, Resolution, MODEL_NAME, SESSION_DIR, INSTANCE_DIR, CAPTIONS_DIR, External_Captions, INSTANCE_NAME, Session_Name, OUTPUT_DIR, ofstnselvl, Save_VRAM, Intermediary_Save_Epoch):
if os.path.exists(INSTANCE_DIR+"/.ipynb_checkpoints"):
call('rm -r '+INSTANCE_DIR+'/.ipynb_checkpoints', shell=True)
if os.path.exists(CAPTIONS_DIR+"/.ipynb_checkpoints"):
call('rm -r '+CAPTIONS_DIR+'/.ipynb_checkpoints', shell=True)
Seed=random.randint(1, 999999)
ofstnse=""
if Offset_Noise:
ofstnse="--offset_noise"
GC=''
if Save_VRAM:
GC='--gradient_checkpointing'
extrnlcptn=""
if External_Captions:
extrnlcptn="--external_captions"
precision="fp16"
def train_only_text(SESSION_DIR, MODEL_NAME, INSTANCE_DIR, OUTPUT_DIR, Seed, Resolution, ofstnse, extrnlcptn, precision, Training_Epochs):
print('[1;33mTraining the Text Encoder...[0m')
call('accelerate launch /notebooks/diffusers/examples/dreambooth/train_dreambooth_sdxl_TI.py \
'+ofstnse+' \
'+extrnlcptn+' \
--dim='+str(dim)+' \
--ofstnselvl='+str(ofstnselvl)+' \
--image_captions_filename \
--Session_dir='+SESSION_DIR+' \
--pretrained_model_name_or_path='+MODEL_NAME+' \
--instance_data_dir='+INSTANCE_DIR+' \
--output_dir='+OUTPUT_DIR+' \
--captions_dir='+CAPTIONS_DIR+' \
--seed='+str(Seed)+' \
--resolution='+str(Resolution)+' \
--mixed_precision='+str(precision)+' \
--train_batch_size=1 \
--gradient_accumulation_steps=1 '+GC+ ' \
--use_8bit_adam \
--learning_rate='+str(Text_Encoder_Learning_Rate)+' \
--lr_scheduler="cosine" \
--lr_warmup_steps=0 \
--num_train_epochs='+str(Training_Epochs), shell=True)
def train_only_unet(SESSION_DIR, MODEL_NAME, INSTANCE_DIR, OUTPUT_DIR, Seed, Resolution, ofstnse, extrnlcptn, precision, Training_Epochs):
print('[1;33mTraining the UNet...[0m')
call('accelerate launch /notebooks/diffusers/examples/dreambooth/train_dreambooth_sdxl_lora.py \
'+ofstnse+' \
'+extrnlcptn+' \
--saves='+Intermediary_Save_Epoch+' \
--dim='+str(dim)+' \
--ofstnselvl='+str(ofstnselvl)+' \
--image_captions_filename \
--Session_dir='+SESSION_DIR+' \
--pretrained_model_name_or_path='+MODEL_NAME+' \
--instance_data_dir='+INSTANCE_DIR+' \
--output_dir='+OUTPUT_DIR+' \
--captions_dir='+CAPTIONS_DIR+' \
--seed='+str(Seed)+' \
--resolution='+str(Resolution)+' \
--mixed_precision='+str(precision)+' \
--train_batch_size=1 \
--gradient_accumulation_steps=1 '+GC+ ' \
--use_8bit_adam \
--learning_rate='+str(Unet_Learning_Rate)+' \
--lr_scheduler="cosine" \
--lr_warmup_steps=0 \
--num_train_epochs='+str(Training_Epochs), shell=True)
if Unet_Training_Epochs!=0:
if Text_Encoder_Training_Epochs!=0:
train_only_text(SESSION_DIR, MODEL_NAME, INSTANCE_DIR, OUTPUT_DIR, Seed, Resolution, ofstnse, extrnlcptn, precision, Training_Epochs=Text_Encoder_Training_Epochs)
clear_output()
train_only_unet(SESSION_DIR, MODEL_NAME, INSTANCE_DIR, OUTPUT_DIR, Seed, Resolution, ofstnse, extrnlcptn, precision, Training_Epochs=Unet_Training_Epochs)
else :
print('[1;32mNothing to do')
if os.path.exists(SESSION_DIR+'/'+Session_Name+'.safetensors'):
clear_output()
print("[1;32mDONE, the LoRa model is in the session's folder")
else:
print("[1;31mSomething went wrong")
def sdcmf(MDLPTH):
from slugify import slugify
from huggingface_hub import HfApi, CommitOperationAdd, create_repo
os.chdir('/notebooks')
print('[1;33mInstalling/Updating the repo...')
if not os.path.exists('ComfyUI'):
call('git clone -q --depth 1 https://github.com/comfyanonymous/ComfyUI', shell=True)
os.chdir('ComfyUI')
call('git reset --hard', shell=True)
print('[1;32m')
call('git pull', shell=True)
if os.path.exists(MDLPTH):
call('ln -s '+os.path.dirname(MDLPTH)+' models/loras', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
clean_symlinks('models/loras')
if not os.path.exists('models/checkpoints/sd_xl_base_1.0.safetensors'):
call('ln -s /datasets/stable-diffusion-xl/sd_xl_base_1.0.safetensors models/checkpoints', shell=True)
localurl="https://tensorboard-"+os.environ.get('PAPERSPACE_FQDN')
call("sed -i 's@logging.info(\"To see the GUI go to: {}://{}:{}\".format(scheme, address_print, port))@print(\"[32m\u2714 Connected\")\\n print(\"[1;34m"+localurl+"[0m\")@' /notebooks/ComfyUI/server.py", shell=True)
os.chdir('/notebooks')
def test(MDLPTH, User, Password):
auth=f"--gradio-auth {User}:{Password}"
if User =="" or Password=="":
auth=""
os.chdir('/notebooks')
if not os.path.exists('/notebooks/sd/stablediffusiond'): #reset later
call('wget -q -O sd_mrep.tar.zst https://huggingface.co/TheLastBen/dependencies/resolve/main/sd_mrep.tar.zst', shell=True)
call('tar --zstd -xf sd_mrep.tar.zst', shell=True)
call('rm sd_mrep.tar.zst', shell=True)
os.chdir('/notebooks/sd')
if not os.path.exists('stable-diffusion-webui'):
call('git clone -q --depth 1 --branch master https://github.com/AUTOMATIC1111/stable-diffusion-webui', shell=True)
os.chdir('/notebooks/sd/stable-diffusion-webui/')
call('git reset --hard', shell=True, stdout=open('/dev/null', 'w'))
print('[1;32m')
call('git checkout master', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('git pull', shell=True, stdout=open('/dev/null', 'w'))
os.makedirs('/notebooks/sd/stable-diffusion-webui/repositories', exist_ok=True)
call('git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui-assets /notebooks/sd/stable-diffusion-webui/repositories/stable-diffusion-webui-assets', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
clear_output()
if not os.path.exists('models/Stable-diffusion/sd_xl_base_1.0.safetensors'):
call('ln -s /datasets/stable-diffusion-xl/sd_xl_base_1.0.safetensors models/Stable-diffusion', shell=True)
if os.path.exists(MDLPTH):
call('ln -s '+os.path.dirname(MDLPTH)+' models/Lora', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
clean_symlinks('models/Lora')
call('wget -q -O /notebooks/sd/stable-diffusion-webui/modules/styles.py https://github.com/TheLastBen/fast-stable-diffusion/raw/main/AUTOMATIC1111_files/styles.py', shell=True)
call('wget -q -O /usr/local/lib/python3.9/dist-packages/gradio/blocks.py https://raw.githubusercontent.com/TheLastBen/fast-stable-diffusion/main/AUTOMATIC1111_files/blocks.py', shell=True)
localurl="tensorboard-"+os.environ.get('PAPERSPACE_FQDN')
for line in fileinput.input('/usr/local/lib/python3.9/dist-packages/gradio/blocks.py', inplace=True):
if line.strip().startswith('self.server_name ='):
line = f' self.server_name = "{localurl}"\n'
if line.strip().startswith('self.protocol = "https"'):
line = ' self.protocol = "https"\n'
if line.strip().startswith('if self.local_url.startswith("https") or self.is_colab'):
line = ''
if line.strip().startswith('else "http"'):
line = ''
sys.stdout.write(line)
os.chdir('/notebooks/sd/stable-diffusion-webui/modules')
call("sed -i 's@possible_sd_paths =.*@possible_sd_paths = [\"/notebooks/sd/stablediffusion\"]@' /notebooks/sd/stable-diffusion-webui/modules/paths.py", shell=True)
call("sed -i 's@\.\.\/@src/@g' /notebooks/sd/stable-diffusion-webui/modules/paths.py", shell=True)
call("sed -i 's@src\/generative-models@generative-models@g' /notebooks/sd/stable-diffusion-webui/modules/paths.py", shell=True)
call("sed -i 's@-> Network | None@@g' /notebooks/sd/stable-diffusion-webui/extensions-builtin/Lora/network.py", shell=True)
call("sed -i 's@|@or@' /notebooks/sd/stable-diffusion-webui/extensions/adetailer/aaaaaa/helper.py", shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call("sed -i 's@\"quicksettings\": OptionInfo(.*@\"quicksettings\": OptionInfo(\"sd_model_checkpoint, sd_vae, CLIP_stop_at_last_layers, inpainting_mask_weight, initial_noise_multiplier\", \"Quicksettings list\"),@' /notebooks/sd/stable-diffusion-webui/modules/shared.py", shell=True)
os.chdir('/notebooks/sd/stable-diffusion-webui')
clear_output()
configf="--disable-console-progressbars --no-gradio-queue --upcast-sampling --no-hashing --no-half-vae --disable-safe-unpickle --api --no-download-sd-model --xformers --enable-insecure-extension-access --port 6006 --listen --skip-version-check --ckpt /notebooks/sd/stable-diffusion-webui/models/Stable-diffusion/sd_xl_base_1.0.safetensors "+auth
return configf
def clean():
Sessions=os.listdir("/notebooks/Fast-Dreambooth/Sessions")
s = widgets.Select(
options=Sessions,
rows=5,
description='',
disabled=False
)
out=widgets.Output()
d = widgets.Button(
description='Remove',
disabled=False,
button_style='warning',
tooltip='Removet the selected session',
icon='warning'
)
def rem(d):
with out:
if s.value is not None:
clear_output()
print("[1;33mTHE SESSION [1;31m"+s.value+" [1;33mHAS BEEN REMOVED FROM THE STORAGE")
call('rm -r /notebooks/Fast-Dreambooth/Sessions/'+s.value, shell=True)
if os.path.exists('/notebooks/models/'+s.value):
call('rm -r /notebooks/models/'+s.value, shell=True)
s.options=os.listdir("/notebooks/Fast-Dreambooth/Sessions")
else:
d.close()
s.close()
clear_output()
print("[1;32mNOTHING TO REMOVE")
d.on_click(rem)
if s.value is not None:
display(s,d,out)
else:
print("[1;32mNOTHING TO REMOVE")
def crop_image(im, size):
import cv2
GREEN = "#0F0"
BLUE = "#00F"
RED = "#F00"
def focal_point(im, settings):
corner_points = image_corner_points(im, settings) if settings.corner_points_weight > 0 else []
entropy_points = image_entropy_points(im, settings) if settings.entropy_points_weight > 0 else []
face_points = image_face_points(im, settings) if settings.face_points_weight > 0 else []
pois = []
weight_pref_total = 0
if len(corner_points) > 0:
weight_pref_total += settings.corner_points_weight
if len(entropy_points) > 0:
weight_pref_total += settings.entropy_points_weight
if len(face_points) > 0:
weight_pref_total += settings.face_points_weight
corner_centroid = None
if len(corner_points) > 0:
corner_centroid = centroid(corner_points)
corner_centroid.weight = settings.corner_points_weight / weight_pref_total
pois.append(corner_centroid)
entropy_centroid = None
if len(entropy_points) > 0:
entropy_centroid = centroid(entropy_points)
entropy_centroid.weight = settings.entropy_points_weight / weight_pref_total
pois.append(entropy_centroid)
face_centroid = None
if len(face_points) > 0:
face_centroid = centroid(face_points)
face_centroid.weight = settings.face_points_weight / weight_pref_total
pois.append(face_centroid)
average_point = poi_average(pois, settings)
return average_point
def image_face_points(im, settings):
np_im = np.array(im)
gray = cv2.cvtColor(np_im, cv2.COLOR_BGR2GRAY)
tries = [
[ f'{cv2.data.haarcascades}haarcascade_eye.xml', 0.01 ],
[ f'{cv2.data.haarcascades}haarcascade_frontalface_default.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_profileface.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_frontalface_alt.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_frontalface_alt2.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_frontalface_alt_tree.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_eye_tree_eyeglasses.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_upperbody.xml', 0.05 ]
]
for t in tries:
classifier = cv2.CascadeClassifier(t[0])
minsize = int(min(im.width, im.height) * t[1]) # at least N percent of the smallest side
try:
faces = classifier.detectMultiScale(gray, scaleFactor=1.1,
minNeighbors=7, minSize=(minsize, minsize), flags=cv2.CASCADE_SCALE_IMAGE)
except:
continue
if len(faces) > 0:
rects = [[f[0], f[1], f[0] + f[2], f[1] + f[3]] for f in faces]
return [PointOfInterest((r[0] +r[2]) // 2, (r[1] + r[3]) // 2, size=abs(r[0]-r[2]), weight=1/len(rects)) for r in rects]
return []
def image_corner_points(im, settings):
grayscale = im.convert("L")
# naive attempt at preventing focal points from collecting at watermarks near the bottom
gd = ImageDraw.Draw(grayscale)
gd.rectangle([0, im.height*.9, im.width, im.height], fill="#999")
np_im = np.array(grayscale)
points = cv2.goodFeaturesToTrack(
np_im,
maxCorners=100,
qualityLevel=0.04,
minDistance=min(grayscale.width, grayscale.height)*0.06,
useHarrisDetector=False,
)
if points is None:
return []
focal_points = []
for point in points:
x, y = point.ravel()
focal_points.append(PointOfInterest(x, y, size=4, weight=1/len(points)))
return focal_points
def image_entropy_points(im, settings):
landscape = im.height < im.width
portrait = im.height > im.width
if landscape:
move_idx = [0, 2]
move_max = im.size[0]
elif portrait:
move_idx = [1, 3]
move_max = im.size[1]
else:
return []
e_max = 0
crop_current = [0, 0, settings.crop_width, settings.crop_height]
crop_best = crop_current
while crop_current[move_idx[1]] < move_max:
crop = im.crop(tuple(crop_current))
e = image_entropy(crop)
if (e > e_max):
e_max = e
crop_best = list(crop_current)
crop_current[move_idx[0]] += 4
crop_current[move_idx[1]] += 4
x_mid = int(crop_best[0] + settings.crop_width/2)
y_mid = int(crop_best[1] + settings.crop_height/2)
return [PointOfInterest(x_mid, y_mid, size=25, weight=1.0)]
def image_entropy(im):
# greyscale image entropy
# band = np.asarray(im.convert("L"))
band = np.asarray(im.convert("1"), dtype=np.uint8)
hist, _ = np.histogram(band, bins=range(0, 256))
hist = hist[hist > 0]
return -np.log2(hist / hist.sum()).sum()
def centroid(pois):
x = [poi.x for poi in pois]
y = [poi.y for poi in pois]
return PointOfInterest(sum(x)/len(pois), sum(y)/len(pois))
def poi_average(pois, settings):
weight = 0.0
x = 0.0
y = 0.0
for poi in pois:
weight += poi.weight
x += poi.x * poi.weight
y += poi.y * poi.weight
avg_x = round(weight and x / weight)
avg_y = round(weight and y / weight)
return PointOfInterest(avg_x, avg_y)
def is_landscape(w, h):
return w > h
def is_portrait(w, h):
return h > w
def is_square(w, h):
return w == h
class PointOfInterest:
def __init__(self, x, y, weight=1.0, size=10):
self.x = x
self.y = y
self.weight = weight
self.size = size
def bounding(self, size):
return [
self.x - size//2,
self.y - size//2,
self.x + size//2,
self.y + size//2
]
class Settings:
def __init__(self, crop_width=512, crop_height=512, corner_points_weight=0.5, entropy_points_weight=0.5, face_points_weight=0.5):
self.crop_width = crop_width
self.crop_height = crop_height
self.corner_points_weight = corner_points_weight
self.entropy_points_weight = entropy_points_weight
self.face_points_weight = face_points_weight
settings = Settings(
crop_width = size,
crop_height = size,
face_points_weight = 0.9,
entropy_points_weight = 0.15,
corner_points_weight = 0.5,
)
scale_by = 1
if is_landscape(im.width, im.height):
scale_by = settings.crop_height / im.height
elif is_portrait(im.width, im.height):
scale_by = settings.crop_width / im.width
elif is_square(im.width, im.height):
if is_square(settings.crop_width, settings.crop_height):
scale_by = settings.crop_width / im.width
elif is_landscape(settings.crop_width, settings.crop_height):
scale_by = settings.crop_width / im.width
elif is_portrait(settings.crop_width, settings.crop_height):
scale_by = settings.crop_height / im.height
im = im.resize((int(im.width * scale_by), int(im.height * scale_by)))
im_debug = im.copy()
focus = focal_point(im_debug, settings)
# take the focal point and turn it into crop coordinates that try to center over the focal
# point but then get adjusted back into the frame
y_half = int(settings.crop_height / 2)
x_half = int(settings.crop_width / 2)
x1 = focus.x - x_half
if x1 < 0:
x1 = 0
elif x1 + settings.crop_width > im.width:
x1 = im.width - settings.crop_width
y1 = focus.y - y_half
if y1 < 0:
y1 = 0
elif y1 + settings.crop_height > im.height:
y1 = im.height - settings.crop_height
x2 = x1 + settings.crop_width
y2 = y1 + settings.crop_height
crop = [x1, y1, x2, y2]
results = []
results.append(im.crop(tuple(crop)))
return results
def resize_keep_aspect(DIR):
min_dimension=1024
for filename in os.listdir(DIR):
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.webp')):
image = cv2.imread(os.path.join(DIR, filename))
org_height, org_width = image.shape[0], image.shape[1]
if org_width < org_height:
new_width = min_dimension
new_height = int(org_height * (min_dimension / org_width))
else:
new_height = min_dimension
new_width = int(org_width * (min_dimension / org_height))
resized_image = cv2.resize(image, (new_width, new_height), interpolation=cv2.INTER_LANCZOS4)
cv2.imwrite(os.path.join(DIR, filename), resized_image, [int(cv2.IMWRITE_PNG_COMPRESSION), 0])
def clean_symlinks(path):
for item in os.listdir(path):
lnk = os.path.join(path, item)
if os.path.islink(lnk) and not os.path.exists(os.readlink(lnk)):
os.remove(lnk)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147from IPython.display import clear_output
from subprocess import call, getoutput, Popen
from IPython.display import display
import ipywidgets as widgets
import io
from PIL import Image, ImageDraw, ImageOps
import fileinput
import time
import os
from os import listdir
from os.path import isfile
import random
import sys
from io import BytesIO
import requests
from collections import defaultdict
from math import log, sqrt
import numpy as np
import sys
import fileinput
import six
import base64
import re
import cv2
from urllib.parse import urlparse, parse_qs, unquote
import urllib.request
from urllib.request import urlopen, Request
import tempfile
from tqdm import tqdm
def Deps(force_reinstall):
if not force_reinstall and os.path.exists('/usr/local/lib/python3.11/dist-packages/gradio'):
ntbk()
call('pip install --root-user-action=ignore --disable-pip-version-check -qq diffusers==0.18.1', shell=True, stdout=open('/dev/null', 'w'))
os.environ['TORCH_HOME'] = '/notebooks/cache/torch'
os.environ['PYTHONWARNINGS'] = 'ignore'
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
print('[1;32mModules and notebooks updated, dependencies already installed')
else:
call("pip install --root-user-action=ignore --no-deps -q accelerate==0.12.0", shell=True, stdout=open('/dev/null', 'w'))
call("pip uninstall -qq deepspeed -y", shell=True, stdout=open('/dev/null', 'w'))
ntbk()
if not os.path.exists('/models'):
call('mkdir /models', shell=True)
if not os.path.exists('/notebooks/models'):
call('ln -s /models /notebooks', shell=True)
if os.path.exists('/deps'):
call("rm -r /deps", shell=True)
call('mkdir /deps', shell=True)
if not os.path.exists('cache'):
call('mkdir cache', shell=True)
os.chdir('/deps')
call('wget -q -i https://raw.githubusercontent.com/TheLastBen/fast-stable-diffusion/main/Dependencies/aptdeps_311.txt', shell=True)
call('dpkg -i *.deb', shell=True, stdout=open('/dev/null', 'w'))
depsinst("https://huggingface.co/TheLastBen/dependencies/resolve/main/ppsdeps_311.tar.zst", "/deps/ppsdeps_311.tar.zst")
call('tar -C / --zstd -xf ppsdeps_311.tar.zst', shell=True, stdout=open('/dev/null', 'w'))
os.chdir('/notebooks')
call('pip install --root-user-action=ignore --disable-pip-version-check -qq diffusers==0.18.1', shell=True, stdout=open('/dev/null', 'w'))
call("git clone --depth 1 -q --branch main https://github.com/TheLastBen/diffusers /diffusers", shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
os.environ['TORCH_HOME'] = '/notebooks/cache/torch'
os.environ['PYTHONWARNINGS'] = 'ignore'
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
call("sed -i 's@text = _formatwarnmsg(msg)@text =\"\"@g' /usr/lib/python3.11/warnings.py", shell=True)
if not os.path.exists('/notebooks/diffusers'):
call('ln -s /diffusers /notebooks', shell=True)
call("rm -r /deps", shell=True)
os.chdir('/notebooks')
clear_output()
done()
def depsinst(url, dst):
file_size = None
req = Request(url, headers={"User-Agent": "torch.hub"})
u = urlopen(req)
meta = u.info()
if hasattr(meta, 'getheaders'):
content_length = meta.getheaders("Content-Length")
else:
content_length = meta.get_all("Content-Length")
if content_length is not None and len(content_length) > 0:
file_size = int(content_length[0])
with tqdm(total=file_size, disable=False, mininterval=0.5,
bar_format='(fast-stable-diffusion will soon stop supporting Paperspace) Installing dependencies |{bar:20}| {percentage:3.0f}%') as pbar:
with open(dst, "wb") as f:
while True:
buffer = u.read(8192)
if len(buffer) == 0:
break
f.write(buffer)
pbar.update(len(buffer))
f.close()
def dwn(url, dst, msg):
file_size = None
req = Request(url, headers={"User-Agent": "torch.hub"})
u = urlopen(req)
meta = u.info()
if hasattr(meta, 'getheaders'):
content_length = meta.getheaders("Content-Length")
else:
content_length = meta.get_all("Content-Length")
if content_length is not None and len(content_length) > 0:
file_size = int(content_length[0])
with tqdm(total=file_size, disable=False, mininterval=0.5,
bar_format=msg+' |{bar:20}| {percentage:3.0f}%') as pbar:
with open(dst, "wb") as f:
while True:
buffer = u.read(8192)
if len(buffer) == 0:
break
f.write(buffer)
pbar.update(len(buffer))
f.close()
def ntbk():
os.chdir('/notebooks')
if not os.path.exists('Latest_Notebooks'):
call('mkdir Latest_Notebooks', shell=True)
else:
call('rm -r Latest_Notebooks', shell=True)
call('mkdir Latest_Notebooks', shell=True)
os.chdir('/notebooks/Latest_Notebooks')
call('wget -q -i https://huggingface.co/datasets/TheLastBen/PPS/raw/main/Notebooks.txt', shell=True)
call('rm Notebooks.txt', shell=True)
os.chdir('/notebooks')
def ntbks():
os.chdir('/notebooks')
if not os.path.exists('Latest_Notebooks'):
call('mkdir Latest_Notebooks', shell=True)
else:
call('rm -r Latest_Notebooks', shell=True)
call('mkdir Latest_Notebooks', shell=True)
os.chdir('/notebooks/Latest_Notebooks')
call('wget -q -i https://huggingface.co/datasets/TheLastBen/RNPD/raw/main/Notebooks.txt', shell=True)
call('rm Notebooks.txt', shell=True)
os.chdir('/notebooks')
def done():
done = widgets.Button(
description='Done!',
disabled=True,
button_style='success',
tooltip='',
icon='check'
)
display(done)
def mdlvxl():
os.chdir('/notebooks')
if os.path.exists('stable-diffusion-XL') and not os.path.exists('/notebooks/stable-diffusion-XL/unet/diffusion_pytorch_model.safetensors'):
call('rm -r stable-diffusion-XL', shell=True)
if not os.path.exists('stable-diffusion-XL'):
print('[1;33mDownloading SDXL model...')
call('mkdir stable-diffusion-XL', shell=True)
os.chdir('stable-diffusion-XL')
call('git init', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('git lfs install --system --skip-repo', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('git remote add -f origin https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('git config core.sparsecheckout true', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('echo -e "\nscheduler\ntext_encoder\ntext_encoder_2\ntokenizer\ntokenizer_2\nunet\nvae\nfeature_extractor\nmodel_index.json\n!*.safetensors\n!*.bin\n!*.onnx*\n!*.xml\n!*.msgpack" > .git/info/sparse-checkout', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('git pull origin main', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
dwn('https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/text_encoder/model.safetensors', 'text_encoder/model.safetensors', '1/4')
dwn('https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/text_encoder_2/model.safetensors', 'text_encoder_2/model.safetensors', '2/4')
dwn('https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/vae/diffusion_pytorch_model.safetensors', 'vae/diffusion_pytorch_model.safetensors', '3/4')
dwn('https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/unet/diffusion_pytorch_model.safetensors', 'unet/diffusion_pytorch_model.safetensors', '4/4')
call('rm -r .git', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
os.chdir('/notebooks')
clear_output()
while not os.path.exists('/notebooks/stable-diffusion-XL/unet/diffusion_pytorch_model.safetensors'):
print('[1;31mInvalid HF token, make sure you have access to the model')
time.sleep(8)
if os.path.exists('/notebooks/stable-diffusion-XL/unet/diffusion_pytorch_model.safetensors'):
print('[1;32mUsing SDXL model')
else:
print('[1;32mUsing SDXL model')
call("sed -i 's@\"force_upcast.*@@' /notebooks/stable-diffusion-XL/vae/config.json", shell=True)
def downloadmodel_hfxl(Path_to_HuggingFace):
os.chdir('/notebooks')
if os.path.exists('stable-diffusion-custom'):
call("rm -r stable-diffusion-custom", shell=True)
clear_output()
if os.path.exists('Fast-Dreambooth/token.txt'):
with open("Fast-Dreambooth/token.txt") as f:
token = f.read()
authe=f'https://USER:{token}@'
else:
authe="https://"
clear_output()
call("mkdir stable-diffusion-custom", shell=True)
os.chdir("stable-diffusion-custom")
call("git init", shell=True)
call("git lfs install --system --skip-repo", shell=True)
call('git remote add -f origin '+authe+'huggingface.co/'+Path_to_HuggingFace, shell=True)
call("git config core.sparsecheckout true", shell=True)
call('echo -e "\nscheduler\ntext_encoder\ntokenizer\nunet\nvae\nfeature_extractor\nmodel_index.json\n!*.safetensors\n!*.fp16.bin" > .git/info/sparse-checkout', shell=True)
call("git pull origin main", shell=True)
if os.path.exists('unet/diffusion_pytorch_model.safetensors'):
call("rm -r .git", shell=True)
os.chdir('/notebooks')
clear_output()
done()
while not os.path.exists('/notebooks/stable-diffusion-custom/unet/diffusion_pytorch_model.safetensors'):
print('[1;31mCheck the link you provided')
os.chdir('/notebooks')
time.sleep(5)
def downloadmodel_link_xl(MODEL_LINK):
import wget
import gdown
from gdown.download import get_url_from_gdrive_confirmation
def getsrc(url):
parsed_url = urlparse(url)
if parsed_url.netloc == 'civitai.com':
src='civitai'
elif parsed_url.netloc == 'drive.google.com':
src='gdrive'
elif parsed_url.netloc == 'huggingface.co':
src='huggingface'
else:
src='others'
return src
src=getsrc(MODEL_LINK)
def get_name(url, gdrive):
if not gdrive:
response = requests.get(url, allow_redirects=False)
if "Location" in response.headers:
redirected_url = response.headers["Location"]
quer = parse_qs(urlparse(redirected_url).query)
if "response-content-disposition" in quer:
disp_val = quer["response-content-disposition"][0].split(";")
for vals in disp_val:
if vals.strip().startswith("filename="):
filenm=unquote(vals.split("=", 1)[1].strip())
return filenm.replace("\"","")
else:
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"}
lnk="https://drive.google.com/uc?id={id}&export=download".format(id=url[url.find("/d/")+3:url.find("/view")])
res = requests.session().get(lnk, headers=headers, stream=True, verify=True)
res = requests.session().get(get_url_from_gdrive_confirmation(res.text), headers=headers, stream=True, verify=True)
content_disposition = six.moves.urllib_parse.unquote(res.headers["Content-Disposition"])
filenm = re.search(r"filename\*=UTF-8''(.*)", content_disposition).groups()[0].replace(os.path.sep, "_")
return filenm
if src=='civitai':
modelname=get_name(MODEL_LINK, False)
elif src=='gdrive':
modelname=get_name(MODEL_LINK, True)
else:
modelname=os.path.basename(MODEL_LINK)
os.chdir('/notebooks')
if src=='huggingface':
dwn(MODEL_LINK, modelname,'[1;33mDownloading the Model')
else:
call("gdown --fuzzy " +MODEL_LINK+ " -O "+modelname, shell=True)
if os.path.exists(modelname):
if os.path.getsize(modelname) > 1810671599:
print('[1;32mConverting to diffusers...')
call('python /notebooks/diffusers/scripts/convert_original_stable_diffusion_to_diffusers.py --checkpoint_path '+modelname+' --dump_path stable-diffusion-custom --from_safetensors', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
if os.path.exists('stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
os.chdir('/notebooks')
clear_output()
done()
else:
while not os.path.exists('stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
print('[1;31mConversion error')
os.chdir('/notebooks')
time.sleep(5)
else:
while os.path.getsize(modelname) < 1810671599:
print('[1;31mWrong link, check that the link is valid')
os.chdir('/notebooks')
time.sleep(5)
def downloadmodel_path_xl(MODEL_PATH):
import wget
os.chdir('/notebooks')
clear_output()
if os.path.exists(str(MODEL_PATH)):
print('[1;32mConverting to diffusers...')
call('python /notebooks/diffusers/scripts/convert_original_stable_diffusion_to_diffusers.py --checkpoint_path '+MODEL_PATH+' --dump_path stable-diffusion-custom --from_safetensors', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
if os.path.exists('stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
clear_output()
done()
while not os.path.exists('stable-diffusion-custom/unet/diffusion_pytorch_model.bin'):
print('[1;31mConversion error')
os.chdir('/notebooks')
time.sleep(5)
else:
while not os.path.exists(str(MODEL_PATH)):
print('[1;31mWrong path, use the file explorer to copy the path')
os.chdir('/notebooks')
time.sleep(5)
def dls_xl(Path_to_HuggingFace, MODEL_PATH, MODEL_LINK):
os.chdir('/notebooks')
if Path_to_HuggingFace != "":
downloadmodel_hfxl(Path_to_HuggingFace)
MODEL_NAMExl="/notebooks/stable-diffusion-custom"
elif MODEL_PATH !="":
downloadmodel_path_xl(MODEL_PATH)
MODEL_NAMExl="/notebooks/stable-diffusion-custom"
elif MODEL_LINK !="":
downloadmodel_link_xl(MODEL_LINK)
MODEL_NAMExl="/notebooks/stable-diffusion-custom"
else:
mdlvxl()
MODEL_NAMExl="/notebooks/stable-diffusion-XL"
return MODEL_NAMExl
def sess_xl(Session_Name, MODEL_NAMExl):
import gdown
import wget
os.chdir('/notebooks')
PT=""
while Session_Name=="":
print('[1;31mInput the Session Name:')
Session_Name=input("")
Session_Name=Session_Name.replace(" ","_")
WORKSPACE='/notebooks/Fast-Dreambooth'
INSTANCE_NAME=Session_Name
OUTPUT_DIR="/notebooks/models/"+Session_Name
SESSION_DIR=WORKSPACE+"/Sessions/"+Session_Name
INSTANCE_DIR=SESSION_DIR+"/instance_images"
CAPTIONS_DIR=SESSION_DIR+'/captions'
MDLPTH=str(SESSION_DIR+"/"+Session_Name+'.safetensors')
if os.path.exists(str(SESSION_DIR)) and not os.path.exists(MDLPTH):
print('[1;32mLoading session with no previous LoRa model')
if MODEL_NAMExl=="":
print('[1;31mNo model found, use the "Model Download" cell to download a model.')
else:
print('[1;32mSession Loaded, proceed')
elif not os.path.exists(str(SESSION_DIR)):
call('mkdir -p '+INSTANCE_DIR, shell=True)
print('[1;32mCreating session...')
if MODEL_NAMExl=="":
print('[1;31mNo model found, use the "Model Download" cell to download a model.')
else:
print('[1;32mSession created, proceed to uploading instance images')
if MODEL_NAMExl=="":
print('[1;31mNo model found, use the "Model Download" cell to download a model.')
else:
print('[1;32mSession Loaded, proceed')
return WORKSPACE, Session_Name, INSTANCE_NAME, OUTPUT_DIR, SESSION_DIR, INSTANCE_DIR, CAPTIONS_DIR, MDLPTH, MODEL_NAMExl
def uplder(Remove_existing_instance_images, Crop_images, Crop_size, Resize_to_1024_and_keep_aspect_ratio, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR):
if os.path.exists(INSTANCE_DIR+"/.ipynb_checkpoints"):
call('rm -r '+INSTANCE_DIR+'/.ipynb_checkpoints', shell=True)
uploader = widgets.FileUpload(description="Choose images",accept='image/*, .txt', multiple=True)
Upload = widgets.Button(
description='Upload',
disabled=False,
button_style='info',
tooltip='Click to upload the chosen instance images',
icon=''
)
def up(Upload):
with out:
uploader.close()
Upload.close()
upld(Remove_existing_instance_images, Crop_images, Crop_size, Resize_to_1024_and_keep_aspect_ratio, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR, uploader)
done()
out=widgets.Output()
if IMAGES_FOLDER_OPTIONAL=="":
Upload.on_click(up)
display(uploader, Upload, out)
else:
upld(Remove_existing_instance_images, Crop_images, Crop_size, Resize_to_1024_and_keep_aspect_ratio, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR, uploader)
done()
def upld(Remove_existing_instance_images, Crop_images, Crop_size, Resize_to_1024_and_keep_aspect_ratio, IMAGES_FOLDER_OPTIONAL, INSTANCE_DIR, CAPTIONS_DIR, uploader):
if Remove_existing_instance_images:
if os.path.exists(str(INSTANCE_DIR)):
call("rm -r " +INSTANCE_DIR, shell=True)
if os.path.exists(str(CAPTIONS_DIR)):
call("rm -r " +CAPTIONS_DIR, shell=True)
if not os.path.exists(str(INSTANCE_DIR)):
call("mkdir -p " +INSTANCE_DIR, shell=True)
if not os.path.exists(str(CAPTIONS_DIR)):
call("mkdir -p " +CAPTIONS_DIR, shell=True)
if IMAGES_FOLDER_OPTIONAL !="":
if os.path.exists(IMAGES_FOLDER_OPTIONAL+"/.ipynb_checkpoints"):
call('rm -r '+IMAGES_FOLDER_OPTIONAL+'/.ipynb_checkpoints', shell=True)
if any(file.endswith('.{}'.format('txt')) for file in os.listdir(IMAGES_FOLDER_OPTIONAL)):
call('mv '+IMAGES_FOLDER_OPTIONAL+'/*.txt '+CAPTIONS_DIR, shell=True)
if Crop_images:
os.chdir(str(IMAGES_FOLDER_OPTIONAL))
call('find . -name "* *" -type f | rename ' "'s/ /-/g'", shell=True)
os.chdir('/notebooks')
for filename in tqdm(os.listdir(IMAGES_FOLDER_OPTIONAL), bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Uploaded'):
extension = filename.split(".")[-1]
identifier=filename.split(".")[0]
new_path_with_file = os.path.join(INSTANCE_DIR, filename)
file = Image.open(IMAGES_FOLDER_OPTIONAL+"/"+filename)
file=file.convert("RGB")
file=ImageOps.exif_transpose(file)
width, height = file.size
if file.size !=(Crop_size, Crop_size):
image=crop_image(file, Crop_size)
if extension.upper()=="JPG" or extension.upper()=="jpg":
image[0].save(new_path_with_file, format="JPEG", quality = 100)
else:
image[0].save(new_path_with_file, format=extension.upper())
else:
call("cp \'"+IMAGES_FOLDER_OPTIONAL+"/"+filename+"\' "+INSTANCE_DIR, shell=True)
else:
for filename in tqdm(os.listdir(IMAGES_FOLDER_OPTIONAL), bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Uploaded'):
call("cp -r " +IMAGES_FOLDER_OPTIONAL+"/. " +INSTANCE_DIR, shell=True)
elif IMAGES_FOLDER_OPTIONAL =="":
up=""
for file in uploader.value:
filename = file['name']
if filename.split(".")[-1]=="txt":
with open(CAPTIONS_DIR+'/'+filename, 'w') as f:
f.write(bytes(file['content']).decode())
up=[file for file in uploader.value if not file['name'].endswith('.txt')]
if Crop_images:
for file in tqdm(up, bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Uploaded'):
filename = file['name']
img = Image.open(io.BytesIO(file['content']))
extension = filename.split(".")[-1]
identifier=filename.split(".")[0]
img=img.convert("RGB")
img=ImageOps.exif_transpose(img)
if extension.upper()=="JPG" or extension.upper()=="jpg":
img.save(INSTANCE_DIR+"/"+filename, format="JPEG", quality = 100)
else:
img.save(INSTANCE_DIR+"/"+filename, format=extension.upper())
new_path_with_file = os.path.join(INSTANCE_DIR, filename)
file = Image.open(new_path_with_file)
width, height = file.size
if file.size !=(Crop_size, Crop_size):
image=crop_image(file, Crop_size)
if extension.upper()=="JPG" or extension.upper()=="jpg":
image[0].save(new_path_with_file, format="JPEG", quality = 100)
else:
image[0].save(new_path_with_file, format=extension.upper())
else:
for file in tqdm(uploader.value, bar_format=' |{bar:15}| {n_fmt}/{total_fmt} Uploaded'):
filename = file['name']
img = Image.open(io.BytesIO(file['content']))
img=img.convert("RGB")
extension = filename.split(".")[-1]
identifier=filename.split(".")[0]
if extension.upper()=="JPG" or extension.upper()=="jpg":
img.save(INSTANCE_DIR+"/"+filename, format="JPEG", quality = 100)
else:
img.save(INSTANCE_DIR+"/"+filename, format=extension.upper())
os.chdir(INSTANCE_DIR)
call('find . -name "* *" -type f | rename ' "'s/ /-/g'", shell=True)
os.chdir(CAPTIONS_DIR)
call('find . -name "* *" -type f | rename ' "'s/ /-/g'", shell=True)
os.chdir('/notebooks')
if Resize_to_1024_and_keep_aspect_ratio and not Crop_images:
resize_keep_aspect(INSTANCE_DIR)
def caption(CAPTIONS_DIR, INSTANCE_DIR):
paths=""
out=""
widgets_l=""
clear_output()
def Caption(path):
if path!="Select an instance image to caption":
name = os.path.splitext(os.path.basename(path))[0]
ext=os.path.splitext(os.path.basename(path))[-1][1:]
if ext=="jpg" or "JPG":
ext="JPEG"
if os.path.exists(CAPTIONS_DIR+"/"+name + '.txt'):
with open(CAPTIONS_DIR+"/"+name + '.txt', 'r') as f:
text = f.read()
else:
with open(CAPTIONS_DIR+"/"+name + '.txt', 'w') as f:
f.write("")
with open(CAPTIONS_DIR+"/"+name + '.txt', 'r') as f:
text = f.read()
img=Image.open(os.path.join(INSTANCE_DIR,path))
img=img.convert("RGB")
img=img.resize((420, 420))
image_bytes = BytesIO()
img.save(image_bytes, format=ext, qualiy=10)
image_bytes.seek(0)
image_data = image_bytes.read()
img= image_data
image = widgets.Image(
value=img,
width=420,
height=420
)
text_area = widgets.Textarea(value=text, description='', disabled=False, layout={'width': '300px', 'height': '120px'})
def update_text(text):
with open(CAPTIONS_DIR+"/"+name + '.txt', 'w') as f:
f.write(text)
button = widgets.Button(description='Save', button_style='success')
button.on_click(lambda b: update_text(text_area.value))
return widgets.VBox([widgets.HBox([image, text_area, button])])
paths = os.listdir(INSTANCE_DIR)
widgets_l = widgets.Select(options=["Select an instance image to caption"]+paths, rows=25)
out = widgets.Output()
def click(change):
with out:
out.clear_output()
display(Caption(change.new))
widgets_l.observe(click, names='value')
display(widgets.HBox([widgets_l, out]))
def dbtrainxl(Unet_Training_Epochs, Text_Encoder_Training_Epochs, Unet_Learning_Rate, Text_Encoder_Learning_Rate, dim, Offset_Noise, Resolution, MODEL_NAME, SESSION_DIR, INSTANCE_DIR, CAPTIONS_DIR, External_Captions, INSTANCE_NAME, Session_Name, OUTPUT_DIR, ofstnselvl, Save_VRAM, Intermediary_Save_Epoch):
if os.path.exists(INSTANCE_DIR+"/.ipynb_checkpoints"):
call('rm -r '+INSTANCE_DIR+'/.ipynb_checkpoints', shell=True)
if os.path.exists(CAPTIONS_DIR+"/.ipynb_checkpoints"):
call('rm -r '+CAPTIONS_DIR+'/.ipynb_checkpoints', shell=True)
Seed=random.randint(1, 999999)
ofstnse=""
if Offset_Noise:
ofstnse="--offset_noise"
GC=''
if Save_VRAM:
GC='--gradient_checkpointing'
extrnlcptn=""
if External_Captions:
extrnlcptn="--external_captions"
precision="fp16"
def train_only_text(SESSION_DIR, MODEL_NAME, INSTANCE_DIR, OUTPUT_DIR, Seed, Resolution, ofstnse, extrnlcptn, precision, Training_Epochs):
print('[1;33mTraining the Text Encoder...[0m')
call('accelerate launch /notebooks/diffusers/examples/dreambooth/train_dreambooth_sdxl_TI.py \
'+ofstnse+' \
'+extrnlcptn+' \
--dim='+str(dim)+' \
--ofstnselvl='+str(ofstnselvl)+' \
--image_captions_filename \
--Session_dir='+SESSION_DIR+' \
--pretrained_model_name_or_path='+MODEL_NAME+' \
--instance_data_dir='+INSTANCE_DIR+' \
--output_dir='+OUTPUT_DIR+' \
--captions_dir='+CAPTIONS_DIR+' \
--seed='+str(Seed)+' \
--resolution='+str(Resolution)+' \
--mixed_precision='+str(precision)+' \
--train_batch_size=1 \
--gradient_accumulation_steps=1 '+GC+ ' \
--use_8bit_adam \
--learning_rate='+str(Text_Encoder_Learning_Rate)+' \
--lr_scheduler="cosine" \
--lr_warmup_steps=0 \
--num_train_epochs='+str(Training_Epochs), shell=True)
def train_only_unet(SESSION_DIR, MODEL_NAME, INSTANCE_DIR, OUTPUT_DIR, Seed, Resolution, ofstnse, extrnlcptn, precision, Training_Epochs):
print('[1;33mTraining the UNet...[0m')
call('accelerate launch /notebooks/diffusers/examples/dreambooth/train_dreambooth_sdxl_lora.py \
'+ofstnse+' \
'+extrnlcptn+' \
--saves='+Intermediary_Save_Epoch+' \
--dim='+str(dim)+' \
--ofstnselvl='+str(ofstnselvl)+' \
--image_captions_filename \
--Session_dir='+SESSION_DIR+' \
--pretrained_model_name_or_path='+MODEL_NAME+' \
--instance_data_dir='+INSTANCE_DIR+' \
--output_dir='+OUTPUT_DIR+' \
--captions_dir='+CAPTIONS_DIR+' \
--seed='+str(Seed)+' \
--resolution='+str(Resolution)+' \
--mixed_precision='+str(precision)+' \
--train_batch_size=1 \
--gradient_accumulation_steps=1 '+GC+ ' \
--use_8bit_adam \
--learning_rate='+str(Unet_Learning_Rate)+' \
--lr_scheduler="cosine" \
--lr_warmup_steps=0 \
--num_train_epochs='+str(Training_Epochs), shell=True)
if Unet_Training_Epochs!=0:
if Text_Encoder_Training_Epochs!=0:
train_only_text(SESSION_DIR, MODEL_NAME, INSTANCE_DIR, OUTPUT_DIR, Seed, Resolution, ofstnse, extrnlcptn, precision, Training_Epochs=Text_Encoder_Training_Epochs)
clear_output()
train_only_unet(SESSION_DIR, MODEL_NAME, INSTANCE_DIR, OUTPUT_DIR, Seed, Resolution, ofstnse, extrnlcptn, precision, Training_Epochs=Unet_Training_Epochs)
else :
print('[1;32mNothing to do')
if os.path.exists(SESSION_DIR+'/'+Session_Name+'.safetensors'):
clear_output()
print("[1;32mDONE, the LoRa model is in the session's folder")
else:
print("[1;31mSomething went wrong")
def sdcmf(MDLPTH):
from slugify import slugify
from huggingface_hub import HfApi, CommitOperationAdd, create_repo
os.chdir('/notebooks')
print('[1;33mInstalling/Updating the repo...')
if not os.path.exists('ComfyUI'):
call('git clone -q --depth 1 https://github.com/comfyanonymous/ComfyUI', shell=True)
os.chdir('ComfyUI')
call('git reset --hard', shell=True)
print('[1;32m')
call('git pull', shell=True)
if os.path.exists(MDLPTH):
call('ln -s '+os.path.dirname(MDLPTH)+' models/loras', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
clean_symlinks('models/loras')
if not os.path.exists('models/checkpoints/sd_xl_base_1.0.safetensors'):
call('ln -s /datasets/stable-diffusion-xl/sd_xl_base_1.0.safetensors models/checkpoints', shell=True)
localurl="https://tensorboard-"+os.environ.get('PAPERSPACE_FQDN')
call("sed -i 's@^ if verbose:@@' /notebooks/ComfyUI/server.py", shell=True)
call("sed -i 's@^ logging.info(\"To see the GUI go to: {}://{}:{}\".format(scheme, address_print, port))@ logging.info(\"[32m\u2714 Connected\");logging.info(\"[1;34m"+localurl+"[0m\")@' /notebooks/ComfyUI/server.py", shell=True)
os.chdir('/notebooks')
def test(MDLPTH, User, Password):
auth=f"--gradio-auth {User}:{Password}"
if User =="" or Password=="":
auth=""
os.chdir('/notebooks')
if not os.path.exists('/notebooks/sd/stablediffusion'):
call('wget -q -O sd_mrep.tar.zst https://huggingface.co/TheLastBen/dependencies/resolve/main/sd_mrep.tar.zst', shell=True)
call('tar --zstd -xf sd_mrep.tar.zst', shell=True)
call('rm sd_mrep.tar.zst', shell=True)
os.chdir('/notebooks/sd')
if not os.path.exists('stable-diffusion-webui'):
call('git clone -q --depth 1 --branch master https://github.com/AUTOMATIC1111/stable-diffusion-webui', shell=True)
os.chdir('/notebooks/sd/stable-diffusion-webui/')
call('git reset --hard', shell=True, stdout=open('/dev/null', 'w'))
print('[1;32m')
call('git checkout master', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
call('git pull', shell=True, stdout=open('/dev/null', 'w'))
os.makedirs('/notebooks/sd/stable-diffusion-webui/repositories', exist_ok=True)
call('git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui-assets /notebooks/sd/stable-diffusion-webui/repositories/stable-diffusion-webui-assets', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
clear_output()
if not os.path.exists('models/Stable-diffusion/sd_xl_base_1.0.safetensors'):
call('ln -s /datasets/stable-diffusion-xl/sd_xl_base_1.0.safetensors models/Stable-diffusion', shell=True)
if os.path.exists(MDLPTH):
call('ln -s '+os.path.dirname(MDLPTH)+' models/Lora', shell=True, stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
clean_symlinks('models/Lora')
call('wget -q -O /usr/local/lib/python3.11/dist-packages/gradio/blocks.py https://raw.githubusercontent.com/TheLastBen/fast-stable-diffusion/main/AUTOMATIC1111_files/blocks.py', shell=True)
localurl="tensorboard-"+os.environ.get('PAPERSPACE_FQDN')
for line in fileinput.input('/usr/local/lib/python3.11/dist-packages/gradio/blocks.py', inplace=True):
if line.strip().startswith('self.server_name ='):
line = f' self.server_name = "{localurl}"\n'
if line.strip().startswith('self.protocol = "https"'):
line = ' self.protocol = "https"\n'
if line.strip().startswith('if self.local_url.startswith("https") or self.is_colab'):
line = ''
if line.strip().startswith('else "http"'):
line = ''
sys.stdout.write(line)
os.chdir('/notebooks/sd/stable-diffusion-webui/modules')
call("sed -i 's@possible_sd_paths =.*@possible_sd_paths = [\"/notebooks/sd/stablediffusion\"]@' /notebooks/sd/stable-diffusion-webui/modules/paths.py", shell=True)
call("sed -i 's@\.\.\/@src/@g' /notebooks/sd/stable-diffusion-webui/modules/paths.py", shell=True)
call("sed -i 's@src\/generative-models@generative-models@g' /notebooks/sd/stable-diffusion-webui/modules/paths.py", shell=True)
os.chdir('/notebooks/sd/stable-diffusion-webui')
clear_output()
configf="--disable-console-progressbars --no-gradio-queue --upcast-sampling --no-hashing --no-half-vae --disable-safe-unpickle --api --no-download-sd-model --xformers --enable-insecure-extension-access --port 6006 --listen --skip-version-check --ckpt /notebooks/sd/stable-diffusion-webui/models/Stable-diffusion/sd_xl_base_1.0.safetensors "+auth
return configf
def clean():
Sessions=os.listdir("/notebooks/Fast-Dreambooth/Sessions")
s = widgets.Select(
options=Sessions,
rows=5,
description='',
disabled=False
)
out=widgets.Output()
d = widgets.Button(
description='Remove',
disabled=False,
button_style='warning',
tooltip='Removet the selected session',
icon='warning'
)
def rem(d):
with out:
if s.value is not None:
clear_output()
print("[1;33mTHE SESSION [1;31m"+s.value+" [1;33mHAS BEEN REMOVED FROM THE STORAGE")
call('rm -r /notebooks/Fast-Dreambooth/Sessions/'+s.value, shell=True)
if os.path.exists('/notebooks/models/'+s.value):
call('rm -r /notebooks/models/'+s.value, shell=True)
s.options=os.listdir("/notebooks/Fast-Dreambooth/Sessions")
else:
d.close()
s.close()
clear_output()
print("[1;32mNOTHING TO REMOVE")
d.on_click(rem)
if s.value is not None:
display(s,d,out)
else:
print("[1;32mNOTHING TO REMOVE")
def crop_image(im, size):
import cv2
GREEN = "#0F0"
BLUE = "#00F"
RED = "#F00"
def focal_point(im, settings):
corner_points = image_corner_points(im, settings) if settings.corner_points_weight > 0 else []
entropy_points = image_entropy_points(im, settings) if settings.entropy_points_weight > 0 else []
face_points = image_face_points(im, settings) if settings.face_points_weight > 0 else []
pois = []
weight_pref_total = 0
if len(corner_points) > 0:
weight_pref_total += settings.corner_points_weight
if len(entropy_points) > 0:
weight_pref_total += settings.entropy_points_weight
if len(face_points) > 0:
weight_pref_total += settings.face_points_weight
corner_centroid = None
if len(corner_points) > 0:
corner_centroid = centroid(corner_points)
corner_centroid.weight = settings.corner_points_weight / weight_pref_total
pois.append(corner_centroid)
entropy_centroid = None
if len(entropy_points) > 0:
entropy_centroid = centroid(entropy_points)
entropy_centroid.weight = settings.entropy_points_weight / weight_pref_total
pois.append(entropy_centroid)
face_centroid = None
if len(face_points) > 0:
face_centroid = centroid(face_points)
face_centroid.weight = settings.face_points_weight / weight_pref_total
pois.append(face_centroid)
average_point = poi_average(pois, settings)
return average_point
def image_face_points(im, settings):
np_im = np.array(im)
gray = cv2.cvtColor(np_im, cv2.COLOR_BGR2GRAY)
tries = [
[ f'{cv2.data.haarcascades}haarcascade_eye.xml', 0.01 ],
[ f'{cv2.data.haarcascades}haarcascade_frontalface_default.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_profileface.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_frontalface_alt.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_frontalface_alt2.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_frontalface_alt_tree.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_eye_tree_eyeglasses.xml', 0.05 ],
[ f'{cv2.data.haarcascades}haarcascade_upperbody.xml', 0.05 ]
]
for t in tries:
classifier = cv2.CascadeClassifier(t[0])
minsize = int(min(im.width, im.height) * t[1]) # at least N percent of the smallest side
try:
faces = classifier.detectMultiScale(gray, scaleFactor=1.1,
minNeighbors=7, minSize=(minsize, minsize), flags=cv2.CASCADE_SCALE_IMAGE)
except:
continue
if len(faces) > 0:
rects = [[f[0], f[1], f[0] + f[2], f[1] + f[3]] for f in faces]
return [PointOfInterest((r[0] +r[2]) // 2, (r[1] + r[3]) // 2, size=abs(r[0]-r[2]), weight=1/len(rects)) for r in rects]
return []
def image_corner_points(im, settings):
grayscale = im.convert("L")
# naive attempt at preventing focal points from collecting at watermarks near the bottom
gd = ImageDraw.Draw(grayscale)
gd.rectangle([0, im.height*.9, im.width, im.height], fill="#999")
np_im = np.array(grayscale)
points = cv2.goodFeaturesToTrack(
np_im,
maxCorners=100,
qualityLevel=0.04,
minDistance=min(grayscale.width, grayscale.height)*0.06,
useHarrisDetector=False,
)
if points is None:
return []
focal_points = []
for point in points:
x, y = point.ravel()
focal_points.append(PointOfInterest(x, y, size=4, weight=1/len(points)))
return focal_points
def image_entropy_points(im, settings):
landscape = im.height < im.width
portrait = im.height > im.width
if landscape:
move_idx = [0, 2]
move_max = im.size[0]
elif portrait:
move_idx = [1, 3]
move_max = im.size[1]
else:
return []
e_max = 0
crop_current = [0, 0, settings.crop_width, settings.crop_height]
crop_best = crop_current
while crop_current[move_idx[1]] < move_max:
crop = im.crop(tuple(crop_current))
e = image_entropy(crop)
if (e > e_max):
e_max = e
crop_best = list(crop_current)
crop_current[move_idx[0]] += 4
crop_current[move_idx[1]] += 4
x_mid = int(crop_best[0] + settings.crop_width/2)
y_mid = int(crop_best[1] + settings.crop_height/2)
return [PointOfInterest(x_mid, y_mid, size=25, weight=1.0)]
def image_entropy(im):
# greyscale image entropy
# band = np.asarray(im.convert("L"))
band = np.asarray(im.convert("1"), dtype=np.uint8)
hist, _ = np.histogram(band, bins=range(0, 256))
hist = hist[hist > 0]
return -np.log2(hist / hist.sum()).sum()
def centroid(pois):
x = [poi.x for poi in pois]
y = [poi.y for poi in pois]
return PointOfInterest(sum(x)/len(pois), sum(y)/len(pois))
def poi_average(pois, settings):
weight = 0.0
x = 0.0
y = 0.0
for poi in pois:
weight += poi.weight
x += poi.x * poi.weight
y += poi.y * poi.weight
avg_x = round(weight and x / weight)
avg_y = round(weight and y / weight)
return PointOfInterest(avg_x, avg_y)
def is_landscape(w, h):
return w > h
def is_portrait(w, h):
return h > w
def is_square(w, h):
return w == h
class PointOfInterest:
def __init__(self, x, y, weight=1.0, size=10):
self.x = x
self.y = y
self.weight = weight
self.size = size
def bounding(self, size):
return [
self.x - size//2,
self.y - size//2,
self.x + size//2,
self.y + size//2
]
class Settings:
def __init__(self, crop_width=512, crop_height=512, corner_points_weight=0.5, entropy_points_weight=0.5, face_points_weight=0.5):
self.crop_width = crop_width
self.crop_height = crop_height
self.corner_points_weight = corner_points_weight
self.entropy_points_weight = entropy_points_weight
self.face_points_weight = face_points_weight
settings = Settings(
crop_width = size,
crop_height = size,
face_points_weight = 0.9,
entropy_points_weight = 0.15,
corner_points_weight = 0.5,
)
scale_by = 1
if is_landscape(im.width, im.height):
scale_by = settings.crop_height / im.height
elif is_portrait(im.width, im.height):
scale_by = settings.crop_width / im.width
elif is_square(im.width, im.height):
if is_square(settings.crop_width, settings.crop_height):
scale_by = settings.crop_width / im.width
elif is_landscape(settings.crop_width, settings.crop_height):
scale_by = settings.crop_width / im.width
elif is_portrait(settings.crop_width, settings.crop_height):
scale_by = settings.crop_height / im.height
im = im.resize((int(im.width * scale_by), int(im.height * scale_by)))
im_debug = im.copy()
focus = focal_point(im_debug, settings)
# take the focal point and turn it into crop coordinates that try to center over the focal
# point but then get adjusted back into the frame
y_half = int(settings.crop_height / 2)
x_half = int(settings.crop_width / 2)
x1 = focus.x - x_half
if x1 < 0:
x1 = 0
elif x1 + settings.crop_width > im.width:
x1 = im.width - settings.crop_width
y1 = focus.y - y_half
if y1 < 0:
y1 = 0
elif y1 + settings.crop_height > im.height:
y1 = im.height - settings.crop_height
x2 = x1 + settings.crop_width
y2 = y1 + settings.crop_height
crop = [x1, y1, x2, y2]
results = []
results.append(im.crop(tuple(crop)))
return results
def resize_keep_aspect(DIR):
min_dimension=1024
for filename in os.listdir(DIR):
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.webp')):
image = cv2.imread(os.path.join(DIR, filename))
org_height, org_width = image.shape[0], image.shape[1]
if org_width < org_height:
new_width = min_dimension
new_height = int(org_height * (min_dimension / org_width))
else:
new_height = min_dimension
new_width = int(org_width * (min_dimension / org_height))
resized_image = cv2.resize(image, (new_width, new_height), interpolation=cv2.INTER_LANCZOS4)
cv2.imwrite(os.path.join(DIR, filename), resized_image, [int(cv2.IMWRITE_PNG_COMPRESSION), 0])
def clean_symlinks(path):
for item in os.listdir(path):
lnk = os.path.join(path, item)
if os.path.islink(lnk) and not os.path.exists(os.readlink(lnk)):
os.remove(lnk).gitattributes+54-59
Notebooks.txtAdded+5
Notebooks/PPS-A1111.ipynbAdded+184
Notebooks/PPS-Dreambooth-v1.ipynbAdded+400
Notebooks/PPS-Dreambooth-v2.ipynbAdded+409
README.md+1-1
Scripts/mainpaperspaceA1111.pyAdded+478
Scripts/mainpaperspaceA1111_311.pyAdded+471
Scripts/mainpaperspacev1.pyAdded+1337
Scripts/mainpaperspacev1_311.pyAdded+1330
Scripts/mainpaperspacev2.pyAdded+1354
Scripts/mainpaperspacev2_311.pyAdded+1347
Scripts/mainppsComfy.pyAdded+415
Scripts/mainppsComfy_311.pyAdded+415
Scripts/sdxllorapps.pyAdded+1152
Scripts/sdxllorapps_311.pyAdded+1147