Spaces:
Sleeping
Update app.py
Browse filesTrying to get it to work, sorry my commit messages are slack
Key Changes and Explanations:
CSS Styling:
The CSS is now correctly passed as a string to the css parameter of gr.Blocks().
I've added an elem_id="main-container" to a gr.Column that wraps the input components and the button. This is important because the CSS targets #main-container to control the layout. Without this, the CSS wouldn't apply correctly.
Markdown Content:
The Markdown content is integrated using gr.Markdown().
I've made some minor formatting improvements:
Used more specific headings (e.g., "### ๐ฅ Input Sources Supported:").
Used bold text (**) to highlight important points (like "CPU" and "WRITE").
Added Markdown links for the Hugging Face token page, the GitHub repository, and the Ko-fi page. The format is [Link Text](URL).
gr.Column: Using a gr.Column with elem_id="main-container" is crucial for applying the CSS that controls the layout (making the button stick to the bottom).
No other code changes: Functionality remains the same.
Key Changes in this Complete Code:
cached_download Import Removed: The unnecessary import of cached_download is removed.
get_from_cache Used Correctly: The download_model function now correctly uses get_from_cache to check for cached URLs.
Manual Download and Caching: If a URL is not cached, the code downloads it using requests, determines a filename, and saves it to the standard Hugging Face cache directory (HUGGINGFACE_HUB_CACHE).
HF Cache dir: Downloads now go to the correct HF cache, inside a subfolder called "downloads".
HUGGINGFACE_HUB_CACHE Imported: The constant for the cache directory is imported.
12 unmodified lines131415161718192021222324252627282930313233343536373839404142433 unmodified lines474849505152535455561 unmodified line5859606162631 unmodified line65666768697071727374757677787 unmodified lines868788899091929394959615 unmodified lines1121131141151161171186 unmodified lines1251261271281291301311321334 unmodified lines1381391401411421431441451461471481491501511521531541 unmodified line15615715815916016116216315 unmodified lines1791801811821831841851861871 unmodified line1891901911921931941951961971981992002012022032042052062072082094 unmodified lines2142152162172182193 unmodified lines22322422522622722822923023123223323423523623723823924024124224312 unmodified linesfrom urllib.parse import urlparse, unquotefrom pathlib import Pathimport tempfile#from tqdm import tqdm # Removed as not crucial and can break display in gradio.import psutilimport mathimport shutilimport hashlibfrom datetime import datetimefrom typing import Dict, List, Optionalfrom huggingface_hub import login, HfApi, hf_hub_download # Import hf_hub_downloadfrom huggingface_hub.utils import validate_repo_id, HFValidationErrorfrom huggingface_hub.errors import HfHubHTTPErrorfrom huggingface_hub import HfApi, hf_hub_download, cached_download, get_from_cache # Import cached_download and get_from_cachefrom huggingface_hub.utils import validate_repo_id, HFValidationErrorfrom huggingface_hub.constants import HUGGINGFACE_HUB_CACHE# ---------------------- DEPENDENCIES ----------------------def install_dependencies_gradio():"""Installs the necessary dependencies."""try:subprocess.run(["pip", "install", "-U", "torch", "diffusers", "transformers", "accelerate", "safetensors", "huggingface_hub", "xformers"])print("Dependencies installed successfully.")except Exception as e:print(f"Error installing dependencies: {e}")# ---------------------- UTILITY FUNCTIONS ----------------------def increment_filename(filename):"""Increments the filename to avoid overwriting existing files."""base, ext = os.path.splitext(filename)3 unmodified linescounter += 1return filename# ---------------------- UPLOAD FUNCTION ----------------------def create_model_repo(api, user, orgs_name, model_name, make_private=False):"""Creates a Hugging Face model repository."""repo_id = f"{orgs_name}/{model_name.strip()}" if orgs_name else f"{user['name']}/{model_name.strip()}"try:api.create_repo(repo_id=repo_id, repo_type="model", private=make_private)print(f"Model repo '{repo_id}' created.")1 unmodified lineprint(f"Model repo '{repo_id}' already exists.")return repo_id# ---------------------- MODEL LOADING AND CONVERSION ----------------------def download_model(model_path_or_url):"""Downloads a model, handling URLs, HF repos, and local paths, caching appropriately."""1 unmodified line# 1. Check if it's a valid Hugging Face repo ID (and potentially a file within)try:validate_repo_id(model_path_or_url)# It's a valid repo ID; use hf_hub_downloadlocal_path = hf_hub_download(repo_id=model_path_or_url)return local_pathexcept HFValidationError:pass # Not a simple repo ID. Might be repo ID + filename, or a URL.# 2. Check if it's a URLif model_path_or_url.startswith("http://") or model_path_or_url.startswith("https://"):# Check if it's already in the cachecache_path = get_from_cache(model_path_or_url) # Use get_from_cacheif cache_path is not None:7 unmodified linesparsed_url = urlparse(model_path_or_url)filename = os.path.basename(unquote(parsed_url.path))if not filename:filename = hashlib.sha256(model_path_or_url.encode()).hexdigest()# Construct the cache path (using HF_HUB_CACHE + "downloads" )cache_dir = os.path.join(HUGGINGFACE_HUB_CACHE, "downloads")os.makedirs(cache_dir, exist_ok=True) # Ensure the cache directory existslocal_path = os.path.join(cache_dir, filename)with open(local_path, "wb") as f:15 unmodified lineslocal_path = hf_hub_download(repo_id=repo_id, filename=filename)return local_pathelse:raise ValueError("Invalid input format.")except HFValidationError:raise ValueError(f"Invalid model path or URL: {model_path_or_url}")6 unmodified lines"""Loads an SDXL checkpoint (.ckpt or .safetensors) and returns components."""if checkpoint_path.endswith(".safetensors"):state_dict = load_file(checkpoint_path, device="cpu")elif checkpoint_path.endswith(".ckpt"):state_dict = torch.load(checkpoint_path, map_location="cpu")["state_dict"]else:raise ValueError("Unsupported checkpoint format. Must be .safetensors or .ckpt")4 unmodified linesfor key, value in state_dict.items():if key.startswith("first_stage_model."): # VAEvae_state[key.replace("first_stage_model.", "")] = value.to(torch.float16)elif key.startswith("condition_model.model.text_encoder."): # Text Encoder 1text_encoder1_state[key.replace("condition_model.model.text_encoder.", "")] = value.to(torch.float16)elif key.startswith("condition_model.model.text_encoder_2."): # Text Encoder 2text_encoder2_state[key.replace("condition_model.model.text_encoder_2.", "")] = value.to(torch.float16)elif key.startswith("model.diffusion_model."): # UNetunet_state[key.replace("model.diffusion_model.", "")] = value.to(torch.float16)return text_encoder1_state, text_encoder2_state, vae_state, unet_statedef build_diffusers_model(text_encoder1_state, text_encoder2_state, vae_state, unet_state, reference_model_path=None):"""Builds the Diffusers pipeline components from the loaded state dicts."""# Default to SDXL base 1.0 if no reference model is provided1 unmodified linereference_model_path = "stabilityai/stable-diffusion-xl-base-1.0"# 1. Text Encodersconfig_text_encoder1 = CLIPTextConfig.from_pretrained(reference_model_path, subfolder="text_encoder")config_text_encoder2 = CLIPTextConfig.from_pretrained(reference_model_path, subfolder="text_encoder_2")text_encoder1 = CLIPTextModel(config_text_encoder1)text_encoder2 = CLIPTextModel(config_text_encoder2)15 unmodified linesreturn text_encoder1, text_encoder2, vae, unetdef convert_and_save_sdxl_to_diffusers(checkpoint_path_or_url, output_path, reference_model_path):"""Converts an SDXL checkpoint to Diffusers format and saves it.Args:checkpoint_path_or_url: The path/URL/repo ID of the checkpoint."""1 unmodified line# Download the model if necessary (handles URLs, repo IDs, and local paths)checkpoint_path = download_model(checkpoint_path_or_url)text_encoder1_state, text_encoder2_state, vae_state, unet_state = load_sdxl_checkpoint(checkpoint_path)text_encoder1, text_encoder2, vae, unet = build_diffusers_model(text_encoder1_state, text_encoder2_state, vae_state, unet_state, reference_model_path)# Load tokenizer and scheduler from the reference modelpipeline = StableDiffusionXLPipeline.from_pretrained(reference_model_path,text_encoder=text_encoder1,text_encoder_2=text_encoder2,vae=vae,unet=unet,torch_dtype=torch.float16,)pipeline.to("cpu")pipeline.save_pretrained(output_path)print(f"Model saved as Diffusers format: {output_path}")# ---------------------- UPLOAD FUNCTION ----------------------def upload_to_huggingface(model_path, hf_token, orgs_name, model_name, make_private):"""Uploads a model to the Hugging Face Hub."""4 unmodified linesapi.upload_folder(folder_path=model_path, repo_id=model_repo)print(f"Model uploaded to: https://huggingface.co/{model_repo}")# ---------------------- GRADIO INTERFACE ----------------------def main(model_to_load, reference_model, output_path, hf_token, orgs_name, model_name, make_private):"""Main function: SDXL checkpoint to Diffusers, always fp16."""3 unmodified linesupload_to_huggingface(output_path, hf_token, orgs_name, model_name, make_private)return "Conversion and upload completed successfully!"except Exception as e:return f"An error occurred: {e}" # Return the error messagewith gr.Blocks() as demo:model_to_load = gr.Textbox(label="SDXL Checkpoint (Path, URL, or HF Repo)", placeholder="Path, URL, or Hugging Face Repo ID (e.g., my-org/my-model or my-org/my-model/file.safetensors)")reference_model = gr.Textbox(label="Reference Diffusers Model (Optional)", placeholder="e.g., stabilityai/stable-diffusion-xl-base-1.0 (Leave blank for default)")output_path = gr.Textbox(label="Output Path (Diffusers Format)", value="output") # Default changed to "output"hf_token = gr.Textbox(label="Hugging Face Token", placeholder="Your Hugging Face write token")orgs_name = gr.Textbox(label="Organization Name (Optional)", placeholder="Your organization name")model_name = gr.Textbox(label="Model Name", placeholder="The name of your model on Hugging Face")make_private = gr.Checkbox(label="Make Repository Private", value=False)convert_button = gr.Button("Convert and Upload")output = gr.Markdown()convert_button.click(fn=main, inputs=[model_to_load, reference_model, output_path, hf_token, orgs_name, model_name, make_private], outputs=output)demo.launch()12 unmodified lines1314151617181920212223242526272829303132333435363738394041424344454647484950515253545556573 unmodified lines6162636465666768697071727374751 unmodified line777879808182831 unmodified line8586878889909192939495969798991007 unmodified lines10810911011111211311411511611711815 unmodified lines1341351361371381391406 unmodified lines1471481491501511521531541551561574 unmodified lines1621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951 unmodified line19719819920020120220320420520620720815 unmodified lines2242252262272282292302312322332341 unmodified line2362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652664 unmodified lines2712722732742752762773 unmodified lines28128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037112 unmodified linesfrom urllib.parse import urlparse, unquotefrom pathlib import Pathimport tempfile# from tqdm import tqdm # Removed: not crucial and can break display in gradio.import psutilimport mathimport shutilimport hashlibfrom datetime import datetimefrom typing import Dict, List, Optionalfrom huggingface_hub import login, HfApi, hf_hub_download, get_from_cache # Corrected importfrom huggingface_hub.utils import validate_repo_id, HFValidationErrorfrom huggingface_hub.errors import HfHubHTTPErrorfrom huggingface_hub.constants import HUGGINGFACE_HUB_CACHE # Import HUGGINGFACE_HUB_CACHE# ---------------------- DEPENDENCIES ----------------------def install_dependencies_gradio():"""Installs the necessary dependencies."""try:subprocess.run(["pip","install","-U","torch","diffusers","transformers","accelerate","safetensors","huggingface_hub","xformers",])print("Dependencies installed successfully.")except Exception as e:print(f"Error installing dependencies: {e}")# ---------------------- UTILITY FUNCTIONS ----------------------def increment_filename(filename):"""Increments the filename to avoid overwriting existing files."""base, ext = os.path.splitext(filename)3 unmodified linescounter += 1return filename# ---------------------- UPLOAD FUNCTION ----------------------def create_model_repo(api, user, orgs_name, model_name, make_private=False):"""Creates a Hugging Face model repository."""repo_id = (f"{orgs_name}/{model_name.strip()}"if orgs_nameelse f"{user['name']}/{model_name.strip()}")try:api.create_repo(repo_id=repo_id, repo_type="model", private=make_private)print(f"Model repo '{repo_id}' created.")1 unmodified lineprint(f"Model repo '{repo_id}' already exists.")return repo_id# ---------------------- MODEL LOADING AND CONVERSION ----------------------def download_model(model_path_or_url):"""Downloads a model, handling URLs, HF repos, and local paths, caching appropriately."""1 unmodified line# 1. Check if it's a valid Hugging Face repo ID (and potentially a file within)try:validate_repo_id(model_path_or_url)# It's a valid repo ID; use hf_hub_download (it handles caching)local_path = hf_hub_download(repo_id=model_path_or_url)return local_pathexcept HFValidationError:pass # Not a simple repo ID. Might be repo ID + filename, or a URL.# 2. Check if it's a URLif model_path_or_url.startswith("http://") or model_path_or_url.startswith("https://"):# Check if it's already in the cachecache_path = get_from_cache(model_path_or_url) # Use get_from_cacheif cache_path is not None:7 unmodified linesparsed_url = urlparse(model_path_or_url)filename = os.path.basename(unquote(parsed_url.path))if not filename:filename = hashlib.sha256(model_path_or_url.encode()).hexdigest()# Construct the cache path (using HF_HUB_CACHE + "downloads")cache_dir = os.path.join(HUGGINGFACE_HUB_CACHE, "downloads")os.makedirs(cache_dir, exist_ok=True) # Ensure cache directory existslocal_path = os.path.join(cache_dir, filename)with open(local_path, "wb") as f:15 unmodified lineslocal_path = hf_hub_download(repo_id=repo_id, filename=filename)return local_pathelse:raise ValueError("Invalid input format.")except HFValidationError:raise ValueError(f"Invalid model path or URL: {model_path_or_url}")6 unmodified lines"""Loads an SDXL checkpoint (.ckpt or .safetensors) and returns components."""if checkpoint_path.endswith(".safetensors"):state_dict = load_file(checkpoint_path, device="cpu") # Load to CPUelif checkpoint_path.endswith(".ckpt"):state_dict = torch.load(checkpoint_path, map_location="cpu")["state_dict"] # Load to CPU, access ["state_dict"]else:raise ValueError("Unsupported checkpoint format. Must be .safetensors or .ckpt")4 unmodified linesfor key, value in state_dict.items():if key.startswith("first_stage_model."): # VAEvae_state[key.replace("first_stage_model.", "")] = value.to(torch.float16) # FP16 conversionelif key.startswith("condition_model.model.text_encoder."): # Text Encoder 1text_encoder1_state[key.replace("condition_model.model.text_encoder.", "")] = value.to(torch.float16) # FP16elif key.startswith("condition_model.model.text_encoder_2."): # Text Encoder 2text_encoder2_state[key.replace("condition_model.model.text_encoder_2.", "")] = value.to(torch.float16) # FP16elif key.startswith("model.diffusion_model."): # UNetunet_state[key.replace("model.diffusion_model.", "")] = value.to(torch.float16) # FP16return text_encoder1_state, text_encoder2_state, vae_state, unet_statedef build_diffusers_model(text_encoder1_state, text_encoder2_state, vae_state, unet_state, reference_model_path=None):"""Builds the Diffusers pipeline components from the loaded state dicts."""# Default to SDXL base 1.0 if no reference model is provided1 unmodified linereference_model_path = "stabilityai/stable-diffusion-xl-base-1.0"# 1. Text Encodersconfig_text_encoder1 = CLIPTextConfig.from_pretrained(reference_model_path, subfolder="text_encoder")config_text_encoder2 = CLIPTextConfig.from_pretrained(reference_model_path, subfolder="text_encoder_2")text_encoder1 = CLIPTextModel(config_text_encoder1)text_encoder2 = CLIPTextModel(config_text_encoder2)15 unmodified linesreturn text_encoder1, text_encoder2, vae, unetdef convert_and_save_sdxl_to_diffusers(checkpoint_path_or_url, output_path, reference_model_path):"""Converts an SDXL checkpoint to Diffusers format and saves it.Args:checkpoint_path_or_url: The path/URL/repo ID of the checkpoint."""1 unmodified line# Download the model if necessary (handles URLs, repo IDs, and local paths)checkpoint_path = download_model(checkpoint_path_or_url)text_encoder1_state, text_encoder2_state, vae_state, unet_state = (load_sdxl_checkpoint(checkpoint_path))text_encoder1, text_encoder2, vae, unet = build_diffusers_model(text_encoder1_state,text_encoder2_state,vae_state,unet_state,reference_model_path,)# Load tokenizer and scheduler from the reference modelpipeline = StableDiffusionXLPipeline.from_pretrained(reference_model_path,text_encoder=text_encoder1,text_encoder_2=text_encoder2,vae=vae,unet=unet,torch_dtype=torch.float16,)pipeline.to("cpu")pipeline.save_pretrained(output_path)print(f"Model saved as Diffusers format: {output_path}")# ---------------------- UPLOAD FUNCTION ----------------------def upload_to_huggingface(model_path, hf_token, orgs_name, model_name, make_private):"""Uploads a model to the Hugging Face Hub."""4 unmodified linesapi.upload_folder(folder_path=model_path, repo_id=model_repo)print(f"Model uploaded to: https://huggingface.co/{model_repo}")# ---------------------- GRADIO INTERFACE ----------------------def main(model_to_load, reference_model, output_path, hf_token, orgs_name, model_name, make_private):"""Main function: SDXL checkpoint to Diffusers, always fp16."""3 unmodified linesupload_to_huggingface(output_path, hf_token, orgs_name, model_name, make_private)return "Conversion and upload completed successfully!"except Exception as e:return f"An error occurred: {e}" # Return the error messagecss = """#main-container {display: flex;flex-direction: column;height: 100vh;justify-content: space-between;font-family: 'Arial', sans-serif;font-size: 16px;color: #333;}#convert-button {margin-top: auto;}"""with gr.Blocks(css=css) as demo:gr.Markdown("""# ๐จ SDXL Model ConverterConvert SDXL checkpoints to Diffusers format (FP16, CPU-only).### ๐ฅ Input Sources Supported:- Local model files (.safetensors, .ckpt)- Direct URLs to model files- Hugging Face model repositories (e.g., 'my-org/my-model' or 'my-org/my-model/file.safetensors')### โน๏ธ Important Notes:- This tool runs on **CPU**, conversion might be slower than on GPU.- For Hugging Face uploads, you need a **WRITE** token (not a read token).- Get your HF token here: [https://huggingface.co/settings/tokens](https://huggingface.co/settings/tokens)### ๐พ Memory Usage:- This space is configured for **FP16** precision to reduce memory usage.- Close other applications during conversion.- For large models, ensure you have at least 16GB of RAM.### ๐ป Source Code:- [GitHub Repository](https://github.com/Ktiseos-Nyx/Gradio-SDXL-Diffusers)### ๐ Support:- If you're interested in funding more projects: [Ko-fi](https://ko-fi.com/duskfallcrew)""")with gr.Column(elem_id="main-container"): # Use a Column for layoutmodel_to_load = gr.Textbox(label="SDXL Checkpoint (Path, URL, or HF Repo)",placeholder="Path, URL, or Hugging Face Repo ID (e.g., my-org/my-model or my-org/my-model/file.safetensors)",)reference_model = gr.Textbox(label="Reference Diffusers Model (Optional)",placeholder="e.g., stabilityai/stable-diffusion-xl-base-1.0 (Leave blank for default)",)output_path = gr.Textbox(label="Output Path (Diffusers Format)", value="output") # Default changed to "output"hf_token = gr.Textbox(label="Hugging Face Token", placeholder="Your Hugging Face write token")orgs_name = gr.Textbox(label="Organization Name (Optional)", placeholder="Your organization name")model_name = gr.Textbox(label="Model Name", placeholder="The name of your model on Hugging Face")make_private = gr.Checkbox(label="Make Repository Private", value=False)convert_button = gr.Button("Convert and Upload", elem_id="convert-button")output = gr.Markdown()convert_button.click(fn=main,inputs=[model_to_load,reference_model,output_path,hf_token,orgs_name,model_name,make_private,],outputs=output,)demo.launch()