Files
rsLXST/tools/generate-codec2-700c-codebooks.py
T

49 lines
2.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Generate immutable Rust 700C codebooks from the pinned Codec2 source tree."""
import argparse
import hashlib
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
BACKEND = ROOT / "crates/lxst-codec2"
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("source", type=Path)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
provenance = json.loads((BACKEND / "UPSTREAM.json").read_text())["codec2_700c"]
lines = [
"// Generated by tools/generate-codec2-700c-codebooks.py; do not edit.",
"// Codec2 codebooks, Copyright David Rowe 2017. LGPL-2.1-only.",
f"// Source: {provenance['repository']} at {provenance['commit']}.",
"// Exact input hashes and original notices: UPSTREAM.json and NOTICE.",
"",
]
for name, relative, width, count in [
("VQ1", "src/codebook/train_120_1.txt", 20, 512),
("VQ2", "src/codebook/train_120_2.txt", 20, 512),
("ENERGY", "src/codebook/newamp1_energy_q.txt", 1, 16),
]:
raw = (args.source / relative).read_bytes()
assert hashlib.sha256(raw).hexdigest() == provenance["source_sha256"][relative], relative
dimensions, entries, *values = raw.decode().split()
assert (int(dimensions), int(entries), len(values)) == (width, count, width * count)
lines.append(f"pub(super) static {name}: [f32; {len(values)}] = [")
for i in range(0, len(values), width):
lines.append(" " + ", ".join(values[i:i + width]) + ",")
lines.extend(["];", ""])
output = "\n".join(lines)
path = BACKEND / "src/native/codebook700c.rs"
if args.check:
assert path.read_text() == output, "700C codebooks differ from pinned generation"
else:
path.write_text(output)
print("700C codebooks: pinned source hashes and 20×512 + 20×512 + 16 entries verified")
if __name__ == "__main__":
main()