File size: 8,764 Bytes
adabee1 | 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 | #!/usr/bin/env python3
"""Validate all prepared tiny-voca data, split separation, WAVs and Danish tokens."""
from __future__ import annotations
import argparse
from collections import Counter, defaultdict
import hashlib
import json
from pathlib import Path
from prepare_coral import text_group_id, waveform_sha256
SPLITS = ("train", "validation", "test")
def read_jsonl(path):
return [json.loads(line) for line in path.read_text(encoding="utf-8").split("\n") if line.strip()]
def check_records(root, metadata, config, tokenize, normalize=lambda text: text, frozen=False):
"""Return a complete report. tokenize is explicit to allow isolated QC tests."""
import numpy as np
import soundfile as sf
errors, counts, groups, ids, audio_hashes = [], Counter(), defaultdict(set), set(), defaultdict(set)
frontend_cache = {}
changed_groups = changed_containers = 0
if metadata.get("complete") is not True:
errors.append("preparation is incomplete")
if metadata.get("smoke_run"):
errors.append("limited smoke preparation is not a full training corpus")
if metadata.get("format") != "tiny-voca" or metadata.get("sample_rate") != config.sample_rate:
errors.append("format/sample rate differs from tiny-voca config")
if getattr(config, "language", None) != "da":
errors.append("config language must be da")
revision = metadata.get("revision")
if not isinstance(revision, str) or len(revision) != 40:
errors.append("missing immutable source revision")
for split in SPLITS:
path = root / f"{split}.jsonl"
try:
rows = read_jsonl(path)
except (OSError, ValueError) as error:
errors.append(f"{split}: manifest read failure: {error}")
continue
if not rows:
errors.append(f"{split}: empty split")
for row in rows:
identifier = row.get("id", "<missing>")
label = f"{split}/{identifier}"
counts[split] += 1
if identifier in ids:
errors.append(f"{label}: duplicate recording id")
ids.add(identifier)
if row.get("split") != split or row.get("voice_id") not in config.speakers:
errors.append(f"{label}: wrong split or unknown voice")
if row.get("source_revision") != revision:
errors.append(f"{label}: source revision differs from preparation")
try:
text = row["text"]
split_text = normalize(text) if metadata.get("admission", {}).get("check_frontend") else text
group = text_group_id(split_text)
historical_text = row.get("split_text", text)
if historical_text != split_text and not frozen:
errors.append(f"{label}: split normalization changed after preparation")
groups[group].add(split)
if (text_group_id(historical_text) if frozen else group) != row.get("text_id"):
errors.append(f"{label}: text changed after preparation")
changed_groups += group != row.get("text_id")
if text not in frontend_cache:
frontend_cache[text] = tokenize(text)
tokens = frontend_cache[text]
if tokens.unknown:
errors.append(f"{label}: unknown phones: {list(tokens.unknown)!r}")
if not tokens.ids or len(tokens.ids) > config.max_tokens:
errors.append(f"{label}: empty or overlong token sequence")
if any(not 0 <= token < config.vocab_size for token in tokens.ids):
errors.append(f"{label}: out-of-vocabulary token ID")
except (KeyError, ValueError) as error:
errors.append(f"{label}: text/frontend failure: {error}")
try:
wav_path = (root / row["audio"]).resolve()
if not wav_path.is_relative_to(root.resolve()):
raise ValueError("audio path escapes data directory")
payload = wav_path.read_bytes()
digest = hashlib.sha256(payload).hexdigest()
container_changed = digest != row.get("audio_sha256")
wave, sample_rate = sf.read(wav_path, dtype="float32", always_2d=True)
if not wave.size or not np.isfinite(wave).all():
raise ValueError("empty/nonfinite WAV")
sample_digest = waveform_sha256(wave, sample_rate)
audio_hashes[sample_digest].add(split)
if row.get("waveform_sha256", sample_digest) != sample_digest:
errors.append(f"{label}: decoded waveform hash changed after preparation")
if container_changed:
if not row.get("waveform_sha256"):
errors.append(f"{label}: WAV hash changed without a frozen decoded-sample hash")
else:
changed_containers += 1
if sample_rate != config.sample_rate or wave.shape[1] != 1:
errors.append(f"{label}: unexpected rate/channels")
if float(np.sqrt(np.mean(wave.astype(np.float64) ** 2))) < 1e-5:
errors.append(f"{label}: effectively silent WAV")
if float(np.max(np.abs(wave))) > 1.01:
errors.append(f"{label}: out-of-range WAV")
if (len(wave) + config.hop - 1) // config.hop > config.max_frames:
errors.append(f"{label}: WAV longer than configured max_frames")
except (OSError, RuntimeError, ValueError, KeyError) as error:
errors.append(f"{label}: audio failure: {error}")
for group, splits in groups.items():
if len(splits) != 1:
errors.append(f"normalized text leakage: {group} -> {sorted(splits)}")
for digest, splits in audio_hashes.items():
if len(splits) != 1:
errors.append(f"identical WAV leakage (decoded samples): {digest} -> {sorted(splits)}")
if dict(counts) != metadata.get("accepted"):
errors.append("manifest counts differ from preparation.json")
return {"status": "FAIL" if errors else "PASS", "source_revision": revision,
"rows": dict(counts), "unique_texts": len(groups), "voice_ids": list(config.speakers),
"vocabulary": config.vocab_size, "errors": errors,
"frozen_source_splits": frozen, "current_normalized_group_keys_changed": changed_groups,
"container_hashes_changed": changed_containers,
"note": "Checks structure, split separation, files and tokenization; pronunciation and transcript/audio agreement require listening."}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--data", type=Path, required=True)
parser.add_argument("--config", type=Path, default=Path(__file__).with_name("config.da.json"))
parser.add_argument("--out", type=Path)
parser.add_argument("--frozen", action="store_true", help="Check frozen source_preparation_v2.json manifests under the current frontend; "
"preserve historical split keys and independently check current normalized-text leakage")
args = parser.parse_args()
from tiny_voca.config import Config
from tiny_voca.text import phonemize, normalize_text, set_frontend
config = Config.from_dict(json.loads(args.config.read_text()))
set_frontend("espeak")
root = args.data.resolve()
metadata = json.loads((root / ("source_preparation_v2.json" if args.frozen else "preparation.json")).read_text())
if args.frozen:
receipt = json.loads((root / 'receipt.json').read_text())
if hashlib.sha256((root / 'source_preparation_v2.json').read_bytes()).hexdigest() != receipt['source_preparation_sha256']:
raise ValueError('Frozen source preparation receipt changed')
for split in SPLITS:
if hashlib.sha256((root / (split + '.jsonl')).read_bytes()).hexdigest() != receipt['splits'][split]['manifest_sha256']:
raise ValueError(f'Frozen {split} manifest changed')
report = check_records(root, metadata, config,
lambda text: phonemize(text, config.profile),
lambda text: normalize_text(text, config.profile), frozen=args.frozen)
rendered = json.dumps(report, ensure_ascii=False, indent=2, allow_nan=False) + "\n"
if args.out:
args.out.parent.mkdir(parents=True, exist_ok=True)
args.out.write_text(rendered, encoding="utf-8")
print(rendered, end="")
raise SystemExit(1 if report["errors"] else 0)
if __name__ == "__main__":
main()
|