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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 # Removed duplicate update_repo_visibility
|
| 5 |
+
from slugify import slugify
|
| 6 |
+
# import gradio as gr # Already imported
|
| 7 |
+
import re
|
| 8 |
+
import uuid
|
| 9 |
+
from typing import Optional, Dict, Any
|
| 10 |
+
import json
|
| 11 |
+
# from bs4 import BeautifulSoup # Not used
|
| 12 |
+
|
| 13 |
+
TRUSTED_UPLOADERS = ["KappaNeuro", "CiroN2022", "Norod78", "joachimsallstrom", "blink7630", "e-n-v-y", "DoctorDiffusion", "RalFinger", "artificialguybr"]
|
| 14 |
+
|
| 15 |
+
# --- Model Mappings ---
|
| 16 |
+
MODEL_MAPPING_IMAGE = {
|
| 17 |
+
"SDXL 1.0": "stabilityai/stable-diffusion-xl-base-1.0",
|
| 18 |
+
"SDXL 0.9": "stabilityai/stable-diffusion-xl-base-1.0", # Usually mapped to 1.0
|
| 19 |
+
"SD 1.5": "runwayml/stable-diffusion-v1-5",
|
| 20 |
+
"SD 1.4": "CompVis/stable-diffusion-v1-4",
|
| 21 |
+
"SD 2.1": "stabilityai/stable-diffusion-2-1-base",
|
| 22 |
+
"SD 2.0": "stabilityai/stable-diffusion-2-base",
|
| 23 |
+
"SD 2.1 768": "stabilityai/stable-diffusion-2-1",
|
| 24 |
+
"SD 2.0 768": "stabilityai/stable-diffusion-2",
|
| 25 |
+
"SD 3": "stabilityai/stable-diffusion-3-medium-diffusers", # Assuming medium, adjust if others are common
|
| 26 |
+
"SD 3.5": "stabilityai/stable-diffusion-3.5-large", # Assuming large, adjust
|
| 27 |
+
"SD 3.5 Large": "stabilityai/stable-diffusion-3.5-large",
|
| 28 |
+
"SD 3.5 Medium": "stabilityai/stable-diffusion-3.5-medium",
|
| 29 |
+
"SD 3.5 Large Turbo": "stabilityai/stable-diffusion-3.5-large-turbo",
|
| 30 |
+
"Flux.1 D": "black-forest-labs/FLUX.1-dev",
|
| 31 |
+
"Flux.1 S": "black-forest-labs/FLUX.1-schnell",
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
MODEL_MAPPING_VIDEO = {
|
| 35 |
+
"LTXV": "Lightricks/LTX-Video-0.9.7-dev",
|
| 36 |
+
"Wan Video 1.3B t2v": "Wan-AI/Wan2.1-T2V-1.3B-Diffusers",
|
| 37 |
+
"Wan Video 14B t2v": "Wan-AI/Wan2.1-T2V-14B-Diffusers",
|
| 38 |
+
"Wan Video 14B i2v 480p": "Wan-AI/Wan2.1-I2V-14B-480P-Diffusers",
|
| 39 |
+
"Wan Video 14B i2v 720p": "Wan-AI/Wan2.1-I2V-14B-720P-Diffusers",
|
| 40 |
+
"Hunyuan Video": "hunyuanvideo-community/HunyuanVideo-I2V", # Default, will be overridden by choice
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
SUPPORTED_CIVITAI_BASE_MODELS = list(MODEL_MAPPING_IMAGE.keys()) + list(MODEL_MAPPING_VIDEO.keys())
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
cookie_info = os.environ.get("COOKIE_INFO")
|
| 47 |
+
|
| 48 |
+
headers = {
|
| 49 |
+
"authority": "civitai.com",
|
| 50 |
+
"accept": "*/*",
|
| 51 |
+
"accept-language": "en-US,en;q=0.9", # Simplified
|
| 52 |
+
"content-type": "application/json",
|
| 53 |
+
"cookie": cookie_info, # Use the env var
|
| 54 |
+
"sec-ch-ua": "\"Chromium\";v=\"118\", \"Not_A Brand\";v=\"99\"", # Example, update if needed
|
| 55 |
+
"sec-ch-ua-mobile": "?0",
|
| 56 |
+
"sec-ch-ua-platform": "\"Windows\"", # Example
|
| 57 |
+
"sec-fetch-dest": "empty",
|
| 58 |
+
"sec-fetch-mode": "cors",
|
| 59 |
+
"sec-fetch-site": "same-origin",
|
| 60 |
+
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36" # Example
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
def get_json_data(url):
|
| 64 |
+
url_split = url.split('/')
|
| 65 |
+
if len(url_split) < 5 or not url_split[4].isdigit():
|
| 66 |
+
print(f"Invalid Civitai URL format or model ID not found: {url}")
|
| 67 |
+
gr.Warning(f"Invalid Civitai URL format. Ensure it's like 'https://civitai.com/models/YOUR_MODEL_ID/MODEL_NAME'. Problem with: {url}")
|
| 68 |
+
return None
|
| 69 |
+
api_url = f"https://civitai.com/api/v1/models/{url_split[4]}"
|
| 70 |
+
try:
|
| 71 |
+
response = requests.get(api_url)
|
| 72 |
+
response.raise_for_status()
|
| 73 |
+
return response.json()
|
| 74 |
+
except requests.exceptions.RequestException as e:
|
| 75 |
+
print(f"Error fetching JSON data from {api_url}: {e}")
|
| 76 |
+
gr.Warning(f"Error fetching data from Civitai API for {url_split[4]}: {e}")
|
| 77 |
+
return None
|
| 78 |
+
|
| 79 |
+
def check_nsfw(json_data: Dict[str, Any], profile: Optional[gr.OAuthProfile]) -> bool:
|
| 80 |
+
if not json_data:
|
| 81 |
+
return False # Should not happen if get_json_data succeeded
|
| 82 |
+
|
| 83 |
+
# Overall model boolean flag - highest priority
|
| 84 |
+
if json_data.get("nsfw", False):
|
| 85 |
+
print("Model flagged as NSFW by 'nsfw: true'.")
|
| 86 |
+
gr.Info("Reason: Model explicitly flagged as NSFW on Civitai.")
|
| 87 |
+
return False # Unsafe
|
| 88 |
+
|
| 89 |
+
# Overall model numeric nsfwLevel - second priority. Max allowed is 5 (nsfwLevel < 6).
|
| 90 |
+
# nsfwLevel definitions: None (1), Mild (2), Mature (4), Adult (5), X (8), R (16), XXX (32)
|
| 91 |
+
model_nsfw_level = json_data.get("nsfwLevel", 0)
|
| 92 |
+
if model_nsfw_level > 5: # Anything above "Adult"
|
| 93 |
+
print(f"Model's overall nsfwLevel ({model_nsfw_level}) is > 5. Blocking.")
|
| 94 |
+
gr.Info(f"Reason: Model's overall NSFW Level ({model_nsfw_level}) is above the allowed threshold (5).")
|
| 95 |
+
return False # Unsafe
|
| 96 |
+
|
| 97 |
+
# If uploader is trusted and the above checks passed, they bypass further version/image checks.
|
| 98 |
+
if profile and profile.username in TRUSTED_UPLOADERS:
|
| 99 |
+
print(f"User {profile.username} is trusted. Model 'nsfw' is false and overall nsfwLevel ({model_nsfw_level}) is <= 5. Allowing.")
|
| 100 |
+
return True
|
| 101 |
+
|
| 102 |
+
# For non-trusted users, check nsfwLevel of model versions and individual images/videos
|
| 103 |
+
for model_version in json_data.get("modelVersions", []):
|
| 104 |
+
version_nsfw_level = model_version.get("nsfwLevel", 0)
|
| 105 |
+
if version_nsfw_level > 5:
|
| 106 |
+
print(f"Model version nsfwLevel ({version_nsfw_level}) is > 5 for non-trusted user. Blocking.")
|
| 107 |
+
gr.Info(f"Reason: A model version's NSFW Level ({version_nsfw_level}) is above 5.")
|
| 108 |
+
return False
|
| 109 |
+
return True # Safe for non-trusted user if all checks pass
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def get_prompts_from_image(image_id_str: str):
|
| 113 |
+
# image_id_str could be non-numeric if URL parsing failed or format changed
|
| 114 |
+
try:
|
| 115 |
+
image_id = int(image_id_str)
|
| 116 |
+
except ValueError:
|
| 117 |
+
print(f"Invalid image_id_str for TRPC call: {image_id_str}. Skipping prompt fetch.")
|
| 118 |
+
return "", ""
|
| 119 |
+
|
| 120 |
+
print(f"Fetching prompts for image_id: {image_id}")
|
| 121 |
+
url = f'https://civitai.com/api/trpc/image.getGenerationData?input={{"json":{{"id":{image_id}}}}}'
|
| 122 |
+
|
| 123 |
+
prompt = ""
|
| 124 |
+
negative_prompt = ""
|
| 125 |
+
try:
|
| 126 |
+
response = requests.get(url, headers=headers, timeout=10) # Added timeout
|
| 127 |
+
response.raise_for_status() # Will raise an HTTPError if the HTTP request returned an unsuccessful status code
|
| 128 |
+
data = response.json()
|
| 129 |
+
print("Response from image: ", data)
|
| 130 |
+
# Expected structure: {'result': {'data': {'json': {'meta': {'prompt': '...', 'negativePrompt': '...'}}}}}
|
| 131 |
+
meta = data.get('result', {}).get('data', {}).get('json', {}).get('meta')
|
| 132 |
+
if meta: # meta can be None
|
| 133 |
+
prompt = meta.get('prompt', "")
|
| 134 |
+
negative_prompt = meta.get('negativePrompt', "")
|
| 135 |
+
except requests.exceptions.RequestException as e:
|
| 136 |
+
print(f"Could not fetch/parse generation data for image_id {image_id}: {e}")
|
| 137 |
+
except json.JSONDecodeError as e:
|
| 138 |
+
print(f"JSONDecodeError for image_id {image_id}: {e}. Response content: {response.text[:200]}")
|
| 139 |
+
|
| 140 |
+
return prompt, negative_prompt
|
| 141 |
+
|
| 142 |
+
def extract_info(json_data: Dict[str, Any], hunyuan_type: Optional[str] = None) -> Optional[Dict[str, Any]]:
|
| 143 |
+
if json_data.get("type") != "LORA":
|
| 144 |
+
print("Model type is not LORA.")
|
| 145 |
+
return None
|
| 146 |
+
|
| 147 |
+
for model_version in json_data.get("modelVersions", []):
|
| 148 |
+
civitai_base_model_name = model_version.get("baseModel")
|
| 149 |
+
if civitai_base_model_name in SUPPORTED_CIVITAI_BASE_MODELS:
|
| 150 |
+
base_model_hf = ""
|
| 151 |
+
is_video = False
|
| 152 |
+
|
| 153 |
+
if civitai_base_model_name == "Hunyuan Video":
|
| 154 |
+
is_video = True
|
| 155 |
+
if hunyuan_type == "Text-to-Video":
|
| 156 |
+
base_model_hf = "hunyuanvideo-community/HunyuanVideo"
|
| 157 |
+
else: # Default or "Image-to-Video"
|
| 158 |
+
base_model_hf = "hunyuanvideo-community/HunyuanVideo-I2V"
|
| 159 |
+
elif civitai_base_model_name in MODEL_MAPPING_VIDEO:
|
| 160 |
+
is_video = True
|
| 161 |
+
base_model_hf = MODEL_MAPPING_VIDEO[civitai_base_model_name]
|
| 162 |
+
elif civitai_base_model_name in MODEL_MAPPING_IMAGE:
|
| 163 |
+
base_model_hf = MODEL_MAPPING_IMAGE[civitai_base_model_name]
|
| 164 |
+
else:
|
| 165 |
+
print(f"Logic error: {civitai_base_model_name} in supported list but not mapped.")
|
| 166 |
+
continue
|
| 167 |
+
|
| 168 |
+
primary_file_info = None
|
| 169 |
+
for file_entry in model_version.get("files", []):
|
| 170 |
+
if file_entry.get("primary", False) and file_entry.get("type") == "Model":
|
| 171 |
+
primary_file_info = file_entry
|
| 172 |
+
break
|
| 173 |
+
|
| 174 |
+
if not primary_file_info:
|
| 175 |
+
for file_entry in model_version.get("files", []):
|
| 176 |
+
if file_entry.get("type") == "Model" and file_entry.get("name","").endswith(".safetensors"):
|
| 177 |
+
primary_file_info = file_entry
|
| 178 |
+
print(f"Using first safetensors file as primary: {primary_file_info['name']}")
|
| 179 |
+
break
|
| 180 |
+
if not primary_file_info:
|
| 181 |
+
print(f"No primary or suitable safetensors model file found for version {model_version.get('name')}")
|
| 182 |
+
continue
|
| 183 |
+
|
| 184 |
+
urls_to_download = [{"url": primary_file_info["downloadUrl"], "filename": primary_file_info["name"], "type": "weightName"}]
|
| 185 |
+
|
| 186 |
+
for image_obj in model_version.get("images", []):
|
| 187 |
+
image_url = image_obj.get("url")
|
| 188 |
+
if not image_url:
|
| 189 |
+
continue
|
| 190 |
+
|
| 191 |
+
image_nsfw_level = image_obj.get("nsfwLevel", 0)
|
| 192 |
+
if image_nsfw_level > 5:
|
| 193 |
+
continue
|
| 194 |
+
|
| 195 |
+
filename_part = os.path.basename(image_url)
|
| 196 |
+
image_id_str = filename_part.split('.')[0]
|
| 197 |
+
|
| 198 |
+
prompt, negative_prompt = "", ""
|
| 199 |
+
if image_obj.get("hasMeta", False):
|
| 200 |
+
prompt, negative_prompt = get_prompts_from_image(image_id_str)
|
| 201 |
+
|
| 202 |
+
urls_to_download.append({
|
| 203 |
+
"url": image_url,
|
| 204 |
+
"filename": filename_part,
|
| 205 |
+
"type": "imageName",
|
| 206 |
+
"prompt": prompt,
|
| 207 |
+
"negative_prompt": negative_prompt,
|
| 208 |
+
"media_type": image_obj.get("type", "image")
|
| 209 |
+
})
|
| 210 |
+
|
| 211 |
+
info = {
|
| 212 |
+
"urls_to_download": urls_to_download,
|
| 213 |
+
"id": model_version["id"],
|
| 214 |
+
"baseModel": base_model_hf,
|
| 215 |
+
"civitai_base_model_name": civitai_base_model_name,
|
| 216 |
+
"is_video_model": is_video,
|
| 217 |
+
"modelId": json_data.get("id", ""),
|
| 218 |
+
"name": json_data["name"],
|
| 219 |
+
"description": json_data.get("description", ""),
|
| 220 |
+
"trainedWords": model_version.get("trainedWords", []),
|
| 221 |
+
"creator": json_data.get("creator", {}).get("username", "Unknown"),
|
| 222 |
+
"tags": json_data.get("tags", []),
|
| 223 |
+
"allowNoCredit": json_data.get("allowNoCredit", True),
|
| 224 |
+
"allowCommercialUse": json_data.get("allowCommercialUse", "Sell"),
|
| 225 |
+
"allowDerivatives": json_data.get("allowDerivatives", True),
|
| 226 |
+
"allowDifferentLicense": json_data.get("allowDifferentLicense", True)
|
| 227 |
+
}
|
| 228 |
+
return info
|
| 229 |
+
print("No suitable model version found with a supported base model.")
|
| 230 |
+
return None
|
| 231 |
+
|
| 232 |
+
def download_files(info, folder="."):
|
| 233 |
+
downloaded_files = {
|
| 234 |
+
"imageName": [], # Will contain both image and video filenames
|
| 235 |
+
"imagePrompt": [],
|
| 236 |
+
"imageNegativePrompt": [],
|
| 237 |
+
"weightName": [],
|
| 238 |
+
"mediaType": [] # To distinguish image/video for gallery if needed later
|
| 239 |
+
}
|
| 240 |
+
for item in info["urls_to_download"]:
|
| 241 |
+
# Ensure filename is safe for filesystem
|
| 242 |
+
safe_filename = slugify(item["filename"].rsplit('.', 1)[0]) + '.' + item["filename"].rsplit('.', 1)[-1] if '.' in item["filename"] else slugify(item["filename"])
|
| 243 |
+
|
| 244 |
+
# Civitai URLs might need auth for direct download if not public
|
| 245 |
+
try:
|
| 246 |
+
download_file_with_auth(item["url"], safe_filename, folder) # Changed to use the auth-aware download
|
| 247 |
+
downloaded_files[item["type"]].append(safe_filename)
|
| 248 |
+
if item["type"] == "imageName": # This list now includes videos too
|
| 249 |
+
prompt_clean = re.sub(r'<.*?>', '', item.get("prompt", ""))
|
| 250 |
+
negative_prompt_clean = re.sub(r'<.*?>', '', item.get("negative_prompt", ""))
|
| 251 |
+
downloaded_files["imagePrompt"].append(prompt_clean)
|
| 252 |
+
downloaded_files["imageNegativePrompt"].append(negative_prompt_clean)
|
| 253 |
+
downloaded_files["mediaType"].append(item.get("media_type", "image"))
|
| 254 |
+
except gr.Error as e: # Catch Gradio errors from download_file_with_auth
|
| 255 |
+
print(f"Skipping file {safe_filename} due to download error: {e.message}")
|
| 256 |
+
gr.Warning(f"Skipping file {safe_filename} due to download error: {e.message}")
|
| 257 |
+
|
| 258 |
+
return downloaded_files
|
| 259 |
+
|
| 260 |
+
# Renamed original download_file to download_file_with_auth
|
| 261 |
+
def download_file_with_auth(url, filename, folder="."):
|
| 262 |
+
headers = {}
|
| 263 |
+
# Add CIVITAI_API_TOKEN if available, for potentially restricted downloads
|
| 264 |
+
# Note: The prompt example didn't use it for image URLs, only for the model file via API.
|
| 265 |
+
# However, some image/video URLs might also require it if they are not fully public.
|
| 266 |
+
if "CIVITAI_API_TOKEN" in os.environ: # Changed from CIVITAI_API
|
| 267 |
+
headers['Authorization'] = f'Bearer {os.environ["CIVITAI_API_TOKEN"]}'
|
| 268 |
+
|
| 269 |
+
try:
|
| 270 |
+
response = requests.get(url, headers=headers, stream=True, timeout=60) # Added stream and timeout
|
| 271 |
+
response.raise_for_status()
|
| 272 |
+
except requests.exceptions.HTTPError as e:
|
| 273 |
+
print(f"HTTPError downloading {url}: {e}")
|
| 274 |
+
# No automatic retry with token here as it was specific to the primary file in original code
|
| 275 |
+
# If it was related to auth, the initial header should have helped.
|
| 276 |
+
raise gr.Error(f"Error downloading file {filename}: {e}")
|
| 277 |
+
except requests.exceptions.RequestException as e:
|
| 278 |
+
print(f"RequestException downloading {url}: {e}")
|
| 279 |
+
raise gr.Error(f"Error downloading file {filename}: {e}")
|
| 280 |
+
|
| 281 |
+
filepath = os.path.join(folder, filename)
|
| 282 |
+
with open(filepath, 'wb') as f:
|
| 283 |
+
for chunk in response.iter_content(chunk_size=8192):
|
| 284 |
+
f.write(chunk)
|
| 285 |
+
print(f"Successfully downloaded {filepath}")
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def process_url(url, profile, do_download=True, folder=".", hunyuan_type: Optional[str] = None):
|
| 289 |
+
json_data = get_json_data(url)
|
| 290 |
+
if json_data:
|
| 291 |
+
if check_nsfw(json_data, profile):
|
| 292 |
+
info = extract_info(json_data, hunyuan_type=hunyuan_type)
|
| 293 |
+
if info:
|
| 294 |
+
downloaded_files_summary = {}
|
| 295 |
+
if do_download:
|
| 296 |
+
gr.Info(f"Downloading files for {info['name']}...")
|
| 297 |
+
downloaded_files_summary = download_files(info, folder)
|
| 298 |
+
gr.Info(f"Finished downloading files for {info['name']}.")
|
| 299 |
+
return info, downloaded_files_summary
|
| 300 |
+
else:
|
| 301 |
+
raise gr.Error("LoRA extraction failed. The base model might not be supported, or it's not a LoRA model, or no suitable files found in the version.")
|
| 302 |
+
else:
|
| 303 |
+
# check_nsfw now prints detailed reasons via gr.Info/print
|
| 304 |
+
raise gr.Error("This model has content tagged as unsafe by CivitAI or exceeds NSFW level limits.")
|
| 305 |
+
else:
|
| 306 |
+
raise gr.Error("Failed to fetch model data from CivitAI API. Please check the URL and Civitai's status.")
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def create_readme(info: Dict[str, Any], downloaded_files: Dict[str, Any], user_repo_id: str, link_civit: bool = False, is_author: bool = True, folder: str = "."):
|
| 310 |
+
readme_content = ""
|
| 311 |
+
original_url = f"https://civitai.com/models/{info['modelId']}" if info.get('modelId') else "CivitAI (ID not found)"
|
| 312 |
+
link_civit_disclaimer = f'([CivitAI]({original_url}))'
|
| 313 |
+
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:'
|
| 314 |
+
|
| 315 |
+
is_video = info.get("is_video_model", False)
|
| 316 |
+
base_hf_model = info["baseModel"] # This is the HF model ID
|
| 317 |
+
civitai_bm_name_lower = info.get("civitai_base_model_name", "").lower()
|
| 318 |
+
|
| 319 |
+
if is_video:
|
| 320 |
+
default_tags = ["lora", "diffusers", "migrated", "video"]
|
| 321 |
+
if "template:" not in " ".join(info.get("tags", [])):
|
| 322 |
+
default_tags.append("template:video-lora")
|
| 323 |
+
if "t2v" in civitai_bm_name_lower or (civitai_bm_name_lower == "hunyuan video" and base_hf_model.endswith("HunyuanVideo")):
|
| 324 |
+
default_tags.append("text-to-video")
|
| 325 |
+
elif "i2v" in civitai_bm_name_lower or (civitai_bm_name_lower == "hunyuan video" and base_hf_model.endswith("HunyuanVideo-I2V")):
|
| 326 |
+
default_tags.append("image-to-video")
|
| 327 |
+
else:
|
| 328 |
+
default_tags = ["text-to-image", "stable-diffusion", "lora", "diffusers", "migrated"]
|
| 329 |
+
if "template:" not in " ".join(info.get("tags", [])):
|
| 330 |
+
default_tags.append("template:sd-lora")
|
| 331 |
+
|
| 332 |
+
civit_tags_raw = info.get("tags", [])
|
| 333 |
+
civit_tags_clean = [t.replace(":", "").strip() for t in civit_tags_raw if t.replace(":", "").strip()]
|
| 334 |
+
final_civit_tags = [tag for tag in civit_tags_clean if tag not in default_tags and tag.lower() not in default_tags]
|
| 335 |
+
tags = default_tags + final_civit_tags
|
| 336 |
+
unpacked_tags = "\n- ".join(sorted(list(set(tags))))
|
| 337 |
+
|
| 338 |
+
trained_words = info.get('trainedWords', [])
|
| 339 |
+
formatted_words = ', '.join(f'`{word}`' for word in trained_words if word)
|
| 340 |
+
trigger_words_section = f"## Trigger words\nYou should use {formatted_words} to trigger the generation." if formatted_words else ""
|
| 341 |
+
|
| 342 |
+
widget_content = ""
|
| 343 |
+
max_widget_items = 5
|
| 344 |
+
items_for_widget = list(zip(
|
| 345 |
+
downloaded_files.get("imagePrompt", []),
|
| 346 |
+
downloaded_files.get("imageNegativePrompt", []),
|
| 347 |
+
downloaded_files.get("imageName", [])
|
| 348 |
+
))[:max_widget_items]
|
| 349 |
+
|
| 350 |
+
for index, (prompt, negative_prompt, media_filename) in enumerate(items_for_widget):
|
| 351 |
+
escaped_prompt = prompt.replace("'", "''") if prompt else ' '
|
| 352 |
+
base_media_filename = os.path.basename(media_filename)
|
| 353 |
+
negative_prompt_content = f"negative_prompt: {negative_prompt}\n" if negative_prompt else ""
|
| 354 |
+
# Corrected YAML for widget:
|
| 355 |
+
widget_content += f"""- text: '{escaped_prompt}'
|
| 356 |
+
{negative_prompt_content}
|
| 357 |
+
output:
|
| 358 |
+
url: >-
|
| 359 |
+
{base_media_filename}
|
| 360 |
+
"""
|
| 361 |
+
|
| 362 |
+
if base_hf_model in ["black-forest-labs/FLUX.1-dev", "black-forest-labs/FLUX.1-schnell"]:
|
| 363 |
+
dtype = "torch.bfloat16"
|
| 364 |
+
else:
|
| 365 |
+
dtype = "torch.float16" # Default for others, Hunyuan examples specify this.
|
| 366 |
+
|
| 367 |
+
main_prompt_for_snippet_raw = formatted_words if formatted_words else 'Your custom prompt'
|
| 368 |
+
if items_for_widget and items_for_widget[0][0]:
|
| 369 |
+
main_prompt_for_snippet_raw = items_for_widget[0][0]
|
| 370 |
+
|
| 371 |
+
# Escape single quotes for Python string literals
|
| 372 |
+
main_prompt_for_snippet = main_prompt_for_snippet_raw.replace("'", "\\'")
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
lora_loader_line = f"pipe.load_lora_weights('{user_repo_id}', weight_name='{downloaded_files.get('weightName', ['your_lora.safetensors'])[0]}')"
|
| 376 |
+
|
| 377 |
+
diffusers_example = ""
|
| 378 |
+
if is_video:
|
| 379 |
+
if base_hf_model == "hunyuanvideo-community/HunyuanVideo-I2V":
|
| 380 |
+
diffusers_example = f"""
|
| 381 |
+
```py
|
| 382 |
+
import torch
|
| 383 |
+
from diffusers import HunyuanVideoImageToVideoPipeline, HunyuanVideoTransformer3DModel
|
| 384 |
+
from diffusers.utils import load_image, export_to_video
|
| 385 |
+
|
| 386 |
+
# Available checkpoints: "hunyuanvideo-community/HunyuanVideo-I2V" and "hunyuanvideo-community/HunyuanVideo-I2V-33ch"
|
| 387 |
+
model_id = "{base_hf_model}"
|
| 388 |
+
transformer = HunyuanVideoTransformer3DModel.from_pretrained(
|
| 389 |
+
model_id, subfolder="transformer", torch_dtype=torch.bfloat16 # Explicitly bfloat16 for transformer
|
| 390 |
+
)
|
| 391 |
+
pipe = HunyuanVideoImageToVideoPipeline.from_pretrained(
|
| 392 |
+
model_id, transformer=transformer, torch_dtype=torch.float16 # float16 for pipeline
|
| 393 |
+
)
|
| 394 |
+
pipe.vae.enable_tiling()
|
| 395 |
+
{lora_loader_line}
|
| 396 |
+
pipe.to("cuda")
|
| 397 |
+
|
| 398 |
+
prompt = "{main_prompt_for_snippet if main_prompt_for_snippet else 'A detailed scene description'}"
|
| 399 |
+
# Replace with your image path or URL
|
| 400 |
+
image_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/guitar-man.png"
|
| 401 |
+
image = load_image(image_url)
|
| 402 |
+
|
| 403 |
+
output = pipe(image=image, prompt=prompt).frames[0]
|
| 404 |
+
export_to_video(output, "output.mp4", fps=15)
|
| 405 |
+
```
|
| 406 |
+
"""
|
| 407 |
+
elif base_hf_model == "hunyuanvideo-community/HunyuanVideo":
|
| 408 |
+
diffusers_example = f"""
|
| 409 |
+
```py
|
| 410 |
+
import torch
|
| 411 |
+
from diffusers import HunyuanVideoPipeline, HunyuanVideoTransformer3DModel
|
| 412 |
+
from diffusers.utils import export_to_video
|
| 413 |
+
|
| 414 |
+
model_id = "{base_hf_model}"
|
| 415 |
+
transformer = HunyuanVideoTransformer3DModel.from_pretrained(
|
| 416 |
+
model_id, subfolder="transformer", torch_dtype=torch.bfloat16
|
| 417 |
+
)
|
| 418 |
+
pipe = HunyuanVideoPipeline.from_pretrained(model_id, transformer=transformer, torch_dtype=torch.float16)
|
| 419 |
+
{lora_loader_line}
|
| 420 |
+
# Enable memory savings
|
| 421 |
+
pipe.vae.enable_tiling()
|
| 422 |
+
pipe.enable_model_cpu_offload() # Optional: if VRAM is limited
|
| 423 |
+
|
| 424 |
+
output = pipe(
|
| 425 |
+
prompt="{main_prompt_for_snippet if main_prompt_for_snippet else 'A cinematic video scene'}",
|
| 426 |
+
height=320, # Adjust as needed
|
| 427 |
+
width=512, # Adjust as needed
|
| 428 |
+
num_frames=61, # Adjust as needed
|
| 429 |
+
num_inference_steps=30, # Adjust as needed
|
| 430 |
+
).frames[0]
|
| 431 |
+
export_to_video(output, "output.mp4", fps=15)
|
| 432 |
+
```
|
| 433 |
+
"""
|
| 434 |
+
elif base_hf_model == "Lightricks/LTX-Video-0.9.7-dev" or base_hf_model == "Lightricks/LTX-Video-0.9.7-distilled": # Assuming -dev is the one from mapping
|
| 435 |
+
# Note: The LTX example is complex. We'll simplify a bit for a LoRA example.
|
| 436 |
+
# The user might need to adapt the full pipeline if they used the distilled one directly.
|
| 437 |
+
# We assume the LoRA is trained on the main LTX pipeline.
|
| 438 |
+
diffusers_example = f"""
|
| 439 |
+
```py
|
| 440 |
+
import torch
|
| 441 |
+
from diffusers import LTXConditionPipeline, LTXLatentUpsamplePipeline
|
| 442 |
+
from diffusers.pipelines.ltx.pipeline_ltx_condition import LTXVideoCondition
|
| 443 |
+
from diffusers.utils import export_to_video, load_image, load_video
|
| 444 |
+
|
| 445 |
+
# Use the base LTX model your LoRA was trained on. The example below uses the distilled version.
|
| 446 |
+
# Adjust if your LoRA is for the non-distilled "Lightricks/LTX-Video-0.9.7-dev".
|
| 447 |
+
pipe = LTXConditionPipeline.from_pretrained("Lightricks/LTX-Video-0.9.7-distilled", torch_dtype=torch.bfloat16)
|
| 448 |
+
{lora_loader_line}
|
| 449 |
+
# The LTX upsampler is separate and typically doesn't have LoRAs loaded into it directly.
|
| 450 |
+
pipe_upsample = LTXLatentUpsamplePipeline.from_pretrained("Lightricks/ltxv-spatial-upscaler-0.9.7", vae=pipe.vae, torch_dtype=torch.bfloat16)
|
| 451 |
+
|
| 452 |
+
pipe.to("cuda")
|
| 453 |
+
pipe_upsample.to("cuda")
|
| 454 |
+
pipe.vae.enable_tiling()
|
| 455 |
+
|
| 456 |
+
def round_to_nearest_resolution_acceptable_by_vae(height, width, vae_spatial_compression_ratio):
|
| 457 |
+
height = height - (height % vae_spatial_compression_ratio)
|
| 458 |
+
width = width - (width % vae_spatial_compression_ratio)
|
| 459 |
+
return height, width
|
| 460 |
+
|
| 461 |
+
# Example image for condition (replace with your own)
|
| 462 |
+
image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/penguin.png")
|
| 463 |
+
video_for_condition = load_video(export_to_video([image])) # Create a dummy video for conditioning
|
| 464 |
+
condition1 = LTXVideoCondition(video=video_for_condition, frame_index=0)
|
| 465 |
+
|
| 466 |
+
prompt = "{main_prompt_for_snippet if main_prompt_for_snippet else 'A cute little penguin takes out a book and starts reading it'}"
|
| 467 |
+
negative_prompt = "worst quality, inconsistent motion, blurry, jittery, distorted" # Example
|
| 468 |
+
expected_height, expected_width = 480, 832 # Target final resolution
|
| 469 |
+
downscale_factor = 2 / 3
|
| 470 |
+
num_frames = 32 # Reduced for quicker example
|
| 471 |
+
|
| 472 |
+
# Part 1. Generate video at smaller resolution
|
| 473 |
+
downscaled_height, downscaled_width = int(expected_height * downscale_factor), int(expected_width * downscale_factor)
|
| 474 |
+
downscaled_height, downscaled_width = round_to_nearest_resolution_acceptable_by_vae(downscaled_height, downscaled_width, pipe.vae_spatial_compression_ratio)
|
| 475 |
+
|
| 476 |
+
latents = pipe(
|
| 477 |
+
conditions=[condition1],
|
| 478 |
+
prompt=prompt,
|
| 479 |
+
negative_prompt=negative_prompt,
|
| 480 |
+
width=downscaled_width,
|
| 481 |
+
height=downscaled_height,
|
| 482 |
+
num_frames=num_frames,
|
| 483 |
+
num_inference_steps=7, # Example steps
|
| 484 |
+
guidance_scale=1.0, # Example guidance
|
| 485 |
+
decode_timestep = 0.05,
|
| 486 |
+
decode_noise_scale = 0.025,
|
| 487 |
+
generator=torch.Generator().manual_seed(0),
|
| 488 |
+
output_type="latent",
|
| 489 |
+
).frames
|
| 490 |
+
|
| 491 |
+
# Part 2. Upscale generated video
|
| 492 |
+
upscaled_latents = pipe_upsample(
|
| 493 |
+
latents=latents,
|
| 494 |
+
output_type="latent"
|
| 495 |
+
).frames
|
| 496 |
+
|
| 497 |
+
# Part 3. Denoise the upscaled video (optional, but recommended)
|
| 498 |
+
video_frames = pipe(
|
| 499 |
+
conditions=[condition1],
|
| 500 |
+
prompt=prompt,
|
| 501 |
+
negative_prompt=negative_prompt,
|
| 502 |
+
width=downscaled_width * 2, # Upscaled width
|
| 503 |
+
height=downscaled_height * 2, # Upscaled height
|
| 504 |
+
num_frames=num_frames,
|
| 505 |
+
denoise_strength=0.3,
|
| 506 |
+
num_inference_steps=10,
|
| 507 |
+
guidance_scale=1.0,
|
| 508 |
+
latents=upscaled_latents,
|
| 509 |
+
decode_timestep = 0.05,
|
| 510 |
+
decode_noise_scale = 0.025,
|
| 511 |
+
image_cond_noise_scale=0.025, # if using image condition
|
| 512 |
+
generator=torch.Generator().manual_seed(0),
|
| 513 |
+
output_type="pil",
|
| 514 |
+
).frames[0]
|
| 515 |
+
|
| 516 |
+
# Part 4. Downscale to target resolution if upscaler overshot
|
| 517 |
+
final_video = [frame.resize((expected_width, expected_height)) for frame in video_frames]
|
| 518 |
+
export_to_video(final_video, "output.mp4", fps=16) # Example fps
|
| 519 |
+
```
|
| 520 |
+
"""
|
| 521 |
+
elif base_hf_model.startswith("Wan-AI/Wan2.1-T2V-"):
|
| 522 |
+
diffusers_example = f"""
|
| 523 |
+
```py
|
| 524 |
+
import torch
|
| 525 |
+
from diffusers import AutoencoderKLWan, WanPipeline
|
| 526 |
+
from diffusers.utils import export_to_video
|
| 527 |
+
|
| 528 |
+
model_id = "{base_hf_model}"
|
| 529 |
+
vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32) # As per example
|
| 530 |
+
pipe = WanPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
|
| 531 |
+
{lora_loader_line}
|
| 532 |
+
pipe.to("cuda")
|
| 533 |
+
|
| 534 |
+
prompt = "{main_prompt_for_snippet if main_prompt_for_snippet else 'A cat walks on the grass, realistic'}"
|
| 535 |
+
negative_prompt = "worst quality, low quality, blurry" # Simplified for LoRA example
|
| 536 |
+
|
| 537 |
+
output = pipe(
|
| 538 |
+
prompt=prompt,
|
| 539 |
+
negative_prompt=negative_prompt,
|
| 540 |
+
height=480, # Adjust as needed
|
| 541 |
+
width=832, # Adjust as needed
|
| 542 |
+
num_frames=30, # Adjust for LoRA, original example had 81
|
| 543 |
+
guidance_scale=5.0 # Adjust as needed
|
| 544 |
+
).frames[0]
|
| 545 |
+
export_to_video(output, "output.mp4", fps=15)
|
| 546 |
+
```
|
| 547 |
+
"""
|
| 548 |
+
elif base_hf_model.startswith("Wan-AI/Wan2.1-I2V-"):
|
| 549 |
+
diffusers_example = f"""
|
| 550 |
+
```py
|
| 551 |
+
import torch
|
| 552 |
+
import numpy as np
|
| 553 |
+
from diffusers import AutoencoderKLWan, WanImageToVideoPipeline
|
| 554 |
+
from diffusers.utils import export_to_video, load_image
|
| 555 |
+
from transformers import CLIPVisionModel
|
| 556 |
+
|
| 557 |
+
model_id = "{base_hf_model}"
|
| 558 |
+
# These components are part of the base model, LoRA is loaded into the pipeline
|
| 559 |
+
image_encoder = CLIPVisionModel.from_pretrained(model_id, subfolder="image_encoder", torch_dtype=torch.float32)
|
| 560 |
+
vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
|
| 561 |
+
pipe = WanImageToVideoPipeline.from_pretrained(model_id, vae=vae, image_encoder=image_encoder, torch_dtype=torch.bfloat16)
|
| 562 |
+
{lora_loader_line}
|
| 563 |
+
pipe.to("cuda")
|
| 564 |
+
|
| 565 |
+
# Replace with your image path or URL
|
| 566 |
+
image_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
|
| 567 |
+
image = load_image(image_url)
|
| 568 |
+
|
| 569 |
+
# Adjust resolution based on model capabilities (480p or 720p variants)
|
| 570 |
+
# This is a simplified example; refer to original Wan I2V docs for precise resolution handling
|
| 571 |
+
if "480P" in model_id:
|
| 572 |
+
max_height, max_width = 480, 832 # Example for 480p
|
| 573 |
+
elif "720P" in model_id:
|
| 574 |
+
max_height, max_width = 720, 1280 # Example for 720p
|
| 575 |
+
else: # Fallback
|
| 576 |
+
max_height, max_width = 480, 832
|
| 577 |
+
|
| 578 |
+
# Simple resize for example, optimal resizing might need to maintain aspect ratio & VAE constraints
|
| 579 |
+
h, w = image.height, image.width
|
| 580 |
+
if w > max_width or h > max_height:
|
| 581 |
+
aspect_ratio = w / h
|
| 582 |
+
if w > h:
|
| 583 |
+
new_w = max_width
|
| 584 |
+
new_h = int(new_w / aspect_ratio)
|
| 585 |
+
else:
|
| 586 |
+
new_h = max_height
|
| 587 |
+
new_w = int(new_h * aspect_ratio)
|
| 588 |
+
# Ensure dimensions are divisible by VAE scale factors (typically 8 or 16)
|
| 589 |
+
# This is a basic adjustment, model specific patch sizes might also matter.
|
| 590 |
+
patch_size_factor = 16 # Common factor
|
| 591 |
+
new_h = (new_h // patch_size_factor) * patch_size_factor
|
| 592 |
+
new_w = (new_w // patch_size_factor) * patch_size_factor
|
| 593 |
+
if new_h > 0 and new_w > 0:
|
| 594 |
+
image = image.resize((new_w, new_h))
|
| 595 |
+
else: # Fallback if calculations lead to zero
|
| 596 |
+
image = image.resize((max_width//2, max_height//2)) # A smaller safe default
|
| 597 |
+
else:
|
| 598 |
+
patch_size_factor = 16
|
| 599 |
+
h = (h // patch_size_factor) * patch_size_factor
|
| 600 |
+
w = (w // patch_size_factor) * patch_size_factor
|
| 601 |
+
if h > 0 and w > 0:
|
| 602 |
+
image = image.resize((w,h))
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
prompt = "{main_prompt_for_snippet if main_prompt_for_snippet else 'An astronaut in a dynamic scene'}"
|
| 606 |
+
negative_prompt = "worst quality, low quality, blurry" # Simplified
|
| 607 |
+
|
| 608 |
+
output = pipe(
|
| 609 |
+
image=image,
|
| 610 |
+
prompt=prompt,
|
| 611 |
+
negative_prompt=negative_prompt,
|
| 612 |
+
height=image.height, # Use resized image height
|
| 613 |
+
width=image.width, # Use resized image width
|
| 614 |
+
num_frames=30, # Adjust for LoRA
|
| 615 |
+
guidance_scale=5.0 # Adjust as needed
|
| 616 |
+
).frames[0]
|
| 617 |
+
export_to_video(output, "output.mp4", fps=16)
|
| 618 |
+
```
|
| 619 |
+
"""
|
| 620 |
+
else: # Fallback for other video LoRAs
|
| 621 |
+
diffusers_example = f"""
|
| 622 |
+
```py
|
| 623 |
+
# This is a video LoRA. Diffusers usage for video models can vary.
|
| 624 |
+
# You may need to install/import specific pipeline classes from diffusers or the model's community.
|
| 625 |
+
# Below is a generic placeholder.
|
| 626 |
+
import torch
|
| 627 |
+
from diffusers import AutoPipelineForTextToVideo # Or the appropriate video pipeline
|
| 628 |
+
|
| 629 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 630 |
+
|
| 631 |
+
pipeline = AutoPipelineForTextToVideo.from_pretrained('{base_hf_model}', torch_dtype={dtype}).to(device)
|
| 632 |
+
{lora_loader_line}
|
| 633 |
+
|
| 634 |
+
# The following generation command is an example and may need adjustments
|
| 635 |
+
# based on the specific pipeline and its required parameters for '{base_hf_model}'.
|
| 636 |
+
# video_frames = pipeline(prompt='{main_prompt_for_snippet}', num_frames=16).frames
|
| 637 |
+
# For more details, consult the Hugging Face Hub page for {base_hf_model}
|
| 638 |
+
# and the Diffusers documentation on LoRAs and video pipelines.
|
| 639 |
+
```
|
| 640 |
+
"""
|
| 641 |
+
else: # Image model
|
| 642 |
+
diffusers_example = f"""
|
| 643 |
+
```py
|
| 644 |
+
from diffusers import AutoPipelineForText2Image
|
| 645 |
+
import torch
|
| 646 |
+
|
| 647 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 648 |
+
|
| 649 |
+
pipeline = AutoPipelineForText2Image.from_pretrained('{base_hf_model}', torch_dtype={dtype}).to(device)
|
| 650 |
+
{lora_loader_line}
|
| 651 |
+
image = pipeline('{main_prompt_for_snippet}').images[0]
|
| 652 |
+
```
|
| 653 |
+
"""
|
| 654 |
+
|
| 655 |
+
license_map_simple = {
|
| 656 |
+
"Public Domain": "public-domain",
|
| 657 |
+
"CreativeML Open RAIL-M": "creativeml-openrail-m",
|
| 658 |
+
"CreativeML Open RAIL++-M": "creativeml-openrail-m",
|
| 659 |
+
"openrail": "creativeml-openrail-m",
|
| 660 |
+
}
|
| 661 |
+
commercial_use = info.get("allowCommercialUse", "None")
|
| 662 |
+
license_identifier = "other"
|
| 663 |
+
license_name = "bespoke-lora-trained-license"
|
| 664 |
+
|
| 665 |
+
if isinstance(commercial_use, str) and commercial_use.lower() == "none" and not info.get("allowDerivatives", True):
|
| 666 |
+
license_identifier = "creativeml-openrail-m"
|
| 667 |
+
license_name = "CreativeML OpenRAIL-M"
|
| 668 |
+
|
| 669 |
+
bespoke_license_link = f"https://multimodal.art/civitai-licenses?allowNoCredit={info['allowNoCredit']}&allowCommercialUse={commercial_use[0] if isinstance(commercial_use, list) and commercial_use else (commercial_use if isinstance(commercial_use, str) else 'None')}&allowDerivatives={info['allowDerivatives']}&allowDifferentLicense={info['allowDifferentLicense']}"
|
| 670 |
+
|
| 671 |
+
content = f"""---
|
| 672 |
+
license: {license_identifier}
|
| 673 |
+
license_name: "{license_name}"
|
| 674 |
+
license_link: {bespoke_license_link}
|
| 675 |
+
tags:
|
| 676 |
+
- {unpacked_tags}
|
| 677 |
+
|
| 678 |
+
base_model: {base_hf_model}
|
| 679 |
+
instance_prompt: {trained_words[0] if trained_words else ''}
|
| 680 |
+
widget:
|
| 681 |
+
{widget_content.strip()}
|
| 682 |
+
---
|
| 683 |
+
|
| 684 |
+
# {info["name"]}
|
| 685 |
+
|
| 686 |
+
<Gallery />
|
| 687 |
+
|
| 688 |
+
{non_author_disclaimer if not is_author else ''}
|
| 689 |
+
{link_civit_disclaimer if link_civit else ''}
|
| 690 |
+
|
| 691 |
+
## Model description
|
| 692 |
+
{info["description"] if info["description"] else "No description provided."}
|
| 693 |
+
|
| 694 |
+
{trigger_words_section}
|
| 695 |
+
|
| 696 |
+
## Download model
|
| 697 |
+
Weights for this model are available in Safetensors format.
|
| 698 |
+
[Download](/{user_repo_id}/tree/main) them in the Files & versions tab.
|
| 699 |
+
|
| 700 |
+
## Use it with the [🧨 diffusers library](https://github.com/huggingface/diffusers)
|
| 701 |
+
{diffusers_example}
|
| 702 |
+
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)
|
| 703 |
+
"""
|
| 704 |
+
readme_content += content + "\n"
|
| 705 |
+
readme_path = os.path.join(folder, "README.md")
|
| 706 |
+
with open(readme_path, "w", encoding="utf-8") as file:
|
| 707 |
+
file.write(readme_content)
|
| 708 |
+
print(f"README.md created at {readme_path}")
|
| 709 |
+
# print(f"README.md content:\n{readme_content}") # For debugging
|
| 710 |
+
|
| 711 |
+
def get_creator(username):
|
| 712 |
+
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"
|
| 713 |
+
try:
|
| 714 |
+
response = requests.get(url, headers=headers, timeout=10)
|
| 715 |
+
response.raise_for_status()
|
| 716 |
+
return response.json()
|
| 717 |
+
except requests.exceptions.RequestException as e:
|
| 718 |
+
print(f"Error fetching creator data for {username}: {e}")
|
| 719 |
+
gr.Warning(f"Could not verify Civitai creator's HF link: {e}")
|
| 720 |
+
return None
|
| 721 |
+
|
| 722 |
+
|
| 723 |
+
def extract_huggingface_username(username_civitai):
|
| 724 |
+
data = get_creator(username_civitai)
|
| 725 |
+
if not data:
|
| 726 |
+
return None
|
| 727 |
+
|
| 728 |
+
links = data.get('result', {}).get('data', {}).get('json', {}).get('links', [])
|
| 729 |
+
for link in links:
|
| 730 |
+
url = link.get('url', '')
|
| 731 |
+
if 'huggingface.co/' in url:
|
| 732 |
+
# Extract username, handling potential variations like www. or trailing slashes
|
| 733 |
+
hf_username = url.split('huggingface.co/')[-1].split('/')[0]
|
| 734 |
+
if hf_username:
|
| 735 |
+
return hf_username
|
| 736 |
+
return None
|
| 737 |
+
|
| 738 |
+
|
| 739 |
+
def check_civit_link(profile: Optional[gr.OAuthProfile], url: str):
|
| 740 |
+
# Initial return structure: instructions_html, submit_interactive, try_again_visible, other_submit_visible, hunyuan_radio_visible
|
| 741 |
+
# Default to disabling/hiding things if checks fail early
|
| 742 |
+
default_fail_updates = ("", gr.update(interactive=False), gr.update(visible=True), gr.update(visible=False), gr.update(visible=False))
|
| 743 |
+
|
| 744 |
+
if not profile: # Should be handled by demo.load and login button
|
| 745 |
+
return "Please log in with Hugging Face.", gr.update(interactive=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
|
| 746 |
+
|
| 747 |
+
if not url or not url.startswith("https://civitai.com/models/"):
|
| 748 |
+
return "Please enter a valid Civitai model URL.", gr.update(interactive=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
|
| 749 |
+
|
| 750 |
+
try:
|
| 751 |
+
# We need hunyuan_type for extract_info, but we don't know it yet.
|
| 752 |
+
# Call get_json_data first to check if it's Hunyuan.
|
| 753 |
+
json_data_preview = get_json_data(url)
|
| 754 |
+
if not json_data_preview:
|
| 755 |
+
return ("Failed to fetch basic model info from Civitai. Check URL.",
|
| 756 |
+
gr.update(interactive=False), gr.update(visible=True), gr.update(visible=False), gr.update(visible=False))
|
| 757 |
+
|
| 758 |
+
is_hunyuan = False
|
| 759 |
+
original_civitai_base_model = ""
|
| 760 |
+
if json_data_preview.get("type") == "LORA":
|
| 761 |
+
for mv in json_data_preview.get("modelVersions", []):
|
| 762 |
+
# Try to find a relevant model version to check its base model
|
| 763 |
+
# This is a simplified check; extract_info does a more thorough search
|
| 764 |
+
cbm = mv.get("baseModel")
|
| 765 |
+
if cbm and cbm in SUPPORTED_CIVITAI_BASE_MODELS:
|
| 766 |
+
original_civitai_base_model = cbm
|
| 767 |
+
if cbm == "Hunyuan Video":
|
| 768 |
+
is_hunyuan = True
|
| 769 |
+
break
|
| 770 |
+
|
| 771 |
+
# Now call process_url with a default hunyuan_type for other checks
|
| 772 |
+
# The actual hunyuan_type choice will be used during the main upload.
|
| 773 |
+
info, _ = process_url(url, profile, do_download=False, hunyuan_type="Image-to-Video") # Use default for check
|
| 774 |
+
|
| 775 |
+
# If process_url raises an error (e.g. NSFW, not supported), it will be caught by Gradio
|
| 776 |
+
# and displayed as a gr.Error. Here, we assume it passed if no exception.
|
| 777 |
+
|
| 778 |
+
except gr.Error as e: # Catch errors from process_url (like NSFW, not supported)
|
| 779 |
+
return (f"Cannot process this model: {e.message}",
|
| 780 |
+
gr.update(interactive=False), gr.update(visible=True), gr.update(visible=False), gr.update(visible=is_hunyuan)) # Show hunyuan if detected
|
| 781 |
+
except Exception as e: # Catch any other unexpected error during preview
|
| 782 |
+
print(f"Unexpected error in check_civit_link: {e}")
|
| 783 |
+
return (f"An unexpected error occurred: {str(e)}",
|
| 784 |
+
gr.update(interactive=False), gr.update(visible=True), gr.update(visible=False), gr.update(visible=is_hunyuan))
|
| 785 |
+
|
| 786 |
+
|
| 787 |
+
hf_username_on_civitai = extract_huggingface_username(info['creator'])
|
| 788 |
+
|
| 789 |
+
if profile.username in TRUSTED_UPLOADERS:
|
| 790 |
+
return ('Admin/Trusted user override: Upload enabled.',
|
| 791 |
+
gr.update(interactive=True), gr.update(visible=False), gr.update(visible=True), gr.update(visible=is_hunyuan))
|
| 792 |
+
|
| 793 |
+
if not hf_username_on_civitai:
|
| 794 |
+
no_username_text = (f'If you are {info["creator"]} on Civitai, hi! Your CivitAI profile does not seem to have a link to your Hugging Face account. '
|
| 795 |
+
f'Please visit <a href="https://civitai.com/user/account" target="_blank">https://civitai.com/user/account</a>, '
|
| 796 |
+
f'go to "Edit profile" and add your Hugging Face profile URL (e.g., https://huggingface.co/{profile.username}) to the "Links" section. '
|
| 797 |
+
f'<br><img width="60%" src="https://i.imgur.com/hCbo9uL.png" alt="Civitai profile links example"/><br>'
|
| 798 |
+
f'(If you are not {info["creator"]}, you cannot submit their model at this time.)')
|
| 799 |
+
return no_username_text, gr.update(interactive=False), gr.update(visible=True), gr.update(visible=False), gr.update(visible=is_hunyuan)
|
| 800 |
+
|
| 801 |
+
if profile.username.lower() != hf_username_on_civitai.lower():
|
| 802 |
+
unmatched_username_text = (f'Oops! The Hugging Face username found on the CivitAI profile of {info["creator"]} is '
|
| 803 |
+
f'"{hf_username_on_civitai}", but you are logged in as "{profile.username}". '
|
| 804 |
+
f'Please ensure your CivitAI profile links to the correct Hugging Face account: '
|
| 805 |
+
f'<a href="https://civitai.com/user/account" target="_blank">https://civitai.com/user/account</a> (Edit profile -> Links section).'
|
| 806 |
+
f'<br><img width="60%" src="https://i.imgur.com/hCbo9uL.png" alt="Civitai profile links example"/>')
|
| 807 |
+
return unmatched_username_text, gr.update(interactive=False), gr.update(visible=True), gr.update(visible=False), gr.update(visible=is_hunyuan)
|
| 808 |
+
|
| 809 |
+
# All checks passed
|
| 810 |
+
return ('Username verified! You can now upload this model.',
|
| 811 |
+
gr.update(interactive=True), gr.update(visible=False), gr.update(visible=True), gr.update(visible=is_hunyuan))
|
| 812 |
+
|
| 813 |
+
|
| 814 |
+
def swap_fill(profile: Optional[gr.OAuthProfile]):
|
| 815 |
+
if profile is None: # Not logged in
|
| 816 |
+
return gr.update(visible=True), gr.update(visible=False)
|
| 817 |
+
else: # Logged in
|
| 818 |
+
return gr.update(visible=False), gr.update(visible=True)
|
| 819 |
+
|
| 820 |
+
def show_output():
|
| 821 |
+
return gr.update(visible=True)
|
| 822 |
+
|
| 823 |
+
def list_civit_models(username_civitai: str):
|
| 824 |
+
if not username_civitai:
|
| 825 |
+
return ""
|
| 826 |
+
url = f"https://civitai.com/api/v1/models?username={username_civitai}&limit=100&sort=Newest" # Added sort
|
| 827 |
+
|
| 828 |
+
all_model_urls = ""
|
| 829 |
+
page_count = 0
|
| 830 |
+
max_pages = 5 # Limit number of pages to fetch to avoid very long requests
|
| 831 |
+
|
| 832 |
+
while url and page_count < max_pages:
|
| 833 |
+
try:
|
| 834 |
+
response = requests.get(url, timeout=10)
|
| 835 |
+
response.raise_for_status()
|
| 836 |
+
data = response.json()
|
| 837 |
+
except requests.exceptions.RequestException as e:
|
| 838 |
+
print(f"Error fetching model list for {username_civitai}: {e}")
|
| 839 |
+
gr.Warning(f"Could not fetch full model list for {username_civitai}.")
|
| 840 |
+
break
|
| 841 |
+
|
| 842 |
+
items = data.get('items', [])
|
| 843 |
+
if not items:
|
| 844 |
+
break
|
| 845 |
+
|
| 846 |
+
for model in items:
|
| 847 |
+
# Only list LORAs of supported base model types to avoid cluttering with unsupported ones
|
| 848 |
+
is_supported_lora = False
|
| 849 |
+
if model.get("type") == "LORA":
|
| 850 |
+
# Check modelVersions for baseModel compatibility
|
| 851 |
+
for mv in model.get("modelVersions", []):
|
| 852 |
+
if mv.get("baseModel") in SUPPORTED_CIVITAI_BASE_MODELS:
|
| 853 |
+
is_supported_lora = True
|
| 854 |
+
break
|
| 855 |
+
if is_supported_lora:
|
| 856 |
+
model_slug = slugify(model.get("name", f"model-{model['id']}"))
|
| 857 |
+
all_model_urls += f'https://civitai.com/models/{model["id"]}/{model_slug}\n'
|
| 858 |
+
|
| 859 |
+
metadata = data.get('metadata', {})
|
| 860 |
+
url = metadata.get('nextPage', None)
|
| 861 |
+
page_count += 1
|
| 862 |
+
if page_count >= max_pages and url:
|
| 863 |
+
print(f"Reached max page limit for fetching models for {username_civitai}.")
|
| 864 |
+
gr.Info(f"Showing first {max_pages*100} models. There might be more.")
|
| 865 |
+
|
| 866 |
+
if not all_model_urls:
|
| 867 |
+
gr.Info(f"No compatible LoRA models found for user {username_civitai} or user not found.")
|
| 868 |
+
return all_model_urls.strip()
|
| 869 |
+
|
| 870 |
+
|
| 871 |
+
def upload_civit_to_hf(profile: Optional[gr.OAuthProfile], oauth_token: Optional[gr.OAuthToken], url: str, link_civit: bool, hunyuan_type: str):
|
| 872 |
+
if not profile or not profile.username: # Check profile and username
|
| 873 |
+
raise gr.Error("You must be logged in to Hugging Face to upload.")
|
| 874 |
+
if not oauth_token or not oauth_token.token:
|
| 875 |
+
raise gr.Error("Hugging Face authentication token is missing or invalid. Please log out and log back in.")
|
| 876 |
+
|
| 877 |
+
folder = str(uuid.uuid4())
|
| 878 |
+
os.makedirs(folder, exist_ok=True) # exist_ok=True is safer if folder might exist
|
| 879 |
+
|
| 880 |
+
gr.Info(f"Starting processing for model {url}")
|
| 881 |
+
try:
|
| 882 |
+
# Pass hunyuan_type to process_url
|
| 883 |
+
info, downloaded_files_summary = process_url(url, profile, do_download=True, folder=folder, hunyuan_type=hunyuan_type)
|
| 884 |
+
except gr.Error as e: # Catch errors from process_url (NSFW, not supported, API fail)
|
| 885 |
+
# Cleanup created folder if download failed or was skipped
|
| 886 |
+
if os.path.exists(folder):
|
| 887 |
+
try:
|
| 888 |
+
import shutil
|
| 889 |
+
shutil.rmtree(folder)
|
| 890 |
+
except Exception as clean_e:
|
| 891 |
+
print(f"Error cleaning up folder {folder}: {clean_e}")
|
| 892 |
+
raise e # Re-raise the Gradio error to display it
|
| 893 |
+
|
| 894 |
+
if not downloaded_files_summary.get("weightName"):
|
| 895 |
+
raise gr.Error("No model weight file was downloaded. Cannot proceed with upload.")
|
| 896 |
+
|
| 897 |
+
# Determine if user is the author for README generation
|
| 898 |
+
# This relies on extract_huggingface_username which needs COOKIE_INFO
|
| 899 |
+
is_author = False
|
| 900 |
+
if "COOKIE_INFO" in os.environ:
|
| 901 |
+
hf_username_on_civitai = extract_huggingface_username(info['creator'])
|
| 902 |
+
if hf_username_on_civitai and profile.username.lower() == hf_username_on_civitai.lower():
|
| 903 |
+
is_author = True
|
| 904 |
+
elif profile.username.lower() == info['creator'].lower(): # Fallback if cookie not set, direct match
|
| 905 |
+
is_author = True
|
| 906 |
+
|
| 907 |
+
|
| 908 |
+
slug_name = slugify(info["name"])
|
| 909 |
+
user_repo_id = f"{profile.username}/{slug_name}"
|
| 910 |
+
|
| 911 |
+
gr.Info(f"Creating README for {user_repo_id}...")
|
| 912 |
+
create_readme(info, downloaded_files_summary, user_repo_id, link_civit, is_author, folder=folder)
|
| 913 |
+
|
| 914 |
+
try:
|
| 915 |
+
gr.Info(f"Creating repository {user_repo_id} on Hugging Face...")
|
| 916 |
+
create_repo(repo_id=user_repo_id, private=True, exist_ok=True, token=oauth_token.token)
|
| 917 |
+
|
| 918 |
+
gr.Info(f"Starting upload of all files to {user_repo_id}...")
|
| 919 |
+
upload_folder(
|
| 920 |
+
folder_path=folder,
|
| 921 |
+
repo_id=user_repo_id,
|
| 922 |
+
repo_type="model",
|
| 923 |
+
token=oauth_token.token,
|
| 924 |
+
commit_message=f"Upload LoRA: {info['name']} from Civitai model ID {info['modelId']}" # Add commit message
|
| 925 |
+
)
|
| 926 |
+
|
| 927 |
+
gr.Info(f"Setting repository {user_repo_id} to public...")
|
| 928 |
+
update_repo_visibility(repo_id=user_repo_id, private=False, token=oauth_token.token)
|
| 929 |
+
gr.Info(f"Model {info['name']} uploaded successfully to {user_repo_id}!")
|
| 930 |
+
except Exception as e:
|
| 931 |
+
print(f"Error during Hugging Face repo operations for {user_repo_id}: {e}")
|
| 932 |
+
# Attempt to provide a more specific error message for token issues
|
| 933 |
+
if "401" in str(e) or "Unauthorized" in str(e):
|
| 934 |
+
raise gr.Error("Hugging Face authentication failed (e.g. token expired or insufficient permissions). Please log out and log back in with a token that has write permissions.")
|
| 935 |
+
raise gr.Error(f"Error during Hugging Face upload: {str(e)}")
|
| 936 |
+
finally:
|
| 937 |
+
# Clean up the temporary folder
|
| 938 |
+
if os.path.exists(folder):
|
| 939 |
+
try:
|
| 940 |
+
import shutil
|
| 941 |
+
shutil.rmtree(folder)
|
| 942 |
+
print(f"Cleaned up temporary folder: {folder}")
|
| 943 |
+
except Exception as clean_e:
|
| 944 |
+
print(f"Error cleaning up folder {folder}: {clean_e}")
|
| 945 |
+
|
| 946 |
+
return f"""# Model uploaded to 🤗!
|
| 947 |
+
Access it here: [{user_repo_id}](https://huggingface.co/{user_repo_id})
|
| 948 |
+
"""
|
| 949 |
+
|
| 950 |
+
def bulk_upload(profile: Optional[gr.OAuthProfile], oauth_token: Optional[gr.OAuthToken], urls_text: str, link_civit: bool, hunyuan_type: str):
|
| 951 |
+
if not urls_text.strip():
|
| 952 |
+
return "No URLs provided for bulk upload."
|
| 953 |
+
|
| 954 |
+
urls = [url.strip() for url in urls_text.split("\n") if url.strip()]
|
| 955 |
+
if not urls:
|
| 956 |
+
return "No valid URLs found in the input."
|
| 957 |
+
|
| 958 |
+
upload_results_md = "## Bulk Upload Results:\n\n"
|
| 959 |
+
success_count = 0
|
| 960 |
+
failure_count = 0
|
| 961 |
+
|
| 962 |
+
for i, url in enumerate(urls):
|
| 963 |
+
gr.Info(f"Processing URL {i+1}/{len(urls)}: {url}")
|
| 964 |
+
try:
|
| 965 |
+
result = upload_civit_to_hf(profile, oauth_token, url, link_civit, hunyuan_type)
|
| 966 |
+
upload_results_md += f"**SUCCESS**: {url}\n{result}\n\n---\n\n"
|
| 967 |
+
success_count +=1
|
| 968 |
+
except gr.Error as e: # Catch Gradio-raised errors (expected failures)
|
| 969 |
+
upload_results_md += f"**FAILED**: {url}\n*Reason*: {e.message}\n\n---\n\n"
|
| 970 |
+
gr.Warning(f"Failed to upload {url}: {e.message}")
|
| 971 |
+
failure_count +=1
|
| 972 |
+
except Exception as e: # Catch unexpected Python errors
|
| 973 |
+
upload_results_md += f"**FAILED**: {url}\n*Unexpected Error*: {str(e)}\n\n---\n\n"
|
| 974 |
+
gr.Warning(f"Unexpected error uploading {url}: {str(e)}")
|
| 975 |
+
failure_count +=1
|
| 976 |
+
|
| 977 |
+
summary = f"Finished bulk upload: {success_count} successful, {failure_count} failed."
|
| 978 |
+
gr.Info(summary)
|
| 979 |
+
upload_results_md = f"## {summary}\n\n" + upload_results_md
|
| 980 |
+
return upload_results_md
|
| 981 |
+
|
| 982 |
+
# --- Gradio UI ---
|
| 983 |
+
css = '''
|
| 984 |
+
#login_button_row button { /* Target login button specifically */
|
| 985 |
+
width: 100% !important;
|
| 986 |
+
margin: 0 auto;
|
| 987 |
+
}
|
| 988 |
+
#disabled_upload_area { /* ID for the disabled area */
|
| 989 |
+
opacity: 0.5;
|
| 990 |
+
pointer-events: none;
|
| 991 |
+
}
|
| 992 |
+
'''
|
| 993 |
+
|
| 994 |
+
with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo: # Added a theme
|
| 995 |
+
gr.Markdown('''# Upload your CivitAI LoRA to Hugging Face 🤗
|
| 996 |
+
By uploading your LoRAs to Hugging Face you get diffusers compatibility, a free GPU-based Inference Widget (for many models)
|
| 997 |
+
''')
|
| 998 |
+
|
| 999 |
+
with gr.Row(elem_id="login_button_row"):
|
| 1000 |
+
login_button = gr.LoginButton() # Moved login_button definition here
|
| 1001 |
+
|
| 1002 |
+
# Area shown when not logged in (or login fails)
|
| 1003 |
+
with gr.Column(elem_id="disabled_upload_area", visible=True) as disabled_area:
|
| 1004 |
+
gr.HTML("<i>Please log in with Hugging Face to enable uploads.</i>")
|
| 1005 |
+
# Add some dummy placeholders to mirror the enabled_area structure if needed for consistent layout
|
| 1006 |
+
gr.Textbox(label="CivitAI model URL (Log in to enable)", interactive=False)
|
| 1007 |
+
gr.Button("Upload (Log in to enable)", interactive=False)
|
| 1008 |
+
|
| 1009 |
+
# Area shown when logged in
|
| 1010 |
+
with gr.Column(visible=False) as enabled_area:
|
| 1011 |
+
with gr.Row():
|
| 1012 |
+
submit_source_civit_enabled = gr.Textbox(
|
| 1013 |
+
placeholder="https://civitai.com/models/144684/pixelartredmond-pixel-art-loras-for-sd-xl",
|
| 1014 |
+
label="CivitAI model URL",
|
| 1015 |
+
info="URL of the CivitAI LoRA model page.",
|
| 1016 |
+
elem_id="submit_source_civit_main" # Unique ID
|
| 1017 |
+
)
|
| 1018 |
+
|
| 1019 |
+
hunyuan_type_radio = gr.Radio(
|
| 1020 |
+
choices=["Image-to-Video", "Text-to-Video"],
|
| 1021 |
+
label="HunyuanVideo Type (Select if model is Hunyuan Video)",
|
| 1022 |
+
value="Image-to-Video", # Default as per prompt
|
| 1023 |
+
visible=False, # Initially hidden
|
| 1024 |
+
interactive=True
|
| 1025 |
+
)
|
| 1026 |
+
|
| 1027 |
+
link_civit_checkbox = gr.Checkbox(label="Link back to original CivitAI page in README?", value=False)
|
| 1028 |
+
|
| 1029 |
+
with gr.Accordion("Bulk Upload (Multiple LoRAs)", open=False):
|
| 1030 |
+
civit_username_to_bulk = gr.Textbox(
|
| 1031 |
+
label="Your CivitAI Username (Optional)",
|
| 1032 |
+
info="Type your CivitAI username here to automatically populate the list below with your compatible LoRAs."
|
| 1033 |
+
)
|
| 1034 |
+
submit_bulk_civit_urls = gr.Textbox(
|
| 1035 |
+
label="CivitAI Model URLs (One per line)",
|
| 1036 |
+
info="Add one CivitAI model URL per line for bulk processing.",
|
| 1037 |
+
lines=6,
|
| 1038 |
+
)
|
| 1039 |
+
bulk_button = gr.Button("Start Bulk Upload")
|
| 1040 |
+
|
| 1041 |
+
instructions_html = gr.HTML("") # For messages from check_civit_link
|
| 1042 |
+
|
| 1043 |
+
# Buttons for single upload
|
| 1044 |
+
# try_again_button is shown if username check fails
|
| 1045 |
+
try_again_button_single = gr.Button("I've updated my CivitAI profile, check again", visible=False)
|
| 1046 |
+
# submit_button_single is the main upload button for single model
|
| 1047 |
+
submit_button_single = gr.Button("Upload Model to Hugging Face", interactive=False, variant="primary")
|
| 1048 |
+
|
| 1049 |
+
output_markdown = gr.Markdown(label="Upload Progress & Results", visible=False)
|
| 1050 |
+
|
| 1051 |
+
# Event Handling
|
| 1052 |
+
# When login status changes (login_button implicitly handles profile state for demo.load)
|
| 1053 |
+
# demo.load updates visibility of disabled_area and enabled_area based on login.
|
| 1054 |
+
# The `profile` argument is implicitly passed by Gradio to functions that declare it.
|
| 1055 |
+
# `oauth_token` is also implicitly passed if `login_button` is used and function expects `gr.OAuthToken`.
|
| 1056 |
+
|
| 1057 |
+
# When URL changes in the enabled area
|
| 1058 |
+
submit_source_civit_enabled.change(
|
| 1059 |
+
fn=check_civit_link,
|
| 1060 |
+
inputs=[submit_source_civit_enabled], # profile is implicitly passed
|
| 1061 |
+
outputs=[instructions_html, submit_button_single, try_again_button_single, submit_button_single, hunyuan_type_radio],
|
| 1062 |
+
# Outputs map to: instructions, submit_interactive, try_again_visible, (submit_visible - seems redundant here, check_civit_link logic ensures one is visible), hunyuan_radio_visible
|
| 1063 |
+
# For submit_button_single: 2nd output controls 'interactive', 4th controls 'visible' (often paired with try_again_button's visibility)
|
| 1064 |
+
)
|
| 1065 |
+
|
| 1066 |
+
# Try again button for single upload (re-checks the same URL)
|
| 1067 |
+
try_again_button_single.click(
|
| 1068 |
+
fn=check_civit_link,
|
| 1069 |
+
inputs=[submit_source_civit_enabled],
|
| 1070 |
+
outputs=[instructions_html, submit_button_single, try_again_button_single, submit_button_single, hunyuan_type_radio],
|
| 1071 |
+
)
|
| 1072 |
+
|
| 1073 |
+
# Autofill bulk URLs from CivitAI username
|
| 1074 |
+
civit_username_to_bulk.change(
|
| 1075 |
+
fn=list_civit_models,
|
| 1076 |
+
inputs=[civit_username_to_bulk],
|
| 1077 |
+
outputs=[submit_bulk_civit_urls]
|
| 1078 |
+
)
|
| 1079 |
+
|
| 1080 |
+
# Single model upload button click
|
| 1081 |
+
submit_button_single.click(fn=show_output, outputs=[output_markdown]).then(
|
| 1082 |
+
fn=upload_civit_to_hf,
|
| 1083 |
+
inputs=[submit_source_civit_enabled, link_civit_checkbox, hunyuan_type_radio], # profile, oauth_token implicit
|
| 1084 |
+
outputs=[output_markdown]
|
| 1085 |
+
)
|
| 1086 |
+
|
| 1087 |
+
# Bulk model upload button click
|
| 1088 |
+
bulk_button.click(fn=show_output, outputs=[output_markdown]).then(
|
| 1089 |
+
fn=bulk_upload,
|
| 1090 |
+
inputs=[submit_bulk_civit_urls, link_civit_checkbox, hunyuan_type_radio], # profile, oauth_token implicit
|
| 1091 |
+
outputs=[output_markdown]
|
| 1092 |
+
)
|
| 1093 |
+
|
| 1094 |
+
# Initial state of visible areas based on login status
|
| 1095 |
+
demo.load(fn=swap_fill, outputs=[disabled_area, enabled_area], queue=False)
|
| 1096 |
+
|
| 1097 |
+
demo.queue(default_concurrency_limit=5) # Reduced concurrency from 50, can be demanding
|
| 1098 |
+
demo.launch(debug=True) # Added debug=True for development
|