import os
import gradio as gr
import json
import logging
import torch
from PIL import Image
import spaces
from diffusers import DiffusionPipeline, AutoencoderTiny, AutoencoderKL, AutoPipelineForImage2Image
from live_preview_helpers import calculate_shift, retrieve_timesteps, flux_pipe_call_that_returns_an_iterable_of_images
from diffusers.utils import load_image
from huggingface_hub import hf_hub_download, HfFileSystem, ModelCard, snapshot_download
import copy
import random
import time
import requests
import pandas as pd
def download_file(url, directory=None):
if directory is None:
directory = os.getcwd() # Use current working directory if not specified
Assistant
The error you're encountering is due to the black-forest-labs/FLUX.1-dev model not having a recognizable model type or lacking a model_type key in its config.json. The transformers library uses the model_type to determine which model class to instantiate, and it seems the model you're trying to load isn't recognized by default.
User
ok can you give me the config.json file content i can use that would work and then provide me the path where it should be stored to be aclled properly
Assistant
code
# Get the filename from the URL
filename = url.split('/')[-1]
# Full path for the downloaded file
filepath = os.path.join(directory, filename)
# Download the file
response = requests.get(url)
response.raise_for_status() # Raise an exception for bad status codes
# Write the content to the file
with open(filepath, 'wb') as file:
file.write(response.content)
return filepath
def update_selection(evt: gr.SelectData, selected_indices, loras_state, width, height):
selected_index = evt.index
selected_indices = selected_indices or []
if selected_index in selected_indices:
selected_indices.remove(selected_index)
else:
if len(selected_indices) < 2:
selected_indices.append(selected_index)
else:
gr.Warning("You can select up to 2 LoRAs, remove one to select a new one.")
return gr.update(), gr.update(), gr.update(), selected_indices, gr.update(), gr.update(), width, height, gr.update(), gr.update()
code
selected_info_1 = "Select a LoRA 1"
selected_info_2 = "Select a LoRA 2"
lora_scale_1 = 1.15
lora_scale_2 = 1.15
lora_image_1 = None
lora_image_2 = None
if len(selected_indices) >= 1:
lora1 = loras_state[selected_indices[0]]
selected_info_1 = f"### LoRA 1 Selected: [{lora1['title']}](https://huggingface.co/{lora1['repo']}) ✨"
lora_image_1 = lora1['image']
if len(selected_indices) >= 2:
lora2 = loras_state[selected_indices[1]]
selected_info_2 = f"### LoRA 2 Selected: [{lora2['title']}](https://huggingface.co/{lora2['repo']}) ✨"
lora_image_2 = lora2['image']
if selected_indices:
last_selected_lora = loras_state[selected_indices[-1]]
new_placeholder = f"Type a prompt for {last_selected_lora['title']}"
else:
new_placeholder = "Type a prompt after selecting a LoRA"
return gr.update(placeholder=new_placeholder), selected_info_1, selected_info_2, selected_indices, lora_scale_1, lora_scale_2, width, height, lora_image_1, lora_image_2
@spaces.GPU(duration=75)
def run_lora(prompt, image_input, image_strength, cfg_scale, steps, selected_indices, lora_scale_1, lora_scale_2, randomize_seed, seed, width, height, loras_state, progress=gr.Progress(track_tqdm=True)):
if not selected_indices:
raise gr.Error("You must select at least one LoRA before proceeding.")
code
selected_loras = [loras_state[idx] for idx in selected_indices]
# Build the prompt with trigger words
prepends = []
appends = []
for lora in selected_loras:
trigger_word = lora.get('trigger_word', '')
if trigger_word:
if lora.get("trigger_position") == "prepend":
prepends.append(trigger_word)
else:
appends.append(trigger_word)
prompt_mash = " ".join(prepends + [prompt] + appends)
print("Prompt Mash: ", prompt_mash)
# Unload previous LoRA weights
with calculateDuration("Unloading LoRA"):
pipe.unload_lora_weights()
pipe_i2i.unload_lora_weights()
print(pipe.get_active_adapters())
# Load LoRA weights with respective scales
lora_names = []
lora_weights = []
with calculateDuration("Loading LoRA weights"):
for idx, lora in enumerate(selected_loras):
lora_name = f"lora_{idx}"
lora_names.append(lora_name)
print(f"Lora Name: {lora_name}")
lora_weights.append(lora_scale_1 if idx == 0 else lora_scale_2)
lora_path = lora['repo']
weight_name = lora.get("weights")
print(f"Lora Path: {lora_path}")
pipe_to_use = pipe_i2i if image_input is not None else pipe
pipe_to_use.load_lora_weights(
lora_path,
weight_name=weight_name if weight_name else None,
low_cpu_mem_usage=True,
adapter_name=lora_name
)
if image_input is not None: pipe_i2i = pipe_to_use
else: pipe = pipe_to_use
code
print("Loaded LoRAs:", lora_names)
print("Adapter weights:", lora_weights)
if image_input is not None:
pipe_i2i.set_adapters(lora_names, adapter_weights=lora_weights)
else:
pipe.set_adapters(lora_names, adapter_weights=lora_weights)
print(pipe.get_active_adapters())
# Set random seed for reproducibility
with calculateDuration("Randomizing seed"):
if randomize_seed:
seed = random.randint(0, MAX_SEED)
# Generate image
if image_input is not None:
final_image = generate_image_to_image(prompt_mash, image_input, image_strength, steps, cfg_scale, width, height, seed)
yield final_image, seed, gr.update(visible=False)
else:
image_generator = generate_image(prompt_mash, steps, seed, cfg_scale, width, height, progress)
# Consume the generator to get the final image
final_image = None
step_counter = 0
for image in image_generator:
step_counter += 1
final_image = image
progress_bar = f'<div class="progress-container"><div class="progress-bar" style="--current: {step_counter}; --total: {steps};"></div></div>'
yield image, seed, gr.update(value=progress_bar, visible=True)
yield final_image, seed, gr.update(value=progress_bar, visible=False)
run_lora.zerogpu = True
def get_huggingface_safetensors(link):
split_link = link.split("/")
if len(split_link) == 2:
model_card = ModelCard.load(link)
base_model = model_card.data.get("base_model")
print(f"Base model: {base_model}")
if base_model not in ["black-forest-labs/FLUX.1-dev", "black-forest-labs/FLUX.1-schnell"]:
raise Exception("Not a FLUX LoRA!")
image_path = model_card.data.get("widget", [{}])[0].get("output", {}).get("url", None)
trigger_word = model_card.data.get("instance_prompt", "")
image_url = f"https://huggingface.co/{link}/resolve/main/{image_path}" if image_path else None
fs = HfFileSystem()
safetensors_name = None
try:
list_of_files = fs.ls(link, detail=False)
for file in list_of_files:
if file.endswith(".safetensors"):
safetensors_name = file.split("/")[-1]
if not image_url and file.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
image_elements = file.split("/")
image_url = f"https://huggingface.co/{link}/resolve/main/{image_elements[-1]}"
except Exception as e:
print(e)
raise gr.Error("Invalid Hugging Face repository with a *.safetensors LoRA")
if not safetensors_name:
raise gr.Error("No *.safetensors file found in the repository")
return split_link[1], link, safetensors_name, trigger_word, image_url
else:
raise gr.Error("Invalid Hugging Face repository link")
def check_custom_model(link):
if link.endswith(".safetensors"):
# Treat as direct link to the LoRA weights
title = os.path.basename(link)
repo = link
path = None # No specific weight name
trigger_word = ""
image_url = None
return title, repo, path, trigger_word, image_url
elif link.startswith("https://"):
if "huggingface.co" in link:
link_split = link.split("huggingface.co/")
return get_huggingface_safetensors(link_split[1])
else:
raise Exception("Unsupported URL")
else:
# Assume it's a Hugging Face model path
return get_huggingface_safetensors(link)
def update_history(new_image, history):
"""Updates the history gallery with the new image."""
if history is None:
history = []
history.insert(0, new_image)
return history
in from_pretrained
config, kwargs = AutoConfig.from_pretrained(
File "/home/completeexcavation/tts_env/lib/python3.9/site-packages/transformers/models/auto/configuration_auto.py", line 1049, in from_pretrained
raise ValueError(
ValueError: Unrecognized model in black-forest-labs/FLUX.1-dev. Should have a model_type key in its config.json, or contain one of the following strings in its name: albert, align, altclip, audio-spectrogram-transformer, autoformer, bark, bart, beit, bert, bert-generation, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot-small, blip, blip-2, blo
To resolve this issue, you have a few options:
Check config.json: Verify that the config.json file of the black-forest-labs/FLUX.1-dev model contains a model_type field. If it's missing, you can manually edit the config.json to include an appropriate model_type.
Use a Custom Model Class:
If this model uses a custom architecture, you may need to define a custom class that extends a base model class from transformers. You can then load this custom class with the model weights.
Contact the Model Provider:
If you are working with a model provided by someone else (like black-forest-labs), you might want to contact them to ensure that the model is intended for use with the transformers library and check if you are using the right identifier for the model.
Check Repository Content:
Ensure that the model repository on Hugging Face is properly structured with the necessary files (config.json, model weights, etc.). The absence of these files, or incorrect formatting, can lead to such errors.
Verify Compatibility:
Ensure that the transformers version you're using is compatible with the model. Check if any updated version of the library provides support for this model or architecture.
Load the Model Differently:
You can attempt to load the model using a different library or method if the model type is not supported by the transformers library. This usually involves writing more custom loading and inference logic, which can be cumbersome but is a fallback method.
Reviewing the structure and the config.json of the black-forest-labs/FLUX.1-dev model is a good starting point because it would help you determine if there is a misconfiguration or missing keys that transformers relies upon.
To create a suitable config.json file for a model in the Hugging Face transformers library, you usually need to include necessary fields like model_type, architectures, and other hyperparameters relevant to the specific model architecture. Since black-forest-labs/FLUX.1-dev is not a standard model recognized by transformers, you'll need to customize based on what the model actually implements.
Here's a basic template you can start with. You'll need to replace the placeholders with appropriate values matching the architecture of your model if you have these specifics:
json
{
"model_type": "your_model_type", // e.g., "bert", "gpt2", etc.
"architectures": [
"YourModelArchitecture"
],
"hidden_size": 768, // Adjust based on your model's architecture
"num_attention_heads": 12, // Adjust based on your model
"num_hidden_layers": 12, // Adjust based on your model
"vocab_size": 30522, // Adjust based on your tokenizer
"max_position_embeddings": 512, // Adjust if your model supports longer sequences
// Include other necessary hyperparameters specific to your model
}
Explanation of Fields:
model_type: This should correspond to the type of model you are using. Standard options include "bert", "gpt2", "roberta", etc. You'll need to enter a custom value if your model doesn't match these but know it might require additional setup in transformers.
architectures: This specifies which architecture class transformers should use to initialize the model.
hidden_size, num_attention_heads, num_hidden_layers: These should be set according to the architecture you're implementing (e.g., sizes specific to Transformer architectures).
vocab_size, max_position_embeddings: These should correspond to the size of the vocabulary your tokenizer can handle and the maximum number of positions the model supports, respectively.
Storage:
Once you've crafted this config.json file to match your model's design, it should be stored in the root of your model directory. If you are using a huggingface model repository, the config.json should be placed directly under the model's directory when you're downloading it to your local environment.
Path:
For usage within transformers, it generally searches for config.json in your model's root directory when using from_pretrained(). You can ensure this by verifying the path from where you're loading with AutoModel.from_pretrained("path/to/your/model"), and having the config.json in that base path.
Remember, this is a blueprint to get you started. You might need to tailor the values based on the intended structure and interactions within your given model architecture. If this model is experimental or custom beyond typical Transformer types, substantial adaptation might be required, possibly involving modifications to the transformers library and defining your own model class implementations.