Yihua7's picture
Build Tripo SimReady Explorer with live dataset and joint previews
91425b8 verified
Raw History Blame Contribute Delete
4.14 kB
"""Exercise the real catalog and preview API, including downloadable GLB structure."""
from __future__ import annotations
import argparse
import json
import math
from pathlib import Path
import struct
import sys
import time
import urllib.request
from urllib.parse import quote, urljoin
def read(url: str, timeout: int = 300) -> bytes:
with urllib.request.urlopen(url, timeout=timeout) as response:
return response.read()
def check_preview(base: str, asset_id: str) -> dict:
start = time.monotonic()
preview = json.loads(read(urljoin(base, "api/assets/" + quote(asset_id, safe="") + "/preview")))
assert preview["id"] == asset_id
assert preview.get("revision"), "Preview must identify its source revision"
bounds = preview["bounds"]
for key in ("min", "max", "size", "center"):
assert len(bounds[key]) == 3 and all(math.isfinite(v) for v in bounds[key]), f"Invalid {key}"
assert max(bounds["size"]) > 0, "Empty model bounds"
glb = read(urljoin(base, preview["glbUrl"]))
magic, version, length = struct.unpack_from("<4sII", glb)
assert magic == b"glTF" and version == 2 and length == len(glb), "Invalid GLB header"
chunk_size, chunk_type = struct.unpack_from("<II", glb, 12)
assert chunk_type == 0x4E4F534A, "Missing GLB JSON chunk"
document = json.loads(glb[20:20 + chunk_size])
names = {n.get("name") for n in document.get("nodes", [])}
assert document.get("meshes"), "GLB contains no meshes"
joints = preview["joints"]
ids = {j["id"] for j in joints}
assert len(ids) == len(joints), "Duplicate joint IDs"
for joint in joints:
assert joint["type"] in ("revolute", "prismatic")
assert abs(sum(v*v for v in joint["axis"]) - 1) < 0.002, "Joint axis must be normalized"
assert all(math.isfinite(v) for v in joint["pivot"])
assert math.isfinite(joint["lower"]) and math.isfinite(joint["upper"])
assert joint["lower"] <= joint["initialValue"] <= joint["upper"], "Rest value outside slider"
assert joint["affectedNodes"], "Interactive joint does not affect visible geometry"
assert set(joint["affectedNodes"]).issubset(names), "Joint references missing GLB nodes"
for mesh in preview["meshes"]:
assert mesh["name"] in names, "Preview metadata references missing GLB nodes"
assert set(mesh["jointChain"]).issubset(ids), "Mesh references unknown joints"
return {"id": asset_id, "joints": len(joints), "meshes": len(document["meshes"]),
"glbBytes": len(glb), "warnings": preview.get("warnings", []),
"seconds": round(time.monotonic() - start, 2)}
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default="http://127.0.0.1:7860/")
parser.add_argument("--all", action="store_true")
parser.add_argument("--asset", action="append")
parser.add_argument("--report")
args = parser.parse_args()
base = args.base_url.rstrip("/") + "/"
catalog = json.loads(read(urljoin(base, "api/catalog")))
items = catalog["items"]
assert items and len({i["id"] for i in items}) == len(items)
requested = args.asset or ([i["id"] for i in items] if args.all else [items[0]["id"]])
results, errors = [], []
for asset_id in requested:
try:
result = check_preview(base, asset_id)
results.append(result)
print(json.dumps(result), flush=True)
except Exception as exc:
error = {"id": asset_id, "error": f"{type(exc).__name__}: {exc}"}
errors.append(error)
print(json.dumps(error), flush=True)
report = {"dataset": catalog["dataset"], "revision": catalog["revision"],
"catalogCount": len(items), "passed": results, "failed": errors}
if args.report:
path = Path(args.report)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(report, indent=2) + "\n")
print(f"Preview checks: {len(results)} passed, {len(errors)} failed.")
return int(bool(errors))
if __name__ == "__main__":
sys.exit(main())