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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
import os
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from huggingface_hub import update_repo_visibility, whoami, upload_folder, create_repo, upload_file, update_repo_visibility
|
| 5 |
+
from slugify import slugify
|
| 6 |
+
import gradio as gr
|
| 7 |
+
import re
|
| 8 |
+
import uuid
|
| 9 |
+
from typing import Optional
|
| 10 |
+
import json
|
| 11 |
+
from bs4 import BeautifulSoup
|
| 12 |
+
|
| 13 |
+
TRUSTED_UPLOADERS = ["KappaNeuro", "CiroN2022", "multimodalart", "Norod78", "joachimsallstrom", "blink7630", "e-n-v-y", "DoctorDiffusion", "RalFinger", "artificialguybr", "nevreal"]
|
| 14 |
+
|
| 15 |
+
def get_json_data(url):
|
| 16 |
+
url_split = url.split('/')
|
| 17 |
+
api_url = f"https://civitai.com/api/v1/models/{url_split[4]}"
|
| 18 |
+
try:
|
| 19 |
+
response = requests.get(api_url)
|
| 20 |
+
response.raise_for_status()
|
| 21 |
+
return response.json()
|
| 22 |
+
except requests.exceptions.RequestException as e:
|
| 23 |
+
print(f"Error fetching JSON data: {e}")
|
| 24 |
+
return None
|
| 25 |
+
|
| 26 |
+
def check_nsfw(json_data, profile):
|
| 27 |
+
if json_data["nsfw"]:
|
| 28 |
+
return False
|
| 29 |
+
print(profile)
|
| 30 |
+
if(profile.username in TRUSTED_UPLOADERS):
|
| 31 |
+
return True
|
| 32 |
+
for model_version in json_data["modelVersions"]:
|
| 33 |
+
for image in model_version["images"]:
|
| 34 |
+
if image["nsfwLevel"] > 5:
|
| 35 |
+
return False
|
| 36 |
+
return True
|
| 37 |
+
|
| 38 |
+
def get_prompts_from_image(image_id):
|
| 39 |
+
url = f'https://civitai.com/api/trpc/image.getGenerationData?input={{"json":{{"id":{image_id}}}}}'
|
| 40 |
+
response = requests.get(url)
|
| 41 |
+
prompt = ""
|
| 42 |
+
negative_prompt = ""
|
| 43 |
+
if response.status_code == 200:
|
| 44 |
+
data = response.json()
|
| 45 |
+
result = data['result']['data']['json']
|
| 46 |
+
if "prompt" in result['meta']:
|
| 47 |
+
prompt = result['meta']['prompt']
|
| 48 |
+
if "negativePrompt" in result['meta']:
|
| 49 |
+
negative_prompt = result["meta"]["negativePrompt"]
|
| 50 |
+
|
| 51 |
+
return prompt, negative_prompt
|
| 52 |
+
|
| 53 |
+
def extract_info(json_data):
|
| 54 |
+
if json_data["type"] == "LORA":
|
| 55 |
+
for model_version in json_data["modelVersions"]:
|
| 56 |
+
if model_version["baseModel"] in ["SDXL 1.0", "SDXL 0.9", "SD 1.5", "SD 1.4", "SD 2.1", "SD 2.0", "SD 2.0 768", "SD 2.1 768", "SD 3", "Flux.1 D", "Flux.1 S"]:
|
| 57 |
+
for file in model_version["files"]:
|
| 58 |
+
print(file)
|
| 59 |
+
if "primary" in file:
|
| 60 |
+
# Start by adding the primary file to the list
|
| 61 |
+
urls_to_download = [{"url": file["downloadUrl"], "filename": file["name"], "type": "weightName"}]
|
| 62 |
+
|
| 63 |
+
# Then append all image URLs to the list
|
| 64 |
+
for image in model_version["images"]:
|
| 65 |
+
image_id = image["url"].split("/")[-1].split(".")[0]
|
| 66 |
+
prompt, negative_prompt = get_prompts_from_image(image_id)
|
| 67 |
+
urls_to_download.append({
|
| 68 |
+
"url": image["url"],
|
| 69 |
+
"filename": os.path.basename(image["url"]),
|
| 70 |
+
"type": "imageName",
|
| 71 |
+
"prompt": prompt, #if "meta" in image and "prompt" in image["meta"] else ""
|
| 72 |
+
"negative_prompt": negative_prompt
|
| 73 |
+
})
|
| 74 |
+
model_mapping = {
|
| 75 |
+
"SDXL 1.0": "stabilityai/stable-diffusion-xl-base-1.0",
|
| 76 |
+
"SDXL 0.9": "stabilityai/stable-diffusion-xl-base-1.0",
|
| 77 |
+
"SD 1.5": "runwayml/stable-diffusion-v1-5",
|
| 78 |
+
"SD 1.4": "CompVis/stable-diffusion-v1-4",
|
| 79 |
+
"SD 2.1": "stabilityai/stable-diffusion-2-1-base",
|
| 80 |
+
"SD 2.0": "stabilityai/stable-diffusion-2-base",
|
| 81 |
+
"SD 2.1 768": "stabilityai/stable-diffusion-2-1",
|
| 82 |
+
"SD 2.0 768": "stabilityai/stable-diffusion-2",
|
| 83 |
+
"SD 3": "stabilityai/stable-diffusion-3-medium-diffusers",
|
| 84 |
+
"Flux.1 D": "black-forest-labs/FLUX.1-dev",
|
| 85 |
+
"Flux.1 S": "black-forest-labs/FLUX.1-schnell"
|
| 86 |
+
}
|
| 87 |
+
base_model = model_mapping[model_version["baseModel"]]
|
| 88 |
+
info = {
|
| 89 |
+
"urls_to_download": urls_to_download,
|
| 90 |
+
"id": model_version["id"],
|
| 91 |
+
"baseModel": base_model,
|
| 92 |
+
"modelId": model_version.get("modelId", ""),
|
| 93 |
+
"name": json_data["name"],
|
| 94 |
+
"description": json_data["description"],
|
| 95 |
+
"trainedWords": model_version["trainedWords"] if "trainedWords" in model_version else [],
|
| 96 |
+
"creator": json_data["creator"]["username"],
|
| 97 |
+
"tags": json_data["tags"],
|
| 98 |
+
"allowNoCredit": json_data["allowNoCredit"],
|
| 99 |
+
"allowCommercialUse": json_data["allowCommercialUse"],
|
| 100 |
+
"allowDerivatives": json_data["allowDerivatives"],
|
| 101 |
+
"allowDifferentLicense": json_data["allowDifferentLicense"]
|
| 102 |
+
}
|
| 103 |
+
return info
|
| 104 |
+
return None
|
| 105 |
+
|
| 106 |
+
def download_files(info, folder="."):
|
| 107 |
+
downloaded_files = {
|
| 108 |
+
"imageName": [],
|
| 109 |
+
"imagePrompt": [],
|
| 110 |
+
"imageNegativePrompt": [],
|
| 111 |
+
"weightName": []
|
| 112 |
+
}
|
| 113 |
+
for item in info["urls_to_download"]:
|
| 114 |
+
download_file(item["url"], item["filename"], folder)
|
| 115 |
+
downloaded_files[item["type"]].append(item["filename"])
|
| 116 |
+
if(item["type"] == "imageName"):
|
| 117 |
+
prompt_clean = re.sub(r'<.*?>', '', item["prompt"])
|
| 118 |
+
negative_prompt_clean = re.sub(r'<.*?>', '', item["negative_prompt"])
|
| 119 |
+
downloaded_files["imagePrompt"].append(prompt_clean)
|
| 120 |
+
downloaded_files["imageNegativePrompt"].append(negative_prompt_clean)
|
| 121 |
+
return downloaded_files
|
| 122 |
+
|
| 123 |
+
def download_file(url, filename, folder="."):
|
| 124 |
+
headers = {}
|
| 125 |
+
try:
|
| 126 |
+
response = requests.get(url, headers=headers)
|
| 127 |
+
response.raise_for_status()
|
| 128 |
+
except requests.exceptions.HTTPError as e:
|
| 129 |
+
print(e)
|
| 130 |
+
if response.status_code == 401:
|
| 131 |
+
headers['Authorization'] = f'Bearer {os.environ["CIVITAI_API"]}'
|
| 132 |
+
try:
|
| 133 |
+
response = requests.get(url, headers=headers)
|
| 134 |
+
response.raise_for_status()
|
| 135 |
+
except requests.exceptions.RequestException as e:
|
| 136 |
+
raise gr.Error(f"Error downloading file: {e}")
|
| 137 |
+
else:
|
| 138 |
+
raise gr.Error(f"Error downloading file: {e}")
|
| 139 |
+
except requests.exceptions.RequestException as e:
|
| 140 |
+
raise gr.Error(f"Error downloading file: {e}")
|
| 141 |
+
|
| 142 |
+
with open(f"{folder}/{filename}", 'wb') as f:
|
| 143 |
+
f.write(response.content)
|
| 144 |
+
|
| 145 |
+
def process_url(url, profile, do_download=True, folder="."):
|
| 146 |
+
json_data = get_json_data(url)
|
| 147 |
+
if json_data:
|
| 148 |
+
if check_nsfw(json_data, profile):
|
| 149 |
+
info = extract_info(json_data)
|
| 150 |
+
if info:
|
| 151 |
+
if(do_download):
|
| 152 |
+
downloaded_files = download_files(info, folder)
|
| 153 |
+
else:
|
| 154 |
+
downloaded_files = []
|
| 155 |
+
return info, downloaded_files
|
| 156 |
+
else:
|
| 157 |
+
raise gr.Error("Only SDXL LoRAs are supported for now")
|
| 158 |
+
else:
|
| 159 |
+
raise gr.Error("This model has content tagged as unsafe by CivitAI")
|
| 160 |
+
else:
|
| 161 |
+
raise gr.Error("Something went wrong in fetching CivitAI API")
|
| 162 |
+
|
| 163 |
+
def create_readme(info, downloaded_files, user_repo_id, link_civit=False, is_author=True, folder="."):
|
| 164 |
+
readme_content = ""
|
| 165 |
+
original_url = f"https://civitai.com/models/{info['modelId']}"
|
| 166 |
+
link_civit_disclaimer = f'([CivitAI]({original_url}))'
|
| 167 |
+
non_author_disclaimer = f'This model was originally uploaded on [CivitAI]({original_url}), by [{info["creator"]}](https://civitai.com/user/{info["creator"]}/models). The information below was provided by the author on CivitAI:'
|
| 168 |
+
default_tags = ["text-to-image", "stable-diffusion", "lora", "diffusers", "template:sd-lora", "migrated"]
|
| 169 |
+
civit_tags = [t.replace(":", "") for t in info["tags"] if t not in default_tags]
|
| 170 |
+
tags = default_tags + civit_tags
|
| 171 |
+
unpacked_tags = "\n- ".join(tags)
|
| 172 |
+
|
| 173 |
+
trained_words = info['trainedWords'] if 'trainedWords' in info and info['trainedWords'] else []
|
| 174 |
+
formatted_words = ', '.join(f'`{word}`' for word in trained_words)
|
| 175 |
+
if formatted_words:
|
| 176 |
+
trigger_words_section = f"""## Trigger words
|
| 177 |
+
You should use {formatted_words} to trigger the image generation.
|
| 178 |
+
"""
|
| 179 |
+
else:
|
| 180 |
+
trigger_words_section = ""
|
| 181 |
+
|
| 182 |
+
widget_content = ""
|
| 183 |
+
for index, (prompt, negative_prompt, image) in enumerate(zip(downloaded_files["imagePrompt"], downloaded_files["imageNegativePrompt"], downloaded_files["imageName"])):
|
| 184 |
+
escaped_prompt = prompt.replace("'", "''")
|
| 185 |
+
negative_prompt_content = f"""parameters:
|
| 186 |
+
negative_prompt: {negative_prompt}
|
| 187 |
+
""" if negative_prompt else ""
|
| 188 |
+
widget_content += f"""- text: '{escaped_prompt if escaped_prompt else ' ' }'
|
| 189 |
+
{negative_prompt_content}
|
| 190 |
+
output:
|
| 191 |
+
url: >-
|
| 192 |
+
{image}
|
| 193 |
+
"""
|
| 194 |
+
dtype = "torch.bfloat16" if info["baseModel"] == "black-forest-labs/FLUX.1-dev" or info["baseModel"] == "black-forest-labs/FLUX.1-schnell" else "torch.float16"
|
| 195 |
+
|
| 196 |
+
content = f"""---
|
| 197 |
+
license: other
|
| 198 |
+
license_name: bespoke-lora-trained-license
|
| 199 |
+
license_link: https://multimodal.art/civitai-licenses?allowNoCredit={info["allowNoCredit"]}&allowCommercialUse={info["allowCommercialUse"][0] if info["allowCommercialUse"] else 1}&allowDerivatives={info["allowDerivatives"]}&allowDifferentLicense={info["allowDifferentLicense"]}
|
| 200 |
+
tags:
|
| 201 |
+
- {unpacked_tags}
|
| 202 |
+
|
| 203 |
+
base_model: {info["baseModel"]}
|
| 204 |
+
instance_prompt: {info['trainedWords'][0] if 'trainedWords' in info and len(info['trainedWords']) > 0 else ''}
|
| 205 |
+
widget:
|
| 206 |
+
{widget_content}
|
| 207 |
+
---
|
| 208 |
+
|
| 209 |
+
# {info["name"]}
|
| 210 |
+
|
| 211 |
+
<Gallery />
|
| 212 |
+
|
| 213 |
+
{non_author_disclaimer if not is_author else ''}
|
| 214 |
+
|
| 215 |
+
{link_civit_disclaimer if link_civit else ''}
|
| 216 |
+
|
| 217 |
+
## Model description
|
| 218 |
+
|
| 219 |
+
{info["description"]}
|
| 220 |
+
|
| 221 |
+
{trigger_words_section}
|
| 222 |
+
|
| 223 |
+
## Download model
|
| 224 |
+
|
| 225 |
+
Weights for this model are available in Safetensors format.
|
| 226 |
+
|
| 227 |
+
[Download](/{user_repo_id}/tree/main) them in the Files & versions tab.
|
| 228 |
+
|
| 229 |
+
## Use it with the [🧨 diffusers library](https://github.com/huggingface/diffusers)
|
| 230 |
+
|
| 231 |
+
```py
|
| 232 |
+
from diffusers import AutoPipelineForText2Image
|
| 233 |
+
import torch
|
| 234 |
+
|
| 235 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 236 |
+
|
| 237 |
+
pipeline = AutoPipelineForText2Image.from_pretrained('{info["baseModel"]}', torch_dtype={dtype}).to(device)
|
| 238 |
+
pipeline.load_lora_weights('{user_repo_id}', weight_name='{downloaded_files["weightName"][0]}')
|
| 239 |
+
image = pipeline('{prompt if prompt else (formatted_words if formatted_words else 'Your custom prompt')}').images[0]
|
| 240 |
+
```
|
| 241 |
+
|
| 242 |
+
For more details, including weighting, merging and fusing LoRAs, check the [documentation on loading LoRAs in diffusers](https://huggingface.co/docs/diffusers/main/en/using-diffusers/loading_adapters)
|
| 243 |
+
"""
|
| 244 |
+
#for index, (image, prompt) in enumerate(zip(downloaded_files["imageName"], downloaded_files["imagePrompt"])):
|
| 245 |
+
# if index == 1:
|
| 246 |
+
# content += f"## Image examples for the model:\n\n> {prompt}\n"
|
| 247 |
+
# elif index > 1:
|
| 248 |
+
# content += f"\n\n> {prompt}\n"
|
| 249 |
+
readme_content += content + "\n"
|
| 250 |
+
with open(f"{folder}/README.md", "w") as file:
|
| 251 |
+
file.write(readme_content)
|
| 252 |
+
|
| 253 |
+
def get_creator(username):
|
| 254 |
+
url = f"https://civitai.com/api/trpc/user.getCreator?input=%7B%22json%22%3A%7B%22username%22%3A%22{username}%22%2C%22authed%22%3Atrue%7D%7D"
|
| 255 |
+
headers = {
|
| 256 |
+
"authority": "civitai.com",
|
| 257 |
+
"accept": "*/*",
|
| 258 |
+
"accept-language": "en-BR,en;q=0.9,pt-BR;q=0.8,pt;q=0.7,es-ES;q=0.6,es;q=0.5,de-LI;q=0.4,de;q=0.3,en-GB;q=0.2,en-US;q=0.1,sk;q=0.1",
|
| 259 |
+
"content-type": "application/json",
|
| 260 |
+
"cookie": f'{os.environ["COOKIE_INFO"]}',
|
| 261 |
+
"if-modified-since": "Tue, 22 Aug 2023 07:18:52 GMT",
|
| 262 |
+
"referer": f"https://civitai.com/user/{username}/models",
|
| 263 |
+
"sec-ch-ua": "\"Not.A/Brand\";v=\"8\", \"Chromium\";v=\"114\", \"Google Chrome\";v=\"114\"",
|
| 264 |
+
"sec-ch-ua-mobile": "?0",
|
| 265 |
+
"sec-ch-ua-platform": "macOS",
|
| 266 |
+
"sec-fetch-dest": "empty",
|
| 267 |
+
"sec-fetch-mode": "cors",
|
| 268 |
+
"sec-fetch-site": "same-origin",
|
| 269 |
+
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
|
| 270 |
+
}
|
| 271 |
+
response = requests.get(url, headers=headers)
|
| 272 |
+
|
| 273 |
+
return response.json()
|
| 274 |
+
|
| 275 |
+
def extract_huggingface_username(username):
|
| 276 |
+
data = get_creator(username)
|
| 277 |
+
links = data.get('result', {}).get('data', {}).get('json', {}).get('links', [])
|
| 278 |
+
for link in links:
|
| 279 |
+
url = link.get('url', '')
|
| 280 |
+
if url.startswith('https://huggingface.co/') or url.startswith('https://www.huggingface.co/'):
|
| 281 |
+
username = url.split('/')[-1]
|
| 282 |
+
return username
|
| 283 |
+
|
| 284 |
+
return None
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def check_civit_link(profile: Optional[gr.OAuthProfile], url):
|
| 288 |
+
info, _ = process_url(url, profile, do_download=False)
|
| 289 |
+
hf_username = extract_huggingface_username(info['creator'])
|
| 290 |
+
attributes_methods = dir(profile)
|
| 291 |
+
|
| 292 |
+
if(profile.username == "multimodalart"):
|
| 293 |
+
return '', gr.update(interactive=True), gr.update(visible=False), gr.update(visible=True)
|
| 294 |
+
|
| 295 |
+
if(not hf_username):
|
| 296 |
+
no_username_text = f'If you are {info["creator"]} on CivitAI, hi! Your CivitAI profile seems to not have information about your Hugging Face account. Please visit <a href="https://civitai.com/user/account" target="_blank">https://civitai.com/user/account</a> and include your 🤗 username there, here\'s mine:<br><img width="60%" src="https://i.imgur.com/hCbo9uL.png" /><br>(if you are not {info["creator"]}, you cannot submit their model at this time)'
|
| 297 |
+
return no_username_text, gr.update(interactive=False), gr.update(visible=True), gr.update(visible=False)
|
| 298 |
+
if(profile.username != hf_username):
|
| 299 |
+
unmatched_username_text = '<h4>Oops, the Hugging Face account in your CivitAI profile seems to be different than the one your are using here. Please visit <a href="https://civitai.com/user/account">https://civitai.com/user/account</a> and update it there to match your Hugging Face account<br><img src="https://i.imgur.com/hCbo9uL.png" /></h4>'
|
| 300 |
+
return unmatched_username_text, gr.update(interactive=False), gr.update(visible=True), gr.update(visible=False)
|
| 301 |
+
else:
|
| 302 |
+
return '', gr.update(interactive=True), gr.update(visible=False), gr.update(visible=True)
|
| 303 |
+
|
| 304 |
+
def swap_fill(profile: Optional[gr.OAuthProfile]):
|
| 305 |
+
if profile is None:
|
| 306 |
+
return gr.update(visible=True), gr.update(visible=False)
|
| 307 |
+
else:
|
| 308 |
+
return gr.update(visible=False), gr.update(visible=True)
|
| 309 |
+
|
| 310 |
+
def show_output():
|
| 311 |
+
return gr.update(visible=True)
|
| 312 |
+
|
| 313 |
+
def list_civit_models(username):
|
| 314 |
+
url = f"https://civitai.com/api/v1/models?username={username}&limit=100"
|
| 315 |
+
json_models_list = []
|
| 316 |
+
|
| 317 |
+
while url:
|
| 318 |
+
response = requests.get(url)
|
| 319 |
+
data = response.json()
|
| 320 |
+
|
| 321 |
+
# Add current page items to the list
|
| 322 |
+
json_models_list.extend(data.get('items', []))
|
| 323 |
+
|
| 324 |
+
# Check if there is a nextPage URL in the metadata
|
| 325 |
+
metadata = data.get('metadata', {})
|
| 326 |
+
url = metadata.get('nextPage', None)
|
| 327 |
+
urls = ""
|
| 328 |
+
for model in json_models_list:
|
| 329 |
+
urls += f'https://civitai.com/models/{model["id"]}/{slugify(model["name"])}\n'
|
| 330 |
+
|
| 331 |
+
return urls
|
| 332 |
+
|
| 333 |
+
def upload_civit_to_hf(profile: Optional[gr.OAuthProfile], oauth_token: gr.OAuthToken, url, link_civit=False):
|
| 334 |
+
if not profile.name:
|
| 335 |
+
return gr.Error("Are you sure you are logged in?")
|
| 336 |
+
|
| 337 |
+
folder = str(uuid.uuid4())
|
| 338 |
+
os.makedirs(folder, exist_ok=False)
|
| 339 |
+
gr.Info(f"Starting download of model {url}")
|
| 340 |
+
info, downloaded_files = process_url(url, profile, folder=folder)
|
| 341 |
+
username = {profile.username}
|
| 342 |
+
slug_name = slugify(info["name"])
|
| 343 |
+
user_repo_id = f"{profile.username}/{slug_name}"
|
| 344 |
+
create_readme(info, downloaded_files, user_repo_id, link_civit, folder=folder)
|
| 345 |
+
try:
|
| 346 |
+
create_repo(repo_id=user_repo_id, private=True, exist_ok=True, token=oauth_token.token)
|
| 347 |
+
gr.Info(f"Starting to upload repo {user_repo_id} to Hugging Face...")
|
| 348 |
+
upload_folder(
|
| 349 |
+
folder_path=folder,
|
| 350 |
+
repo_id=user_repo_id,
|
| 351 |
+
repo_type="model",
|
| 352 |
+
token=oauth_token.token
|
| 353 |
+
)
|
| 354 |
+
update_repo_visibility(repo_id=user_repo_id, private=False, token=oauth_token.token)
|
| 355 |
+
gr.Info(f"Model uploaded!")
|
| 356 |
+
except Exception as e:
|
| 357 |
+
print(e)
|
| 358 |
+
raise gr.Error("Your Hugging Face Token expired. Log out and in again to upload your models.")
|
| 359 |
+
|
| 360 |
+
return f'''# Model uploaded to 🤗!
|
| 361 |
+
## Access it here [{user_repo_id}](https://huggingface.co/{user_repo_id}) '''
|
| 362 |
+
|
| 363 |
+
def bulk_upload(profile: Optional[gr.OAuthProfile], oauth_token: gr.OAuthToken, urls, link_civit=False):
|
| 364 |
+
urls = urls.split("\n")
|
| 365 |
+
print(urls)
|
| 366 |
+
upload_results = ""
|
| 367 |
+
for url in urls:
|
| 368 |
+
if(url):
|
| 369 |
+
try:
|
| 370 |
+
upload_result = upload_civit_to_hf(profile, oauth_token, url, link_civit)
|
| 371 |
+
upload_results += upload_result+"\n"
|
| 372 |
+
except Exception as e:
|
| 373 |
+
gr.Warning(f"Error uploading the model {url}")
|
| 374 |
+
return upload_results
|
| 375 |
+
|
| 376 |
+
css = '''
|
| 377 |
+
#login {
|
| 378 |
+
width: 100% !important;
|
| 379 |
+
margin: 0 auto;
|
| 380 |
+
}
|
| 381 |
+
#disabled_upload{
|
| 382 |
+
opacity: 0.5;
|
| 383 |
+
pointer-events:none;
|
| 384 |
+
}
|
| 385 |
+
'''
|
| 386 |
+
|
| 387 |
+
with gr.Blocks(css=css) as demo:
|
| 388 |
+
gr.Markdown('''# Upload your CivitAI LoRA to Hugging Face 🤗
|
| 389 |
+
By uploading your LoRAs to Hugging Face you get diffusers compatibility, a free GPU-based Inference Widget, you'll be listed in [LoRA Studio](https://lorastudio.co/models) after a short review, and get the possibility to submit your model to the [LoRA the Explorer](https://huggingface.co/spaces/multimodalart/LoraTheExplorer) ✨
|
| 390 |
+
''')
|
| 391 |
+
gr.LoginButton(elem_id="login")
|
| 392 |
+
with gr.Column(elem_id="disabled_upload") as disabled_area:
|
| 393 |
+
with gr.Row():
|
| 394 |
+
submit_source_civit = gr.Textbox(
|
| 395 |
+
placeholder="https://civitai.com/models/144684/pixelartredmond-pixel-art-loras-for-sd-xl",
|
| 396 |
+
label="CivitAI model URL",
|
| 397 |
+
info="URL of the CivitAI LoRA",
|
| 398 |
+
)
|
| 399 |
+
submit_button_civit = gr.Button("Upload model to Hugging Face and submit", interactive=False)
|
| 400 |
+
with gr.Column(visible=False) as enabled_area:
|
| 401 |
+
with gr.Column():
|
| 402 |
+
submit_source_civit = gr.Textbox(
|
| 403 |
+
placeholder="https://civitai.com/models/144684/pixelartredmond-pixel-art-loras-for-sd-xl",
|
| 404 |
+
label="CivitAI model URL",
|
| 405 |
+
info="URL of the CivitAI LoRA",
|
| 406 |
+
|
| 407 |
+
)
|
| 408 |
+
with gr.Accordion("Bulk upload (bring in multiple LoRAs)", open=False):
|
| 409 |
+
civit_username_to_bulk = gr.Textbox(label="CivitAI username (optional)", info="Type your CivitAI username here to automagically fill the bulk models URLs list below (optional, you can paste links down here directly)")
|
| 410 |
+
submit_bulk_civit = gr.Textbox(
|
| 411 |
+
label="CivitAI bulk models URLs",
|
| 412 |
+
info="Add one URL per line",
|
| 413 |
+
lines=6,
|
| 414 |
+
)
|
| 415 |
+
link_civit = gr.Checkbox(label="Link back to CivitAI?", value=False)
|
| 416 |
+
bulk_button = gr.Button("Bulk upload")
|
| 417 |
+
|
| 418 |
+
instructions = gr.HTML("")
|
| 419 |
+
try_again_button = gr.Button("I have added my HF profile to my account (it may take 1 minute to refresh)", visible=False)
|
| 420 |
+
submit_button_civit = gr.Button("Upload model to Hugging Face", interactive=False)
|
| 421 |
+
output = gr.Markdown(label="Output progress", visible=False)
|
| 422 |
+
|
| 423 |
+
demo.load(fn=swap_fill, outputs=[disabled_area, enabled_area], queue=False)
|
| 424 |
+
|
| 425 |
+
submit_source_civit.change(fn=check_civit_link, inputs=[submit_source_civit], outputs=[instructions, submit_button_civit, try_again_button, submit_button_civit])
|
| 426 |
+
civit_username_to_bulk.change(fn=list_civit_models, inputs=[civit_username_to_bulk], outputs=[submit_bulk_civit])
|
| 427 |
+
try_again_button.click(fn=check_civit_link, inputs=[submit_source_civit], outputs=[instructions, submit_button_civit, try_again_button, submit_button_civit])
|
| 428 |
+
|
| 429 |
+
submit_button_civit.click(fn=show_output, inputs=[], outputs=[output]).then(fn=upload_civit_to_hf, inputs=[submit_source_civit, link_civit], outputs=[output])
|
| 430 |
+
bulk_button.click(fn=show_output, inputs=[], outputs=[output]).then(fn=bulk_upload, inputs=[submit_bulk_civit, link_civit], outputs=[output])
|
| 431 |
+
#gr.LogoutButton(elem_id="logout")
|
| 432 |
+
|
| 433 |
+
demo.queue(default_concurrency_limit=50)
|
| 434 |
+
demo.launch()
|