H2SMV-FPV / generator /scripts /run_portrait_sequence.py
mage0001's picture
Add portable H2SMV-FPV generator and third-party asset policy
73a87be verified
Raw History Blame Contribute Delete
11.9 kB
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import json
import os
import shutil
import sys
import tempfile
import time
from pathlib import Path
import numpy as np
from PIL import Image
from pipeline_common import ROOT, load_config, require_dir, require_file, resolve_path, run, safe_seq_id
def main() -> None:
parser = argparse.ArgumentParser(description="Render one SMPL-X NPZ as portrait RGB/mask PNG + COCO.")
parser.add_argument("npz", type=Path)
parser.add_argument("--config", type=Path, default=ROOT / "config/linux.json")
parser.add_argument("--seq-id")
parser.add_argument("--output-root", type=Path, default=ROOT / "portrait_png")
parser.add_argument("--frames", default=None)
parser.add_argument("--width", type=int, default=768)
parser.add_argument("--height", type=int, default=1024)
parser.add_argument("--fps", type=int, default=16)
parser.add_argument("--motion-slowdown", type=int, default=2)
parser.add_argument("--max-output-frames", type=int, default=121)
parser.add_argument("--camera-margin", type=float, default=0.08)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--beta-std", type=float, default=1.0)
parser.add_argument("--beta-clip", type=float, default=2.0)
parser.add_argument("--hair-max-bytes", type=int, default=200_000_000)
parser.add_argument("--hair-alignment", choices=["auto", "off"], default="auto")
parser.add_argument("--hair-scalp-gap", type=float, default=0.004)
parser.add_argument("--hair-max-adjust", type=float, default=0.05)
parser.add_argument("--hair-vertical-offset", type=float, default=0.0)
parser.add_argument("--gender", choices=["female", "male", "random"], default="female")
parser.add_argument(
"--clothing-texture-dir",
type=Path,
required=True,
help="Directory of user-supplied SMPL-X UV clothing PNGs. Third-party textures are not distributed.",
)
parser.add_argument("--disable-hair", action="store_true")
parser.add_argument("--hand-rgb-reference", action="store_true")
parser.add_argument("--hand-rgb-strength", type=float, default=1.25)
parser.add_argument("--overwrite", action="store_true")
args = parser.parse_args()
if args.motion_slowdown < 1 or args.max_output_frames < 0:
parser.error("motion slowdown must be >=1 and max output frames must be >=0 (0 means unlimited)")
if args.hair_scalp_gap < 0.0 or args.hair_max_adjust < 0.0:
parser.error("hair scalp gap and maximum adjustment must be non-negative")
if (args.width, args.height) != (768, 1024):
parser.error("portrait_png_v1 requires exactly --width 768 --height 1024")
config = load_config(args.config.resolve())
npz = args.npz.expanduser().resolve()
require_file(npz, "Input NPZ")
template = resolve_path(config, "template_blend")
addon = resolve_path(config, "addon_dir")
manifest = resolve_path(config, "asset_manifest")
hair_manifest = None if args.disable_hair else resolve_path(config, "hair_manifest")
clothing_texture_dir = args.clothing_texture_dir.expanduser().resolve()
require_file(template, "Blender template")
require_dir(addon, "SMPL-X addon")
require_file(manifest, "Asset manifest")
require_dir(clothing_texture_dir, "Fixed clothing texture directory")
if not args.disable_hair:
assert hair_manifest is not None
require_file(hair_manifest, "Hair manifest")
clothing_files = sorted(clothing_texture_dir.glob("*.png"))
if not clothing_files:
raise RuntimeError(f"No PNG clothing textures in {clothing_texture_dir}")
clothing_stats = [path.stat() for path in clothing_files]
seq_id = safe_seq_id(args.seq_id or npz.stem)
output_root = args.output_root.expanduser().resolve()
final_dir = output_root / seq_id
log_path = output_root / "logs" / f"{seq_id}.log"
source_stat = npz.stat()
signature = {
"pipeline": "portrait_png_v1",
"source_npz": str(npz),
"source_size": source_stat.st_size,
"source_mtime_ns": source_stat.st_mtime_ns,
"seed": args.seed,
"width": args.width,
"height": args.height,
"fps_metadata": args.fps,
"motion_slowdown": args.motion_slowdown,
"max_output_frames": args.max_output_frames,
"frames": args.frames,
"camera_margin": args.camera_margin,
"beta_std": args.beta_std,
"beta_clip": args.beta_clip,
"disable_hair": args.disable_hair,
"hand_rgb_reference": args.hand_rgb_reference,
"hand_rgb_strength": args.hand_rgb_strength,
"hair_max_bytes": args.hair_max_bytes,
"hair_alignment": args.hair_alignment,
"hair_scalp_gap": args.hair_scalp_gap,
"hair_max_adjust": args.hair_max_adjust,
"hair_vertical_offset": args.hair_vertical_offset,
"gender": args.gender,
"clothing_texture_dir": str(clothing_texture_dir),
"clothing_texture_dir_mtime_ns": clothing_texture_dir.stat().st_mtime_ns,
"clothing_texture_count": len(clothing_files),
"clothing_texture_total_bytes": sum(stat.st_size for stat in clothing_stats),
"clothing_texture_latest_mtime_ns": max(stat.st_mtime_ns for stat in clothing_stats),
"template_mtime_ns": template.stat().st_mtime_ns,
"manifest_mtime_ns": manifest.stat().st_mtime_ns,
"hair_manifest_mtime_ns": None if hair_manifest is None else hair_manifest.stat().st_mtime_ns,
}
marker = final_dir / "_SUCCESS.json"
if marker.is_file() and not args.overwrite:
try:
saved = json.loads(marker.read_text(encoding="utf-8"))
if saved.get("signature") == signature:
print(f"[SKIP] Portrait output already complete: {final_dir}")
return
except (OSError, json.JSONDecodeError):
pass
print(f"[STALE] Portrait signature changed: {seq_id}")
timings: dict[str, float] = {}
started = time.perf_counter()
temp_parent = Path(os.environ.get("TMPDIR", "/tmp"))
temp_parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix=f"portrait_{seq_id}_", dir=temp_parent) as temp_name:
work = Path(temp_name)
cache_dir = work / "cache"
stage_dir = work / "output"
cache_dir.mkdir()
stage_dir.mkdir()
render_config = cache_dir / "render_config.json"
scripts = ROOT / "scripts"
blender = str(config.get("blender_exe", "blender"))
stage_start = time.perf_counter()
blender_cmd = [
blender, "-b", "--python-exit-code", "1", str(template),
"-P", str(scripts / "run_portrait_blender_job.py"), "--",
"--npz", str(npz), "--cache-dir", str(cache_dir), "--out-dir", str(stage_dir),
"--manifest", str(manifest), "--addon-dir", str(addon),
"--camera-collection", config.get("camera_collection", "CAMERA_PRESETS"),
"--fps", str(args.fps), "--seed", str(args.seed),
"--motion-slowdown", str(args.motion_slowdown),
"--max-output-frames", str(args.max_output_frames),
"--camera-margin", str(args.camera_margin),
"--hair-max-bytes", str(args.hair_max_bytes),
"--hair-alignment", args.hair_alignment,
"--hair-scalp-gap", str(args.hair_scalp_gap),
"--hair-max-adjust", str(args.hair_max_adjust),
"--hair-vertical-offset", str(args.hair_vertical_offset),
"--gender", args.gender,
"--clothing-texture-dir", str(clothing_texture_dir),
"--beta-std", str(args.beta_std), "--beta-clip", str(args.beta_clip),
]
if args.hand_rgb_reference:
blender_cmd += ["--hand-rgb-reference", "--hand-rgb-strength", str(args.hand_rgb_strength)]
if args.frames:
blender_cmd += ["--frames", args.frames]
if not args.disable_hair:
assert hair_manifest is not None
blender_cmd += ["--hair-manifest", str(hair_manifest)]
if args.disable_hair:
blender_cmd.append("--disable-hair")
run(blender_cmd, "portrait-blender", log_path)
timings["blender_total_seconds"] = time.perf_counter() - stage_start
stage_start = time.perf_counter()
run([
sys.executable, str(scripts / "make_portrait_coco_json.py"),
"--sequence-dir", str(cache_dir), "--portrait-dir", str(stage_dir),
"--out", str(stage_dir / "coco_wholebody.json"), f"--seq-id={seq_id}",
], "portrait-coco", log_path)
timings["coco_seconds"] = time.perf_counter() - stage_start
stage_start = time.perf_counter()
rgb_frames = sorted((stage_dir / "rgb").glob("frame_*.png"))
mask_frames = sorted((stage_dir / "hand_mask").glob("frame_*.png"))
hand_rgb_frames = sorted((stage_dir / "hand_rgb").glob("frame_*.png")) if args.hand_rgb_reference else []
expected = int(np.load(cache_dir / "vertices.npy", mmap_mode="r").shape[0])
if len(rgb_frames) != expected or len(mask_frames) != expected or (args.hand_rgb_reference and len(hand_rgb_frames) != expected):
raise RuntimeError(
f"Portrait frame validation failed: expected={expected}, rgb={len(rgb_frames)}, "
f"mask={len(mask_frames)}, hand_rgb={len(hand_rgb_frames)}"
)
for image_path in rgb_frames:
with Image.open(image_path) as image:
if image.size != (768, 1024) or image.mode != "RGB":
raise ValueError(f"Invalid RGB PNG {image_path}: mode={image.mode}, size={image.size}")
for mask_path in mask_frames:
with Image.open(mask_path) as image:
array = np.asarray(image.convert("L"))
binary = np.where(array >= 128, 255, 0).astype(np.uint8)
Image.fromarray(binary, mode="L").save(mask_path, format="PNG", compress_level=3)
values = np.unique(binary)
if not set(values.tolist()).issubset({0, 255}):
raise ValueError(f"Non-binary hand mask {mask_path}: values={values[:20].tolist()}")
for image_path in hand_rgb_frames:
with Image.open(image_path) as image:
if image.size != (768, 1024) or image.mode != "RGB":
raise ValueError(f"Invalid hand RGB PNG {image_path}: mode={image.mode}, size={image.size}")
timings["validation_seconds"] = time.perf_counter() - stage_start
timings["total_before_publish_seconds"] = time.perf_counter() - started
metadata = {
"signature": signature,
"frame_count": expected,
"output_source_frame_positions": json.loads((cache_dir / "meta.json").read_text(encoding="utf-8"))["output_source_frame_positions"],
"timings": timings,
}
(stage_dir / "meta.json").write_text(json.dumps(metadata, indent=2), encoding="utf-8")
(stage_dir / "_SUCCESS.json").write_text(json.dumps({"signature": signature, "frame_count": expected}, indent=2), encoding="utf-8")
publish_start = time.perf_counter()
output_root.mkdir(parents=True, exist_ok=True)
publishing = output_root / f".{seq_id}.publishing"
if publishing.exists():
shutil.rmtree(publishing)
shutil.copytree(stage_dir, publishing)
if final_dir.exists():
shutil.rmtree(final_dir)
os.replace(publishing, final_dir)
timings["publish_seconds"] = time.perf_counter() - publish_start
metadata["timings"] = timings
(final_dir / "meta.json").write_text(json.dumps(metadata, indent=2), encoding="utf-8")
print(f"[OK] Portrait dataset sample complete: {final_dir}")
if __name__ == "__main__":
main()