#!/usr/bin/env python3 """Strict read-only audit for an HFD third-party pilot dataset.""" from __future__ import annotations import argparse import hashlib import json import os import random import sys from collections import Counter, defaultdict from pathlib import Path from typing import Any import numpy as np PROJECT_ROOT = Path(__file__).resolve().parents[2] if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) from scripts.data.build_hfd_third_party_sessions import ( # noqa: E402 DIFFICULTY_WEIGHTS, PROFILE_WEIGHTS, _difficulty_counts, _choose_event_start, _motion_sha256, _profile_counts, _read_resampled_speech_float, _target_level_db, _timeline_content_sha256, ) from scripts.data.hfd_third_party_common import ( # noqa: E402 SAMPLE_RATE, active_rms, canonical_json_sha256, expected_window_count, quantize_pcm16, read_jsonl, read_pcm16_wav, sha256_file, signal_to_residual_db_on_active_signal, stable_u64, write_json_atomic, ) from scripts.data.hfd_third_party_speech_v3 import ( # noqa: E402 SPEECH_PROFILES, SPEECH_FOCUS_PROFILE_WEIGHTS, continuous_event_geometry, speech_language, speaker_capacity_tier, ) FORMAT_V1 = "hfd_third_party_pilot_strict_audit_v1" FORMAT_V2 = "hfd_third_party_pilot_strict_audit_v2" LOUDNESS_REVISION_FORMAT = "hfd_background_gain_revision_v1" def _audit_loudness_build( build: dict[str, Any], recipes: list[dict[str, Any]], ) -> list[str]: """Keep the historical build contract, with a declared in-place revision.""" revised_count = sum("loudness_revision" in recipe for recipe in recipes) if "loudness_revision" not in build: return ["loudness_build_declaration_missing"] if revised_count else [] declaration = build["loudness_revision"] if not isinstance(declaration, dict): return ["loudness_build_declaration_invalid"] errors = [] if declaration.get("format") != LOUDNESS_REVISION_FORMAT: errors.append("loudness_build_format") if declaration.get("complete") is not True: errors.append("loudness_build_incomplete") count = declaration.get("adjusted_sessions") if type(count) is not int or count != revised_count: errors.append("loudness_build_adjusted_count") return errors def _audit_loudness_revision( recipe: dict[str, Any], assets_by_id: dict[str, Any], root: Path, ) -> tuple[bool, list[str]]: """Only verified waveform/recipe replay may relax historical retention.""" if "loudness_revision" not in recipe: return False, [] revision = recipe["loudness_revision"] if not isinstance(revision, dict) or revision.get("format") != LOUDNESS_REVISION_FORMAT: return False, ["loudness_revision_format"] if recipe.get("audio_corruption_profile") not in SPEECH_PROFILES: return False, ["loudness_revision_non_speech_profile"] try: # Lazy import leaves all historical/unrevised datasets independent of # the repair implementation and its waveform replay dependencies. from scripts.data.repair_hfd_third_party_loudness import validate_revised_recipe problems = validate_revised_recipe(recipe, assets_by_id, root) if not isinstance(problems, list) or any(not isinstance(value, str) for value in problems): return False, ["loudness_revision_validator_contract"] if problems: return False, [f"loudness_revision:{problem}" for problem in problems] for key in ("before_audio_sha256", "before_recipe_sha256"): digest = revision.get(key) if not isinstance(digest, str) or len(digest) != 64 or any( value not in "0123456789abcdef" for value in digest ): return False, [f"loudness_revision_digest:{key}"] if not isinstance(revision.get("before_interference_events"), list) or not revision["before_interference_events"]: return False, ["loudness_revision_before_events"] if not isinstance(revision.get("before_mix_metadata"), dict): return False, ["loudness_revision_before_mix"] if not isinstance(revision.get("before_audio"), dict) or revision["before_audio"].get("sha256") != revision["before_audio_sha256"]: return False, ["loudness_revision_before_audio"] if not isinstance(revision.get("changes"), list) or not revision["changes"]: return False, ["loudness_revision_changes"] except (ImportError, KeyError, TypeError, ValueError, OSError, RuntimeError) as exc: return False, [f"loudness_revision_validation:{type(exc).__name__}:{exc}"] return True, [] def _audit_cross_retention( recipe: dict[str, Any], old: dict[str, Any], cell: dict[str, Any], *, loudness_revision_valid: bool, ) -> list[str]: """Retention denotes the crossed refresh before a verified gain revision.""" revision = recipe.get("loudness_revision", {}) if loudness_revision_valid else {} compared_sha = revision.get("before_audio_sha256", recipe["audio"]["sha256"]) compared_events = revision.get("before_interference_events", recipe["interference_events"]) errors = [] if (compared_sha == old["audio"]["sha256"]) != cell["retained_audio"]: errors.append("cross_retention_audio") if cell["retained_audio"] and ( compared_events != old["interference_events"] or recipe["session_id"] != old["session_id"] ): errors.append("cross_retention_identity") return errors def _audit_target_level( event: dict[str, Any], *, profile: str, difficulty: str, split: str, loudness_revision_valid: bool, ) -> list[str]: expected = _target_level_db(profile, difficulty, split) actual = float(event.get("target_sir_db", event.get("target_snr_db"))) if not np.isfinite(actual): return ["target_level_non_finite"] if loudness_revision_valid and "target_sir_db" in event: nominal = float(event.get("nominal_target_sir_db")) if not np.isfinite(nominal) or nominal != expected: return [f"nominal_target_level:{nominal}!={expected}"] return [] return [] if actual == expected else [f"target_level:{actual}!={expected}"] def _parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--production-root", type=Path, required=True) parser.add_argument("--strict", action="store_true") return parser.parse_args() def _safe_path(root: Path, relative: str) -> Path: path = (root / relative).resolve() try: path.relative_to(root.resolve()) except ValueError as exc: raise ValueError(f"Output path escapes production root: {relative}") from exc return path def _cached_sha(path: Path, cache: dict[str, str]) -> str: key = str(path.resolve()) value = cache.get(key) if value is None: value = sha256_file(path) cache[key] = value return value def _audio_pcm_sha(audio: np.ndarray) -> str: return hashlib.sha256(quantize_pcm16(audio).tobytes()).hexdigest() def _session_signature(turns: list[dict[str, Any]]) -> str: return canonical_json_sha256( [ { "primitive_id": turn["primitive_id"], "tts_source_key": turn["tts_source_key"], } for turn in turns ] ) def _markdown_cell(value: object) -> str: return str(value).replace("|", r"\|").replace("\n", " ").strip() PROFILE_GUIDE = { "clean_reference": ( "干净对照", "不添加新的 third-party 干扰,只保留重新组合后的目标指令和师兄原有办公室背景。", "确认新 session 的指令、转场和原有背景本身是否自然,作为同条样本的听感基线。", ), "ambient_noise": ( "连续环境噪声", "把真实或合成的办公室环境录音铺满整条 session,因此指令播放时也存在环境噪声。", "测试模型在风扇、空调、走廊等持续背景下提取真正动作指令的能力。", ), "white_or_colored_noise": ( "白噪声或粉噪声", "把确定性生成的白噪声或粉噪声铺满整条 session,并按目标 SNR 调整响度。", "测试宽带噪声及偏低频噪声下的语音鲁棒性。", ), "foreground_non_command": ( "单人非指令语音", "加入一名第三方说话人的普通叙述;部分样本放在指令前、轮次间或动作中,60% 与第二轮或后续目标指令直接重叠。", "训练模型忽略非动作语义,同时利用整条 session 中一致的目标说话人继续执行真正指令。", ), "babble": ( "三人背景人声", "把三个不同说话人的非指令语音混成多人声;60% 与第二轮或后续目标指令直接重叠,其余放在动作执行阶段。", "测试多人交谈环境中的语义选择和目标说话人连续性。", ), "babble_continuous": ( "持续多人非指令人声", "2–4名不同说话人的完整原始片段分轨串接并混合;约一半安排覆盖全session,另一半覆盖40%–80%的随机区间。片段间保留短暂停顿,非真实连贯会议。", "测试持续语义干扰下忽略非指令内容的能力;不添加背景动作命令或VQA问题。", ), "invalid_audio_stream": ( "旧版无效音频流", "旧 v1 中模拟短时丢包、重复包或低通失真。", "仅用于兼容旧 pilot;v2 已按人工反馈删除,不再生成此类样本。", ), } PLACEMENT_CN = { "uniform_session": "完整片段在整条 session 内按采样点均匀随机放置", "full_session": "覆盖整条 session(包含指令期间)", "before_first_command": "首条目标指令之前", "between_turns": "两个目标轮次之间", "during_motion": "动作执行阶段(不与目标指令同时播放)", "partial_command_overlap": "与第二轮或后续目标指令同时播放", "none": "不添加新的 third-party 干扰", } DIFFICULTY_CN = {"easy": "容易", "medium": "中等", "hard": "困难"} def _write_listening_sheet( root: Path, previews: list[dict[str, Any]], recipes_by_id: dict[str, dict[str, Any]], ) -> Path: path = root / "reports" / "listening_review.md" preview_root = (root / "previews").resolve() present_profiles = { str(recipe["audio_corruption_profile"]) for recipe in recipes_by_id.values() } uniform = any(event.get("placement") == "uniform_session" for recipe in recipes_by_id.values() for event in recipe["interference_events"]) ordered_profiles = [ profile for profile in PROFILE_GUIDE if profile in present_profiles ] lines = [ "# HFD third-party pilot 人工试听表", "", "> 自动审计只能确认数据合同,不能代替人耳判断。逐行比较同一条 session 的 base 与 augmented 后再决定后续使用;自动审计通过不代表训练就绪。", "", "## 音频文件位置", "", f"- Base audio 绝对路径规则:`{preview_root}///.base.wav`", f"- Augmented audio 绝对路径规则:`{preview_root}///.augmented.wav`", f"- Train 预览根目录:`{preview_root / 'train'}`", f"- Validation 预览根目录:`{preview_root / 'validation'}`", "- 表格链接显示从 production root 开始的相对路径,点击即可定位对应 WAV。", "", "> Base 是同一条新组合 session 加入本轮 third-party 干扰前的音频,仍含师兄已有办公室背景;Augmented 在 Base 上加入本行所述的新干扰。两者的目标指令、turn 顺序和监督完全相同。", "", "## 不同处理类型及作用", "", "| profile | 中文名称 | 如何修改音频 | 作用 |", "|---|---|---|---|", ] for profile in ordered_profiles: label, method, purpose = PROFILE_GUIDE[profile] if uniform and profile in {"foreground_non_command", "babble"}: method = "非指令语音在整条 session 内均匀随机选择完整片段起点;中英素材均覆盖,不预设指令重叠配额。" if uniform and profile == "ambient_noise": label = "连续背景/短时环境声" method = "连续长环境背景与短时环境事件各约一半;短事件在全 session 均匀随机放置,不循环短片段。" purpose = "测试生活、自然、交通等环境背景及短时声音事件下的目标指令鲁棒性。" lines.append( f"| `{_markdown_cell(profile)}` | {_markdown_cell(label)} | " f"{_markdown_cell(method)} | {_markdown_cell(purpose)} |" ) lines.extend( [ "", "## 强度字段怎么理解", "", "- SNR 用于环境声、白噪声和粉噪声;SIR 用于单人或多人背景人声。数值越大,目标指令相对本次新增干扰越响;0 dB 表示两者有效 RMS 接近,负数表示新增干扰更响。", "- 总有效信干比把师兄原有办公室背景和本次新增干扰一起计算,只在目标指令的有效语音采样点统计。表中用 `Base → Augmented` 展示加入新干扰前后的变化。", "", "## 配对试听记录", "", "| split | 类型 | 难度 | 位置与强度 | 目标指令 | 干扰内容 | Base audio | Augmented audio | 人工结论 |", "|---|---|---|---|---|---|---|---|---|", ] ) for row in sorted( previews, key=lambda value: ( value["split"], value["profile"], value.get("preview_bucket", ""), ), ): session_id = str(row["session_id"]) recipe = recipes_by_id[session_id] profile = str(row["profile"]) profile_label = PROFILE_GUIDE.get(profile, (profile, "", ""))[0] if uniform and profile == "ambient_noise": profile_label = "连续背景/短时环境声" difficulty = str(recipe.get("corruption_difficulty", "unknown")) targets = " / ".join( str(turn["instruction_text"]) for turn in recipe["turns"] ) events = list(recipe["interference_events"]) if not events: placement_text = PLACEMENT_CN["none"] strength_text = "无新增干扰" interference = "无" else: event = events[0] placement = str(event.get("placement", "full_session")) placement_text = PLACEMENT_CN.get(placement, placement) if ( placement == "during_motion" and row.get("preview_bucket") == "non_overlap" ): placement_text = ( "试听片段先保留此前目标指令;背景语音随后出现在" "动作执行阶段,不与指令同时播放" ) if "target_sir_db" in event: strength_text = f"新增干扰 SIR={float(event['target_sir_db']):g} dB" elif "target_snr_db" in event: strength_text = f"新增干扰 SNR={float(event['target_snr_db']):g} dB" else: strength_text = "未定义新增干扰强度" transcripts = list(event.get("transcripts", [])) if transcripts: interference = " / ".join(str(value) for value in transcripts) elif event.get("type") == "ambient_noise": interference = f"环境录音:{event.get('asset_id', '')}" elif event.get("type") == "white_noise": interference = "白噪声" elif event.get("type") == "colored_noise": interference = "粉噪声" else: interference = str(event.get("type", "未知")) mix = dict(recipe.get("mix_metadata", {})) base_total = mix.get("base_total_signal_to_residual_db") augmented_total = mix.get("augmented_total_signal_to_residual_db") if base_total is not None and augmented_total is not None: total_text = ( f"总有效信干比 {float(base_total):.1f} → " f"{float(augmented_total):.1f} dB" ) else: total_text = "旧版未记录总有效信干比" event_summary = f"{placement_text};{strength_text};{total_text}" base = str(row["base_audio_path"]) augmented = str(row["augmented_audio_path"]) lines.append( f"| {_markdown_cell(row['split'])} | " f"{_markdown_cell(profile_label)} (`{_markdown_cell(profile)}`) | " f"{_markdown_cell(DIFFICULTY_CN.get(difficulty, difficulty))} | " f"{_markdown_cell(event_summary)} | " f"{_markdown_cell(targets)} | " f"{_markdown_cell(interference)} | " f"[{_markdown_cell(base)}](../{base}) | " f"[{_markdown_cell(augmented)}](../{augmented}) | 待审核 |" ) lines.extend( [ "", "人工检查项:真正指令是否可辨认;干扰是否存在动作/控制语义;位置是否符合该版本规则(uniform_session 允许与首条指令重叠);是否有爆音、削波或明显拼接突变;处理位置和响度是否与表格一致。", "", ] ) path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp") temporary.write_text("\n".join(lines), encoding="utf-8") os.replace(temporary, path) return path def _weights_from_build( build: dict[str, Any], *, values_key: str, order_key: str, fallback: tuple[tuple[str, float], ...], ) -> tuple[tuple[str, float], ...]: raw = build.get(values_key) if not isinstance(raw, dict) or not raw: return fallback order = build.get(order_key) names = list(order) if isinstance(order, list) else list(raw) if set(names) != set(raw): raise ValueError(f"{order_key} does not match {values_key}") return tuple((str(name), float(raw[name])) for name in names) def _target_track_from_recipe( recipe: dict[str, Any], sample_count: int, ) -> np.ndarray: track = np.zeros(sample_count, dtype=np.float32) for event in recipe.get("target_speech_events", []): path = Path(str(event["original_audio_path"])) speech = _read_resampled_speech_float(path, SAMPLE_RATE) expected = int(event["sample_count"]) if speech.size != expected: raise ValueError( f"target speech length changed: {path} {speech.size}!={expected}" ) start = int(event["start_sample"]) end = int(event["end_sample"]) if end - start != expected or not (0 <= start < end <= sample_count): raise ValueError(f"target event bounds changed: {start}:{end}") track[start:end] += speech * np.float32(event["speech_scale"]) return track def _audit_continuous_event(event: dict, assets: dict, *, sample_count: int, profile_index: int, seed: int, source_rms: dict | None = None) -> list[str]: """Check provenance of every complete utterance; offsets are event-local.""" errors = [] geometry = continuous_event_geometry(sample_count, profile_index, seed) for key, value in geometry.items(): if event.get(key) != value: errors.append(f"continuous_geometry:{key}") if event.get("synthesis_policy") != "speaker_tracks_complete_utterances_v1" or event.get("synthetic_babble") is not True: errors.append("continuous_synthesis_policy") if (event.get("segment_offsets_relative_to") != "interference_event_start" or event.get("coverage_measure") != "complete_utterance_interval_union_including_internal_pauses" or not isinstance(event.get("synthesis_attempt"), int) or not 0 <= event["synthesis_attempt"] < 16): errors.append("continuous_synthesis_metadata") tracks = event.get("tracks", []) if len(tracks) != event.get("track_count") or not 2 <= len(tracks) <= 4: errors.append("continuous_track_count") if len({track.get("speaker_id") for track in tracks}) != len(tracks): errors.append("continuous_duplicate_speakers") length = int(event["end_sample"]) - int(event["start_sample"]) intervals, flattened = [], [] reused_count = 0 for index, track in enumerate(tracks): if track.get("track_index") != index or not track.get("segments"): errors.append(f"continuous_empty_or_unordered_track:{index}") if not 0 <= int(track.get("start_offset_samples", -1)) <= round(0.6 * SAMPLE_RATE): errors.append("continuous_initial_offset_bounds") previous_end = 0 previous_id = None used = set() for segment in track.get("segments", []): asset = assets.get(segment.get("asset_id")) if asset is None: errors.append("continuous_unknown_asset") continue start, end = int(segment["start_sample"]), int(segment["end_sample"]) if not 0 <= previous_end <= start < end <= length: errors.append("continuous_segment_bounds_or_self_overlap") if previous_id is not None: if not round(0.1 * SAMPLE_RATE) <= start - previous_end <= round(0.6 * SAMPLE_RATE): errors.append("continuous_pause_bounds") if previous_id == segment.get("asset_id"): errors.append("continuous_immediate_sentence_repeat") elif start != track.get("start_offset_samples"): errors.append("continuous_track_offset") reused = segment["asset_id"] in used if segment.get("reused_asset") != reused: errors.append("continuous_reused_asset_metadata") reused_count += int(reused) used.add(segment["asset_id"]) previous_id = segment["asset_id"] previous_end = end intervals.append((start, end)) flattened.append(segment) if (segment.get("source_start_sample"), segment.get("source_end_sample"), end - start) != (0, asset["sample_count"], asset["sample_count"]): errors.append("continuous_incomplete_utterance") if (track.get("speaker_id"), track.get("language")) != (asset["speaker_id"], asset["language"]): errors.append("continuous_track_identity") for key, asset_key in (("asset_sha256", "normalized_sha256"), ("source_group", "source_group"), ("transcript", "transcript")): if segment.get(key) != asset.get(asset_key): errors.append(f"continuous_segment_provenance:{key}") gain = float(segment.get("normalization_gain", 0)) if not np.isfinite(gain) or gain <= 0: errors.append("continuous_segment_gain") if source_rms is not None: expected_gain = 1.0 / source_rms[segment["asset_id"]] / len(tracks) if abs(gain - expected_gain) > 1e-7 * expected_gain: errors.append("continuous_segment_gain_replay") for key, field in (("asset_ids", "asset_id"), ("asset_sha256", "asset_sha256"), ("source_groups", "source_group"), ("transcripts", "transcript")): if event.get(key) != [segment[field] for segment in flattened]: errors.append(f"continuous_flattened_provenance:{key}") for key, field in (("speaker_ids", "speaker_id"), ("languages", "language")): if event.get(key) != [assets[segment["asset_id"]][field] for segment in flattened]: errors.append(f"continuous_flattened_provenance:{key}") covered, right = 0, 0 for start, end in sorted(intervals): covered += max(0, end - max(start, right)) right = max(right, end) if covered / max(1, length) < 0.70: errors.append("continuous_insufficient_utterance_coverage") reported_coverage = float(event.get("actual_union_coverage", -1)) if not np.isfinite(reported_coverage) or abs(reported_coverage - covered / max(1, length)) > 1e-12: errors.append("continuous_coverage_metadata") if event.get("reused_asset_segments") != reused_count: errors.append("continuous_reused_count") if flattened: exemplar = assets[flattened[0]["asset_id"]] by_speaker = defaultdict(list) for asset in assets.values(): if (asset.get("role") == "non_command_speech" and asset.get("split") == exemplar["split"] and asset.get("language") == exemplar["language"] and 0 < int(asset["sample_count"]) <= length): by_speaker[asset["speaker_id"]].append(asset) capacities = {speaker: sum(int(row["sample_count"]) for row in rows) for speaker, rows in by_speaker.items() if speaker and len({row["asset_id"] for row in rows}) >= 2} tiers = {speaker: speaker_capacity_tier(capacity, length) for speaker, capacity in capacities.items()} tier_counts = {tier: sum(value == tier for value in tiers.values()) for tier in ("full", "near", "limited")} if event.get("speaker_selection_policy") != "prefer_distinct_content_capacity_v1" or event.get("speaker_capacity_tier_counts") != tier_counts: errors.append("continuous_speaker_capacity_policy") k = min(2 + stable_u64("continuous-track-count-v3", seed) % 3, len(capacities)) attempt = int(event["synthesis_attempt"]) synthesis_seed = seed if attempt == 0 else stable_u64("continuous-coverage-retry-v3", seed, attempt) tier_rank = {"full": 0, "near": 1, "limited": 2} selected = sorted(capacities, key=lambda speaker: (tier_rank[tiers[speaker]], stable_u64("continuous-speaker-v3", synthesis_seed, speaker)))[:k] if [track["speaker_id"] for track in tracks] != selected: errors.append("continuous_speaker_selection_replay") for track in tracks: speaker = track["speaker_id"] if track.get("available_unique_samples") != capacities.get(speaker) or track.get("capacity_tier") != tiers.get(speaker): errors.append("continuous_speaker_capacity_metadata") return errors def audit(root: Path) -> dict[str, Any]: root = root.resolve() errors: list[str] = [] warnings: list[str] = [] file_hash_cache: dict[str, str] = {} hold_path = root / "reports" / "semantic_hold.json" if hold_path.is_file() and json.loads(hold_path.read_text()).get("eligible_for_final_handoff") is not True: errors.append("dataset_on_semantic_hold") build_path = root / "reports" / "pilot_build.json" source_contract_path = root / "manifests" / "source_contract.json" recipe_path = root / "manifests" / "session_recipes.jsonl" assignment_path = root / "manifests" / "composed_session_assignments.jsonl" primitive_path = root / "manifests" / "primitive_split_snapshot.jsonl" baseline_path = root / "manifests" / "baseline_session_signatures.jsonl" preview_path = root / "manifests" / "preview_index.jsonl" required = ( build_path, source_contract_path, recipe_path, assignment_path, primitive_path, baseline_path, preview_path, ) missing = [str(path) for path in required if not path.is_file()] if missing: return { "format": FORMAT_V2, "passed": False, "errors": [f"missing:{path}" for path in missing], "warnings": [], } build = json.loads(build_path.read_text(encoding="utf-8")) source_contract = json.loads(source_contract_path.read_text(encoding="utf-8")) recipes = read_jsonl(recipe_path) assignments = read_jsonl(assignment_path) primitive_rows = read_jsonl(primitive_path) baseline_rows = read_jsonl(baseline_path) previews = read_jsonl(preview_path) errors.extend(_audit_loudness_build(build, recipes)) build_format = str(build.get("format", "")) is_v2 = build_format == "hfd_third_party_pilot_build_v2" uniform = build.get("placement_policy") == "uniform_session_v1" speech_focus = build.get("profile_policy") == "speech_focus_v3" cross = build.get("speech_domain_policy") == "crossed_60_40_v1" audit_format = FORMAT_V2 if is_v2 else FORMAT_V1 try: profile_weights = _weights_from_build( build, values_key="profiles", order_key="profile_order", fallback=PROFILE_WEIGHTS, ) difficulty_weights = _weights_from_build( build, values_key="difficulty_weights", order_key="difficulty_order", fallback=DIFFICULTY_WEIGHTS, ) except (KeyError, TypeError, ValueError) as exc: errors.append(f"build_weight_contract:{exc}") profile_weights = PROFILE_WEIGHTS difficulty_weights = DIFFICULTY_WEIGHTS placement_schedules = build.get("placement_schedules") if not isinstance(placement_schedules, dict): placement_schedules = { "foreground_non_command": [ "before_first_command", "between_turns", "during_motion", "partial_command_overlap", ], "babble": ["during_motion", "partial_command_overlap"], } if not bool(build.get("complete")): errors.append("build_report_not_complete") if bool(build.get("production_ready")): errors.append("pilot_must_not_claim_production_ready") if is_v2: profile_names = {name for name, _ in profile_weights} excluded_profiles = set(build.get("excluded_profiles", [])) if "invalid_audio_stream" in profile_names: errors.append("v2_invalid_audio_stream_profile_present") if "invalid_audio_stream" not in excluded_profiles: errors.append("v2_invalid_audio_stream_exclusion_missing") if speech_focus: if tuple(profile_weights) != SPEECH_FOCUS_PROFILE_WEIGHTS: errors.append("speech_focus_profile_weights") if not uniform or build.get("balanced_speech_languages") is not True: errors.append("speech_focus_placement_or_language_contract") if not {"clean_reference", "ambient_noise", "white_or_colored_noise"} <= excluded_profiles: errors.append("speech_focus_exclusions") helper = Path(__file__).with_name("hfd_third_party_speech_v3.py") if sha256_file(helper) != build.get("speech_synthesis_script_sha256"): errors.append("speech_focus_synthesis_code_changed") if source_contract.get("tts_sources_are_not_resplit") is not True: errors.append("tts_source_resplit_contract_missing") if int(source_contract.get("tts_source_count", -1)) != 41_694: errors.append("tts_source_count_not_41694") for key, expected in ( ("source_assignment_sha256", source_contract.get("source_assignment_path")), ("source_production_marker_sha256", source_contract.get("source_production_marker_path")), ("target_metadata_sha256", source_contract.get("target_metadata_path")), ("motion_metadata_sha256", source_contract.get("motion_metadata_path")), ): path_value = str(expected or "") path = Path(path_value) if not path.is_file(): errors.append(f"source_contract_missing:{path_value}") elif _cached_sha(path, file_hash_cache) != source_contract.get(key): errors.append(f"source_contract_sha256:{key}") manifest_hashes = { "primitive_snapshot": primitive_path, "baseline_session_signatures": baseline_path, "source_contract": source_contract_path, } for name, path in manifest_hashes.items(): if sha256_file(path) != build.get("input_hashes", {}).get(name): errors.append(f"build_input_sha256:{name}") for name, path in ( ("session_recipes", recipe_path), ("composed_session_assignments", assignment_path), ("preview_index", preview_path), ): if sha256_file(path) != build.get("output_hashes", {}).get(name): errors.append(f"build_output_sha256:{name}") catalog_path = Path(str(build.get("input_paths", {}).get("catalog_registry", ""))) catalog_hold_path = catalog_path.parent.parent / "reports" / "semantic_hold.json" if catalog_hold_path.is_file() and json.loads(catalog_hold_path.read_text()).get("eligible_for_final_handoff") is not True: errors.append("catalog_on_semantic_hold") catalog_verify_path = Path( str(build.get("input_paths", {}).get("catalog_verify_report", "")) ) catalog: list[dict[str, Any]] = [] if not catalog_path.is_file(): errors.append(f"missing_catalog_registry:{catalog_path}") else: if sha256_file(catalog_path) != build.get("input_hashes", {}).get( "catalog_manifest" ): errors.append("catalog_manifest_sha256") catalog = read_jsonl(catalog_path) if not catalog_verify_path.is_file(): errors.append(f"missing_catalog_verify:{catalog_verify_path}") else: if sha256_file(catalog_verify_path) != build.get("input_hashes", {}).get( "catalog_verify_report" ): errors.append("catalog_verify_sha256") catalog_verify = json.loads( catalog_verify_path.read_text(encoding="utf-8") ) if not bool(catalog_verify.get("passed")): errors.append("catalog_verify_not_passed") for name in ( "control_command_manifest", "backchannel_command_manifest", "hesitation_pause_manifest", ): path = Path(str(build.get("input_paths", {}).get(name, ""))) if not path.is_file(): errors.append(f"missing_v24_baseline_input:{name}:{path}") elif sha256_file(path) != build.get("input_hashes", {}).get(name): errors.append(f"v24_baseline_input_sha256:{name}") groups_by_split: dict[str, set[str]] = defaultdict(set) assets_by_id: dict[str, dict[str, Any]] = {} speech_semantics = {} speech_source_rms = {} if speech_focus: from scripts.data.build_hfd_diverse_catalog import FILTER_VERSION, filter_text semantics_path = catalog_path.parent / "command_semantics.json" speech_semantics = json.loads(semantics_path.read_text(encoding="utf-8")) speech_semantics_hash = canonical_json_sha256(speech_semantics) speech_phrases = {key: set(values) for key, values in speech_semantics.get("target_phrases", {}).items()} if speech_semantics.get("version") != FILTER_VERSION: errors.append("speech_focus_semantic_contract_version") if cross: from scripts.data.build_hfd_cross_catalog import NEW_SOURCE_POLICY, new_source_filter_reason extra_policy = json.loads((catalog_path.parent / "new_source_filter.json").read_text()) if extra_policy != NEW_SOURCE_POLICY: errors.append("cross_source_filter_policy_drift") for asset in catalog: asset_id = str(asset.get("asset_id", "")) if not asset_id or asset_id in assets_by_id: errors.append(f"catalog_duplicate_asset:{asset_id}") continue assets_by_id[asset_id] = asset groups_by_split[str(asset.get("split"))].add(str(asset.get("source_group"))) normalized_path = Path(str(asset.get("normalized_path", ""))) if not normalized_path.is_file(): errors.append(f"catalog_missing_audio:{asset_id}") elif _cached_sha(normalized_path, file_hash_cache) != asset.get( "normalized_sha256" ): errors.append(f"catalog_audio_sha256:{asset_id}") if asset.get("role") == "non_command_speech": if not str(asset.get("transcript", "")).strip(): errors.append(f"speech_missing_transcript:{asset_id}") if asset.get("semantic_filter") not in {"conservative_command_words_v1", "bilingual_conservative_v2", "bilingual_conservative_v3", "speech_intent_v4", "speech_intent_v5"}: errors.append(f"speech_filter_contract:{asset_id}") if speech_focus: speech_source_rms[asset_id] = active_rms(read_pcm16_wav(normalized_path)) phrases = speech_phrases.get(asset["language"], set()) reason = filter_text(asset["transcript"], asset["language"], phrases, semantics=speech_semantics) if reason or asset.get("semantic_filter") != FILTER_VERSION: errors.append(f"speech_focus_semantic_recheck:{asset_id}:{reason}") if asset.get("command_semantics_sha256") != speech_semantics_hash: errors.append(f"speech_focus_semantic_hash:{asset_id}") if cross and asset_id.split(":")[0] in {"ami", "aishell"}: if asset.get("new_source_filter_sha256") != canonical_json_sha256(NEW_SOURCE_POLICY) or new_source_filter_reason(asset, speech_semantics): errors.append(f"cross_new_source_semantic_filter:{asset_id}") for path_key, hash_key in (("raw_path", "raw_sha256"), ("annotation_path", "annotation_sha256"), ("license_snapshot_path", "license_snapshot_sha256"), ("mirror_path", "mirror_sha256")): if path_key == "mirror_path" and path_key not in asset: continue path = Path(str(asset.get(path_key, ""))) if not path.is_file() or _cached_sha(path, file_hash_cache) != asset.get(hash_key): errors.append(f"cross_new_source_provenance:{asset_id}:{path_key}") group_overlap = groups_by_split["train"].intersection( groups_by_split["validation"] ) if group_overlap: errors.append(f"catalog_split_group_overlap:{sorted(group_overlap)}") primitive_by_id: dict[str, str] = {} primitive_counts: Counter[str] = Counter() for row in primitive_rows: primitive_id = str(row["primitive_id"]) split = str(row["split"]) previous = primitive_by_id.setdefault(primitive_id, split) if previous != split: errors.append(f"primitive_split_overlap:{primitive_id}") primitive_counts[split] += 1 expected_primitive_counts = {"train": 99_457, "validation": 11_389} if dict(primitive_counts) != expected_primitive_counts: errors.append( f"primitive_counts:{dict(primitive_counts)}!={expected_primitive_counts}" ) if len(primitive_by_id) != sum(expected_primitive_counts.values()): errors.append("primitive_ids_not_unique") baseline_by_split: dict[str, set[str]] = defaultdict(set) for row in baseline_rows: baseline_by_split[str(row["split"])].add(str(row["session_signature"])) baseline_manifest_count = sum(len(values) for values in baseline_by_split.values()) if baseline_manifest_count != len(baseline_rows): errors.append("baseline_signature_duplicates") assignments_by_id = {str(row["session_id"]): row for row in assignments} if len(assignments_by_id) != len(assignments): errors.append("duplicate_assignment_session_id") seen_ids: set[str] = set() seen_signatures: dict[str, set[str]] = defaultdict(set) profile_counts: dict[str, Counter[str]] = defaultdict(Counter) split_counts: Counter[str] = Counter() language_counts: Counter[str] = Counter() difficulty_counts: Counter[str] = Counter() difficulty_counts_by_split_profile: dict[ str, dict[str, Counter[str]] ] = defaultdict(lambda: defaultdict(Counter)) placement_counts: Counter[str] = Counter() speech_interference_sessions = 0 speech_overlap_sessions = 0 speech_interference_by_split: Counter[str] = Counter() speech_overlap_by_split: Counter[str] = Counter() uniform_start_bins: Counter[int] = Counter() ambient_uniform_start_bins: Counter[int] = Counter() speech_languages: Counter[str] = Counter() continuous_coverage: Counter[str] = Counter() start_bins_by_profile: dict[str, Counter[int]] = defaultdict(Counter) references = {} cross_references = [] if build.get("reference_recipes"): reference_path = Path(build["reference_recipes"]) if sha256_file(reference_path) != build.get("reference_recipes_sha256"): errors.append("reference_recipes_sha256") with reference_path.open(encoding="utf-8") as handle: for line in handle: row = json.loads(line) references[row["session_signature"]] = (row["session_id"], row["timeline"]["content_sha256"]) if cross: cross_references.append(row) cross_assignments = {} if cross: from scripts.data.hfd_third_party_cross_v4 import cross_plan, validate_cross_recipe cross_assignments = cross_plan(cross_references) if canonical_json_sha256(cross_assignments) != build.get("cross_plan_sha256"): errors.append("cross_plan_hash") if sha256_file(Path(__file__).with_name("hfd_third_party_cross_v4.py")) != build.get("cross_policy_script_sha256"): errors.append("cross_policy_code_changed") if build.get("speech_domain_weights") != {"zh/conversation": .30, "zh/read": .30, "en/conversation": .20, "en/read": .20}: errors.append("cross_domain_weight_contract") cross_reference_by_id = {r["session_id"]: r for r in cross_references} total_semantic = 0 total_dense = 0 total_samples = 0 baseline_collisions = 0 for recipe_number, recipe in enumerate(recipes, 1): if speech_focus and (recipe_number == 1 or recipe_number % 1000 == 0): print(f"speech-focus audit {recipe_number}/{len(recipes)}", file=sys.stderr, flush=True) session_id = str(recipe.get("session_id", "")) split = str(recipe.get("split", "")) profile = str(recipe.get("audio_corruption_profile", "")) split_counts[split] += 1 profile_counts[split][profile] += 1 language_counts[str(recipe.get("session_language"))] += 1 difficulty = str(recipe.get("corruption_difficulty")) difficulty_counts[difficulty] += 1 difficulty_counts_by_split_profile[split][profile][difficulty] += 1 if not session_id or session_id in seen_ids: errors.append(f"duplicate_or_empty_session_id:{session_id}") continue seen_ids.add(session_id) loudness_revision_valid, loudness_problems = _audit_loudness_revision( recipe, assets_by_id, root, ) errors.extend(f"{problem}:{session_id}" for problem in loudness_problems) turns = list(recipe.get("turns", [])) if not 2 <= len(turns) <= 4 or int(recipe.get("turn_count", -1)) != len(turns): errors.append(f"turn_count:{session_id}") signature = _session_signature(turns) cell = cross_assignments.get(signature) if cross else None if cross: if cell is None: errors.append(f"cross_reference_missing:{session_id}") else: errors.extend(f"{problem}:{session_id}" for problem in validate_cross_recipe(recipe, cell, assets_by_id)) old = cross_reference_by_id[cell["reference_session_id"]] if (recipe["audio_corruption_profile"], recipe["corruption_difficulty"], recipe["profile_index"]) != (old["audio_corruption_profile"], old["corruption_difficulty"], old["profile_index"]): errors.append(f"cross_profile_drift:{session_id}") errors.extend(f"{problem}:{session_id}" for problem in _audit_cross_retention( recipe, old, cell, loudness_revision_valid=loudness_revision_valid, )) if signature != recipe.get("session_signature"): errors.append(f"session_signature:{session_id}") if references and references.get(signature) != (recipe.get("replaces_session_id"), recipe["timeline"]["content_sha256"]): errors.append(f"replacement_supervision_changed:{session_id}") if signature in seen_signatures[split]: errors.append(f"duplicate_session_signature:{session_id}") seen_signatures[split].add(signature) if signature in baseline_by_split[split]: errors.append(f"baseline_collision:{session_id}") baseline_collisions += 1 voices = {str(turn.get("voice_name")) for turn in turns} languages = {str(turn.get("language")) for turn in turns} audio_dirs = [str(turn.get("audio_dir")) for turn in turns] if len(voices) != 1 or str(recipe.get("session_voice_name")) not in voices: errors.append(f"session_voice_policy:{session_id}") if len(languages) != 1 or str(recipe.get("session_language")) not in languages: errors.append(f"session_language_policy:{session_id}") if len(set(audio_dirs)) != len(audio_dirs): errors.append(f"duplicate_audio_dir_in_session:{session_id}") for expected_turn, turn in enumerate(turns): if int(turn.get("turn_index", -1)) != expected_turn: errors.append(f"turn_order:{session_id}:{expected_turn}") primitive_id = str(turn.get("primitive_id", "")) if primitive_by_id.get(primitive_id) != split: errors.append(f"primitive_wrong_split:{session_id}:{primitive_id}") for path_key, hash_key in ( ("motion_dir", "motion_sha256"), ("tts_audio_path", "tts_audio_sha256"), ): path = Path(str(turn.get(path_key, ""))) if not path.exists(): errors.append(f"turn_source_missing:{session_id}:{path_key}") elif path_key == "motion_dir": if _motion_sha256(path, file_hash_cache) != turn.get(hash_key): errors.append( f"turn_source_sha256:{session_id}:{path_key}" ) elif _cached_sha(path, file_hash_cache) != turn.get(hash_key): errors.append(f"turn_source_sha256:{session_id}:{path_key}") if not str(turn.get("instruction_text", "")).strip(): errors.append(f"empty_instruction:{session_id}:{expected_turn}") audio_meta = dict(recipe.get("audio", {})) try: audio_path = _safe_path(root, str(audio_meta["path"])) except (KeyError, ValueError) as exc: errors.append(f"audio_path:{session_id}:{exc}") continue if not audio_path.is_file(): errors.append(f"audio_missing:{session_id}") continue if _cached_sha(audio_path, file_hash_cache) != audio_meta.get("sha256"): errors.append(f"audio_sha256:{session_id}") try: audio = read_pcm16_wav(audio_path) except Exception as exc: errors.append(f"audio_contract:{session_id}:{exc}") continue samples = int(audio.size) total_samples += samples semantic_steps = int(recipe["timeline"]["semantic_window_count"]) dense_steps = int(recipe["timeline"]["action_steps"]) total_semantic += semantic_steps total_dense += dense_steps if samples != int(audio_meta.get("sample_count", -1)): errors.append(f"audio_sample_count:{session_id}") if expected_window_count(samples) != semantic_steps: errors.append(f"audio_window_geometry:{session_id}") if int(audio_meta.get("window_count", -1)) != semantic_steps: errors.append(f"audio_window_count:{session_id}") peak = float(np.max(np.abs(audio), initial=0.0)) if not np.isfinite(audio).all(): errors.append(f"audio_non_finite:{session_id}") if peak > 0.9501: errors.append(f"audio_peak:{session_id}:{peak}") if np.count_nonzero(np.abs(audio) >= 1.0): errors.append(f"audio_clipping:{session_id}") if _audio_pcm_sha(audio) != audio_meta.get("pcm16_sha256"): errors.append(f"audio_pcm_sha256:{session_id}") target_events = list(recipe.get("target_speech_events", [])) if len(target_events) != len(turns): errors.append(f"target_event_count:{session_id}") previous_end = -1 for event_index, event in enumerate(target_events): start = int(event.get("start_sample", -1)) end = int(event.get("end_sample", -1)) if not (0 <= start < end <= samples): errors.append(f"target_event_bounds:{session_id}:{event_index}") if start < previous_end: errors.append(f"target_event_overlap:{session_id}:{event_index}") previous_end = end if event_index < len(turns): turn = turns[event_index] if event.get("source_key") != turn.get("tts_source_key"): errors.append(f"target_event_pairing:{session_id}:{event_index}") if event.get("original_audio_sha256") != turn.get( "tts_audio_sha256" ): errors.append(f"target_event_sha256:{session_id}:{event_index}") if is_v2: mix_metadata = dict(recipe.get("mix_metadata", {})) try: target_track = _target_track_from_recipe(recipe, samples) global_scale = float(mix_metadata["global_scale"]) measured_total = signal_to_residual_db_on_active_signal( target_track * np.float32(global_scale), audio ) reported_total = float( mix_metadata["augmented_total_signal_to_residual_db"] ) base_total = float( mix_metadata["base_total_signal_to_residual_db"] ) if not np.isfinite(base_total): errors.append(f"base_total_ratio_non_finite:{session_id}") if abs(measured_total - reported_total) > 0.15: errors.append( f"augmented_total_ratio:{session_id}:" f"{measured_total}!={reported_total}" ) except (KeyError, TypeError, ValueError, OSError, RuntimeError) as exc: errors.append(f"total_ratio_contract:{session_id}:{exc}") events = list(recipe.get("interference_events", [])) if profile == "clean_reference" and events: errors.append(f"clean_has_interference:{session_id}") if profile != "clean_reference" and not events: errors.append(f"profile_missing_interference:{session_id}") if events and profile in {"foreground_non_command", "babble"}: speech_interference_sessions += 1 speech_interference_by_split[split] += 1 schedule = list(placement_schedules.get(profile, [])) if not schedule: errors.append(f"missing_placement_schedule:{profile}") else: expected_placement = schedule[ int(recipe.get("profile_index", -1)) % len(schedule) ] actual_placement = str(events[0].get("placement")) if actual_placement != expected_placement: errors.append( f"speech_placement:{session_id}:" f"{actual_placement}!={expected_placement}" ) if actual_placement == "partial_command_overlap": speech_overlap_sessions += 1 speech_overlap_by_split[split] += 1 if is_v2: turn_index = events[0].get( "overlapped_target_turn_index" ) if not isinstance(turn_index, int) or not ( 1 <= turn_index < len(target_events) ): errors.append( f"overlap_target_turn:{session_id}:{turn_index}" ) else: target_event = target_events[turn_index] overlap = min( int(events[0]["end_sample"]), int(target_event["end_sample"]), ) - max( int(events[0]["start_sample"]), int(target_event["start_sample"]), ) if overlap <= 0: errors.append( f"missing_command_overlap:{session_id}" ) first_event = target_events[0] if ( int(events[0]["start_sample"]) < int(first_event["end_sample"]) and int(events[0]["end_sample"]) > int(first_event["start_sample"]) ): errors.append( f"first_turn_must_be_clean:{session_id}" ) elif is_v2 and events[0].get( "overlapped_target_turn_index" ) is not None and not uniform: errors.append(f"non_overlap_has_target_turn:{session_id}") if uniform: event = events[0] length = int(event["end_sample"]) - int(event["start_sample"]) expected_start, _, expected_turn = _choose_event_start( placement="uniform_session", event_samples=length, total_samples=samples, target_events=target_events, semantic_steps=[], rng=random.Random(recipe["interference_seed"])) if expected_start != int(event["start_sample"]) or expected_turn != event.get("overlapped_target_turn_index"): errors.append(f"uniform_start_replay:{session_id}") overlaps = [int(target["turn_index"]) for target in target_events if int(event["start_sample"]) < int(target["end_sample"]) and int(event["end_sample"]) > int(target["start_sample"])] if overlaps != event.get("overlapped_target_turn_indices"): errors.append(f"uniform_overlap_metadata:{session_id}") if overlaps: speech_overlap_sessions += 1 speech_overlap_by_split[split] += 1 maximum = samples - length if event.get("uniform_start_max_sample") != maximum: errors.append(f"uniform_support:{session_id}") uniform_start_bins[min(9, expected_start * 10 // (maximum + 1))] += 1 start_bins_by_profile[profile][min(9, expected_start * 10 // (maximum + 1))] += 1 languages = event.get("languages", []) expected_language = cell["language"] if cell else speech_language(profile, int(recipe["profile_index"]), build.get("profile_policy", "legacy_v2")) if build.get("balanced_speech_languages") and set(languages) != {expected_language}: errors.append(f"speech_language_balance:{session_id}") speech_languages[languages[0] if languages else "missing"] += 1 if events and profile == "babble_continuous": speech_interference_sessions += 1 speech_interference_by_split[split] += 1 if not speech_focus or len(events) != 1: errors.append(f"continuous_profile_contract:{session_id}") event = events[0] try: eligible_assets = ({k: a for k, a in assets_by_id.items() if a.get("speech_domain") == cell["domain"]} if cell else assets_by_id) problems = _audit_continuous_event(event, eligible_assets, sample_count=samples, profile_index=int(recipe["profile_index"]), seed=int(recipe["interference_seed"]), source_rms=speech_source_rms) errors.extend(f"{problem}:{session_id}" for problem in problems) except (KeyError, TypeError, ValueError) as exc: errors.append(f"continuous_metadata:{session_id}:{exc}") start, end = int(event["start_sample"]), int(event["end_sample"]) overlaps = [int(target["turn_index"]) for target in target_events if start < int(target["end_sample"]) and end > int(target["start_sample"])] if overlaps != event.get("overlapped_target_turn_indices"): errors.append(f"continuous_overlap_metadata:{session_id}") if overlaps: speech_overlap_sessions += 1 speech_overlap_by_split[split] += 1 languages = event.get("languages", []) expected_language = cell["language"] if cell else speech_language(profile, int(recipe["profile_index"]), build.get("profile_policy", "legacy_v2")) if set(languages) != {expected_language}: errors.append(f"continuous_language_balance:{session_id}") speech_languages[languages[0] if languages else "missing"] += 1 continuous_coverage[str(event.get("coverage_mode"))] += 1 if event.get("coverage_mode") == "partial": maximum = samples - (end - start) bin_index = min(9, start * 10 // (maximum + 1)) uniform_start_bins[bin_index] += 1 start_bins_by_profile[profile][bin_index] += 1 for event_index, event in enumerate(events): start = int(event.get("start_sample", -1)) end = int(event.get("end_sample", -1)) if not (0 <= start < end <= samples): errors.append(f"interference_bounds:{session_id}:{event_index}") if profile == "ambient_noise" and build.get("ambient_policy") == "mixed_continuous_transient_v1": transient = int(recipe["profile_index"]) % 2 == 1 if transient: expected = random.Random(recipe["interference_seed"]).randrange(samples - (end - start) + 1) if start != expected or event.get("placement") != "uniform_session": errors.append(f"ambient_uniform_replay:{session_id}") if not 1.5 * SAMPLE_RATE <= end - start <= 15 * SAMPLE_RATE: errors.append(f"ambient_transient_duration:{session_id}") ambient_uniform_start_bins[min(9, start * 10 // (samples - (end - start) + 1))] += 1 elif start != 0 or end != samples or event.get("placement") != "full_session": errors.append(f"ambient_full_session:{session_id}") if "target_snr_db" in event: if not np.isfinite(float(event["measured_snr_db"])) or abs(float(event["target_snr_db"]) - float(event["measured_snr_db"])) > 0.5: errors.append(f"snr_tolerance:{session_id}:{event_index}") if "target_sir_db" in event: if not np.isfinite(float(event["measured_sir_db"])) or abs(float(event["target_sir_db"]) - float(event["measured_sir_db"])) > 0.5: errors.append(f"sir_tolerance:{session_id}:{event_index}") if is_v2: try: errors.extend(f"{problem}:{session_id}" for problem in _audit_target_level( event, profile=profile, difficulty=difficulty, split=split, loudness_revision_valid=loudness_revision_valid, )) except (TypeError, ValueError) as exc: errors.append(f"target_level_contract:{session_id}:{exc}") if event.get("placement"): placement_counts[str(event["placement"])] += 1 asset_ids = list(event.get("asset_ids", [])) if event.get("asset_id"): asset_ids.append(str(event["asset_id"])) expected_asset_split = "train" if split == "train" else "validation" if speech_focus and event.get("type") != profile: errors.append(f"speech_focus_event_type:{session_id}") for asset_id in asset_ids: asset = assets_by_id.get(str(asset_id)) if asset is None: errors.append(f"unknown_interference_asset:{session_id}:{asset_id}") elif asset.get("split") != expected_asset_split: errors.append(f"interference_wrong_split:{session_id}:{asset_id}") elif speech_focus and asset.get("role") != "non_command_speech": errors.append(f"speech_focus_non_speech_asset:{session_id}:{asset_id}") elif speech_focus and profile in {"foreground_non_command", "babble"} and ( int(asset["sample_count"]) > 8 * SAMPLE_RATE or asset.get("planned_usage") == "continuous_only" ): errors.append(f"speech_focus_long_asset_in_short_profile:{session_id}:{asset_id}") if speech_focus: for field, key in (("asset_sha256", "normalized_sha256"), ("source_groups", "source_group"), ("speaker_ids", "speaker_id"), ("languages", "language"), ("transcripts", "transcript")): expected_values = [assets_by_id.get(identifier, {}).get(key) for identifier in asset_ids] if event.get(field) != expected_values: errors.append(f"speech_focus_event_provenance:{session_id}:{field}") timeline_meta = dict(recipe.get("timeline", {})) try: timeline_path = _safe_path(root, str(timeline_meta["path"])) except (KeyError, ValueError) as exc: errors.append(f"timeline_path:{session_id}:{exc}") continue if not timeline_path.is_file(): errors.append(f"timeline_missing:{session_id}") continue if _cached_sha(timeline_path, file_hash_cache) != timeline_meta.get( "file_sha256" ): errors.append(f"timeline_sha256:{session_id}") try: with np.load(timeline_path, allow_pickle=False) as loaded: arrays = {key: loaded[key] for key in loaded.files} except Exception as exc: errors.append(f"timeline_npz:{session_id}:{exc}") continue if _timeline_content_sha256(arrays) != timeline_meta.get("content_sha256"): errors.append(f"timeline_content_sha256:{session_id}") if any(int(value.shape[0]) != dense_steps for value in arrays.values()): errors.append(f"timeline_length:{session_id}") if int(np.count_nonzero(arrays["update_semantic_cache"])) != semantic_steps: errors.append(f"timeline_semantic_mask:{session_id}") if int(np.count_nonzero(arrays["motion_duration_target_mask"])) != len(turns): errors.append(f"duration_target_count:{session_id}") if int(np.count_nonzero(arrays["latest_instruction_target_mask"])) != len(turns): errors.append(f"latest_text_target_count:{session_id}") if int(np.count_nonzero(arrays["instruction_memory_target_mask"])) != len(turns) - 1: errors.append(f"memory_target_count:{session_id}") assignment = assignments_by_id.get(session_id) if assignment is None: errors.append(f"assignment_missing:{session_id}") else: for assignment_key, recipe_value in ( ("split", split), ("audio_path", audio_meta.get("path")), ("audio_sha256", audio_meta.get("sha256")), ("audio_sample_count", samples), ("semantic_window_count", semantic_steps), ("audio_corruption_profile", profile), ): if assignment.get(assignment_key) != recipe_value: errors.append(f"assignment_mismatch:{session_id}:{assignment_key}") if set(assignments_by_id) != seen_ids: errors.append("recipe_assignment_id_set_mismatch") expected_split_counts = { "train": int(build.get("train_sessions", -1)), "validation": int(build.get("validation_sessions", -1)), } if dict(split_counts) != expected_split_counts: errors.append(f"session_split_counts:{dict(split_counts)}") for split, count in expected_split_counts.items(): expected_profiles = _profile_counts(count, profile_weights) if dict(profile_counts[split]) != expected_profiles: errors.append( f"profile_counts:{split}:{dict(profile_counts[split])}!={expected_profiles}" ) if is_v2: for profile, profile_count in expected_profiles.items(): expected_difficulties = _difficulty_counts( profile_count, difficulty_weights ) actual_difficulties = dict( difficulty_counts_by_split_profile[split][profile] ) if actual_difficulties != expected_difficulties: errors.append( f"difficulty_counts:{split}:{profile}:" f"{actual_difficulties}!={expected_difficulties}" ) expected_speech = sum( expected_profiles.get(profile, 0) for profile in SPEECH_PROFILES ) expected_overlap = 0 for profile in ("foreground_non_command", "babble"): schedule = list(placement_schedules.get(profile, [])) if schedule: expected_overlap += sum( schedule[index % len(schedule)] == "partial_command_overlap" for index in range(expected_profiles.get(profile, 0)) ) if speech_interference_by_split[split] != expected_speech: errors.append( f"speech_session_count:{split}:" f"{speech_interference_by_split[split]}!={expected_speech}" ) if not uniform and speech_overlap_by_split[split] != expected_overlap: errors.append( f"speech_overlap_count:{split}:" f"{speech_overlap_by_split[split]}!={expected_overlap}" ) reported_counts = build.get("counts", {}) for name, actual in ( ("sessions", len(recipes)), ("turns", sum(int(row.get("turn_count", 0)) for row in recipes)), ("semantic_windows", total_semantic), ("dense_action_windows", total_dense), ("audio_samples", total_samples), ("baseline_unique_signatures", baseline_manifest_count), ("primitive_snapshot_rows", len(primitive_rows)), ): if int(reported_counts.get(name, -1)) != actual: errors.append(f"build_count:{name}") expected_baseline_sessions = {"train": 267_850, "validation": 7_698} if build.get("counts", {}).get("baseline_v24_sessions_by_split") != expected_baseline_sessions: errors.append("baseline_v24_session_counts") if int(build.get("counts", {}).get("baseline_v24_sessions", -1)) != sum( expected_baseline_sessions.values() ): errors.append("baseline_v24_session_total") if baseline_collisions != 0 or int(build.get("baseline_collision_count", -1)) != 0: errors.append("nonzero_baseline_collision_count") preview_pairs: Counter[tuple[str, str]] = Counter() preview_buckets: dict[tuple[str, str], set[str]] = defaultdict(set) recipes_by_id = {str(row["session_id"]): row for row in recipes} for preview in previews: key = (str(preview.get("split")), str(preview.get("profile"))) preview_pairs[key] += 1 preview_buckets[key].add(str(preview.get("preview_bucket", ""))) recipe = recipes_by_id.get(str(preview.get("session_id", ""))) if recipe is None: errors.append(f"preview_unknown_session:{preview.get('session_id')}") elif ( recipe.get("split") != key[0] or recipe.get("audio_corruption_profile") != key[1] ): errors.append(f"preview_recipe_mismatch:{preview.get('session_id')}") try: preview_start = int(preview["start_sample"]) preview_end = int(preview["end_sample"]) except (KeyError, TypeError, ValueError) as exc: errors.append(f"preview_bounds:{key}:{exc}") preview_start = -1 preview_end = -1 recipe_samples = ( int(recipe.get("audio", {}).get("sample_count", -1)) if recipe is not None else -1 ) if not (0 <= preview_start < preview_end <= recipe_samples): errors.append( f"preview_bounds:{preview.get('session_id')}:" f"{preview_start}:{preview_end}:{recipe_samples}" ) if ( is_v2 and recipe is not None and (preview.get("preview_bucket") == "non_overlap" or (uniform and str(preview.get("preview_bucket", "")).startswith("random_"))) ): contains_target = any( preview_start <= int(event["start_sample"]) and int(event["end_sample"]) <= preview_end for event in recipe.get("target_speech_events", []) ) contains_interference = any( preview_start <= int(event["start_sample"]) and int(event["end_sample"]) <= preview_end for event in recipe.get("interference_events", []) ) if not contains_target: errors.append( f"non_overlap_preview_missing_target:" f"{preview.get('session_id')}" ) if not contains_interference: errors.append( f"non_overlap_preview_missing_interference:" f"{preview.get('session_id')}" ) for path_key, hash_key in ( ("base_audio_path", "base_audio_sha256"), ("augmented_audio_path", "augmented_audio_sha256"), ): try: path = _safe_path(root, str(preview[path_key])) except (KeyError, ValueError) as exc: errors.append(f"preview_path:{key}:{exc}") continue if not path.is_file(): errors.append(f"preview_missing:{path}") continue if _cached_sha(path, file_hash_cache) != preview.get(hash_key): errors.append(f"preview_sha256:{path}") try: preview_audio = read_pcm16_wav(path) except (OSError, RuntimeError, ValueError) as exc: errors.append(f"preview_audio:{path}:{exc}") else: if preview_audio.size != preview_end - preview_start: errors.append( f"preview_audio_samples:{path}:" f"{preview_audio.size}!={preview_end - preview_start}" ) for split in expected_split_counts: for profile, _ in profile_weights: if preview_pairs[(split, profile)] < 1: errors.append(f"preview_coverage:{split}:{profile}") if is_v2: expected_buckets = { "clean_reference": {"clean_reference"}, "ambient_noise": {"easy", "hard"}, "white_or_colored_noise": {"easy", "hard"}, "foreground_non_command": { "command_overlap", "non_overlap", }, "babble": {"command_overlap", "non_overlap"}, "babble_continuous": {"random_zh", "random_en"}, }[profile] if uniform and profile in {"foreground_non_command", "babble"}: expected_buckets = {"random_zh", "random_en"} if cross: expected_buckets = {f"random_{lang}_{domain}" for lang in ("zh", "en") for domain in ("conversation", "read")} if preview_buckets[(split, profile)] != expected_buckets: errors.append( f"preview_buckets:{split}:{profile}:" f"{sorted(preview_buckets[(split, profile)])}!=" f"{sorted(expected_buckets)}" ) warnings.extend( [ "human_listening_review_pending", "pilot_recipe_loader_is_not_connected_to_training", ] ) if not uniform: warnings.extend(["non_command_speech_is_english_only_in_this_pilot", "demand_license_requires_production_reverification"]) listening_sheet = _write_listening_sheet( root, previews, recipes_by_id ) report = { "format": audit_format, "passed": not errors, "automated_checks_complete": not errors, "production_ready": False, "human_listening_review": "pending", "errors": errors, "warnings": warnings, "counts": { "sessions": len(recipes), "sessions_by_split": dict(split_counts), "turns": sum(int(row.get("turn_count", 0)) for row in recipes), "semantic_windows": total_semantic, "dense_action_windows": total_dense, "audio_hours": total_samples / SAMPLE_RATE / 3600.0, "profiles_by_split": { split: dict(counts) for split, counts in profile_counts.items() }, "languages": dict(language_counts), "difficulties": dict(difficulty_counts), "placements": dict(placement_counts), "speech_interference_sessions": speech_interference_sessions, "uniform_start_deciles": dict(sorted(uniform_start_bins.items())), "ambient_uniform_start_deciles": dict(sorted(ambient_uniform_start_bins.items())), "interference_languages": dict(speech_languages), "continuous_coverage_modes": dict(continuous_coverage), "uniform_start_deciles_by_profile": {key: dict(sorted(value.items())) for key, value in start_bins_by_profile.items()}, "speech_command_overlap_sessions": speech_overlap_sessions, "speech_command_overlap_fraction": ( speech_overlap_sessions / speech_interference_sessions if speech_interference_sessions else 0.0 ), "baseline_v24_sessions": int( build.get("counts", {}).get("baseline_v24_sessions", -1) ), "baseline_unique_signatures": baseline_manifest_count, "baseline_collisions": baseline_collisions, "third_party_source_group_overlap": len(group_overlap), "preview_pairs": len(previews), }, "artifacts": { "pilot_build": str(build_path), "session_recipes": str(recipe_path), "composed_assignments": str(assignment_path), "listening_review": str(listening_sheet), }, } return report def main() -> None: args = _parse_args() root = args.production_root.resolve() report = audit(root) report_path = root / "reports" / "strict_audit.json" write_json_atomic(report_path, report) audit_format = str(report["format"]) marker_format = ( "hfd_third_party_pilot_complete_v2" if audit_format == FORMAT_V2 else "hfd_third_party_pilot_complete_v1" ) marker = { "format": marker_format, "automated_checks_complete": bool(report["passed"]), "automated_audit_sha256": sha256_file(report_path), "human_listening_review": "pending", "production_ready": False, "training_started": False, } write_json_atomic(root / "reports" / "pilot_complete.json", marker) print(json.dumps(report, ensure_ascii=False, indent=2), flush=True) if args.strict and not report["passed"]: raise SystemExit(1) if __name__ == "__main__": main()