File size: 14,196 Bytes
b22b80e
 
 
b05966a
27cb6d3
 
ec858e0
b22b80e
9c2430d
27cb6d3
b22b80e
ec858e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
afa2559
 
 
27cb6d3
afa2559
 
 
 
 
 
 
 
ec858e0
 
 
 
27cb6d3
 
ec858e0
 
 
 
 
 
 
 
 
 
 
27cb6d3
 
ec858e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27cb6d3
ec858e0
 
 
 
 
 
 
 
 
 
b22b80e
ec858e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d7f489
ec858e0
 
6d7f489
9c2430d
ec858e0
 
 
b05966a
9c2430d
ec858e0
 
 
 
 
 
9c2430d
ec858e0
9c2430d
ec858e0
9c2430d
ec858e0
9c2430d
ec858e0
9c2430d
ec858e0
afa2559
ec858e0
afa2559
ec858e0
9c2430d
ec858e0
9c2430d
ec858e0
9c2430d
 
 
 
27cb6d3
 
 
afa2559
9c2430d
 
b05966a
27cb6d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b05966a
27cb6d3
 
b05966a
b22b80e
 
b05966a
 
9c2430d
b05966a
 
ec858e0
b05966a
 
afa2559
 
27cb6d3
afa2559
b05966a
27cb6d3
b05966a
ec858e0
 
 
b05966a
ec858e0
 
 
 
 
 
 
 
 
 
b05966a
b22b80e
9c2430d
b05966a
b22b80e
9c2430d
 
 
 
 
 
b05966a
9c2430d
 
b22b80e
 
9c2430d
b22b80e
 
9c2430d
b22b80e
27cb6d3
 
 
 
 
 
b22b80e
 
 
 
34faca9
27cb6d3
d172548
645e05e
27cb6d3
 
ec858e0
b22b80e
 
 
 
 
 
 
9c2430d
 
b05966a
9c2430d
b22b80e
 
 
 
 
 
9c2430d
b22b80e
9c2430d
b22b80e
9c2430d
b22b80e
9c2430d
b05966a
afa2559
ec858e0
b22b80e
afa2559
9c2430d
b22b80e
9c2430d
27cb6d3
 
ec858e0
9c2430d
d172548
9c2430d
 
b22b80e
9c2430d
27cb6d3
ec858e0
b22b80e
d172548
b22b80e
 
b05966a
 
b22b80e
9c2430d
b22b80e
9c2430d
 
 
 
 
 
 
afa2559
9c2430d
 
b22b80e
 
9c2430d
ec858e0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
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("""
        <div id="logo-title">
            <img src="https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-Image/qwen_image_logo.png" alt="Qwen-Image Logo" width="400" style="display: block; margin: 0 auto;">
            <h2 style="font-style: italic;color: #5b47d1;margin-top: -33px !important;margin-left: 133px;">Fast, 8-steps with Lightining LoRA</h2>
        </div>
        """)
    gr.Markdown("[了解更多](https://github.com/QwenLM/Qwen-Image)。本空间使用 [Qwen-Image-Lightning](https://huggingface.co/lightx2v/Qwen-Image-Lightning) 的 LoRA,在 CPU 上进行了内存优化(默认分辨率更小、开启 slicing/tiling),以便在免费 16GB CPU 空间中运行。建议耐心等待推理完成,首次加载模型会较慢。")
        with gr.Row():
            prompt = gr.Text(
                label="Prompt",
                show_label=False,
                placeholder="Enter your prompt",
                container=False,
            )
            run_button = gr.Button("Run", scale=0, variant="primary")

        result = gr.Image(label="Result", show_label=False, type="pil")

        with gr.Accordion("Advanced Settings", open=False):
            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():
                aspect_ratio = gr.Radio(
                    label="Aspect ratio (width:height)",
                    choices=["1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3"],
                    value="1:1",
                )
                prompt_enhance = gr.Checkbox(label="Prompt Enhance", value=True)

            with gr.Row():
                guidance_scale = gr.Slider(
                    label="Guidance scale (True CFG Scale)",
                    minimum=1.0,
                    maximum=3.0,
                    step=0.1,
                    value=1.0, 
                )

                num_inference_steps = gr.Slider(
                    label="Number of inference steps",
                    minimum=4,
                    maximum=20,
                    step=1,
                    value=8,
                )

        gr.Examples(examples=examples, inputs=[prompt], outputs=[result, seed], fn=infer, cache_examples=False)

    gr.on(
        triggers=[run_button.click, prompt.submit],
        fn=infer,
        inputs=[
            prompt,
            seed,
            randomize_seed,
            aspect_ratio,
            guidance_scale,
            num_inference_steps,
            prompt_enhance,
        ],
        outputs=[result, seed],
    )

if __name__ == "__main__":
    demo.launch()