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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
调用 Hugging Face Spaces:wkea/blockdiffusion-api
|
| 5 |
+
|
| 6 |
+
用途:
|
| 7 |
+
- 以“伪私有”方式调用 Space(必须提供 SPACE_API_KEY)
|
| 8 |
+
- 传入 prompt / CFG / DDIM 等参数
|
| 9 |
+
- 将返回的 grid 与 gallery 图片保存到本地目录
|
| 10 |
+
|
| 11 |
+
说明:
|
| 12 |
+
- 本脚本优先使用 gradio_client(推荐且最稳定)
|
| 13 |
+
- 若你的环境缺少 gradio_client,请先安装后再运行(通常安装 gradio 时会自带)
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import os
|
| 18 |
+
import shutil
|
| 19 |
+
from datetime import datetime
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
from typing import Any, List, Tuple
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
DEFAULT_SPACE = "wkea/blockdiffusion-api"
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _now_tag() -> str:
|
| 28 |
+
return datetime.now().strftime("%Y%m%d-%H%M%S")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _ensure_dir(p: str) -> str:
|
| 32 |
+
Path(p).mkdir(parents=True, exist_ok=True)
|
| 33 |
+
return p
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _as_path(maybe_path: Any) -> str | None:
|
| 37 |
+
"""
|
| 38 |
+
gradio_client 的 Image/Gallery 返回值常见形式:
|
| 39 |
+
- 本地文件路径(str)
|
| 40 |
+
- {"path": "..."} / {"name": "..."} 之类的 dict
|
| 41 |
+
本函数尽量从这些结构中提取本地路径。
|
| 42 |
+
"""
|
| 43 |
+
if maybe_path is None:
|
| 44 |
+
return None
|
| 45 |
+
if isinstance(maybe_path, str):
|
| 46 |
+
return maybe_path
|
| 47 |
+
if isinstance(maybe_path, dict):
|
| 48 |
+
for k in ("path", "name", "file", "filepath"):
|
| 49 |
+
v = maybe_path.get(k, None)
|
| 50 |
+
if isinstance(v, str) and v:
|
| 51 |
+
return v
|
| 52 |
+
return None
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _save_one(src: Any, dst_path: str) -> str | None:
|
| 56 |
+
"""
|
| 57 |
+
把 gradio_client 返回的文件对象/路径落盘到 dst_path。
|
| 58 |
+
"""
|
| 59 |
+
sp = _as_path(src)
|
| 60 |
+
if not sp:
|
| 61 |
+
return None
|
| 62 |
+
if not os.path.isfile(sp):
|
| 63 |
+
return None
|
| 64 |
+
_ensure_dir(str(Path(dst_path).parent))
|
| 65 |
+
shutil.copyfile(sp, dst_path)
|
| 66 |
+
return dst_path
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _call_space(
|
| 70 |
+
space: str,
|
| 71 |
+
api_key: str,
|
| 72 |
+
prompt: str,
|
| 73 |
+
cfg_scale: float,
|
| 74 |
+
use_ema: bool,
|
| 75 |
+
use_ddim: bool,
|
| 76 |
+
ddim_steps: int,
|
| 77 |
+
ddim_eta: float,
|
| 78 |
+
n_images: int,
|
| 79 |
+
batch: int,
|
| 80 |
+
seed: int,
|
| 81 |
+
preview_upscale: int,
|
| 82 |
+
) -> Tuple[str, Any, List[Any]]:
|
| 83 |
+
"""
|
| 84 |
+
返回:(info_text, grid_obj, gallery_objs)
|
| 85 |
+
"""
|
| 86 |
+
try:
|
| 87 |
+
from gradio_client import Client # type: ignore
|
| 88 |
+
except Exception as e:
|
| 89 |
+
raise RuntimeError("缺少依赖:gradio_client(建议安装 gradio 时一并安装)") from e
|
| 90 |
+
|
| 91 |
+
# Space 是公开的,通常不需要 hf_token;仅当 Space 本身是私有才需要。
|
| 92 |
+
client = Client(space)
|
| 93 |
+
|
| 94 |
+
# 输入顺序必须与 Space 的 gradio inputs 一致(见 app.py run.click(inputs=...))
|
| 95 |
+
res = client.predict(
|
| 96 |
+
api_key,
|
| 97 |
+
prompt,
|
| 98 |
+
float(cfg_scale),
|
| 99 |
+
bool(use_ema),
|
| 100 |
+
bool(use_ddim),
|
| 101 |
+
int(ddim_steps),
|
| 102 |
+
float(ddim_eta),
|
| 103 |
+
int(n_images),
|
| 104 |
+
int(batch),
|
| 105 |
+
int(seed),
|
| 106 |
+
int(preview_upscale),
|
| 107 |
+
fn_index=0,
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
# 期望输出:(info, grid, gallery)
|
| 111 |
+
if not isinstance(res, (list, tuple)) or len(res) != 3:
|
| 112 |
+
raise RuntimeError(f"Space返回结构异常:{type(res)} len={getattr(res, '__len__', lambda: 'NA')()}")
|
| 113 |
+
info, grid, gallery = res[0], res[1], res[2]
|
| 114 |
+
if not isinstance(gallery, list):
|
| 115 |
+
gallery = []
|
| 116 |
+
return str(info), grid, gallery
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def parse_args() -> argparse.Namespace:
|
| 120 |
+
p = argparse.ArgumentParser(description="调用 Hugging Face Space:BlockDiffusion API(伪私有)")
|
| 121 |
+
p.add_argument("--space", type=str, default=DEFAULT_SPACE, help="Space 名称,例如 wkea/blockdiffusion-api")
|
| 122 |
+
p.add_argument(
|
| 123 |
+
"--api_key",
|
| 124 |
+
type=str,
|
| 125 |
+
default=os.getenv("SPACE_API_KEY", ""),
|
| 126 |
+
help="伪私有 API_KEY(优先从环境变量 SPACE_API_KEY 读取)",
|
| 127 |
+
)
|
| 128 |
+
p.add_argument("--prompt", type=str, default="stone block texture", help="提示词(条件模型可用;留空=无条件)")
|
| 129 |
+
p.add_argument("--cfg_scale", type=float, default=3.0)
|
| 130 |
+
p.add_argument("--use_ema", action="store_true", help="使用 EMA 权重(推荐)")
|
| 131 |
+
p.add_argument("--no_use_ema", action="store_true", help="禁用 EMA(仅排查用)")
|
| 132 |
+
p.add_argument("--use_ddim", action="store_true", help="使用 DDIM(更快)")
|
| 133 |
+
p.add_argument("--no_use_ddim", action="store_true", help="禁用 DDIM(用 DDPM)")
|
| 134 |
+
p.add_argument("--ddim_steps", type=int, default=50)
|
| 135 |
+
p.add_argument("--ddim_eta", type=float, default=0.0)
|
| 136 |
+
p.add_argument("--n", type=int, default=1, help="生成张数(Space建议<=8)")
|
| 137 |
+
p.add_argument("--batch", type=int, default=1)
|
| 138 |
+
p.add_argument("--seed", type=int, default=123)
|
| 139 |
+
p.add_argument("--preview_upscale", type=int, default=16)
|
| 140 |
+
p.add_argument("--out_dir", type=str, default="space_outputs", help="输出目录")
|
| 141 |
+
return p.parse_args()
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def main() -> None:
|
| 145 |
+
args = parse_args()
|
| 146 |
+
if not (args.api_key or "").strip():
|
| 147 |
+
raise RuntimeError("缺少 --api_key ���环境变量 SPACE_API_KEY(Space端要求必填)")
|
| 148 |
+
|
| 149 |
+
use_ema = bool(args.use_ema) and (not bool(args.no_use_ema))
|
| 150 |
+
use_ddim = bool(args.use_ddim) and (not bool(args.no_use_ddim))
|
| 151 |
+
|
| 152 |
+
out_dir = _ensure_dir(args.out_dir)
|
| 153 |
+
tag = _now_tag()
|
| 154 |
+
|
| 155 |
+
info, grid, gallery = _call_space(
|
| 156 |
+
space=args.space,
|
| 157 |
+
api_key=args.api_key,
|
| 158 |
+
prompt=args.prompt,
|
| 159 |
+
cfg_scale=float(args.cfg_scale),
|
| 160 |
+
use_ema=use_ema,
|
| 161 |
+
use_ddim=use_ddim,
|
| 162 |
+
ddim_steps=int(args.ddim_steps),
|
| 163 |
+
ddim_eta=float(args.ddim_eta),
|
| 164 |
+
n_images=int(args.n),
|
| 165 |
+
batch=int(args.batch),
|
| 166 |
+
seed=int(args.seed),
|
| 167 |
+
preview_upscale=int(args.preview_upscale),
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
# 保存 info
|
| 171 |
+
info_path = os.path.join(out_dir, f"info_{tag}.txt")
|
| 172 |
+
Path(info_path).write_text(info, encoding="utf-8")
|
| 173 |
+
|
| 174 |
+
# 保存 grid
|
| 175 |
+
grid_path = os.path.join(out_dir, f"grid_{tag}.png")
|
| 176 |
+
_save_one(grid, grid_path)
|
| 177 |
+
|
| 178 |
+
# 保存 gallery(如果有)
|
| 179 |
+
saved = 0
|
| 180 |
+
for i, one in enumerate(gallery):
|
| 181 |
+
p = os.path.join(out_dir, f"img_{tag}_{i:02d}.png")
|
| 182 |
+
if _save_one(one, p):
|
| 183 |
+
saved += 1
|
| 184 |
+
|
| 185 |
+
print(f"[ok] out_dir={out_dir} grid={grid_path} gallery_saved={saved} info={info_path}")
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
if __name__ == "__main__":
|
| 189 |
+
main()
|
| 190 |
+
|
| 191 |
+
|
webui.py
CHANGED
|
@@ -382,9 +382,9 @@ def _sample(
|
|
| 382 |
if prompt_tokens
|
| 383 |
else ""
|
| 384 |
)
|
| 385 |
-
f"preview_upscale(NEAREST): {int(preview_upscale)}x\n"
|
| 386 |
-
f"save: {os.path.abspath(out_path)}\n"
|
| 387 |
-
f"time: {dt:.2f}s\n"
|
| 388 |
)
|
| 389 |
return info, os.path.abspath(out_path), gallery, grid_im
|
| 390 |
|
|
|
|
| 382 |
if prompt_tokens
|
| 383 |
else ""
|
| 384 |
)
|
| 385 |
+
+ f"preview_upscale(NEAREST): {int(preview_upscale)}x\n"
|
| 386 |
+
+ f"save: {os.path.abspath(out_path)}\n"
|
| 387 |
+
+ f"time: {dt:.2f}s\n"
|
| 388 |
)
|
| 389 |
return info, os.path.abspath(out_path), gallery, grid_im
|
| 390 |
|