Update utils.py
Browse files
utils.py
CHANGED
|
@@ -1,270 +1,269 @@
|
|
| 1 |
-
|
| 2 |
-
import
|
| 3 |
-
import
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
from
|
| 13 |
-
from
|
| 14 |
-
from
|
| 15 |
-
from
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
os.
|
| 25 |
-
os.
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
url =
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
parameters
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
parameters
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
steps_match
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
size_match
|
| 92 |
-
|
| 93 |
-
parameters['Size']
|
| 94 |
-
|
| 95 |
-
parameters['
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
new_lora_model_list
|
| 111 |
-
new_lora_model_list
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
<
|
| 131 |
-
|
| 132 |
-
<
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
api
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
import
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
#
|
| 239 |
-
#
|
| 240 |
-
#
|
| 241 |
-
#
|
| 242 |
-
#
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
<div style="width:
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
<div style="width:
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
"""
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from constants import (
|
| 5 |
+
DIFFUSERS_FORMAT_LORAS,
|
| 6 |
+
CIVITAI_API_KEY,
|
| 7 |
+
HF_TOKEN,
|
| 8 |
+
MODEL_TYPE_CLASS,
|
| 9 |
+
DIRECTORY_LORAS,
|
| 10 |
+
)
|
| 11 |
+
from huggingface_hub import HfApi
|
| 12 |
+
from diffusers import DiffusionPipeline
|
| 13 |
+
from huggingface_hub import model_info as model_info_data
|
| 14 |
+
from diffusers.pipelines.pipeline_loading_utils import variant_compatible_siblings
|
| 15 |
+
from pathlib import PosixPath
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def download_things(directory, url, hf_token="", civitai_api_key=""):
|
| 19 |
+
url = url.strip()
|
| 20 |
+
|
| 21 |
+
if "drive.google.com" in url:
|
| 22 |
+
original_dir = os.getcwd()
|
| 23 |
+
os.chdir(directory)
|
| 24 |
+
os.system(f"gdown --fuzzy {url}")
|
| 25 |
+
os.chdir(original_dir)
|
| 26 |
+
elif "huggingface.co" in url:
|
| 27 |
+
url = url.replace("?download=true", "")
|
| 28 |
+
# url = urllib.parse.quote(url, safe=':/') # fix encoding
|
| 29 |
+
if "/blob/" in url:
|
| 30 |
+
url = url.replace("/blob/", "/resolve/")
|
| 31 |
+
user_header = f'"Authorization: Bearer {hf_token}"'
|
| 32 |
+
if hf_token:
|
| 33 |
+
os.system(f"aria2c --console-log-level=error --summary-interval=10 --header={user_header} -c -x 16 -k 1M -s 16 {url} -d {directory} -o {url.split('/')[-1]}")
|
| 34 |
+
else:
|
| 35 |
+
os.system(f"aria2c --optimize-concurrent-downloads --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 {url} -d {directory} -o {url.split('/')[-1]}")
|
| 36 |
+
elif "civitai.com" in url:
|
| 37 |
+
if "?" in url:
|
| 38 |
+
url = url.split("?")[0]
|
| 39 |
+
if civitai_api_key:
|
| 40 |
+
url = url + f"?token={civitai_api_key}"
|
| 41 |
+
os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
|
| 42 |
+
else:
|
| 43 |
+
print("\033[91mYou need an API key to download Civitai models.\033[0m")
|
| 44 |
+
else:
|
| 45 |
+
os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def get_model_list(directory_path):
|
| 49 |
+
model_list = []
|
| 50 |
+
valid_extensions = {'.ckpt', '.pt', '.pth', '.safetensors', '.bin'}
|
| 51 |
+
|
| 52 |
+
for filename in os.listdir(directory_path):
|
| 53 |
+
if os.path.splitext(filename)[1] in valid_extensions:
|
| 54 |
+
# name_without_extension = os.path.splitext(filename)[0]
|
| 55 |
+
file_path = os.path.join(directory_path, filename)
|
| 56 |
+
# model_list.append((name_without_extension, file_path))
|
| 57 |
+
model_list.append(file_path)
|
| 58 |
+
print('\033[34mFILE: ' + file_path + '\033[0m')
|
| 59 |
+
return model_list
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def extract_parameters(input_string):
|
| 63 |
+
parameters = {}
|
| 64 |
+
input_string = input_string.replace("\n", "")
|
| 65 |
+
|
| 66 |
+
if "Negative prompt:" not in input_string:
|
| 67 |
+
if "Steps:" in input_string:
|
| 68 |
+
input_string = input_string.replace("Steps:", "Negative prompt: Steps:")
|
| 69 |
+
else:
|
| 70 |
+
print("Invalid metadata")
|
| 71 |
+
parameters["prompt"] = input_string
|
| 72 |
+
return parameters
|
| 73 |
+
|
| 74 |
+
parm = input_string.split("Negative prompt:")
|
| 75 |
+
parameters["prompt"] = parm[0].strip()
|
| 76 |
+
if "Steps:" not in parm[1]:
|
| 77 |
+
print("Steps not detected")
|
| 78 |
+
parameters["neg_prompt"] = parm[1].strip()
|
| 79 |
+
return parameters
|
| 80 |
+
parm = parm[1].split("Steps:")
|
| 81 |
+
parameters["neg_prompt"] = parm[0].strip()
|
| 82 |
+
input_string = "Steps:" + parm[1]
|
| 83 |
+
|
| 84 |
+
# Extracting Steps
|
| 85 |
+
steps_match = re.search(r'Steps: (\d+)', input_string)
|
| 86 |
+
if steps_match:
|
| 87 |
+
parameters['Steps'] = int(steps_match.group(1))
|
| 88 |
+
|
| 89 |
+
# Extracting Size
|
| 90 |
+
size_match = re.search(r'Size: (\d+x\d+)', input_string)
|
| 91 |
+
if size_match:
|
| 92 |
+
parameters['Size'] = size_match.group(1)
|
| 93 |
+
width, height = map(int, parameters['Size'].split('x'))
|
| 94 |
+
parameters['width'] = width
|
| 95 |
+
parameters['height'] = height
|
| 96 |
+
|
| 97 |
+
# Extracting other parameters
|
| 98 |
+
other_parameters = re.findall(r'(\w+): (.*?)(?=, \w+|$)', input_string)
|
| 99 |
+
for param in other_parameters:
|
| 100 |
+
parameters[param[0]] = param[1].strip('"')
|
| 101 |
+
|
| 102 |
+
return parameters
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def get_my_lora(link_url):
|
| 106 |
+
for url in [url.strip() for url in link_url.split(',')]:
|
| 107 |
+
if not os.path.exists(f"./loras/{url.split('/')[-1]}"):
|
| 108 |
+
download_things(DIRECTORY_LORAS, url, HF_TOKEN, CIVITAI_API_KEY)
|
| 109 |
+
new_lora_model_list = get_model_list(DIRECTORY_LORAS)
|
| 110 |
+
new_lora_model_list.insert(0, "None")
|
| 111 |
+
new_lora_model_list = new_lora_model_list + DIFFUSERS_FORMAT_LORAS
|
| 112 |
+
|
| 113 |
+
return gr.update(
|
| 114 |
+
choices=new_lora_model_list
|
| 115 |
+
), gr.update(
|
| 116 |
+
choices=new_lora_model_list
|
| 117 |
+
), gr.update(
|
| 118 |
+
choices=new_lora_model_list
|
| 119 |
+
), gr.update(
|
| 120 |
+
choices=new_lora_model_list
|
| 121 |
+
), gr.update(
|
| 122 |
+
choices=new_lora_model_list
|
| 123 |
+
),
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def info_html(json_data, title, subtitle):
|
| 127 |
+
return f"""
|
| 128 |
+
<div style='padding: 0; border-radius: 10px;'>
|
| 129 |
+
<p style='margin: 0; font-weight: bold;'>{title}</p>
|
| 130 |
+
<details>
|
| 131 |
+
<summary>Details</summary>
|
| 132 |
+
<p style='margin: 0; font-weight: bold;'>{subtitle}</p>
|
| 133 |
+
</details>
|
| 134 |
+
</div>
|
| 135 |
+
"""
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def get_model_type(repo_id: str):
|
| 139 |
+
api = HfApi(token=os.environ.get("HF_TOKEN")) # if use private or gated model
|
| 140 |
+
default = "SD 1.5"
|
| 141 |
+
try:
|
| 142 |
+
model = api.model_info(repo_id=repo_id, timeout=5.0)
|
| 143 |
+
tags = model.tags
|
| 144 |
+
for tag in tags:
|
| 145 |
+
if tag in MODEL_TYPE_CLASS.keys(): return MODEL_TYPE_CLASS.get(tag, default)
|
| 146 |
+
except Exception:
|
| 147 |
+
return default
|
| 148 |
+
return default
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def restart_space(repo_id: str, factory_reboot: bool, token: str):
|
| 152 |
+
api = HfApi(token=token)
|
| 153 |
+
api.restart_space(repo_id=repo_id, factory_reboot=factory_reboot)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def extract_exif_data(image):
|
| 157 |
+
if image is None: return ""
|
| 158 |
+
|
| 159 |
+
try:
|
| 160 |
+
metadata_keys = ['parameters', 'metadata', 'prompt', 'Comment']
|
| 161 |
+
|
| 162 |
+
for key in metadata_keys:
|
| 163 |
+
if key in image.info:
|
| 164 |
+
return image.info[key]
|
| 165 |
+
|
| 166 |
+
return str(image.info)
|
| 167 |
+
|
| 168 |
+
except Exception as e:
|
| 169 |
+
return f"Error extracting metadata: {str(e)}"
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def create_mask_now(img, invert):
|
| 173 |
+
import numpy as np
|
| 174 |
+
import time
|
| 175 |
+
|
| 176 |
+
time.sleep(0.5)
|
| 177 |
+
|
| 178 |
+
transparent_image = img["layers"][0]
|
| 179 |
+
|
| 180 |
+
# Extract the alpha channel
|
| 181 |
+
alpha_channel = np.array(transparent_image)[:, :, 3]
|
| 182 |
+
|
| 183 |
+
# Create a binary mask by thresholding the alpha channel
|
| 184 |
+
binary_mask = alpha_channel > 1
|
| 185 |
+
|
| 186 |
+
if invert:
|
| 187 |
+
print("Invert")
|
| 188 |
+
# Invert the binary mask so that the drawn shape is white and the rest is black
|
| 189 |
+
binary_mask = np.invert(binary_mask)
|
| 190 |
+
|
| 191 |
+
# Convert the binary mask to a 3-channel RGB mask
|
| 192 |
+
rgb_mask = np.stack((binary_mask,) * 3, axis=-1)
|
| 193 |
+
|
| 194 |
+
# Convert the mask to uint8
|
| 195 |
+
rgb_mask = rgb_mask.astype(np.uint8) * 255
|
| 196 |
+
|
| 197 |
+
return img["background"], rgb_mask
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def download_diffuser_repo(repo_name: str, model_type: str, revision: str = "main", token=True):
|
| 201 |
+
|
| 202 |
+
variant = None
|
| 203 |
+
if token is True and not os.environ.get("HF_TOKEN"):
|
| 204 |
+
token = None
|
| 205 |
+
|
| 206 |
+
if model_type == "SDXL":
|
| 207 |
+
info = model_info_data(
|
| 208 |
+
repo_name,
|
| 209 |
+
token=token,
|
| 210 |
+
revision=revision,
|
| 211 |
+
timeout=5.0,
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
filenames = {sibling.rfilename for sibling in info.siblings}
|
| 215 |
+
model_filenames, variant_filenames = variant_compatible_siblings(
|
| 216 |
+
filenames, variant="fp16"
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
if len(variant_filenames):
|
| 220 |
+
variant = "fp16"
|
| 221 |
+
|
| 222 |
+
cached_folder = DiffusionPipeline.download(
|
| 223 |
+
pretrained_model_name=repo_name,
|
| 224 |
+
force_download=False,
|
| 225 |
+
token=token,
|
| 226 |
+
revision=revision,
|
| 227 |
+
# mirror="https://hf-mirror.com",
|
| 228 |
+
variant=variant,
|
| 229 |
+
use_safetensors=True,
|
| 230 |
+
trust_remote_code=False,
|
| 231 |
+
timeout=5.0,
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
if isinstance(cached_folder, PosixPath):
|
| 235 |
+
cached_folder = cached_folder.as_posix()
|
| 236 |
+
|
| 237 |
+
# Task model
|
| 238 |
+
# from huggingface_hub import hf_hub_download
|
| 239 |
+
# hf_hub_download(
|
| 240 |
+
# task_model,
|
| 241 |
+
# filename="diffusion_pytorch_model.safetensors", # fix fp16 variant
|
| 242 |
+
# )
|
| 243 |
+
|
| 244 |
+
return cached_folder
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def progress_step_bar(step, total):
|
| 248 |
+
# Calculate the percentage for the progress bar width
|
| 249 |
+
percentage = min(100, ((step / total) * 100))
|
| 250 |
+
|
| 251 |
+
return f"""
|
| 252 |
+
<div style="position: relative; width: 100%; background-color: gray; border-radius: 5px; overflow: hidden;">
|
| 253 |
+
<div style="width: {percentage}%; height: 17px; background-color: #800080; transition: width 0.5s;"></div>
|
| 254 |
+
<div style="position: absolute; width: 100%; text-align: center; color: white; top: 0; line-height: 19px; font-size: 13px;">
|
| 255 |
+
{int(percentage)}%
|
| 256 |
+
</div>
|
| 257 |
+
</div>
|
| 258 |
+
"""
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def html_template_message(msg):
|
| 262 |
+
return f"""
|
| 263 |
+
<div style="position: relative; width: 100%; background-color: gray; border-radius: 5px; overflow: hidden;">
|
| 264 |
+
<div style="width: 0%; height: 17px; background-color: #800080; transition: width 0.5s;"></div>
|
| 265 |
+
<div style="position: absolute; width: 100%; text-align: center; color: white; top: 0; line-height: 19px; font-size: 14px; font-weight: bold; text-shadow: 1px 1px 2px black;">
|
| 266 |
+
{msg}
|
| 267 |
+
</div>
|
| 268 |
+
</div>
|
| 269 |
+
"""
|
|
|