import os
import gradio as gr
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
import pandas as pd
import random
import time
# --- Configuration Principale ---
KRYPTO_LORA = {
"repo": "Econogoat/Krypt0_LORA",
"trigger": "Krypt0",
"adapter_name": "krypt0"
}
# Charger les prompts pour le bouton de randomisation
df = pd.read_csv('prompts.csv', header=None)
prompt_values = df.values.flatten()
# Récupérer le token d'accès depuis les secrets du Space
HF_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.bfloat16
device = "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'application
print(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 - 1
pipe.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, resolution
elif aspect_ratio == "Portrait (9:16)":
width, height = int(resolution * 9 / 16), resolution
elif 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, resolution
width = (width // 64) * 64
height = (height // 64) * 64
return width, height
def 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,
num_inference_steps=steps,
guidance_scale=cfg_scale,
width=width,
height=height,
generator=generator,
joint_attention_kwargs={"scale": 1.0},
output_type="pil",
good_vae=good_vae,
)
final_image = None
step_counter = 0
for image in image_generator:
step_counter += 1
final_image = image
progress_bar = f'
'
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_image
def 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_update
run_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(
"""
Krypt0 Image Generator
Générez des images avec le style artistique Krypt0 """
)
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)
random_prompt_btn.click(
fn=get_random_prompt,
inputs=[],
outputs=[prompt]
)
generation_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,
)
app.queue(max_size=20)
app.launch()