File size: 5,329 Bytes
94e279b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
4K Image Generation Pipeline:
  1. Generate 1024px with fine-tuned Flux Dev LoRA
  2. Upscale to 4096px with Real-ESRGAN x4

Usage:
  python3 inference_4k.py --prompt "a beautiful landscape" --output output.png
  python3 inference_4k.py --prompt "a cat" --lora-path /path/to/checkpoint --output cat_4k.png
"""
import argparse
import time
from pathlib import Path

import torch
import numpy as np
from PIL import Image


def load_flux_pipeline(model_name, lora_path=None, device="cuda:0", dtype=torch.bfloat16):
    from diffusers import FluxPipeline

    print(f"  Loading Flux Dev pipeline...")
    pipe = FluxPipeline.from_pretrained(
        model_name,
        torch_dtype=dtype,
    )

    if lora_path:
        lora_path = Path(lora_path)
        if (lora_path / "adapter_model.safetensors").exists():
            pipe.load_lora_weights(str(lora_path))
            print(f"  Loaded LoRA from {lora_path}")
        else:
            print(f"  WARNING: No adapter_model.safetensors in {lora_path}")

    pipe = pipe.to(device)
    pipe.enable_model_cpu_offload()
    return pipe


def load_realesrgan(device="cuda:0", scale=4):
    """Load Real-ESRGAN x4 model for upscaling."""
    try:
        from realesrgan import RealESRGANer
        from basicsr.archs.rrdbnet_arch import RRDBNet
    except ImportError:
        print("  Installing Real-ESRGAN...")
        import subprocess
        subprocess.run([
            "pip3", "install", "-q",
            "realesrgan", "basicsr", "facexlib", "gfpgan"
        ], check=True)
        from realesrgan import RealESRGANer
        from basicsr.archs.rrdbnet_arch import RRDBNet

    model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=scale)

    model_path = Path("/data0/models/RealESRGAN_x4plus.pth")
    if not model_path.exists():
        print("  Downloading RealESRGAN_x4plus model...")
        model_path.parent.mkdir(parents=True, exist_ok=True)
        import urllib.request
        urllib.request.urlretrieve(
            "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth",
            str(model_path),
        )

    upsampler = RealESRGANer(
        scale=scale,
        model_path=str(model_path),
        model=model,
        tile=512,
        tile_pad=10,
        pre_pad=0,
        half=True,
        device=device,
    )
    print(f"  Real-ESRGAN x{scale} loaded")
    return upsampler


def generate_1k(pipe, prompt, num_steps=28, guidance_scale=3.5, seed=None):
    """Generate 1024x1024 image with Flux Dev."""
    generator = None
    if seed is not None:
        generator = torch.Generator(device=pipe.device).manual_seed(seed)

    image = pipe(
        prompt=prompt,
        num_inference_steps=num_steps,
        guidance_scale=guidance_scale,
        height=1024,
        width=1024,
        generator=generator,
    ).images[0]

    return image


def upscale_4k(upsampler, image):
    """Upscale PIL image to 4K using Real-ESRGAN."""
    import cv2

    img_np = np.array(image)
    img_bgr = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)

    output, _ = upsampler.enhance(img_bgr, outscale=4)

    output_rgb = cv2.cvtColor(output, cv2.COLOR_BGR2RGB)
    return Image.fromarray(output_rgb)


def main():
    parser = argparse.ArgumentParser(description="Generate 4K images")
    parser.add_argument("--prompt", type=str, required=True)
    parser.add_argument("--output", type=str, default="output_4k.png")
    parser.add_argument("--model-name", default="black-forest-labs/FLUX.1-dev")
    parser.add_argument("--lora-path", type=str, default=None)
    parser.add_argument("--num-steps", type=int, default=28)
    parser.add_argument("--guidance-scale", type=float, default=3.5)
    parser.add_argument("--seed", type=int, default=None)
    parser.add_argument("--device", default="cuda:0")
    parser.add_argument("--skip-upscale", action="store_true")
    parser.add_argument("--save-1k", action="store_true", help="Also save 1K intermediate")
    args = parser.parse_args()

    t0 = time.time()

    # Stage 1: Generate 1024px
    print("=== Stage 1: Generate 1024px ===")
    pipe = load_flux_pipeline(args.model_name, args.lora_path, args.device)
    image_1k = generate_1k(pipe, args.prompt, args.num_steps, args.guidance_scale, args.seed)
    print(f"  Generated 1024x1024 in {time.time()-t0:.1f}s")

    if args.save_1k:
        path_1k = Path(args.output).with_suffix("").with_name(Path(args.output).stem + "_1k.png")
        image_1k.save(path_1k)
        print(f"  Saved 1K: {path_1k}")

    # Free GPU memory
    del pipe
    torch.cuda.empty_cache()

    if args.skip_upscale:
        image_1k.save(args.output)
        print(f"  Saved (no upscale): {args.output}")
        return

    # Stage 2: Upscale to 4K
    print("=== Stage 2: Upscale to 4096px ===")
    t1 = time.time()
    upsampler = load_realesrgan(args.device)
    image_4k = upscale_4k(upsampler, image_1k)
    print(f"  Upscaled to {image_4k.size[0]}x{image_4k.size[1]} in {time.time()-t1:.1f}s")

    # Save
    output_path = Path(args.output)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    image_4k.save(output_path, quality=95)
    print(f"\n  Final 4K image saved: {output_path}")
    print(f"  Total time: {time.time()-t0:.1f}s")


if __name__ == "__main__":
    main()