Buckets:
| #!/usr/bin/env python3 | |
| """Forge Neo 2.29 / Linux: generate one Anima Halloween image through the local API. | |
| Python standard library only. Nothing runs until you execute this script. | |
| Examples: | |
| python3 forge_neo_anima_halloween.py | |
| python3 forge_neo_anima_halloween.py --url http://127.0.0.1:7861 | |
| python3 forge_neo_anima_halloween.py --output-dir ./my_images | |
| Forge Neo must already be running with --api. The checkpoint, companion | |
| modules and three LoRAs must already be installed on the Forge Neo server. | |
| """ | |
| import argparse | |
| import base64 | |
| from datetime import datetime | |
| import json | |
| from pathlib import Path | |
| import sys | |
| from urllib.error import HTTPError, URLError | |
| from urllib.request import Request, urlopen | |
| import os | |
| MODEL_NAME = "anima-base-v1.0" | |
| MODEL_SHORT_HASH = "bd43b7cffe" | |
| MODULE_NAMES = ("qwen_image_vae", "qwen_3_06b_base") | |
| SEED = 1141574337 | |
| PROMPT = """realstyle2, 1girl, beach, bikini, silk, ribbon, hoshimachi suisei, hololive, oshi no ko, highres, absurdres, ai-generated, widescreen, standing, sunlight, ray tracing, smile, looking at viewers, front view | |
| <lora:realstyle2_anima-000040:1>""" | |
| NEGATIVE_PROMPT = """Lowres, worst quality, low quality, blurry, (jpeg artifacts, grainy, cropped and out of frame, overexposed, signature, watermark, text, multiple angles, artist name, simple background, unfinished, flat background, Poorly defined details, with bad proportions, off-topic, poorly drawn crappy art of bad quality:1.5) (score_1, score_2, score_3:0.25)""" | |
| def api_call(base_url, path, payload=None, *, auth=None, timeout=30): | |
| """GET if payload is None, otherwise POST JSON.""" | |
| data = None if payload is None else json.dumps(payload).encode("utf-8") | |
| headers = {"Accept": "application/json"} | |
| if data is not None: | |
| headers["Content-Type"] = "application/json" | |
| if auth is not None: | |
| token = base64.b64encode(f"{auth[0]}:{auth[1]}".encode()).decode("ascii") | |
| headers["Authorization"] = f"Basic {token}" | |
| req = Request(base_url + path, data=data, headers=headers) | |
| try: | |
| with urlopen(req, timeout=timeout) as response: | |
| return json.load(response) | |
| except HTTPError as exc: | |
| detail = exc.read().decode("utf-8", errors="replace")[:2000] | |
| raise RuntimeError(f"{path}: HTTP {exc.code}: {detail}") from exc | |
| except URLError as exc: | |
| raise RuntimeError(f"{path}: 连接失败:{exc.reason}。确认 Forge 已用 --api 启动,地址/端口正确。") from exc | |
| def name_matches(item, expected): | |
| target = expected.casefold() | |
| for key in ("model_name", "filename"): | |
| val = item.get(key) | |
| if isinstance(val, str): | |
| basename = val.replace("\\", "/").rsplit("/", 1)[-1] | |
| # Don't use Path.stem on a model_name like "anima-base-v1.0": | |
| # it would incorrectly strip ".0" as a file extension. | |
| for extension in (".safetensors", ".ckpt", ".pt", ".bin", ".gguf"): | |
| if basename.casefold().endswith(extension): | |
| basename = basename[: -len(extension)] | |
| break | |
| if basename.casefold() == target: | |
| return True | |
| return False | |
| def select_checkpoint(models): | |
| candidates = [m for m in models if name_matches(m, MODEL_NAME)] | |
| if not candidates: | |
| raise RuntimeError(f"未发现主模型 {MODEL_NAME}(请在 Forge 里刷新模型列表)。") | |
| def checked_hashes(model): | |
| values = [] | |
| for key in ("shorthash", "sha256"): | |
| value = model.get(key) | |
| if isinstance(value, str) and value: | |
| values.append(value.lower().removeprefix("0x")) | |
| return values | |
| exact = [m for m in candidates if any(h.startswith(MODEL_SHORT_HASH) for h in checked_hashes(m))] | |
| if len(exact) == 1: | |
| selected = exact[0] | |
| elif len(candidates) == 1 and not checked_hashes(candidates[0]): | |
| selected = candidates[0] | |
| print("警告:服务端未返回 SHA256,无法核对主模型哈希。", file=sys.stderr) | |
| else: | |
| details = [(m.get("title"), m.get("shorthash"), m.get("sha256")) for m in candidates] | |
| raise RuntimeError(f"主模型哈希不符或匹配到多个文件;要求 {MODEL_SHORT_HASH},实际 {details}") | |
| title = selected.get("title") or selected.get("filename") | |
| if not title: | |
| raise RuntimeError("模型列表缺少 title/filename,无法准确选择主模型。") | |
| return title | |
| def select_modules(modules): | |
| selected = [] | |
| for name in MODULE_NAMES: | |
| matches = [m for m in modules if name_matches(m, name)] | |
| if len(matches) != 1 or not matches[0].get("filename"): | |
| raise RuntimeError( | |
| f"附加模块 {name} 需要且只能匹配一个文件,当前匹配:" | |
| f"{[m.get('filename') for m in matches]}" | |
| ) | |
| selected.append(matches[0]["filename"]) | |
| return selected | |
| def make_payload(checkpoint, modules): | |
| return { | |
| "prompt": PROMPT, | |
| "negative_prompt": NEGATIVE_PROMPT, | |
| "steps": 36, | |
| "sampler_name": "Euler a", | |
| "scheduler": "Beta", | |
| "cfg_scale": 4, | |
| "distilled_cfg_scale": 3, # Shift = 3 | |
| "seed": SEED, | |
| "width": 1024, | |
| "height": 1536, | |
| "batch_size": 1, | |
| "n_iter": 1, | |
| "enable_hr": True, | |
| "denoising_strength": 0.7, | |
| "hr_scale": 1.5, | |
| "hr_upscaler": "4x_foolhardy_Remacri", | |
| "hr_second_pass_steps": 32, | |
| "hr_cfg": 4, | |
| "hr_distilled_cfg": 3, # Hires Shift = 3 | |
| "hr_checkpoint_name": None, | |
| "hr_additional_modules": ["Use same choices"], | |
| # API uses None to inherit the first-pass sampler and scheduler. | |
| # "Use same ..." strings are UI dropdown labels, not API names. | |
| "hr_sampler_name": None, | |
| "hr_scheduler": None, | |
| "send_images": True, | |
| "save_images": True, # Also save on the Forge server | |
| "override_settings_restore_afterwards": True, | |
| "override_settings": { | |
| "forge_preset": "anima", | |
| "sd_model_checkpoint": checkpoint, | |
| "forge_additional_modules": modules, | |
| "randn_source": "CPU", # RNG: CPU, not CPU inference | |
| "beta_dist_alpha": 0.6, | |
| "beta_dist_beta": 0.6, | |
| "emphasis": "Original", | |
| "samples_format": "png", | |
| }, | |
| } | |
| def save_result(result, payload, output_dir): | |
| images = result.get("images") | |
| if not isinstance(images, list) or not images: | |
| raise RuntimeError("API 返回中没有 images;请检查服务端日志和返回的 info。") | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| stamp = datetime.now().strftime("%Y%m%d_%H%M%S") | |
| base_name = f"azusa_halloween_{SEED}_{stamp}" | |
| for i, encoded in enumerate(images, start=1): | |
| raw = base64.b64decode(encoded.split(",", 1)[-1], validate=True) | |
| if raw.startswith(b"\x89PNG\r\n\x1a\n"): | |
| ext = ".png" | |
| elif raw.startswith(b"\xff\xd8\xff"): | |
| ext = ".jpg" | |
| elif raw.startswith(b"RIFF") and raw[8:12] == b"WEBP": | |
| ext = ".webp" | |
| else: | |
| raise RuntimeError("服务端返回未知图像格式;没有写入错误扩展名的文件。") | |
| suffix = f"_{i}" if len(images) > 1 else "" | |
| n = 0 | |
| while True: | |
| # 'xb' prevents overwriting existing user-generated files. | |
| unique = f"_{n}" if n else "" | |
| path = output_dir / f"{base_name}{suffix}{unique}{ext}" | |
| if path.with_suffix(".json").exists(): | |
| n += 1 | |
| continue | |
| try: | |
| with path.open("xb") as output: | |
| output.write(raw) | |
| break | |
| except FileExistsError: | |
| n += 1 | |
| info = result.get("info", "") | |
| try: | |
| info = json.loads(info) if isinstance(info, str) else info | |
| except json.JSONDecodeError: | |
| pass | |
| # Retain the actual request and server info for reproducibility. | |
| sidecar = path.with_suffix(".json") | |
| sidecar.write_text(json.dumps({"request": payload, "info": info}, ensure_ascii=False, indent=2), encoding="utf-8") | |
| print(f"已保存:{path.resolve()}") | |
| print(f"参数文件:{sidecar.resolve()}") | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Linux / Forge Neo 2.29 / Anima Halloween API") | |
| parser.add_argument("--url", default=os.environ.get("FORGE_API_URL", "http://127.0.0.1:7860")) | |
| parser.add_argument("--output-dir", type=Path, default=Path("./outputs")) | |
| parser.add_argument("--dry-run", action="store_true", help="只查询模型并打印请求 JSON,不发起生图") | |
| args = parser.parse_args() | |
| base_url = args.url.rstrip("/") | |
| username = os.environ.get("FORGE_API_USER", "") | |
| password = os.environ.get("FORGE_API_PASSWORD", "") | |
| auth = (username, password) if username else None | |
| models = api_call(base_url, "/sdapi/v1/sd-models", auth=auth) | |
| modules = api_call(base_url, "/sdapi/v1/sd-modules", auth=auth) | |
| checkpoint = select_checkpoint(models) | |
| additional_modules = select_modules(modules) | |
| payload = make_payload(checkpoint, additional_modules) | |
| print(f"主模型:{checkpoint}") | |
| print(f"附加模块:{', '.join(Path(m).name for m in additional_modules)}") | |
| final_w = round(payload["width"] * payload["hr_scale"]) | |
| final_h = round(payload["height"] * payload["hr_scale"]) | |
| print( | |
| f"首轮:{payload['width']}x{payload['height']}," | |
| f"高清修复 {payload['hr_scale']}x -> {final_w}x{final_h}," | |
| f"Seed {payload['seed']}" | |
| ) | |
| if args.dry_run: | |
| print(json.dumps(payload, ensure_ascii=False, indent=2)) | |
| print("\n--dry-run:未提交生图请求。") | |
| return | |
| print("正在请求 /sdapi/v1/txt2img(高分辨率可能需要较长时间)……", flush=True) | |
| result = api_call(base_url, "/sdapi/v1/txt2img", payload, auth=auth, timeout=3600) | |
| save_result(result, payload, args.output_dir) | |
| if __name__ == "__main__": | |
| try: | |
| main() | |
| except (RuntimeError, ValueError, KeyError) as error: | |
| print(f"错误:{error}", file=sys.stderr) | |
| sys.exit(1) | |
Xet Storage Details
- Size:
- 10.3 kB
- Xet hash:
- 315d08b77fe356bd44b84eea624fb83bfc4082d31013902c46c8d5e567a360a7
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.