File size: 21,623 Bytes
10ed3aa | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 | #!/usr/bin/env python3
"""Derive FreiHAND training labels: exactly 255 -> 255; every other value -> 0.
Writes a new candidate tree, never the input. In the unchanged warehouse schema,
0 means unassigned (not a newly asserted background category). Evaluation and all
non-segment annotations remain byte-identical. No downloads, raw, models or GPU.
"""
import argparse
from contextlib import closing
import copy
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
import shutil
import subprocess
import tempfile
import time
import numpy as np
import torch
try:
from render_full_random_review import decode_frames, probe_video
except ModuleNotFoundError as exc:
if exc.name != "render_full_random_review":
raise
from updated.render_full_random_review import decode_frames, probe_video
REPORT = "doc/validation/segment-eq255-20261014.json"
RULE = "output = 255 if decoded source intensity == 255 else 0; 0 = unassigned"
METHOD = "User-approved 2026-10-14 FreiHAND training-only exact-255 selection; " + RULE
LABEL = {"mask_value": 255, "category_id": "hand", "entity_id": "hand_right",
"part_id": None, "source_instance_id": None,
"source_attributes": {"selected_source_intensity": 255}}
REMOVED_KEYS = ("value_range", "normalization_scale", "foreground_category", "entity_id")
TRAIN_COUNTS = {f"training_{start:08d}": min(4096, 130240 - start) for start in range(0, 130240, 4096)}
FRAME_COUNTS = {**TRAIN_COUNTS, "evaluation_00000000": 3960}
def scope_sequences(scope):
training = sorted(TRAIN_COUNTS)
if scope == "pilot":
return sorted([training[0], training[-1], "evaluation_00000000"])
if scope == "all_33_shards":
return sorted(FRAME_COUNTS)
raise ValueError("Unknown scope")
def check_scope(source, report):
expected = scope_sequences(report["scope"])
if report["sequences"] != expected:
raise ValueError("Missing, duplicated or unexpected shards for declared scope")
if sorted(p.name for p in (source / "data").iterdir() if p.is_dir()) != sorted(FRAME_COUNTS):
raise ValueError("Source is not the full original 33-shard release")
for seq in expected:
meta = read_json(source / "data" / seq / "camera/metainfo.json")
if meta["num_frames"] != FRAME_COUNTS[seq] or meta["camera"]["image_size"] != [224, 224]:
raise ValueError(f"Wrong fixed-source frame count or dimensions: {seq}")
def check_totals(report, views):
expected = {"training_frames": sum(v["frames"] for v in views),
"pixels_checked": sum(v["pixels_checked"] for v in views),
"empty_frames": sum(len(v["empty_after_selection_frames"]) for v in views)}
if any(report.get(k) != value for k, value in expected.items()):
raise ValueError("Report totals disagree with complete decoded views")
def sha(path):
with Path(path).open("rb") as f:
return hashlib.file_digest(f, "sha256").hexdigest()
def read_json(path):
return json.loads(Path(path).read_text(encoding="utf-8"))
def write_json(path, value):
Path(path).write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n", encoding="utf-8")
def inventory(root):
return {p.relative_to(root).as_posix(): sha(p) for p in sorted(root.rglob("*")) if p.is_file()}
def verify_sums(root):
rows = {}
for line in (root / "doc/FILE_SHA256SUMS").read_text().splitlines():
digest, name = line.split(" ", 1)
p = root / name
if name in rows or not p.resolve().is_relative_to(root.resolve()) or sha(p) != digest:
raise ValueError(f"Invalid or changed checksum entry: {name}")
rows[name] = digest
actual = {p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file()}
if actual != set(rows) | {"doc/FILE_SHA256SUMS"}:
raise ValueError("File set differs from FILE_SHA256SUMS")
rows["doc/FILE_SHA256SUMS"] = sha(root / "doc/FILE_SHA256SUMS")
return rows
def selected(mask):
if mask.dtype not in (np.uint8, np.uint16) or mask.ndim != 2 or np.any(mask > 255):
raise ValueError("Expected a decoded uint8-range, single-channel training mask")
return np.where(mask == 255, 255, 0).astype(np.uint8)
def label_row(index, has_hand):
return {"frame_index": index, "labels": [copy.deepcopy(LABEL)] if has_hand else []}
def new_metadata(meta):
meta = copy.deepcopy(meta)
seg = meta["components"]["segment"]
if (meta["dataset_id"] != "FreiHAND" or meta["split"] != "train" or
seg["schema_id"] != "segment/foreground_intensity/v1" or
seg.get("entity_id") != "hand_right" or seg["storage"]["pixel_format"] != "gray"):
raise ValueError("Only original FreiHAND training foreground-intensity masks may be converted")
seg["schema_id"] = "segment/uint16_labels/v1"
seg["mapping_ref"] = "annotation/segment/instances.jsonl"
for key in REMOVED_KEYS:
del seg[key]
seg["provenance"] = {"kind": "derived", "method": METHOD}
# The original source JPEG was lossy. The new FFV1 stores the derived labels
# exactly; it does not restore discarded intensities or upstream precision.
seg["storage"]["encoder_parameters"] = {"level": 3, "threads": 1, "input_pixel_format": "gray"}
seg["storage"]["decoder"] = "FFmpeg native gray; uint8 to uint16 widening, no value scaling"
return meta
def check_metadata(old, new):
old_other, new_other = copy.deepcopy(old), copy.deepcopy(new)
a = old_other["components"].pop("segment")
b = new_other["components"].pop("segment")
if old_other != new_other:
raise ValueError("Metadata outside components.segment changed")
allowed = set(REMOVED_KEYS) | {"schema_id", "mapping_ref", "provenance", "storage"}
if {k: v for k, v in a.items() if k not in allowed} != {k: v for k, v in b.items() if k not in allowed}:
raise ValueError("Unapproved segment metadata change")
if (any(k in b for k in REMOVED_KEYS) or b["schema_id"] != "segment/uint16_labels/v1" or
b["mapping_ref"] != "annotation/segment/instances.jsonl" or
b["provenance"] != {"kind": "derived", "method": METHOD}):
raise ValueError("Wrong derived label declaration")
for key in set(a["storage"]) | set(b["storage"]):
if key not in {"encoder_parameters", "decoder"} and a["storage"].get(key) != b["storage"].get(key):
raise ValueError(f"Unapproved storage change: {key}")
expected_storage = new_metadata(old)["components"]["segment"]["storage"]
for key in ("decoder", "encoder_parameters"):
if b["storage"].get(key) != expected_storage[key]:
raise ValueError(f"Wrong derived gray8 storage declaration: {key}")
def encode_frames(path, frames, width, height):
command = ["ffmpeg", "-nostdin", "-v", "error", "-n", "-f", "rawvideo", "-pixel_format", "gray",
"-video_size", f"{width}x{height}", "-framerate", "1", "-i", "pipe:0", "-an",
"-c:v", "ffv1", "-level", "3", "-threads", "1", "-pix_fmt", "gray", str(path)]
with tempfile.TemporaryFile() as errors:
p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=errors)
try:
for frame in frames:
if frame.dtype != np.uint8 or frame.shape != (height, width):
raise ValueError("Unexpected encoder input shape or dtype")
p.stdin.write(frame.tobytes())
p.stdin.close()
if p.wait() != 0:
errors.seek(0)
raise RuntimeError(errors.read().decode(errors="replace"))
finally:
if not p.stdin.closed:
p.stdin.close()
if p.poll() is None:
p.terminate()
p.wait(timeout=10)
def convert_view(source, target):
meta = read_json(source / "metainfo.json")
updated = new_metadata(meta)
count = meta["num_frames"]
width, height = meta["camera"]["image_size"]
seg = meta["components"]["segment"]
probe_video(source / seg["data_ref"], seg["storage"], [width, height])
output = target / seg["data_ref"]
partial = output.with_name("mask.eq255-partial.mkv")
mapping = target / updated["components"]["segment"]["mapping_ref"]
with mapping.open("x", encoding="utf-8") as rows, closing(
decode_frames(source / seg["data_ref"], "gray", width, height, count)) as stream:
def frames():
for index, old in enumerate(stream):
out = selected(old)
rows.write(json.dumps(label_row(index, bool(np.any(out))), separators=(",", ":")) + "\n")
yield out
encode_frames(partial, frames(), width, height)
partial.replace(output) # only replaces the newly copied candidate mask
write_json(target / "metainfo.json", updated)
def verify_view(source, target):
oldmeta, newmeta = read_json(source / "metainfo.json"), read_json(target / "metainfo.json")
check_metadata(oldmeta, newmeta)
count = oldmeta["num_frames"]
width, height = oldmeta["camera"]["image_size"]
oldseg, newseg = oldmeta["components"]["segment"], newmeta["components"]["segment"]
for base, comp in ((source, oldseg), (target, newseg)):
probe_video(base / comp["data_ref"], comp["storage"], [width, height])
valid = torch.load(target / newseg["valid_ref"], map_location="cpu", weights_only=True)
if valid.dtype != torch.bool or tuple(valid.shape) != (count,):
raise ValueError("Wrong standalone mask validity")
if sha(source / oldseg["valid_ref"]) != sha(target / newseg["valid_ref"]):
raise ValueError("Mask validity changed")
histogram = np.zeros(256, dtype=np.int64)
empty = []
with (target / newseg["mapping_ref"]).open() as mappings, closing(
decode_frames(source / oldseg["data_ref"], "gray", width, height, count)) as oldframes, closing(
decode_frames(target / newseg["data_ref"], "gray", width, height, count)) as newframes:
for i, (old, new) in enumerate(zip(oldframes, newframes, strict=True)):
# Independently check the predicate and complement, not selected().
if np.any((new != 0) & (new != 255)) or not np.array_equal(new == 255, old == 255):
raise ValueError(f"Selection/roundtrip mismatch: {target}, frame {i}")
has_hand = bool(np.any(new == 255))
row = json.loads(mappings.readline())
if row != label_row(i, has_hand):
raise ValueError(f"Wrong mapping or frame order: {target}, frame {i}")
histogram += np.bincount(old.ravel(), minlength=256)
if not has_hand:
empty.append(i)
if mappings.read().strip():
raise ValueError("Extra mapping rows")
return {"sequence": source.parent.name, "frames": count,
"pixels_checked": count * width * height, "source_histogram": histogram.tolist(),
"retained_255_pixels": int(histogram[255]), "discarded_1_254_pixels": int(histogram[1:255].sum()),
"empty_after_selection_frames": empty, "valid_frames": int(valid.sum()),
"all_pixels_match_exact_255_rule": True}
def check_frozen(source, target, sequences, source_hashes):
expected_data = {n for n in source_hashes if n.startswith("data/") and n.split("/")[1] in sequences}
changes = {f"data/{seq}/camera/{rel}" for seq in sequences if seq.startswith("training_")
for rel in ("metainfo.json", "annotation/segment/mask.mkv")}
added = {f"data/{seq}/camera/annotation/segment/instances.jsonl" for seq in sequences if seq.startswith("training_")}
actual = {p.relative_to(target).as_posix() for p in (target / "data").rglob("*") if p.is_file()}
if actual != expected_data | added or added & expected_data:
raise ValueError("Candidate data paths changed outside approved additions")
for name in sorted(expected_data - changes):
if sha(target / name) != source_hashes[name]:
raise ValueError(f"Frozen data changed: {name}")
if inventory(source) != source_hashes:
raise ValueError("Original input tree changed")
return {"frozen_data_files_verified": len(expected_data - changes),
"changed_data_files": sorted(changes), "added_data_files": sorted(added),
"original_source_unchanged": True, "evaluation_unchanged": "evaluation_00000000" in sequences}
def prepend(path, text):
path.write_text(text + path.read_text(encoding="utf-8"), encoding="utf-8")
def write_docs(target, report):
summary = ("# 2026-10-14 训练 segment 精确255派生候选\n\n"
"本候选不是单纯的 v1.0→v1.1 无损重打包。用户新增确认:训练原mask值255保留为255,0–254设为0;"
"统一标签规范中0仍为unassigned,不能将其声明为已确认背景,也不新增0的JSON映射。"
"255通过每帧instances.jsonl映射到hand/hand_right;不推测手指部位。"
"评估集原区域码与映射全部保留;其他annotation、RGB、帧表、split和mask_valid原字节不变。\n\n"
"这是一次会丢失中间强度的、按用户规则生成的标签派生。只保证保留集合恰为原值255,"
"不宣称边界更准确或原手前景面积不变。过滤后全0的样本单列在机器报告中,不删图、不改valid;"
"全0表示没有已分配手区域,不证明原图没有手。无SAM3、raw、新下载或上传。\n\n"
f"本次范围:{report['scope']},训练{report['training_frames']}张,"
f"逐像素对照{report['pixels_checked']}个像素,过滤后空mask {report['empty_frames']}张。"
"完整机械校验与逐分片统计见[本次报告](validation/segment-eq255-20261014.json)。\n\n"
"当前检查入口是 `script/segment_eq255.py verify --source /path/to/original/shared-v1.1 --release .`。"
"旧validate_freihand.py和旧媒体校验是灰度原版的专用工具,不用于本派生候选;保留以追溯原迁移。"
"下方旧报告、doc/validation旧图和旧验收仅为原灰度版本的历史证据,不代表本次派生结果。\n\n"
"## 以下为此前无损存储迁移记录\n\n")
prepend(target / "doc/MIGRATION_REPORT.md", summary)
prepend(target / "doc/CONTRACT.md", "# 本候选的训练segment特定补充(2026-10-14)\n\n"
"用户新增确认以精确255选择替代FreiHAND训练强度存储:255→255,0–254→0。"
"采用已有segment/uint16_labels/v1及每帧instances.jsonl;0=unassigned,255=hand/hand_right。"
"FFV1 gray8存储0/255,读取精确拓宽至uint16,不缩放。此补充仅替代历史合同中本训练集保留中间灰度的约定,"
"不改变通用保留码、schema.json、评估集或其他标注。归档规范原件未改。"
"派生有损信息与验收范围见[MIGRATION_REPORT.md](MIGRATION_REPORT.md)。\n\n")
prepend(target / "doc/RAW_MAPPING.md", "# 当前训练mask派生映射(2026-10-14)\n\n"
"实际输入为已验收shared-v1.1的训练FFV1灰度,不读取raw。解码值255→标签255;0–254→标签0(unassigned)。"
"255映射category_id=hand、entity_id=hand_right、part_id=null、source_instance_id=null;"
"source_attributes.selected_source_intensity=255是原强度,不能当作源实例ID。"
"每帧有255时写此标签,无255时labels=[]。评估集的20/30等是区域码,绝不套用训练强度规则。"
"下面原始raw→shared映射是历史上游说明,原件不改;当前派生规则优先适用于训练segment。\n\n")
prepend(target / "script/README.md", "# 当前精确255候选的使用入口\n\n"
"`segment_eq255.py`只处理已有FreiHAND训练强度,不读取raw、不下载、不运行模型。"
"依赖Python、NumPy、PyTorch、FFmpeg及同目录原媒体解码工具。\n\n"
"```bash\npython -B script/segment_eq255.py verify --source /path/to/original/shared-v1.1 --release .\n"
"sha256sum -c doc/FILE_SHA256SUMS\n"
"python -B script/segment_eq255.py convert --source /path/to/original/shared-v1.1 --output /new/path/shared-v1.1 --pilot\n"
"# 去掉--pilot才覆盖全部33分片;输出必须是新目录。\n```\n\n"
"读取mask时gray8只拓宽uint16,不归一化为旧强度;0未分配、255右手。"
"未来训练把0当负样本还是不监督需要在任务读取器明确规定,不由这次存储编码暗中决定。"
"只使用本入口验证派生候选;下面的旧专用验证和预览命令仍要求原灰度训练mask,不适用于当前候选。\n\n"
"## 原无损迁移工具的历史说明\n\n")
def convert(source, target, pilot=False):
torch.set_num_threads(1)
source, target = source.resolve(), target.resolve()
if target.exists() or target.is_relative_to(source) or source.is_relative_to(target):
raise ValueError("Output must be a new tree outside the original input")
started = time.monotonic()
source_hashes = verify_sums(source)
scope = "pilot" if pilot else "all_33_shards"
sequences = scope_sequences(scope)
check_scope(source, {"scope": scope, "sequences": sequences})
target.mkdir(parents=True)
for part in ("doc", "script"):
shutil.copytree(source / part, target / part)
for seq in sequences:
shutil.copytree(source / "data" / seq, target / "data" / seq)
results = []
for seq in sequences:
if not seq.startswith("training_"):
continue
a, b = source / "data" / seq / "camera", target / "data" / seq / "camera"
convert_view(a, b)
results.append(verify_view(a, b))
print(f"verified {seq}: {results[-1]['frames']} frames; empty={len(results[-1]['empty_after_selection_frames'])}", flush=True)
frozen = check_frozen(source, target, sequences, source_hashes)
report = {"status": "candidate_machine_verified", "scope": scope,
"created_utc": datetime.now(timezone.utc).isoformat(), "rule": RULE,
"zero_semantics": "unassigned", "hand_label": LABEL, "source_files_sha256": source_hashes,
"sequences": sequences, "views": results, **frozen,
"training_frames": sum(r["frames"] for r in results),
"pixels_checked": sum(r["pixels_checked"] for r in results),
"empty_frames": sum(len(r["empty_after_selection_frames"]) for r in results),
"elapsed_seconds": round(time.monotonic() - started, 2),
"quality_claim": "Exact chosen rule, not independently verified hand boundaries",
"human_review": "not_claimed", "independent_agent_review": "not_claimed"}
write_docs(target, report)
shutil.copy2(Path(__file__), target / "script/segment_eq255.py")
test = Path(__file__).with_name("test_segment_eq255.py")
if test.exists():
shutil.copy2(test, target / "script/test_segment_eq255.py")
write_json(target / REPORT, report)
files = inventory(target)
(target / "doc/FILE_SHA256SUMS").write_text("".join(f"{digest} {name}\n" for name, digest in sorted(files.items())
if name != "doc/FILE_SHA256SUMS"), encoding="utf-8")
verify_sums(target)
print(json.dumps({k: report[k] for k in ("status", "scope", "training_frames", "pixels_checked", "empty_frames", "elapsed_seconds")}), flush=True)
def verify(source, release):
torch.set_num_threads(1)
report = read_json(release / REPORT)
if report["rule"] != RULE or report["zero_semantics"] != "unassigned":
raise ValueError("Wrong derivation policy")
check_scope(source, report)
verify_sums(release)
frozen = check_frozen(source, release, report["sequences"], report["source_files_sha256"])
if any(report[k] != v for k, v in frozen.items()):
raise ValueError("Frozen-file receipt differs from recomputed result")
recomputed = []
for seq in report["sequences"]:
if seq.startswith("training_"):
recomputed.append(verify_view(source / "data" / seq / "camera", release / "data" / seq / "camera"))
print(f"reverified {seq}", flush=True)
if recomputed != report["views"]:
raise ValueError("Recomputed per-frame results differ")
check_totals(report, recomputed)
print(json.dumps({"status": "source_candidate_readback_passed", "training_frames": sum(v['frames'] for v in recomputed),
"original_source_unchanged": True, "other_annotations_unchanged": True}), flush=True)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest="command", required=True)
p = sub.add_parser("convert")
p.add_argument("--source", type=Path, required=True)
p.add_argument("--output", type=Path, required=True)
p.add_argument("--pilot", action="store_true")
p = sub.add_parser("verify")
p.add_argument("--source", type=Path, required=True)
p.add_argument("--release", type=Path, required=True)
args = parser.parse_args()
if args.command == "convert":
convert(args.source, args.output, args.pilot)
else:
verify(args.source, args.release)
|