File size: 4,061 Bytes
6119223
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Screen compressed candidates on matching audio and cached FP32 transcripts."""
import argparse
import hashlib
import json
import time
from pathlib import Path

from .runtime import CoreMLShruti, _upstream
from .score import score_lattices, score_paired
from .sources import ROOT

CORPORA = {
    "fleurs": "fleurs/hi_in",
    "monsoon": "monsoon",
    "mucs": "mucs",
}


def digest(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def read_rows(path, *, growing=False):
    with path.open() as file:
        return [json.loads(line) for line in file if not growing or line.endswith("\n")]


def measure(folder, count, output):
    if count < 1:
        raise ValueError("The clip count must be positive")
    output.mkdir(parents=True, exist_ok=True)
    candidate = CoreMLShruti(folder)
    result = {"candidate": candidate.meta["weight_compression"], "corpora": {}}
    fp32 = None
    for corpus, directory in CORPORA.items():
        manifest = ROOT / "data/bench" / directory / "test.jsonl"
        baseline = ROOT / "results/local" / f"hi-{corpus}"
        run = json.loads((baseline / "run.json").read_text())
        manifest_hash = digest(manifest)
        if run["language"] != "hi" or run["compute"] != "CPU_ONLY" or run["manifest_sha256"] != manifest_hash:
            raise ValueError(f"Incompatible reference run: {baseline}")
        if run["source"] != candidate.meta["source"]:
            raise ValueError(f"Reference checkpoint differs from candidate: {baseline}")
        previous = {row["id"]: row for row in read_rows(baseline / "clips.jsonl", growing=True)}
        clips = sorted(
            read_rows(manifest),
            key=lambda row: hashlib.sha256(row["id"].encode()).digest(),
        )[:count]
        rows = []
        with (output / f"{corpus}.jsonl").open("w", buffering=1) as file:
            for clip in clips:
                path = manifest.parent / clip["audio"]
                if digest(path) != clip["audio_sha256"]:
                    raise ValueError(f"Unexpected fixture: {path}")
                pcm = _upstream.read_audio(str(path))
                existing = previous.get(clip["id"])
                if existing:
                    if existing["audio_sha256"] != clip["audio_sha256"]:
                        raise ValueError(f"Cached reference mismatch: {path}")
                    reference = existing["coreml"]["text"]
                else:
                    if fp32 is None:
                        fp32 = CoreMLShruti(ROOT / "build/hi")
                    reference = fp32.transcribe(pcm, language="hi")["text"]
                start = time.perf_counter()
                text = candidate.transcribe(pcm, language="hi")["text"]
                row = {
                    **{key: value for key, value in clip.items() if key != "audio"},
                    "baseline": {"text": reference},
                    "coreml": {"text": text},
                    "seconds": time.perf_counter() - start,
                    "audio_seconds": len(pcm) / 16_000,
                }
                file.write(json.dumps(row, ensure_ascii=False) + "\n")
                rows.append(row)
        summary = score_lattices(rows) if corpus == "monsoon" else score_paired(rows)
        summary["manifest_sha256"] = manifest_hash
        summary["matched_clip_ids"] = [row["id"] for row in rows]
        summary["candidate_sampled_seconds"] = sum(row["seconds"] for row in rows)
        result["corpora"][corpus] = summary
        print(corpus, json.dumps({k: v for k, v in summary.items() if k != "matched_clip_ids"}), flush=True)
    (output / "summary.json").write_text(json.dumps(result, indent=2) + "\n")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("candidate", type=Path)
    parser.add_argument("--clips-per-corpus", type=int, default=24)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    measure(args.candidate, args.clips_per_corpus, args.output)


if __name__ == "__main__":
    main()