gongxiangp2/apps/detail-agent-pi/scripts/verify-production-exports.py
WuYongJie 90408a4f02 Merge commit '93df00c892890bbf08a72ac8de8d79742f91deb3' into feat/xiaoyi-slice4-auto-delivery-bundle
# Conflicts:
#	apps/detail-agent-pi/src/agent.mjs
#	apps/detail-agent-pi/src/desktop-host.mjs
#	apps/detail-agent-pi/src/store.mjs
#	apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs
#	apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs
#	apps/detail-photocraft/crates/ui-egui/src/jiansun.rs
#	apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs
#	apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs
2026-11-26 19:09:05 +08:00

148 lines
7.2 KiB
Python

"""Check an isolated run's delivered artwork against the saved canvas mappings."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import zipfile
from PIL import Image
OUTPUTS = ("detail", "main_images", "sku_images")
WINDOWS_PREFIX = chr(92) * 2 + "?" + chr(92)
def absolute_path(file):
file = Path(file)
if os.name == "nt" and not str(file).startswith(WINDOWS_PREFIX):
return Path(WINDOWS_PREFIX + str(file.absolute()))
return file.absolute()
def read_json(file):
with file.open(encoding="utf-8-sig") as stream:
return json.load(stream)
def layers_by_id(layers, parent_visible=True):
for layer in layers:
visible = parent_visible and layer["visible"] and layer["opacity"] > 0
yield layer["id"], (visible, layer["content"])
yield from layers_by_id(layer["content"].get("children", []), visible)
def checked_file(record, generation, directory):
file = absolute_path(record["path"])
if record["generationId"] != generation or file.parent.parent != directory:
raise ValueError(f"{file.name} 不属于本次交付版本")
with file.open("rb") as stream:
digest = hashlib.file_digest(stream, "sha256").hexdigest()
if digest != record["sha256"] or file.stat().st_size != record["sizeBytes"]:
raise ValueError(f"{file.name} 内容与交付回执不一致")
return file
def inspect_receipt(receipt_file):
receipt = read_json(receipt_file)
generation = receipt["generationId"]
directory = receipt_file.parent / "generations"
if "publishedPointer" in receipt:
manifest = Path("generations") / generation / "manifest.json"
if Path(generation).name != generation or not generation.startswith("generation-") or Path(receipt["publishedPointer"]) != manifest:
raise ValueError("交付指针无效")
published = read_json(receipt_file.parent / manifest)
identity = ("generationId", "workspaceId", "outputId", "variantId")
if any(published[key] != receipt[key] for key in identity):
raise ValueError("交付指针与清单不一致")
receipt = published
source = receipt["sourceDocument"]
files = []
for photo in receipt["files"] + receipt.get("screenFiles", []):
file = checked_file(photo, generation, directory)
with Image.open(file) as image:
image.load()
if image.size != (photo["width"], photo["height"]):
raise ValueError(f"{file.name} 解码尺寸与交付回执不一致")
files.append(str(file))
if not files:
raise ValueError("没有导出图片")
editable = checked_file(source, generation, directory)
with zipfile.ZipFile(editable) as bundle:
document = json.loads(bundle.read("manifest.json"))["document"]
if document["size"] != {"width": source["width"], "height": source["height"]}:
raise ValueError("可编辑画布尺寸与交付回执不一致")
metadata = dict(document["metadata"]["text"])
mapping = json.loads(metadata["jiansun.slot-mapping.v1"])
if any(mapping[key] != receipt[value] for key, value in (
("workspaceId", "workspaceId"), ("templateHash", "templateHash"),
("variantId", "variantId"), ("component", "outputId"),
)):
raise ValueError("可编辑画布与交付身份不一致")
pages = mapping["outputs"]
screens = [(page["top"], page["width"], page["height"]) for page in pages]
regions = lambda rows: [(row["top"], row["width"], row["height"]) for row in rows]
if receipt["outputId"] == "detail":
expected_long = (0, max(width for _, width, _ in screens), max(top + height for top, _, height in screens))
if regions(receipt["files"]) != [expected_long] or regions(receipt.get("screenFiles", [])) != screens:
raise ValueError("详情长图或分屏集与实际画布页面不一致")
elif regions(receipt["files"]) != screens:
raise ValueError("输出图片集与实际画布页面不一致")
layers = dict(layers_by_id(document["layers"]))
fixed = mapping.get("fixedTemplateText", {})
blank_reasons = receipt.get("blankCopyReasons", {})
fields = []
issues = []
for page in pages:
for field in page["mapping"]["fields"]:
layer = field["nativeLayerId"]
label = f'{page["documentId"]}/{field["fieldId"]}'
visible, content = layers.get(layer, (False, {}))
if field["kind"] == "image":
adopted = metadata.get(f'jiansun.adopted.{receipt["variantId"]}.{field["slotId"]}')
if not visible or content.get("kind") != "smart" or not adopted:
issues.append({"field": label, "problem": "缺已采纳并可见的图片"})
fields.append({"field": label, "kind": "image", "adopted": adopted})
elif field["kind"] == "text":
current = content.get("text", "").strip()
sample = (field.get("originalText") or "").strip()
kept = bool(current and fixed.get(str(layer), "").strip() == current)
blank = blank_reasons.get(str(layer), {})
blank_reason = blank.get("reason") if (
not current and content.get("kind") == "text" and blank.get("field") == field["fieldId"]
) else None
if not visible or (not current and not blank_reason):
issues.append({"field": label, "problem": "文字缺失或不可见"})
elif current == sample and not kept:
issues.append({"field": label, "problem": "仍是模板样稿,缺保留依据"})
fields.append({"field": label, "kind": "text", "changed": current != sample,
"keepReason": "模板发布许可" if kept else blank_reason})
return {"generation": generation, "files": files, "editable": str(editable),
"fields": fields, "issues": issues}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("project", type=Path, help="独立验收配置中的本地项目目录")
parser.add_argument("report", type=Path, help="验收日志输出文件")
args = parser.parse_args()
project = absolute_path(args.project)
result = {output: [] for output in OUTPUTS}
for receipt in sorted((project / "product-exports").glob("*/*.json")):
if receipt.stem not in result:
continue
try:
result[receipt.stem].append(inspect_receipt(receipt))
except (OSError, ValueError, KeyError, zipfile.BadZipFile) as error:
result[receipt.stem].append({"receipt": str(receipt), "issues": [{"problem": str(error)}]})
passed = all(generations and all(item.get("files") and not item["issues"] for item in generations)
for generations in result.values())
args.report.write_text(json.dumps({"passed": passed, "outputs": result}, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8")
return 0 if passed else 1
if __name__ == "__main__":
raise SystemExit(main())