Spaces:
Running on Zero
Running on Zero
update app
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354import spacesimport gradio as grimport torchfrom PIL import Imagefrom diffusers import DiffusionPipelineimport randomimport uuidfrom typing import Union, List, Optionalimport numpy as npimport timeimport zipfileimport osimport requestsfrom urllib.parse import urlparseimport tempfileimport shutilfrom typing import Iterabledef save_image(img):unique_name = str(uuid.uuid4()) + ".png"img.save(unique_name)return unique_namedef randomize_seed_fn(seed: int, randomize_seed: bool) -> int:if randomize_seed:seed = random.randint(0, MAX_SEED)return seedMAX_SEED = np.iinfo(np.int32).maxMAX_IMAGE_SIZE = 2048# Load Qwen/Qwen-Image pipelinedtype = torch.bfloat16device = torch.device("cuda" if torch.cuda.is_available() else "cpu")# --- Model Loading ---pipe_qwen = DiffusionPipeline.from_pretrained("Qwen/Qwen-Image", torch_dtype=dtype).to(device)# Aspect ratiosaspect_ratios = {"1:1": (1328, 1328),"16:9": (1664, 928),"9:16": (928, 1664),"4:3": (1472, 1140),"3:4": (1140, 1472)}def load_lora_opt(pipe, lora_input):lora_input = lora_input.strip()if not lora_input:return# If it's just an ID like "author/model"if "/" in lora_input and not lora_input.startswith("http"):pipe.load_lora_weights(lora_input, adapter_name="default")returnif lora_input.startswith("http"):url = lora_input# Repo page (no blob/resolve)if "huggingface.co" in url and "/blob/" not in url and "/resolve/" not in url:repo_id = urlparse(url).path.strip("/")pipe.load_lora_weights(repo_id, adapter_name="default")return# Blob link → convert to resolve linkif "/blob/" in url:url = url.replace("/blob/", "/resolve/")# Download direct filetmp_dir = tempfile.mkdtemp()local_path = os.path.join(tmp_dir, os.path.basename(urlparse(url).path))try:print(f"Downloading LoRA from {url}...")resp = requests.get(url, stream=True)resp.raise_for_status()with open(local_path, "wb") as f:for chunk in resp.iter_content(chunk_size=8192):f.write(chunk)print(f"Saved LoRA to {local_path}")pipe.load_lora_weights(local_path, adapter_name="default")finally:shutil.rmtree(tmp_dir, ignore_errors=True)# Generation function for Qwen/Qwen-Image@spaces.GPU(duration=120)def generate_qwen(prompt: str,negative_prompt: str = "",seed: int = 0,width: int = 1024,height: int = 1024,guidance_scale: float = 4.0,randomize_seed: bool = False,num_inference_steps: int = 50,num_images: int = 1,zip_images: bool = False,lora_input: str = "",lora_scale: float = 1.0,progress=gr.Progress(track_tqdm=True),):if randomize_seed:seed = random.randint(0, MAX_SEED)generator = torch.Generator(device).manual_seed(seed)start_time = time.time()current_adapters = pipe_qwen.get_list_adapters()for adapter in current_adapters:pipe_qwen.delete_adapters(adapter)pipe_qwen.disable_lora()use_lora = Falseif lora_input and lora_input.strip() != "":load_lora_opt(pipe_qwen, lora_input)pipe_qwen.set_adapters(["default"], adapter_weights=[lora_scale])use_lora = Trueimages = pipe_qwen(prompt=prompt,negative_prompt=negative_prompt if negative_prompt else "",height=height,width=width,guidance_scale=guidance_scale,num_inference_steps=num_inference_steps,num_images_per_prompt=num_images,generator=generator,output_type="pil",).imagesend_time = time.time()duration = end_time - start_timeimage_paths = [save_image(img) for img in images]zip_path = Noneif zip_images:zip_name = str(uuid.uuid4()) + ".zip"with zipfile.ZipFile(zip_name, 'w') as zipf:for i, img_path in enumerate(image_paths):zipf.write(img_path, arcname=f"Img_{i}.png")zip_path = zip_name# Clean up adapterscurrent_adapters = pipe_qwen.get_list_adapters()for adapter in current_adapters:pipe_qwen.delete_adapters(adapter)pipe_qwen.disable_lora()return image_paths, seed, f"{duration:.2f}", zip_path# Wrapper function to handle UI logic@spaces.GPU(duration=120)def generate(prompt: str,negative_prompt: str,use_negative_prompt: bool,seed: int,width: int,height: int,guidance_scale: float,randomize_seed: bool,num_inference_steps: int,num_images: int,zip_images: bool,lora_input: str,lora_scale: float,progress=gr.Progress(track_tqdm=True),):final_negative_prompt = negative_prompt if use_negative_prompt else ""return generate_qwen(prompt=prompt,negative_prompt=final_negative_prompt,seed=seed,width=width,height=height,guidance_scale=guidance_scale,randomize_seed=randomize_seed,num_inference_steps=num_inference_steps,num_images=num_images,zip_images=zip_images,lora_input=lora_input,lora_scale=lora_scale,progress=progress,)# Examplesexamples = ["A decadent slice of layered chocolate cake on a ceramic plate with a drizzle of chocolate syrup and powdered sugar dusted on top. photographed from a slightly low angle with high resolution, natural soft lighting, rich contrast, shallow depth of field, and professional color grading to highlight the dessert’s textures --ar 85:128 --v 6.0 --style raw","A beautifully decorated round chocolate birthday cake with rich chocolate frosting and elegant piping, topped with the name 'Qwen' written in white icing. placed on a wooden cake stand with scattered chocolate shavings around, softly lit with natural light, high resolution, professional food photography, clean background, no branding --ar 85:128 --v 6.0 --style raw","Realistic still life photography style: A single, fresh apple, resting on a clean, soft-textured surface. The apple is slightly off-center, softly backlit to highlight its natural gloss and subtle color gradients—deep crimson red blending into light golden hues. Fine details such as small blemishes, dew drops, and a few light highlights enhance its lifelike appearance. A shallow depth of field gently blurs the neutral background, drawing full attention to the apple. Hyper-detailed 8K resolution, studio lighting, photorealistic render, emphasizing texture and form.","一幅精致细腻的工笔画,画面中心是一株蓬勃生长的红色牡丹,花朵繁茂,既有盛开的硕大花瓣,也有含苞待放的花蕾,层次丰富,色彩艳丽而不失典雅。牡丹枝叶舒展,叶片浓绿饱满,脉络清晰可见,与红花相映成趣。一只蓝紫色蝴蝶仿佛被画中花朵吸引,停驻在画面中央的一朵盛开牡丹上,流连忘返,蝶翼轻展,细节逼真,仿佛随时会随风飞舞。整幅画作笔触工整严谨,色彩浓郁鲜明,展现出中国传统工笔画的精妙与神韵,画面充满生机与灵动之感。","A young girl wearing school uniform stands in a classroom, writing on a chalkboard. The text Introducing Qwen-Image, a foundational image generation model that excels in complex text rendering and precise image editing appears in neat white chalk at the center of the blackboard. Soft natural light filters through windows, casting gentle shadows. The scene is rendered in a realistic photography style with fine details, shallow depth of field, and warm tones. The girl's focused expression and chalk dust in the air add dynamism. Background elements include desks and educational posters, subtly blurred to emphasize the central action. Ultra-detailed 32K resolution, DSLR-quality, soft bokeh effect, documentary-style composition","手绘风格的水循环示意图,整体画面呈现出一幅生动形象的水循环过程图解。画面中央是一片起伏的山脉和山谷,山谷中流淌着一条清澈的河流,河流最终汇入一片广阔的海洋。山体和陆地上绘制有绿色植被。画面下方为地下水层,用蓝色渐变色块表现,与地表水形成层次分明的空间关系。太阳位于画面右上角,促使地表水蒸发,用上升的曲线箭头表示蒸发过程。云朵漂浮在空中,由白色棉絮状绘制而成,部分云层厚重,表示水汽凝结成雨,用向下箭头连接表示降雨过程。雨水以蓝色线条和点状符号表示,从云中落下,补充河流与地下水。整幅图以卡通手绘风格呈现,线条柔和,色彩明亮,标注清晰。背景为浅黄色纸张质感,带有轻微的手绘纹理。"]css = '''.gradio-container {max-width: 590px !important;margin: 0 auto !important;}#main-title h1 { font-size: 2.3em !important; }'''with gr.Blocks() as demo:gr.Markdown("# **Qwen-Image-Diffusion**", elem_id="main-title")result = gr.Gallery(label="Result", columns=1, show_label=False, preview=True)with gr.Row():prompt = gr.Text(label="Prompt",show_label=True,max_lines=2,placeholder="Enter your prompt..",)run_button = gr.Button("Run", scale=0, variant="primary")with gr.Row():aspect_ratio = gr.Dropdown(label="Aspect Ratio",choices=list(aspect_ratios.keys()),value="1:1",)lora = gr.Textbox(label="qwen image lora (optional)", placeholder="enter the path...")with gr.Accordion("Additional Options", open=False):use_negative_prompt = gr.Checkbox(label="Use negative prompt",value=True,visible=True)negative_prompt = gr.Text(label="Negative prompt",max_lines=1,placeholder="Enter a negative prompt",value="text, watermark, copyright, blurry, low resolution",visible=True,)seed = gr.Slider(label="Seed",minimum=0,maximum=MAX_SEED,step=1,value=0,)randomize_seed = gr.Checkbox(label="Randomize seed", value=True)with gr.Row():width = gr.Slider(label="Width",minimum=512,maximum=2048,step=64,value=1024,)height = gr.Slider(label="Height",minimum=512,maximum=2048,step=64,value=1024,)guidance_scale = gr.Slider(label="Guidance Scale",minimum=0.0,maximum=20.0,step=0.1,value=4.0,)num_inference_steps = gr.Slider(label="Number of inference steps",minimum=1,maximum=100,step=1,value=50,)num_images = gr.Slider(label="Number of images",minimum=1,maximum=5,step=1,value=1,)zip_images = gr.Checkbox(label="Zip generated images", value=False)with gr.Row():lora_scale = gr.Slider(label="LoRA Scale",minimum=0,maximum=2,step=0.01,value=1,)gr.Markdown("### Output Information")seed_display = gr.Textbox(label="Seed used", interactive=False)generation_time = gr.Textbox(label="Generation time (seconds)", interactive=False)zip_file = gr.File(label="Download ZIP")# Update aspect ratiodef set_dimensions(ar):w, h = aspect_ratios[ar]return gr.update(value=w), gr.update(value=h)aspect_ratio.change(fn=set_dimensions,inputs=aspect_ratio,outputs=[width, height])# Negative prompt visibilityuse_negative_prompt.change(fn=lambda x: gr.update(visible=x),inputs=use_negative_prompt,outputs=negative_prompt)# Run button and prompt submitgr.on(triggers=[prompt.submit, run_button.click],fn=generate,inputs=[prompt,negative_prompt,use_negative_prompt,seed,width,height,guidance_scale,randomize_seed,num_inference_steps,num_images,zip_images,lora,lora_scale,],outputs=[result, seed_display, generation_time, zip_file],api_name="run",)# Examplesgr.Examples(examples=examples,inputs=prompt,outputs=[result, seed_display, generation_time, zip_file],fn=generate,cache_examples=False,)if __name__ == "__main__":demo.queue(max_size=30).launch(css=css, theme=gr.themes.Soft(primary_hue="blue",secondary_hue="indigo",neutral_hue="slate",), mcp_server=True, ssr_mode=False, show_error=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610import osimport jsonimport copyimport mathimport timeimport randomimport loggingimport numpy as npfrom typing import Any, Dict, List, Optional, Unionimport torchfrom PIL import Imageimport gradio as grimport spacesfrom diffusers import (DiffusionPipeline,FlowMatchEulerDiscreteScheduler)from huggingface_hub import (hf_hub_download,HfFileSystem,ModelCard,snapshot_download)from diffusers.utils import load_imageimport requestsfrom urllib.parse import urlparsefrom typing import Iterableimport tempfileimport shutilimport uuidimport zipfilefrom gradio.themes import Softfrom gradio.themes.utils import colors, fonts, sizescolors.orange_red = colors.Color(name="orange_red",c50="#FFF0E5",c100="#FFE0CC",c200="#FFC299",c300="#FFA366",c400="#FF8533",c500="#FF4500",c600="#E63E00",c700="#CC3700",c800="#B33000",c900="#992900",c950="#802200",)class OrangeRedTheme(Soft):def __init__(self,*,primary_hue: colors.Color | str = colors.gray,secondary_hue: colors.Color | str = colors.orange_red, # Use the new colorneutral_hue: colors.Color | str = colors.slate,text_size: sizes.Size | str = sizes.text_lg,font: fonts.Font | str | Iterable[fonts.Font | str] = (fonts.GoogleFont("Outfit"), "Arial", "sans-serif",),font_mono: fonts.Font | str | Iterable[fonts.Font | str] = (fonts.GoogleFont("IBM Plex Mono"), "ui-monospace", "monospace",),):super().__init__(primary_hue=primary_hue,secondary_hue=secondary_hue,neutral_hue=neutral_hue,text_size=text_size,font=font,font_mono=font_mono,)super().set(background_fill_primary="*primary_50",background_fill_primary_dark="*primary_900",body_background_fill="linear-gradient(135deg, *primary_200, *primary_100)",body_background_fill_dark="linear-gradient(135deg, *primary_900, *primary_800)",button_primary_text_color="white",button_primary_text_color_hover="white",button_primary_background_fill="linear-gradient(90deg, *secondary_500, *secondary_600)",button_primary_background_fill_hover="linear-gradient(90deg, *secondary_600, *secondary_700)",button_primary_background_fill_dark="linear-gradient(90deg, *secondary_600, *secondary_700)",button_primary_background_fill_hover_dark="linear-gradient(90deg, *secondary_500, *secondary_600)",button_secondary_text_color="black",button_secondary_text_color_hover="white",button_secondary_background_fill="linear-gradient(90deg, *primary_300, *primary_300)",button_secondary_background_fill_hover="linear-gradient(90deg, *primary_400, *primary_400)",button_secondary_background_fill_dark="linear-gradient(90deg, *primary_500, *primary_600)",button_secondary_background_fill_hover_dark="linear-gradient(90deg, *primary_500, *primary_500)",slider_color="*secondary_500",slider_color_dark="*secondary_600",block_title_text_weight="600",block_border_width="3px",block_shadow="*shadow_drop_lg",button_primary_shadow="*shadow_drop_lg",button_large_padding="11px",color_accent_soft="*primary_100",block_label_background_fill="*primary_200",)orange_red_theme = OrangeRedTheme()# META: CUDA_CHECK / GPU_INFOdevice = "cuda" if torch.cuda.is_available() else "cpu"print("CUDA_VISIBLE_DEVICES=", os.environ.get("CUDA_VISIBLE_DEVICES"))print("torch.__version__ =", torch.__version__)print("torch.version.cuda =", torch.version.cuda)print("cuda available:", torch.cuda.is_available())print("cuda device count:", torch.cuda.device_count())if torch.cuda.is_available():print("current device:", torch.cuda.current_device())print("device name:", torch.cuda.get_device_name(torch.cuda.current_device()))print("Using device:", device)loras = [# Sample Qwen-compatible LoRAs{"image": "https://huggingface.co/prithivMLmods/Qwen-Image-Studio-Realism/resolve/main/images/2.png","title": "Studio Realism","repo": "prithivMLmods/Qwen-Image-Studio-Realism","weights": "qwen-studio-realism.safetensors","trigger_word": "Studio Realism"},{"image": "https://huggingface.co/prithivMLmods/Qwen-Image-Sketch-Smudge/resolve/main/images/1.png","title": "Sketch Smudge","repo": "prithivMLmods/Qwen-Image-Sketch-Smudge","weights": "qwen-sketch-smudge.safetensors","trigger_word": "Sketch Smudge"},{"image": "https://huggingface.co/Shakker-Labs/AWPortrait-QW/resolve/main/images/08fdaf6b644b61136340d5c908ca37993e47f34cdbe2e8e8251c4c72.jpg","title": "AWPortrait QW","repo": "Shakker-Labs/AWPortrait-QW","weights": "AWPortrait-QW_1.0.safetensors","trigger_word": "Portrait"},{"image": "https://huggingface.co/prithivMLmods/Qwen-Image-Anime-LoRA/resolve/main/images/1.png","title": "Qwen Anime","repo": "prithivMLmods/Qwen-Image-Anime-LoRA","weights": "qwen-anime.safetensors","trigger_word": "Qwen Anime"},{"image": "https://huggingface.co/flymy-ai/qwen-image-realism-lora/resolve/main/assets/flymy_realism.png","title": "Image Realism","repo": "flymy-ai/qwen-image-realism-lora","weights": "flymy_realism.safetensors","trigger_word": "Super Realism Portrait"},{"image": "https://huggingface.co/prithivMLmods/Qwen-Image-Fragmented-Portraiture/resolve/main/images/3.png","title": "Fragmented Portraiture","repo": "prithivMLmods/Qwen-Image-Fragmented-Portraiture","weights": "qwen-fragmented-portraiture.safetensors","trigger_word": "Fragmented Portraiture"},{"image": "https://huggingface.co/prithivMLmods/Qwen-Image-Synthetic-Face/resolve/main/images/2.png","title": "Synthetic Face","repo": "prithivMLmods/Qwen-Image-Synthetic-Face","weights": "qwen-synthetic-face.safetensors","trigger_word": "Synthetic Face"},{"image": "https://huggingface.co/itspoidaman/qwenglitch/resolve/main/images/GyZTwJIbkAAhS4h.jpeg","title": "Qwen Glitch","repo": "itspoidaman/qwenglitch","weights": "qwenglitch1.safetensors","trigger_word": "qwenglitch"},{"image": "https://huggingface.co/alfredplpl/qwen-image-modern-anime-lora/resolve/main/sample1.jpg","title": "Modern Anime Lora","repo": "alfredplpl/qwen-image-modern-anime-lora","weights": "lora.safetensors","trigger_word": "Japanese modern anime style"},]# Initialize the base modeldtype = torch.bfloat16base_model = "Qwen/Qwen-Image-2512"# Scheduler configuration from the Qwen-Image-Lightning repositoryscheduler_config = {"base_image_seq_len": 256,"base_shift": math.log(3),"invert_sigmas": False,"max_image_seq_len": 8192,"max_shift": math.log(3),"num_train_timesteps": 1000,"shift": 1.0,"shift_terminal": None,"stochastic_sampling": False,"time_shift_type": "exponential","use_beta_sigmas": False,"use_dynamic_shifting": True,"use_exponential_sigmas": False,"use_karras_sigmas": False,}scheduler = FlowMatchEulerDiscreteScheduler.from_config(scheduler_config)pipe = DiffusionPipeline.from_pretrained(base_model, scheduler=scheduler, torch_dtype=dtype).to(device)# Lightning LoRA info (no global state)LIGHTNING_LORA_REPO = "lightx2v/Qwen-Image-2512-Lightning"LIGHTNING_LORA_WEIGHT = "Qwen-Image-2512-Lightning-4steps-V1.0-fp32.safetensors"MAX_SEED = np.iinfo(np.int32).maxclass Timer:def __init__(self, task_name=""):self.task_name = task_namedef __enter__(self):self.start_time = time.time()return selfdef __exit__(self, exc_type, exc_value, traceback):self.end_time = time.time()self.elapsed_time = self.end_time - self.start_timeif self.task_name:print(f"Elapsed time for {self.task_name}: {self.elapsed_time:.6f} seconds")else:print(f"Elapsed time: {self.elapsed_time:.6f} seconds")def compute_image_dimensions(aspect_ratio):"""Converts aspect ratio string to width, height tuple."""if aspect_ratio == "1:1":return 1024, 1024elif aspect_ratio == "16:9":return 1152, 640elif aspect_ratio == "9:16":return 640, 1152elif aspect_ratio == "4:3":return 1024, 768elif aspect_ratio == "3:4":return 768, 1024elif aspect_ratio == "3:2":return 1024, 688elif aspect_ratio == "2:3":return 688, 1024else:return 1024, 1024def handle_lora_selection(evt: gr.SelectData, aspect_ratio):selected_lora = loras[evt.index]new_placeholder = f"Type a prompt for {selected_lora['title']}"lora_repo = selected_lora["repo"]updated_text = f"### Selected: [{lora_repo}](https://huggingface.co/{lora_repo}) ✅"# Update aspect ratio if specified in LoRA configif "aspect" in selected_lora:if selected_lora["aspect"] == "portrait":aspect_ratio = "9:16"elif selected_lora["aspect"] == "landscape":aspect_ratio = "16:9"else:aspect_ratio = "1:1"return (gr.update(placeholder=new_placeholder),updated_text,evt.index,aspect_ratio,)def adjust_generation_mode(speed_mode):"""Update UI based on speed/quality toggle."""if speed_mode == "Fast (8 steps)":return gr.update(value="Fast mode selected - 8 steps with Lightning LoRA"), 8, 1.0else:return gr.update(value="Base mode selected - 50 steps for best quality"), 50, 4.0@spaces.GPU(duration=100)def create_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale, negative_prompt=""):pipe.to("cuda")generator = torch.Generator(device="cuda").manual_seed(seed)with Timer("Generating image"):# Generate imageimage = pipe(prompt=prompt_mash,negative_prompt=negative_prompt,num_inference_steps=steps,true_cfg_scale=cfg_scale, # Use true_cfg_scale for Qwen-Imagewidth=width,height=height,generator=generator,).images[0]return image@spaces.GPU(duration=100)def process_adapter_generation(prompt, cfg_scale, steps, selected_index, randomize_seed, seed, aspect_ratio, lora_scale, speed_mode, progress=gr.Progress(track_tqdm=True)):if selected_index is None:raise gr.Error("You must select a LoRA before proceeding.")selected_lora = loras[selected_index]lora_path = selected_lora["repo"]trigger_word = selected_lora["trigger_word"]# Prepare prompt with trigger wordif trigger_word:if "trigger_position" in selected_lora:if selected_lora["trigger_position"] == "prepend":prompt_mash = f"{trigger_word} {prompt}"else:prompt_mash = f"{prompt} {trigger_word}"else:prompt_mash = f"{trigger_word} {prompt}"else:prompt_mash = prompt# Always unload any existing LoRAs first to avoid conflictswith Timer("Unloading existing LoRAs"):pipe.unload_lora_weights()# Load LoRAs based on speed modeif speed_mode == "Fast (8 steps)":with Timer("Loading Lightning LoRA and style LoRA"):# Load Lightning LoRA firstpipe.load_lora_weights(LIGHTNING_LORA_REPO,weight_name=LIGHTNING_LORA_WEIGHT,adapter_name="lightning")# Load the selected style LoRAweight_name = selected_lora.get("weights", None)pipe.load_lora_weights(lora_path,weight_name=weight_name,low_cpu_mem_usage=True,adapter_name="style")# Set both adapters active with their weightspipe.set_adapters(["lightning", "style"], adapter_weights=[1.0, lora_scale])else:# Quality mode - only load the style LoRAwith Timer(f"Loading LoRA weights for {selected_lora['title']}"):weight_name = selected_lora.get("weights", None)pipe.load_lora_weights(lora_path,weight_name=weight_name,low_cpu_mem_usage=True,adapter_name="style")pipe.set_adapters(["style"], adapter_weights=[lora_scale])# Set random seed for reproducibilitywith Timer("Randomizing seed"):if randomize_seed:seed = random.randint(0, MAX_SEED)# Get image dimensions from aspect ratiowidth, height = compute_image_dimensions(aspect_ratio)# Generate the imagefinal_image = create_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale)return final_image, seeddef fetch_hf_adapter_files(link):split_link = link.split("/")if len(split_link) != 2:raise Exception("Invalid Hugging Face repository link format.")print(f"Repository attempted: {split_link}")# Load model cardmodel_card = ModelCard.load(link)base_model = model_card.data.get("base_model")print(f"Base model: {base_model}")# Validate model type (for Qwen-Image)acceptable_models = {"Qwen/Qwen-Image"}models_to_check = base_model if isinstance(base_model, list) else [base_model]if not any(model in acceptable_models for model in models_to_check):raise Exception("Not a Qwen-Image LoRA!")# Extract image and trigger wordimage_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# Initialize Hugging Face file systemfs = HfFileSystem()try:list_of_files = fs.ls(link, detail=False)# Find safetensors filesafetensors_name = Nonefor file in list_of_files:filename = file.split("/")[-1]if filename.endswith(".safetensors"):safetensors_name = filenamebreakif not safetensors_name:raise Exception("No valid *.safetensors file found in the repository.")except Exception as e:print(e)raise Exception("You didn't include a valid Hugging Face repository with a *.safetensors LoRA")return split_link[1], link, safetensors_name, trigger_word, image_urldef validate_custom_adapter(link):print(f"Checking a custom model on: {link}")if link.endswith('.safetensors'):if 'huggingface.co' in link:parts = link.split('/')try:hf_index = parts.index('huggingface.co')username = parts[hf_index + 1]repo_name = parts[hf_index + 2]repo = f"{username}/{repo_name}"safetensors_name = parts[-1]try:model_card = ModelCard.load(repo)trigger_word = model_card.data.get("instance_prompt", "")image_path = model_card.data.get("widget", [{}])[0].get("output", {}).get("url", None)image_url = f"https://huggingface.co/{repo}/resolve/main/{image_path}" if image_path else Noneexcept:trigger_word = ""image_url = Nonereturn repo_name, repo, safetensors_name, trigger_word, image_urlexcept:raise Exception("Invalid safetensors URL format")if link.startswith("https://"):if link.startswith("https://huggingface.co") or link.startswith("https://www.huggingface.co"):link_split = link.split("huggingface.co/")return fetch_hf_adapter_files(link_split[1])else:return fetch_hf_adapter_files(link)def incorporate_custom_adapter(custom_lora):global lorasif custom_lora:try:title, repo, path, trigger_word, image = validate_custom_adapter(custom_lora)print(f"Loaded custom LoRA: {repo}")card = f'''<div class="custom_lora_card"><span>Loaded custom LoRA:</span><div class="card_internal"><img src="{image}" /><div><h3>{title}</h3><small>{"Using: <code><b>"+trigger_word+"</code></b> as the trigger word" if trigger_word else "No trigger word found. If there's a trigger word, include it in your prompt"}<br></small></div></div></div>'''existing_item_index = next((index for (index, item) in enumerate(loras) if item['repo'] == repo), None)if existing_item_index is None:new_item = {"image": image,"title": title,"repo": repo,"weights": path,"trigger_word": trigger_word}print(new_item)loras.append(new_item)existing_item_index = len(loras) - 1 # Get the actual index after addingreturn gr.update(visible=True, value=card), gr.update(visible=True), gr.Gallery(selected_index=None), f"Custom: {path}", existing_item_index, trigger_wordexcept Exception as e:gr.Warning(f"Invalid LoRA: either you entered an invalid link, or a non-Qwen-Image LoRA, this was the issue: {e}")return gr.update(visible=True, value=f"Invalid LoRA: either you entered an invalid link, a non-Qwen-Image LoRA"), gr.update(visible=True), gr.update(), "", None, ""else:return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""def discard_custom_adapter():return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""process_adapter_generation.zerogpu = Truecss = '''#gen_btn{height: 100%}#gen_column{align-self: stretch}#title{text-align: center}#title h1{font-size: 3em; display:inline-flex; align-items:center}#title img{width: 100px; margin-right: 0.5em}#gallery .grid-wrap{height: 10vh}#lora_list{background: var(--block-background-fill);padding: 0 1em .3em; font-size: 90%}.card_internal{display: flex;height: 100px;margin-top: .5em}.card_internal img{margin-right: 1em}.styler{--form-gap-width: 0px !important}#speed_status{padding: .5em; border-radius: 5px; margin: 1em 0}'''with gr.Blocks(delete_cache=(240, 240)) as app:title = gr.HTML("""<h1>Qwen-Image-2512 LoRA DLC⛵</h1>""", elem_id="title")selected_index = gr.State(None)with gr.Row():with gr.Column(scale=3):prompt = gr.Textbox(label="Prompt", lines=1, placeholder="✦︎ Choose the LoRA and type the prompt")with gr.Column(scale=1, elem_id="gen_column"):generate_button = gr.Button("Generate", variant="primary", elem_id="gen_btn")with gr.Row():with gr.Column():selected_info = gr.Markdown("")gallery = gr.Gallery([(item["image"], item["title"]) for item in loras],label="LoRA Gallery",allow_preview=False,columns=3,elem_id="gallery",#show_share_button=False)with gr.Group():custom_lora = gr.Textbox(label="Custom LoRA", placeholder="username/lora-model-name")gr.Markdown("[Check Qwen-Image LoRAs](https://huggingface.co/models?other=base_model:adapter:Qwen/Qwen-Image)", elem_id="lora_list")custom_lora_info = gr.HTML(visible=False)custom_lora_button = gr.Button("Remove custom LoRA", visible=False)with gr.Column():result = gr.Image(label="Generated Image", format="png")with gr.Row():aspect_ratio = gr.Dropdown(label="Aspect Ratio",choices=["1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3"],value="3:2")with gr.Row():speed_mode = gr.Dropdown(label="Output Mode",choices=["Fast (8 steps)", "Base (50 steps)"],value="Base (50 steps)",)speed_status = gr.Markdown("Base mode selected - 50 steps for best quality", elem_id="speed_status")with gr.Row():with gr.Accordion("Advanced Settings", open=False):with gr.Column():with gr.Row():cfg_scale = gr.Slider(label="Guidance Scale (True CFG)",minimum=1.0,maximum=5.0,step=0.1,value=4.0,info="Lower for speed mode, higher for quality")steps = gr.Slider(label="Steps",minimum=4,maximum=50,step=1,value=50,info="Automatically set by speed mode")with gr.Row():randomize_seed = gr.Checkbox(True, label="Randomize seed")seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0, randomize=True)lora_scale = gr.Slider(label="LoRA Scale", minimum=0, maximum=2, step=0.01, value=1.0)# Event handlersgallery.select(handle_lora_selection,inputs=[aspect_ratio],outputs=[prompt, selected_info, selected_index, aspect_ratio])speed_mode.change(adjust_generation_mode,inputs=[speed_mode],outputs=[speed_status, steps, cfg_scale])custom_lora.input(incorporate_custom_adapter,inputs=[custom_lora],outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, prompt])custom_lora_button.click(discard_custom_adapter,outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, custom_lora])gr.on(triggers=[generate_button.click, prompt.submit],fn=process_adapter_generation,inputs=[prompt, cfg_scale, steps, selected_index, randomize_seed, seed, aspect_ratio, lora_scale, speed_mode],outputs=[result, seed])app.queue()app.launch(theme=orange_red_theme, css=css, mcp_server=True, ssr_mode=False, show_error=True)
app.py+569-313