Update app.py
Browse files
app.py
CHANGED
|
@@ -1,46 +1,201 @@
|
|
| 1 |
"""
|
| 2 |
FLUX.2-klein-4B GGUF — CPU-only Inference Space
|
| 3 |
-
硬件
|
| 4 |
"""
|
| 5 |
|
| 6 |
import os
|
| 7 |
-
import
|
|
|
|
| 8 |
import torch
|
| 9 |
-
import
|
| 10 |
-
from
|
| 11 |
|
| 12 |
# ── 环境配置 ──────────────────────────────────────────────────
|
| 13 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 14 |
-
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
|
| 15 |
torch.set_num_threads(os.cpu_count() or 4)
|
| 16 |
|
| 17 |
-
|
|
|
|
| 18 |
|
| 19 |
-
# ──
|
| 20 |
print("╔═══════════════════════════════════════════════════╗")
|
| 21 |
print("║ FLUX.2-klein-4B GGUF — CPU Inference ║")
|
| 22 |
print("╚═══════════════════════════════════════════════════╝")
|
| 23 |
-
print(f" Model : {MODEL_ID}")
|
| 24 |
-
print(f" Threads : {torch.get_num_threads()}")
|
| 25 |
-
print(f" PyTorch : {torch.__version__}")
|
| 26 |
-
print(" Loading...")
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
# from diffusers import FluxPipeline
|
| 38 |
-
# BASE_ID = "black-forest-labs/FLUX.2-klein-4B" # 原始非量化模型
|
| 39 |
-
# pipe = FluxPipeline.from_pretrained(BASE_ID, torch_dtype=torch.float32)
|
| 40 |
-
# # 然后用 gguf 包手动加载量化权重替换 pipe.transformer
|
| 41 |
-
|
| 42 |
-
print(" ✓ Model loaded successfully!\n")
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
# ── 推理函数 ──────────────────────────────────────────────────
|
| 46 |
@torch.no_grad()
|
|
@@ -54,17 +209,13 @@ def generate(
|
|
| 54 |
seed: int,
|
| 55 |
progress=gr.Progress(track_tqdm=True),
|
| 56 |
):
|
| 57 |
-
"""文本生成图像"""
|
| 58 |
-
|
| 59 |
if not prompt.strip():
|
| 60 |
raise gr.Error("请输入提示词")
|
| 61 |
|
| 62 |
-
# 种子处理
|
| 63 |
seed = seed if seed >= 0 else int(time.time() * 1000) % (2**32)
|
| 64 |
generator = torch.Generator("cpu").manual_seed(seed)
|
| 65 |
|
| 66 |
t0 = time.time()
|
| 67 |
-
|
| 68 |
result = pipe(
|
| 69 |
prompt=prompt,
|
| 70 |
negative_prompt=negative_prompt if negative_prompt.strip() else None,
|
|
@@ -74,251 +225,80 @@ def generate(
|
|
| 74 |
guidance_scale=guidance,
|
| 75 |
generator=generator,
|
| 76 |
)
|
| 77 |
-
|
| 78 |
dt = time.time() - t0
|
| 79 |
-
img = result.images[0]
|
| 80 |
|
| 81 |
-
return
|
| 82 |
|
| 83 |
|
| 84 |
-
# ── 样式 ──────────────────────────────────────────────────
|
| 85 |
CSS = """
|
| 86 |
-
:root
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
}
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
.
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
max-width: 1080px !important;
|
| 102 |
-
padding-top: 1rem !important;
|
| 103 |
-
}
|
| 104 |
-
|
| 105 |
-
/* 卡片 */
|
| 106 |
-
.gr-block, .gr-panel {
|
| 107 |
-
background: var(--card) !important;
|
| 108 |
-
border: 1px solid var(--border) !important;
|
| 109 |
-
border-radius: 14px !important;
|
| 110 |
-
}
|
| 111 |
-
|
| 112 |
-
/* 输入框 */
|
| 113 |
-
.gr-input, .gr-text-input, textarea.gr-textbox,
|
| 114 |
-
input[type=number].gr-number {
|
| 115 |
-
background: #0e0e16 !important;
|
| 116 |
-
border: 1px solid var(--border) !important;
|
| 117 |
-
color: var(--fg) !important;
|
| 118 |
-
border-radius: 10px !important;
|
| 119 |
-
font-size: .92rem !important;
|
| 120 |
-
}
|
| 121 |
-
textarea.gr-textbox { resize: vertical !important; }
|
| 122 |
-
|
| 123 |
-
/* 标签 */
|
| 124 |
-
.gr-label {
|
| 125 |
-
color: var(--muted) !important;
|
| 126 |
-
font-size: .78rem !important;
|
| 127 |
-
text-transform: uppercase !important;
|
| 128 |
-
letter-spacing: .06em !important;
|
| 129 |
-
font-weight: 600 !important;
|
| 130 |
-
}
|
| 131 |
-
|
| 132 |
-
/* 按钮 */
|
| 133 |
-
.gr-button-primary {
|
| 134 |
-
background: linear-gradient(135deg, #7c5cfc, #a78bfa) !important;
|
| 135 |
-
border: none !important;
|
| 136 |
-
font-weight: 700 !important;
|
| 137 |
-
font-size: 1rem !important;
|
| 138 |
-
border-radius: 10px !important;
|
| 139 |
-
padding: .7rem 1.5rem !important;
|
| 140 |
-
box-shadow: 0 4px 24px var(--accent-glow) !important;
|
| 141 |
-
transition: all .2s ease !important;
|
| 142 |
-
}
|
| 143 |
-
.gr-button-primary:hover {
|
| 144 |
-
transform: translateY(-1px) !important;
|
| 145 |
-
box-shadow: 0 6px 32px var(--accent-glow) !important;
|
| 146 |
-
filter: brightness(1.1) !important;
|
| 147 |
-
}
|
| 148 |
-
.gr-button-primary:active {
|
| 149 |
-
transform: translateY(0) !important;
|
| 150 |
-
}
|
| 151 |
-
|
| 152 |
-
/* 滑块 */
|
| 153 |
-
.gr-slider input[type=range] { accent-color: var(--accent) !important; }
|
| 154 |
-
|
| 155 |
-
/* 图片输出 */
|
| 156 |
-
.gr-image { border-radius: 12px !important; overflow: hidden !important; }
|
| 157 |
-
.gr-image img { border-radius: 12px !important; }
|
| 158 |
-
|
| 159 |
-
/* Examples */
|
| 160 |
-
.gr-examples { border-radius: 12px !important; }
|
| 161 |
-
|
| 162 |
-
/* 隐藏 footer */
|
| 163 |
-
footer { display: none !important; }
|
| 164 |
-
|
| 165 |
-
/* 滚动条 */
|
| 166 |
-
::-webkit-scrollbar { width: 6px; }
|
| 167 |
-
::-webkit-scrollbar-track { background: transparent; }
|
| 168 |
-
::-webkit-scrollbar-thumb { background: #333; border-radius: 3px; }
|
| 169 |
-
|
| 170 |
-
/* 警告条 */
|
| 171 |
-
.warn-bar {
|
| 172 |
-
background: linear-gradient(90deg, #1c1a2e, #1a1428);
|
| 173 |
-
border: 1px solid #2e2848;
|
| 174 |
-
border-radius: 10px;
|
| 175 |
-
padding: .7rem 1rem;
|
| 176 |
-
margin-bottom: 1.2rem;
|
| 177 |
-
font-size: .82rem;
|
| 178 |
-
color: #a0a0b8;
|
| 179 |
-
line-height: 1.5;
|
| 180 |
-
}
|
| 181 |
-
.warn-bar strong { color: #c4b5fd; }
|
| 182 |
-
|
| 183 |
-
/* 信息栏 */
|
| 184 |
-
.info-bar {
|
| 185 |
-
background: #0e0e16;
|
| 186 |
-
border: 1px solid var(--border);
|
| 187 |
-
border-radius: 8px;
|
| 188 |
-
padding: .5rem .8rem;
|
| 189 |
-
font-size: .82rem;
|
| 190 |
-
color: var(--muted);
|
| 191 |
-
font-family: 'SF Mono', 'Fira Code', monospace;
|
| 192 |
-
}
|
| 193 |
"""
|
| 194 |
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
theme=gr.themes.Soft(primary_hue="violet"),
|
| 200 |
-
) as demo:
|
| 201 |
|
| 202 |
-
# ── 顶部标题 ──
|
| 203 |
gr.HTML("""
|
| 204 |
-
<div style="text-align:center;
|
| 205 |
-
<h1 style="font-size:2.4rem;
|
| 206 |
background:linear-gradient(135deg,#7c5cfc 0%,#c084fc 50%,#f0abfc 100%);
|
| 207 |
-
-webkit-background-clip:text;
|
| 208 |
-
margin:0;
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
</p>
|
| 215 |
-
</div>
|
| 216 |
-
""")
|
| 217 |
-
|
| 218 |
-
# ── 警告 ──
|
| 219 |
gr.HTML("""
|
| 220 |
<div class="warn-bar">
|
| 221 |
-
⚠ 纯 CPU 推理,速度较慢。建议 <strong>512×512</strong> 以下
|
| 222 |
-
<strong>8~12 步</strong>
|
| 223 |
-
|
| 224 |
-
</div>
|
| 225 |
-
""")
|
| 226 |
|
| 227 |
with gr.Row(equal_height=False):
|
| 228 |
-
|
| 229 |
-
# ── 左栏:控制面板 ──
|
| 230 |
with gr.Column(scale=3):
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
label="Prompt",
|
| 234 |
-
placeholder="A cyberpunk city at night with neon signs reflecting in rain-soaked streets, cinematic lighting...",
|
| 235 |
-
lines=3,
|
| 236 |
-
show_label=True,
|
| 237 |
-
)
|
| 238 |
-
|
| 239 |
-
negative_prompt = gr.Textbox(
|
| 240 |
-
label="Negative Prompt",
|
| 241 |
-
placeholder="blurry, low quality, distorted, watermark...",
|
| 242 |
-
lines=1,
|
| 243 |
-
show_label=True,
|
| 244 |
-
)
|
| 245 |
-
|
| 246 |
with gr.Row():
|
| 247 |
w = gr.Slider(256, 768, value=512, step=64, label="Width")
|
| 248 |
h = gr.Slider(256, 768, value=512, step=64, label="Height")
|
| 249 |
-
|
| 250 |
with gr.Row():
|
| 251 |
steps = gr.Slider(4, 30, value=10, step=1, label="Steps")
|
| 252 |
guidance = gr.Slider(1.0, 10.0, value=3.5, step=0.5, label="Guidance Scale")
|
| 253 |
-
|
| 254 |
seed = gr.Number(label="Seed(-1 随机)", value=-1, precision=0)
|
| 255 |
-
|
| 256 |
btn = gr.Button("✦ Generate", variant="primary", size="lg")
|
| 257 |
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
"Futuristic space station interior, holographic star maps floating in zero gravity, bioluminescent plants, cinematic wide shot",
|
| 267 |
-
""
|
| 268 |
-
],
|
| 269 |
-
[
|
| 270 |
-
"Oil painting of a cozy wooden cabin in snowy mountains, warm orange light from windows, smoke from chimney, impressionist style",
|
| 271 |
-
""
|
| 272 |
-
],
|
| 273 |
-
[
|
| 274 |
-
"Macro photograph of a dewdrop on a spider web at sunrise, prismatic light refraction, extreme shallow depth of field",
|
| 275 |
-
""
|
| 276 |
-
],
|
| 277 |
-
[
|
| 278 |
-
"A whimsical treehouse library at twilight, floating books with glowing pages, warm lanterns, fairy tale atmosphere",
|
| 279 |
-
"blurry, low quality"
|
| 280 |
-
],
|
| 281 |
-
[
|
| 282 |
-
"Underwater coral reef city with bioluminescent architecture, schools of tropical fish, volumetric god rays, wide angle",
|
| 283 |
-
""
|
| 284 |
-
],
|
| 285 |
-
],
|
| 286 |
-
inputs=[prompt, negative_prompt],
|
| 287 |
-
label="Quick Examples",
|
| 288 |
-
)
|
| 289 |
-
|
| 290 |
-
# ── 右栏:输出 ──
|
| 291 |
-
with gr.Column(scale=4):
|
| 292 |
-
output_img = gr.Image(
|
| 293 |
-
label="Output",
|
| 294 |
-
show_label=False,
|
| 295 |
-
height=540,
|
| 296 |
-
elem_classes="output-image",
|
| 297 |
-
)
|
| 298 |
-
info_text = gr.Textbox(
|
| 299 |
-
label="Status",
|
| 300 |
-
interactive=False,
|
| 301 |
-
show_label=True,
|
| 302 |
-
max_lines=1,
|
| 303 |
-
elem_classes="info-bar",
|
| 304 |
-
value="Ready — enter a prompt and click Generate",
|
| 305 |
-
)
|
| 306 |
-
|
| 307 |
-
# ── 绑定事件 ──
|
| 308 |
-
btn.click(
|
| 309 |
-
fn=generate,
|
| 310 |
-
inputs=[prompt, negative_prompt, w, h, steps, guidance, seed],
|
| 311 |
-
outputs=[output_img, seed, info_text],
|
| 312 |
-
)
|
| 313 |
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
inputs=[prompt, negative_prompt, w, h, steps, guidance, seed],
|
| 318 |
-
outputs=[output_img, seed, info_text],
|
| 319 |
-
)
|
| 320 |
|
|
|
|
|
|
|
| 321 |
|
| 322 |
-
|
| 323 |
-
if __name__ == "__main__":
|
| 324 |
-
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 1 |
"""
|
| 2 |
FLUX.2-klein-4B GGUF — CPU-only Inference Space
|
| 3 |
+
硬件:无 GPU · CPU · 18 GB RAM
|
| 4 |
"""
|
| 5 |
|
| 6 |
import os
|
| 7 |
+
import sys
|
| 8 |
+
import json
|
| 9 |
import torch
|
| 10 |
+
import numpy as np
|
| 11 |
+
from huggingface_hub import login, hf_hub_download, list_repo_files
|
| 12 |
|
| 13 |
# ── 环境配置 ──────────────────────────────────────────────────
|
| 14 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
|
|
|
| 15 |
torch.set_num_threads(os.cpu_count() or 4)
|
| 16 |
|
| 17 |
+
GGUF_REPO = "unsloth/FLUX-2-klein-4B-GGUF"
|
| 18 |
+
TOKEN = os.environ.get("HF_TOKEN", "")
|
| 19 |
|
| 20 |
+
# ── 认证 ──────────────────────────────────────────────────────
|
| 21 |
print("╔═══════════════════════════════════════════════════╗")
|
| 22 |
print("║ FLUX.2-klein-4B GGUF — CPU Inference ║")
|
| 23 |
print("╚═══════════════════════════════════════════════════╝")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
if TOKEN:
|
| 26 |
+
login(token=TOKEN, add_to_git_credential=False)
|
| 27 |
+
print(" ✓ HF_TOKEN authenticated")
|
| 28 |
+
else:
|
| 29 |
+
print(" ✗ HF_TOKEN not set!")
|
| 30 |
+
print(" → Go to Space Settings → Repository Secrets → Add HF_TOKEN")
|
| 31 |
+
print(" → Get token: https://huggingface.co/settings/tokens")
|
| 32 |
+
print(" → Also accept model license on the model page first!\n")
|
| 33 |
|
| 34 |
+
print(f" Model : {GGUF_REPO}")
|
| 35 |
+
print(f" Threads : {torch.get_num_threads()}")
|
| 36 |
+
print(f" PyTorch : {torch.__version__}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
+
# ── 加载模型(双重策略) ─────────────────────────────────────
|
| 39 |
+
from diffusers import FluxPipeline, FluxTransformer2DModel
|
| 40 |
+
|
| 41 |
+
pipe = None
|
| 42 |
+
|
| 43 |
+
# ═══════════════════════════════════════════════════════════
|
| 44 |
+
# Strategy A:直接加载(diffusers 原生 GGUF 支持)
|
| 45 |
+
# ═══════════════════════════════════════════════════════════
|
| 46 |
+
if pipe is None:
|
| 47 |
+
try:
|
| 48 |
+
print("\n[A] Trying direct diffusers loading...")
|
| 49 |
+
pipe = FluxPipeline.from_pretrained(
|
| 50 |
+
GGUF_REPO,
|
| 51 |
+
torch_dtype=torch.float32,
|
| 52 |
+
token=TOKEN or None,
|
| 53 |
+
)
|
| 54 |
+
pipe.to("cpu")
|
| 55 |
+
print("[A] ✓ Direct loading succeeded!\n")
|
| 56 |
+
except Exception as e:
|
| 57 |
+
print(f"[A] ✗ Failed: {e}\n")
|
| 58 |
+
|
| 59 |
+
# ═══════════════════════════════════════════════════════════
|
| 60 |
+
# Strategy B:手动解析 GGUF → 注入 transformer
|
| 61 |
+
# ═══════════════════════════════════════════════════════════
|
| 62 |
+
if pipe is None:
|
| 63 |
+
try:
|
| 64 |
+
print("[B] Manual GGUF loading...")
|
| 65 |
+
from gguf import GGUFReader
|
| 66 |
+
|
| 67 |
+
# 1) 列出仓库文件,找到 .gguf
|
| 68 |
+
print(" Listing repo files...")
|
| 69 |
+
repo_files = list_repo_files(GGUF_REPO, token=TOKEN or None)
|
| 70 |
+
gguf_candidates = [f for f in repo_files if f.endswith(".gguf")]
|
| 71 |
+
if not gguf_candidates:
|
| 72 |
+
raise FileNotFoundError("No .gguf file found in repo")
|
| 73 |
+
|
| 74 |
+
# 优先选 Q4_K_M(精度与速度平衡),没有则选第一个
|
| 75 |
+
preferred = [f for f in gguf_candidates if "Q4_K_M" in f.upper()]
|
| 76 |
+
gguf_fname = preferred[0] if preferred else gguf_candidates[0]
|
| 77 |
+
print(f" Selected: {gguf_fname}")
|
| 78 |
+
|
| 79 |
+
# 2) 下载 GGUF 文件
|
| 80 |
+
print(" Downloading GGUF file...")
|
| 81 |
+
gguf_path = hf_hub_download(
|
| 82 |
+
GGUF_REPO, gguf_fname, token=TOKEN or None
|
| 83 |
+
)
|
| 84 |
+
print(f" Saved to: {gguf_path}")
|
| 85 |
+
|
| 86 |
+
# 3) 读取 GGUF 张量
|
| 87 |
+
print(" Reading GGUF tensors...")
|
| 88 |
+
reader = GGUFReader(gguf_path)
|
| 89 |
+
gguf_sd = {}
|
| 90 |
+
for tensor in reader.tensors:
|
| 91 |
+
name = tensor.name
|
| 92 |
+
if isinstance(name, bytes):
|
| 93 |
+
name = name.decode("utf-8")
|
| 94 |
+
data = np.array(tensor.data, dtype=np.float32)
|
| 95 |
+
data = data.reshape(tensor.shape).copy()
|
| 96 |
+
gguf_sd[name] = torch.from_numpy(data)
|
| 97 |
+
|
| 98 |
+
print(f" Loaded {len(gguf_sd)} tensors")
|
| 99 |
+
sample_keys = list(gguf_sd.keys())[:5]
|
| 100 |
+
print(f" Sample keys: {sample_keys}")
|
| 101 |
+
|
| 102 |
+
# 4) 下载 transformer config
|
| 103 |
+
print(" Loading transformer config...")
|
| 104 |
+
config_path = hf_hub_download(
|
| 105 |
+
GGUF_REPO, "transformer/config.json", token=TOKEN or None
|
| 106 |
+
)
|
| 107 |
+
with open(config_path, "r") as f:
|
| 108 |
+
tf_config = json.load(f)
|
| 109 |
+
|
| 110 |
+
# 5) 创建空 transformer 并加载 GGUF 权重
|
| 111 |
+
print(" Building transformer and loading weights...")
|
| 112 |
+
transformer = FluxTransformer2DModel.from_config(tf_config)
|
| 113 |
+
|
| 114 |
+
# 尝试多种 key 映射
|
| 115 |
+
loaded_ok = False
|
| 116 |
+
|
| 117 |
+
# B1: 直接映射
|
| 118 |
+
try:
|
| 119 |
+
info = transformer.load_state_dict(gguf_sd, strict=False)
|
| 120 |
+
missing = [k for k in info.missing_keys if "bias" not in k.lower()]
|
| 121 |
+
if len(missing) < 5:
|
| 122 |
+
loaded_ok = True
|
| 123 |
+
print(f" B1 ✓ Direct mapping (missing={len(missing)})")
|
| 124 |
+
except Exception:
|
| 125 |
+
pass
|
| 126 |
+
|
| 127 |
+
# B2: 加 "transformer." 前缀
|
| 128 |
+
if not loaded_ok:
|
| 129 |
+
try:
|
| 130 |
+
mapped = {"transformer." + k: v for k, v in gguf_sd.items()}
|
| 131 |
+
info = transformer.load_state_dict(mapped, strict=False)
|
| 132 |
+
missing = [k for k in info.missing_keys if "bias" not in k.lower()]
|
| 133 |
+
if len(missing) < 5:
|
| 134 |
+
loaded_ok = True
|
| 135 |
+
print(f" B2 ✓ Prefix mapping (missing={len(missing)})")
|
| 136 |
+
except Exception:
|
| 137 |
+
pass
|
| 138 |
+
|
| 139 |
+
# B3: 去掉已有前缀再映射
|
| 140 |
+
if not loaded_ok:
|
| 141 |
+
try:
|
| 142 |
+
mapped = {}
|
| 143 |
+
for k, v in gguf_sd.items():
|
| 144 |
+
new_key = k
|
| 145 |
+
for prefix in ["transformer.", "model."]:
|
| 146 |
+
if k.startswith(prefix):
|
| 147 |
+
new_key = k[len(prefix):]
|
| 148 |
+
break
|
| 149 |
+
mapped[new_key] = v
|
| 150 |
+
info = transformer.load_state_dict(mapped, strict=False)
|
| 151 |
+
missing = [k for k in info.missing_keys if "bias" not in k.lower()]
|
| 152 |
+
if len(missing) < 5:
|
| 153 |
+
loaded_ok = True
|
| 154 |
+
print(f" B3 ✓ Strip-prefix mapping (missing={len(missing)})")
|
| 155 |
+
except Exception:
|
| 156 |
+
pass
|
| 157 |
+
|
| 158 |
+
if not loaded_ok:
|
| 159 |
+
# 打印诊断信息帮助调试
|
| 160 |
+
model_keys = set(transformer.state_dict().keys())
|
| 161 |
+
gguf_keys = set(gguf_sd.keys())
|
| 162 |
+
print(f"\n ── Key mismatch diagnostics ──")
|
| 163 |
+
print(f" Model expects {len(model_keys)} keys")
|
| 164 |
+
print(f" GGUF has {len(gguf_keys)} keys")
|
| 165 |
+
print(f" Model key sample : {list(model_keys)[:3]}")
|
| 166 |
+
print(f" GGUF key sample : {list(gguf_keys)[:3]}")
|
| 167 |
+
raise RuntimeError("Could not map GGUF keys to model keys")
|
| 168 |
+
|
| 169 |
+
# 6) 构建完整 pipeline(传入 transformer 跳过磁盘加载)
|
| 170 |
+
print(" Building full pipeline...")
|
| 171 |
+
pipe = FluxPipeline.from_pretrained(
|
| 172 |
+
GGUF_REPO,
|
| 173 |
+
transformer=transformer,
|
| 174 |
+
torch_dtype=torch.float32,
|
| 175 |
+
token=TOKEN or None,
|
| 176 |
+
)
|
| 177 |
+
pipe.to("cpu")
|
| 178 |
+
print("[B] ✓ Manual GGUF loading succeeded!\n")
|
| 179 |
+
|
| 180 |
+
except Exception as e:
|
| 181 |
+
print(f"[B] ✗ Failed: {e}")
|
| 182 |
+
import traceback
|
| 183 |
+
traceback.print_exc()
|
| 184 |
+
print()
|
| 185 |
+
|
| 186 |
+
# ── 最终检查 ──────────────────────────────────────────────────
|
| 187 |
+
if pipe is None:
|
| 188 |
+
print("=" * 58)
|
| 189 |
+
print("FATAL: Could not load model.")
|
| 190 |
+
print("")
|
| 191 |
+
print("Please check:")
|
| 192 |
+
print(" 1. HF_TOKEN is set as a Space secret")
|
| 193 |
+
print(" 2. You have accepted the model license at:")
|
| 194 |
+
print(f" https://huggingface.co/{GGUF_REPO}")
|
| 195 |
+
print("=" * 58)
|
| 196 |
+
sys.exit(1)
|
| 197 |
+
|
| 198 |
+
print("✓ Model ready for inference!\n")
|
| 199 |
|
| 200 |
# ── 推理函数 ──────────────────────────────────────────────────
|
| 201 |
@torch.no_grad()
|
|
|
|
| 209 |
seed: int,
|
| 210 |
progress=gr.Progress(track_tqdm=True),
|
| 211 |
):
|
|
|
|
|
|
|
| 212 |
if not prompt.strip():
|
| 213 |
raise gr.Error("请输入提示词")
|
| 214 |
|
|
|
|
| 215 |
seed = seed if seed >= 0 else int(time.time() * 1000) % (2**32)
|
| 216 |
generator = torch.Generator("cpu").manual_seed(seed)
|
| 217 |
|
| 218 |
t0 = time.time()
|
|
|
|
| 219 |
result = pipe(
|
| 220 |
prompt=prompt,
|
| 221 |
negative_prompt=negative_prompt if negative_prompt.strip() else None,
|
|
|
|
| 225 |
guidance_scale=guidance,
|
| 226 |
generator=generator,
|
| 227 |
)
|
|
|
|
| 228 |
dt = time.time() - t0
|
|
|
|
| 229 |
|
| 230 |
+
return result.images[0], seed, f"完成 · 耗时 {dt:.1f}s · seed {seed}"
|
| 231 |
|
| 232 |
|
| 233 |
+
# ── 界面样式 ──────────────────────────────────────────────────
|
| 234 |
CSS = """
|
| 235 |
+
:root{--bg:#0a0a0f;--card:#13131a;--border:#23233a;--fg:#e4e4ec;--muted:#6b6b80;--accent:#7c5cfc;--glow:rgba(124,92,252,.25)}
|
| 236 |
+
.gradio-container{background:var(--bg)!important;color:var(--fg)!important;max-width:1080px!important;padding-top:1rem!important}
|
| 237 |
+
.gr-block,.gr-panel{background:var(--card)!important;border:1px solid var(--border)!important;border-radius:14px!important}
|
| 238 |
+
.gr-input,textarea.gr-textbox,input[type=number].gr-number{background:#0e0e16!important;border:1px solid var(--border)!important;color:var(--fg)!important;border-radius:10px!important;font-size:.92rem!important}
|
| 239 |
+
textarea.gr-textbox{resize:vertical!important}
|
| 240 |
+
.gr-label{color:var(--muted)!important;font-size:.78rem!important;text-transform:uppercase!important;letter-spacing:.06em!important;font-weight:600!important}
|
| 241 |
+
.gr-button-primary{background:linear-gradient(135deg,#7c5cfc,#a78bfa)!important;border:none!important;font-weight:700!important;font-size:1rem!important;border-radius:10px!important;padding:.7rem 1.5rem!important;box-shadow:0 4px 24px var(--glow)!important;transition:all .2s ease!important}
|
| 242 |
+
.gr-button-primary:hover{transform:translateY(-1px)!important;box-shadow:0 6px 32px var(--glow)!important;filter:brightness(1.1)!important}
|
| 243 |
+
.gr-slider input[type=range]{accent-color:var(--accent)!important}
|
| 244 |
+
.gr-image{border-radius:12px!important;overflow:hidden!important}
|
| 245 |
+
footer{display:none!important}
|
| 246 |
+
::-webkit-scrollbar{width:6px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:#333;border-radius:3px}
|
| 247 |
+
.warn-bar{background:linear-gradient(90deg,#1c1a2e,#1a1428);border:1px solid #2e2848;border-radius:10px;padding:.7rem 1rem;margin-bottom:1.2rem;font-size:.82rem;color:#a0a0b8;line-height:1.5}
|
| 248 |
+
.warn-bar strong{color:#c4b5fd}
|
| 249 |
+
.info-bar{background:#0e0e16;border:1px solid var(--border);border-radius:8px;padding:.5rem .8rem;font-size:.82rem;color:var(--muted);font-family:'SF Mono','Fira Code',monospace}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
"""
|
| 251 |
|
| 252 |
+
import time
|
| 253 |
+
import gradio as gr
|
| 254 |
+
|
| 255 |
+
with gr.Blocks(title="FLUX.2-klein-4B GGUF", css=CSS, theme=gr.themes.Soft(primary_hue="violet")) as demo:
|
|
|
|
|
|
|
| 256 |
|
|
|
|
| 257 |
gr.HTML("""
|
| 258 |
+
<div style="text-align:center;padding:2rem 0 .6rem">
|
| 259 |
+
<h1 style="font-size:2.4rem;font-weight:800;letter-spacing:-.03em;
|
| 260 |
background:linear-gradient(135deg,#7c5cfc 0%,#c084fc 50%,#f0abfc 100%);
|
| 261 |
+
-webkit-background-clip:text;-webkit-text-fill-color:transparent;
|
| 262 |
+
margin:0;line-height:1.2">FLUX.2-klein-4B</h1>
|
| 263 |
+
<p style="color:#555;font-size:.88rem;margin-top:.5rem;font-weight:500;
|
| 264 |
+
letter-spacing:.08em;text-transform:uppercase">
|
| 265 |
+
GGUF Quantized · CPU Inference · 4B Parameters</p>
|
| 266 |
+
</div>""")
|
| 267 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
gr.HTML("""
|
| 269 |
<div class="warn-bar">
|
| 270 |
+
⚠ 纯 CPU 推理,速度较慢。建议 <strong>512×512</strong> 以下 +
|
| 271 |
+
<strong>8~12 步</strong>。首次生成因 JIT 编译更慢,后续加速。
|
| 272 |
+
超时请降低分辨率或步数。
|
| 273 |
+
</div>""")
|
|
|
|
| 274 |
|
| 275 |
with gr.Row(equal_height=False):
|
|
|
|
|
|
|
| 276 |
with gr.Column(scale=3):
|
| 277 |
+
prompt = gr.Textbox(label="Prompt", placeholder="A cyberpunk city at night with neon signs reflecting in rain-soaked streets...", lines=3)
|
| 278 |
+
negative_prompt = gr.Textbox(label="Negative Prompt", placeholder="blurry, low quality, distorted...", lines=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
with gr.Row():
|
| 280 |
w = gr.Slider(256, 768, value=512, step=64, label="Width")
|
| 281 |
h = gr.Slider(256, 768, value=512, step=64, label="Height")
|
|
|
|
| 282 |
with gr.Row():
|
| 283 |
steps = gr.Slider(4, 30, value=10, step=1, label="Steps")
|
| 284 |
guidance = gr.Slider(1.0, 10.0, value=3.5, step=0.5, label="Guidance Scale")
|
|
|
|
| 285 |
seed = gr.Number(label="Seed(-1 随机)", value=-1, precision=0)
|
|
|
|
| 286 |
btn = gr.Button("✦ Generate", variant="primary", size="lg")
|
| 287 |
|
| 288 |
+
gr.Examples(examples=[
|
| 289 |
+
["A serene Japanese garden with cherry blossoms over a stone bridge, koi pond, golden hour, 4K", ""],
|
| 290 |
+
["Futuristic space station interior, holographic star maps, bioluminescent plants, cinematic wide shot", ""],
|
| 291 |
+
["Oil painting of a cozy wooden cabin in snowy mountains, warm light from windows, impressionist style", ""],
|
| 292 |
+
["Macro photograph of a dewdrop on a spider web at sunrise, prismatic light, shallow depth of field", ""],
|
| 293 |
+
["Whimsical treehouse library at twilight, floating books with glowing pages, fairy tale atmosphere", "blurry"],
|
| 294 |
+
["Underwater coral reef city, bioluminescent architecture, tropical fish, volumetric god rays", ""],
|
| 295 |
+
], inputs=[prompt, negative_prompt], label="Quick Examples")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
|
| 297 |
+
with gr.Column(scale=4):
|
| 298 |
+
output_img = gr.Image(label="Output", show_label=False, height=540)
|
| 299 |
+
info_text = gr.Textbox(label="Status", interactive=False, max_lines=1, elem_classes="info-bar", value="Ready")
|
|
|
|
|
|
|
|
|
|
| 300 |
|
| 301 |
+
btn.click(fn=generate, inputs=[prompt, negative_prompt, w, h, steps, guidance, seed], outputs=[output_img, seed, info_text])
|
| 302 |
+
prompt.submit(fn=generate, inputs=[prompt, negative_prompt, w, h, steps, guidance, seed], outputs=[output_img, seed, info_text])
|
| 303 |
|
| 304 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
|
|