Spaces:
Runtime error
Runtime error
Update app.py
Browse files5 unmodified lines678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364653 unmodified lines69707172737475767778798081826 unmodified lines8990919293942 unmodified lines9798991001011021034 unmodified lines1081091101111121131141151161171181191201211223 unmodified lines1261271281291301311 unmodified line13313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119212 unmodified lines2052062072082092105 unmodified linesfrom 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 time# --- Configuration Principale ---KRYPTO_LORA = {"repo": "Econogoat/Krypt0_LORA","trigger": "Krypt0","adapter_name": "krypt0"}MAX_SEED = 2**32 - 1# --- Lazy Loading Setup ---pipe = Nonegood_vae = Nonetaef1 = Nonedtype = torch.bfloat16base_model = "black-forest-labs/FLUX.1-dev"# Récupérer le token d'accès depuis les secrets du SpaceHF_TOKEN = os.getenv("HF_TOKEN")def load_models():"""Charge tous les modèles et les place sur le GPU.N'est appelée qu'une seule fois, depuis un contexte GPU."""global pipe, good_vae, taef1if pipe is not None:returnprint("Performing first-time setup: loading all models directly to GPU...")taef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype).to("cuda")good_vae = AutoencoderKL.from_pretrained(base_model, subfolder="vae", torch_dtype=dtype, token=HF_TOKEN).to("cuda")pipe = DiffusionPipeline.from_pretrained(base_model,torch_dtype=dtype,vae=taef1,token=HF_TOKEN).to("cuda")print(f"Loading on-board LoRA: {KRYPTO_LORA['repo']}")pipe.load_lora_weights(KRYPTO_LORA['repo'],adapter_name=KRYPTO_LORA['adapter_name'],token=HF_TOKEN)pipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)print("Models loaded and ready on GPU.")def calculate_dimensions(aspect_ratio, resolution):resolution = int(resolution)if aspect_ratio == "Square (1:1)":width, height = resolution, resolution3 unmodified lineswidth, height = resolution, int(resolution * 9 / 16)elif aspect_ratio == "Ultrawide (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):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 = Nonefor i, image in enumerate(image_generator):final_image = image2 unmodified linesyield final_image, gr.update(visible=False)def update_history(new_image, history):if new_image is None:return historyif history is None:history = []4 unmodified linesdef 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.")load_models()hidden_prompt_main = "Krypt0 the white scruffy superdog with a red cape"hidden_prompt_style = "cinematic, ultra-high-detail, photorealistic still"prompt_mash = f"{KRYPTO_LORA['trigger']}, {prompt}, {hidden_prompt_main}, {hidden_prompt_style}"print("Final prompt sent to model:", prompt_mash)pipe.set_adapters([KRYPTO_LORA['adapter_name']], adapter_weights=[lora_scale])print(f"Adapter '{KRYPTO_LORA['adapter_name']}' activated with weight {lora_scale}.")3 unmodified lineswidth, height = calculate_dimensions(aspect_ratio, base_resolution)print(f"Generating a {width}x{height} image.")for image, progress_update in generate_image(prompt_mash, steps, seed, cfg_scale, width, height, progress):yield image, seed, progress_update1 unmodified line# --- User Interface (Gradio) ---css = '''#title_container { text-align: center; margin-bottom: 1em; }#title_line { display: flex; justify-content: center; align-items: center; }#title_line img { width: 70px; margin-right: 0.5em; }#title_line h1 { font-size: 2.5em; margin: 0; }#subtitle { font-size: 1.1em; color: #57606a; margin-top: 0.3em; }.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:# --- Header ---gr.HTML("""<div id="title_container"><div id="title_line"><img src="/file=logo.png" alt="Krypt0 Logo"><h1>Krypto Image Generator - beta v1</h1></div><div id="subtitle">Powered by $Krypto | @Kryptocoinonsol</div></div>""")with gr.Row():# --- LEFT COLUMN: CONTROLS ---with gr.Column(scale=3):with gr.Group():# MODIFICATION : Mise à jour du placeholderprompt = gr.Textbox(label="Prompt",lines=2,placeholder="Krypto the superdog sits in the snow, with snow on his muzzle, looking innocent. It's a medium shot of the dog, and the image creates a friendly atmosphere.")# Image Shape and Style Controlswith gr.Group():aspect_ratio = gr.Radio(label="Aspect Ratio",choices=["Square (1:1)", "Portrait (9:16)", "Landscape (16:9)", "Ultrawide (21:9)"],value="Square (1:1)")lora_scale = gr.Slider(label="Krypt0 Style Strength",minimum=0,maximum=2,step=0.05,value=0.9,info="Controls how strongly the artistic style is applied. Higher values mean a more stylized image.")# Advanced Settingswith gr.Accordion("Advanced Settings", open=False):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)12 unmodified lineshistory_gallery = gr.Gallery(label="History", columns=4, object_fit="contain", interactive=False)# --- Event Logic ---generation_event = gr.on(triggers=[generate_button.click, prompt.submit],fn=run_generation,5 unmodified lines6789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960613 unmodified lines6566676869707172737475767778798081826 unmodified lines899091929394952 unmodified lines98991001011021031041054 unmodified lines1101111121131141151161171181191203 unmodified lines1241251261271281291301 unmodified line13213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117212 unmodified lines1851861871881891901911921931941951961971981995 unmodified linesfrom 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, resolution3 unmodified lineswidth, 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 = image2 unmodified linesyield 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 = []4 unmodified linesdef 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}.")3 unmodified lineswidth, 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_update1 unmodified line# --- 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)12 unmodified lineshistory_gallery = gr.Gallery(label="History", columns=4, object_fit="contain", interactive=False)# --- Event Logic ---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,
app.py+80-91