import gradio as gr import numpy as np import random import torch import math import os from typing import Tuple from PIL import Image from diffusers import DiffusionPipeline, FlowMatchEulerDiscreteScheduler # NOTE: This CPU-friendly rewrite removes ZeroGPU usage and external LLM calls. # It loads Qwen-Image on CPU, applies Lightning LoRA if available, and uses # aggressive memory-saving options (smaller default size, slicing/tiling). # ----------------------- # Global CPU configuration # ----------------------- DEVICE = "cpu" # BF16 on many free CPUs may not be available; float32 is safer on CPU. DTYPE = torch.float32 TORCH_THREADS = max(1, int(os.environ.get("TORCH_NUM_THREADS", str(max(1, (os.cpu_count() or 2) - 1))))) torch.set_num_threads(TORCH_THREADS) torch.set_grad_enabled(False) try: torch.set_float32_matmul_precision("high") except Exception: pass def get_caption_language(prompt): """Detects if the prompt contains Chinese characters.""" ranges = [ ('\u4e00', '\u9fff'), # CJK Unified Ideographs ] for char in prompt: if any(start <= char <= end for start, end in ranges): return 'zh' return 'en' def rewrite(input_prompt: str) -> str: """Lightweight, offline prompt enhancer to avoid network/API usage. Preserves original meaning, adds a short style tail only. """ lang = get_caption_language(input_prompt) magic_prompt_en = "Ultra HD, 4K, cinematic composition, finely detailed, crisp lighting" magic_prompt_zh = "超清,4K,电影级构图,细节丰富,光影清晰" suffix = magic_prompt_zh if lang == 'zh' else magic_prompt_en # Keep it short to avoid excessive text rendering on CPU models return (input_prompt or "").strip() + " — " + suffix ###################### # Model Lazy Loading # ###################### _pipe = None ckpt_id = "Qwen/Qwen-Image" def build_scheduler(): # Scheduler configuration from the Qwen-Image-Lightning repository scheduler_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, } return FlowMatchEulerDiscreteScheduler.from_config(scheduler_config) def get_pipe() -> DiffusionPipeline: global _pipe if _pipe is not None: return _pipe scheduler = build_scheduler() print(f"Loading pipeline on {DEVICE} with dtype={DTYPE} and {TORCH_THREADS} threads…") pipe = DiffusionPipeline.from_pretrained( ckpt_id, scheduler=scheduler, torch_dtype=DTYPE, ) pipe = pipe.to(DEVICE) # Apply Lightning LoRA (if available). If memory tight, we still try and then fuse. try: pipe.load_lora_weights( "lightx2v/Qwen-Image-Lightning", weight_name="Qwen-Image-Lightning-8steps-V1.1.safetensors", ) pipe.fuse_lora() print("LoRA fused successfully.") except Exception as e: print(f"Warning: failed to load/fuse Lightning LoRA: {e}") # Memory optimizations for CPU try: pipe.enable_attention_slicing() except Exception: pass try: pipe.enable_vae_slicing() pipe.enable_vae_tiling() except Exception: pass try: pipe.set_progress_bar_config(disable=True) except Exception: pass # Reduce peak memory on CPU with channels_last when possible try: pipe.unet.to(memory_format=torch.channels_last) except Exception: pass _pipe = pipe return _pipe ############################# # UI Constants and Helpers # ############################# MAX_SEED = np.iinfo(np.int32).max def get_image_size(aspect_ratio: str) -> Tuple[int, int]: """Converts aspect ratio string to width, height tuple, optimized for CPU. Default base is 768 on the longer side to fit within ~16GB RAM. You can increase sizes at your own risk. """ if aspect_ratio == "1:1": return 768, 768 elif aspect_ratio == "16:9": return 896, 504 elif aspect_ratio == "9:16": return 504, 896 elif aspect_ratio == "4:3": return 768, 576 elif aspect_ratio == "3:4": return 576, 768 elif aspect_ratio == "3:2": return 768, 512 elif aspect_ratio == "2:3": return 512, 768 else: return 768, 768 # --- Main Inference Function (CPU, with hardcoded negative prompt) --- def infer( prompt, seed=42, randomize_seed=False, aspect_ratio="1:1", guidance_scale=1.0, num_inference_steps=8, prompt_enhance=True, progress=gr.Progress(track_tqdm=True), ): """ Generates an image based on a text prompt using the Qwen-Image-Lightning model. Args: prompt (str): The text prompt to generate the image from. seed (int): The seed for the random number generator for reproducibility. randomize_seed (bool): If True, a random seed is used. aspect_ratio (str): The desired aspect ratio of the output image. guidance_scale (float): Corresponds to `true_cfg_scale`. A higher value encourages the model to generate images that are more closely related to the prompt. num_inference_steps (int): The number of denoising steps. prompt_enhance (bool): If True, the prompt is rewritten by an external LLM to add more detail. progress (gr.Progress): A Gradio Progress object to track the generation progress in the UI. Returns: tuple[Image.Image, int]: A tuple containing the generated PIL Image and the integer seed used for the generation. """ # Use a blank negative prompt as per the lightning model's recommendation negative_prompt = " " if randomize_seed: seed = random.randint(0, MAX_SEED) # Convert aspect ratio to width and height width, height = get_image_size(aspect_ratio) # Set up the generator for reproducibility generator = torch.Generator(device=DEVICE).manual_seed(seed) print(f"Calling pipeline with prompt: '{prompt}'") if prompt_enhance: prompt = rewrite(prompt) print(f"Actual Prompt: '{prompt}'") print(f"Negative Prompt: '{negative_prompt}'") print(f"Seed: {seed}, Size: {width}x{height}, Steps: {num_inference_steps}, True CFG Scale: {guidance_scale}") # Load pipeline lazily (first request) and run on CPU pipe = get_pipe() # Generate the image with torch.inference_mode(): image = pipe( prompt=prompt, negative_prompt=negative_prompt, width=width, height=height, num_inference_steps=num_inference_steps, generator=generator, true_cfg_scale=guidance_scale, # Use true_cfg_scale for this model ).images[0] return image, seed # --- Examples and UI Layout --- examples = [ "A capybara wearing a suit holding a sign that reads Hello World", "一幅精致细腻的工笔画,画面中心是一株蓬勃生长的红色牡丹,花朵繁茂,既有盛开的硕大花瓣,也有含苞待放的花蕾,层次丰富,色彩艳丽而不失典雅。牡丹枝叶舒展,叶片浓绿饱满,脉络清晰可见,与红花相映成趣。一只蓝紫色蝴蝶仿佛被画中花朵吸引,停驻在画面中央的一朵盛开牡丹上,流连忘返,蝶翼轻展,细节逼真,仿佛随时会随风飞舞。整幅画作笔触工整严谨,色彩浓郁鲜明,展现出中国传统工笔画的精妙与神韵,画面充满生机与灵动之感。", "一位身着淡雅水粉色交领襦裙的年轻女子背对镜头而坐,俯身专注地手持毛笔在素白宣纸上书写“通義千問”四个遒劲汉字。古色古香的室内陈设典雅考究,案头错落摆放着青瓷茶盏与鎏金香炉,一缕熏香轻盈升腾;柔和光线洒落肩头,勾勒出她衣裙的柔美质感与专注神情,仿佛凝固了一段宁静温润的旧时光。", " 一个可抽取式的纸巾盒子,上面写着'Face, CLEAN & SOFT TISSUE'下面写着'亲肤可湿水',左上角是品牌名'洁柔',整体是白色和浅黄色的色调", "手绘风格的水循环示意图,整体画面呈现出一幅生动形象的水循环过程图解。画面中央是一片起伏的山脉和山谷,山谷中流淌着一条清澈的河流,河流最终汇入一片广阔的海洋。山体和陆地上绘制有绿色植被。画面下方为地下水层,用蓝色渐变色块表现,与地表水形成层次分明的空间关系。太阳位于画面右上角,促使地表水蒸发,用上升的曲线箭头表示蒸发过程。云朵漂浮在空中,由白色棉絮状绘制而成,部分云层厚重,表示水汽凝结成雨,用向下箭头连接表示降雨过程。雨水以蓝色线条和点状符号表示,从云中落下,补充河流与地下水。整幅图以卡通手绘风格呈现,线条柔和,色彩明亮,标注清晰。背景为浅黄色纸张质感,带有轻微的手绘纹理。", '一个会议室,墙上写着"3.14159265-358979-32384626-4338327950",一个小陀螺在桌上转动', '一个咖啡店门口有一个黑板,上面写着通义千问咖啡,2美元一杯,旁边有个霓虹灯,写着阿里巴巴,旁边有个海报,海报上面是一个中国美女,海报下方写着qwen newbee', """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""", "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." ] css = """ #col-container { margin: 0 auto; max-width: 1024px; } #logo-title { text-align: center; } #logo-title img { width: 400px; } """ with gr.Blocks(css=css) as demo: with gr.Column(elem_id="col-container"): gr.HTML("""