Spaces:
Runtime error
Runtime error
Update app.py
Browse files2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495966 unmodified lines1031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202216 unmodified lines2282292302312322332342352362372382392 unmodified linesimport torchfrom PIL import Imageimport spacesfrom diffusers import DiffusionPipeline, AutoencoderTiny, AutoencoderKL, AutoPipelineForImage2Imagefrom live_preview_helpers import calculate_shift, retrieve_timesteps, flux_pipe_call_that_returns_an_iterable_of_imagesfrom diffusers.utils import load_imageimport pandas as pdimport randomimport time# --- Configuration Principale ---KRYPTO_LORA = {"repo": "Econogoat/Krypt0_LORA","trigger": "Krypt0","adapter_name": "krypt0"}# Charger les prompts pour le bouton de randomisationdf = pd.read_csv('prompts.csv', header=None)prompt_values = df.values.flatten()# Récupérer le token d'accès depuis les secrets du SpaceHF_TOKEN = os.getenv("HF_TOKEN")if not HF_TOKEN:print("AVERTISSEMENT : Le secret HF_TOKEN n'est pas défini. Le téléchargement de modèles protégés peut échouer.")# --- Initialisation des Modèles ---dtype = torch.bfloat16device = "cuda" if torch.cuda.is_available() else "cpu"base_model = "black-forest-labs/FLUX.1-dev"print("Chargement du taef1 (VAE rapide)...")taef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype).to(device)print("Chargement du good_vae (VAE de qualité)...")good_vae = AutoencoderKL.from_pretrained(base_model, subfolder="vae", torch_dtype=dtype, token=HF_TOKEN).to(device)print("Chargement du pipeline de base (Text-to-Image)...")pipe = DiffusionPipeline.from_pretrained(base_model, torch_dtype=dtype, vae=taef1, token=HF_TOKEN).to(device)print("Chargement du pipeline Image-to-Image...")pipe_i2i = AutoPipelineForImage2Image.from_pretrained(base_model,vae=good_vae,transformer=pipe.transformer,text_encoder=pipe.text_encoder,tokenizer=pipe.tokenizer,text_encoder_2=pipe.text_encoder_2,tokenizer_2=pipe.tokenizer_2,torch_dtype=dtype,token=HF_TOKEN)print("Pipelines chargés.")# Charger le LoRA une seule fois au démarrage de l'applicationprint(f"Chargement du LoRA intégré : {KRYPTO_LORA['repo']}")pipe.load_lora_weights(KRYPTO_LORA['repo'],low_cpu_mem_usage=True,adapter_name=KRYPTO_LORA['adapter_name'])# --- CORRECTION APPLIQUÉE ---# L'appel ci-dessous a été supprimé. Il n'est pas nécessaire car `pipe` et `pipe_i2i`# partagent le même `transformer`. Charger le LoRA une fois suffit pour les deux.# pipe_i2i.load_lora_weights(...)print("LoRA chargé avec succès et disponible pour les deux pipelines.")MAX_SEED = 2**32 - 1pipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)def calculate_dimensions(aspect_ratio, resolution):resolution = int(resolution)if aspect_ratio == "Carré (1:1)":width, height = resolution, resolutionelif aspect_ratio == "Portrait (9:16)":width, height = int(resolution * 9 / 16), resolutionelif aspect_ratio == "Paysage (16:9)":width, height = resolution, int(resolution * 9 / 16)elif aspect_ratio == "Ultra-large (21:9)":width, height = resolution, int(resolution * 9 / 21)else:width, height = resolution, resolutionwidth = (width // 64) * 64height = (height // 64) * 64return width, heightdef generate_image(prompt_mash, steps, seed, cfg_scale, width, height, progress):pipe.to("cuda")generator = torch.Generator(device="cuda").manual_seed(seed)image_generator = pipe.flux_pipe_call_that_returns_an_iterable_of_images(prompt=prompt_mash,6 unmodified linesoutput_type="pil",good_vae=good_vae,)final_image = Nonestep_counter = 0for image in image_generator:step_counter += 1final_image = imageprogress_bar = f'<div class="progress-container"><div class="progress-bar" style="--current: {step_counter}; --total: {steps};"></div></div>'yield image, gr.update(value=progress_bar, visible=True)yield final_image, gr.update(value=progress_bar, visible=False)def generate_image_to_image(prompt_mash, image_input_path, image_strength, steps, cfg_scale, width, height, seed):pipe_i2i.to("cuda")generator = torch.Generator(device="cuda").manual_seed(seed)image_input = load_image(image_input_path)final_image = pipe_i2i(prompt=prompt_mash,image=image_input,strength=image_strength,num_inference_steps=steps,guidance_scale=cfg_scale,width=width,height=height,generator=generator,joint_attention_kwargs={"scale": 1.0},output_type="pil",).images[0]return final_imagedef update_history(new_image, history):if history is None:history = []history.insert(0, new_image)return history@spaces.GPU(duration=75)def run_generation(prompt, image_input, image_strength, lora_scale, cfg_scale, steps, randomize_seed, seed, aspect_ratio, base_resolution, progress=gr.Progress(track_tqdm=True)):prompt_mash = f"{KRYPTO_LORA['trigger']}, {prompt}"print("Prompt final : ", prompt_mash)# Activer l'adaptateur LoRA pour les deux pipelines# C'est correct, chaque pipeline doit être configuré pour utiliser l'adaptateur lors de la génération.pipe.set_adapters([KRYPTO_LORA['adapter_name']], adapter_weights=[lora_scale])pipe_i2i.set_adapters([KRYPTO_LORA['adapter_name']], adapter_weights=[lora_scale])print(f"Adaptateur '{KRYPTO_LORA['adapter_name']}' activé avec un poids de {lora_scale}.")if randomize_seed:seed = random.randint(0, MAX_SEED)width, height = calculate_dimensions(aspect_ratio, base_resolution)print(f"Génération d'une image de {width}x{height} pixels.")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:for image, progress_update in generate_image(prompt_mash, steps, seed, cfg_scale, width, height, progress):yield image, seed, progress_updaterun_generation.zerogpu = True# --- Interface Utilisateur (Gradio) ---css = '''#gen_btn{height: 100%}#title{text-align: center}#title h1{font-size: 3em; display:inline-flex; align-items:center}#title img{width: 80px; margin-right: 0.25em}.progress-container {width: 100%;height: 30px;background-color: #f0f0f0;border-radius: 15px;overflow: hidden;margin-bottom: 20px}.progress-bar {height: 100%;background-color: #4f46e5;width: calc(var(--current) / var(--total) * 100%);transition: width 0.1s ease-in-out}'''with gr.Blocks(css=css, theme=gr.themes.Soft()) as app:with gr.Row():gr.HTML("""<div id='title'><h1><img src="https://huggingface.co/Econogoat/Krypt0_LORA/resolve/main/krypt0.png" alt="LoRA"> Krypt0 Image Generator</h1><br><span>Générez des images avec le style artistique Krypt0</span></div>""")with gr.Row():with gr.Column(scale=3):with gr.Group():with gr.Row():prompt = gr.Textbox(label="Prompt", lines=2, placeholder="Ex: a portrait of a warrior queen")random_prompt_btn = gr.Button("🎲", size="sm")lora_scale = gr.Slider(label="Force du style Krypt0", minimum=0, maximum=2, step=0.05, value=0.9)with gr.Accordion("Paramètres de l'image et de la génération", open=True):aspect_ratio = gr.Radio(label="Ratio de l'image",choices=["Carré (1:1)", "Portrait (9:16)", "Paysage (16:9)", "Ultra-large (21:9)"],value="Carré (1:1)")base_resolution = gr.Slider(label="Résolution (côté le plus long)", minimum=768, maximum=1408, step=64, value=1024)steps = gr.Slider(label="Étapes de génération", minimum=4, maximum=50, step=1, value=20)cfg_scale = gr.Slider(label="Guidage (CFG Scale)", minimum=1, maximum=10, step=0.5, value=3.5)with gr.Row():randomize_seed = gr.Checkbox(True, label="Graine aléatoire")seed = gr.Slider(label="Graine (Seed)", minimum=0, maximum=MAX_SEED, step=1, value=0)with gr.Accordion("Image-to-Image (Optionnel)", open=False):input_image = gr.Image(label="Image d'entrée", type="filepath", show_share_button=False)image_strength = gr.Slider(label="Force du débruitage", info="Plus la valeur est basse, plus l'image originale est préservée.", minimum=0.1, maximum=1.0, step=0.01, value=0.75)generate_button = gr.Button("Générer", variant="primary")with gr.Column(scale=2):progress_bar = gr.Markdown(elem_id="progress", visible=False)result = gr.Image(label="Image Générée", interactive=False, show_share_button=True, elem_id="result_image")with gr.Accordion("Historique", open=False):history_gallery = gr.Gallery(label="Historique", columns=4, object_fit="contain", interactive=False)def get_random_prompt():return random.choice(prompt_values)6 unmodified linesgeneration_event = gr.on(triggers=[generate_button.click, prompt.submit],fn=run_generation,inputs=[prompt, input_image, image_strength, lora_scale, cfg_scale, steps, randomize_seed, seed, aspect_ratio, base_resolution],outputs=[result, seed, progress_bar])generation_event.then(fn=lambda x, history: update_history(x, history),inputs=[result, history_gallery],outputs=history_gallery,)2 unmodified lines3456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081826 unmodified lines89909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891906 unmodified lines1971981992002012022032042052062072082 unmodified linesimport torchfrom PIL import Imageimport spacesfrom diffusers import DiffusionPipeline, AutoencoderTiny, AutoencoderKLfrom live_preview_helpers import calculate_shift, retrieve_timesteps, flux_pipe_call_that_returns_an_iterable_of_imagesfrom diffusers.utils import load_imageimport pandas as pdimport randomimport time# --- Main Configuration ---KRYPTO_LORA = {"repo": "Econogoat/Krypt0_LORA","trigger": "Krypt0","adapter_name": "krypt0"}# Load prompts for the randomize buttondf = pd.read_csv('prompts.csv', header=None)prompt_values = df.values.flatten()# Get access token from Space secretsHF_TOKEN = os.getenv("HF_TOKEN")if not HF_TOKEN:print("WARNING: HF_TOKEN secret is not set. Gated model downloads may fail.")# --- Model Initialization ---device = "cuda" if torch.cuda.is_available() else "cpu"print(f"Using device: {device}")dtype = torch.bfloat16base_model = "black-forest-labs/FLUX.1-dev"# Load model componentsprint("Loading model components...")taef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype).to(device)good_vae = AutoencoderKL.from_pretrained(base_model, subfolder="vae", torch_dtype=dtype, token=HF_TOKEN).to(device)pipe = DiffusionPipeline.from_pretrained(base_model, torch_dtype=dtype, vae=taef1, token=HF_TOKEN).to(device)print("Models loaded.")# Load the LoRA adapter once on startupprint(f"Loading on-board LoRA: {KRYPTO_LORA['repo']}")pipe.load_lora_weights(KRYPTO_LORA['repo'],low_cpu_mem_usage=True,adapter_name=KRYPTO_LORA['adapter_name'])print("LoRA loaded successfully.")MAX_SEED = 2**32 - 1# Monkey-patch the pipeline for live previewpipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)def calculate_dimensions(aspect_ratio, resolution):"""Calculates width and height based on aspect ratio and base resolution."""resolution = int(resolution)if aspect_ratio == "Square (1:1)":width, height = resolution, resolutionelif aspect_ratio == "Portrait (9:16)":width, height = int(resolution * 9 / 16), resolutionelif aspect_ratio == "Landscape (16:9)":width, height = resolution, int(resolution * 9 / 16)elif aspect_ratio == "Ultrawide (21:9)":width, height = resolution, int(resolution * 9 / 21)else: # Fallbackwidth, height = resolution, resolution# Ensure dimensions are multiples of 64 for optimal performancewidth = (width // 64) * 64height = (height // 64) * 64return width, heightdef generate_image(prompt_mash, steps, seed, cfg_scale, width, height, progress):"""Generator function for text-to-image with live preview."""# The parent @spaces.GPU function has already allocated a GPUpipe.to(device)generator = torch.Generator(device=device).manual_seed(seed)image_generator = pipe.flux_pipe_call_that_returns_an_iterable_of_images(prompt=prompt_mash,6 unmodified linesoutput_type="pil",good_vae=good_vae,)# Yield previews and the final imagefinal_image = Nonefor i, image in enumerate(image_generator):final_image = imageprogress_bar = f'<div class="progress-container"><div class="progress-bar" style="--current: {i + 1}; --total: {steps};"></div></div>'yield image, gr.update(value=progress_bar, visible=True)yield final_image, gr.update(visible=False)def update_history(new_image, history):"""Adds the new image to the history gallery."""if new_image is None: # Don't add empty images on errorreturn historyif history is None:history = []history.insert(0, new_image)return history@spaces.GPU(duration=75)def run_generation(prompt, lora_scale, cfg_scale, steps, randomize_seed, seed, aspect_ratio, base_resolution, progress=gr.Progress(track_tqdm=True)):if not prompt:raise gr.Error("Prompt cannot be empty.")prompt_mash = f"{KRYPTO_LORA['trigger']}, {prompt}"print("Final prompt:", prompt_mash)# Activate the LoRA adapter with the slider's weightpipe.set_adapters([KRYPTO_LORA['adapter_name']], adapter_weights=[lora_scale])print(f"Adapter '{KRYPTO_LORA['adapter_name']}' activated with weight {lora_scale}.")if randomize_seed:seed = random.randint(0, MAX_SEED)width, height = calculate_dimensions(aspect_ratio, base_resolution)print(f"Generating a {width}x{height} image.")# The function now only handles text-to-imagefor image, progress_update in generate_image(prompt_mash, steps, seed, cfg_scale, width, height, progress):yield image, seed, progress_updaterun_generation.zerogpu = True# --- User Interface (Gradio) ---css = '''#title{text-align: center}#title h1{font-size: 3em; display:inline-flex; align-items:center}#title img{width: 80px; margin-right: 0.25em}.progress-container {width: 100%;height: 30px;background-color: #f0f0f0;border-radius: 15px;overflow: hidden;margin-bottom: 20px}.progress-bar {height: 100%;background-color: #4f46e5;width: calc(var(--current) / var(--total) * 100%);transition: width 0.1s ease-in-out}#random_prompt_btn{max-width: 2.5em; min-width: 2.5em !important; height: 100% !important;}'''with gr.Blocks(css=css, theme=gr.themes.Soft()) as app:# --- Header ---with gr.Row():gr.HTML("""<div id='title'><h1><img src="https://huggingface.co/Econogoat/KRYPTO_LORA/resolve/main/krypt0.png" alt="LoRA"> Krypt0 Image Generator</h1><br><span>Generate images with the Krypt0 artistic style</span></div>""")with gr.Row():# --- LEFT COLUMN: CONTROLS ---with gr.Column(scale=3):# Prompt and Style Controlswith gr.Group():with gr.Row():random_prompt_btn = gr.Button("🎲", elem_id="random_prompt_btn")prompt = gr.Textbox(label="Prompt", lines=2, placeholder="e.g., a portrait of a warrior queen", scale=8)lora_scale = gr.Slider(label="Krypt0 Style Strength", minimum=0, maximum=2, step=0.05, value=0.9)# Image Shape Controlsaspect_ratio = gr.Radio(label="Aspect Ratio",choices=["Square (1:1)", "Portrait (9:16)", "Landscape (16:9)", "Ultrawide (21:9)"],value="Square (1:1)")# Advanced Settingswith gr.Accordion("Advanced Settings", open=True):base_resolution = gr.Slider(label="Resolution (longest side)", minimum=768, maximum=1408, step=64, value=1024)steps = gr.Slider(label="Generation Steps", minimum=4, maximum=50, step=1, value=20)cfg_scale = gr.Slider(label="Guidance (CFG Scale)", minimum=1, maximum=10, step=0.5, value=3.5)with gr.Row():randomize_seed = gr.Checkbox(True, label="Random Seed")seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)generate_button = gr.Button("Generate", variant="primary")# --- RIGHT COLUMN: RESULTS ---with gr.Column(scale=2):progress_bar = gr.Markdown(elem_id="progress", visible=False)result = gr.Image(label="Generated Image", interactive=False, show_share_button=True)with gr.Accordion("History", open=False):history_gallery = gr.Gallery(label="History", columns=4, object_fit="contain", interactive=False)# --- Event Logic ---def get_random_prompt():return random.choice(prompt_values)6 unmodified linesgeneration_event = gr.on(triggers=[generate_button.click, prompt.submit],fn=run_generation,inputs=[prompt, lora_scale, cfg_scale, steps, randomize_seed, seed, aspect_ratio, base_resolution],outputs=[result, seed, progress_bar])generation_event.then(fn=update_history,inputs=[result, history_gallery],outputs=history_gallery,)
app.py+74-105