File size: 35,323 Bytes
66b4588
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
#!/usr/bin/env python3
"""Check aligned_transcript.json files against audio; report folders and mismatching sections.

Run in your existing working NeMo environment (Python 3.10+):
    python -m pip install 'pyctcdecode==0.5.0' kenlm 'numpy<2'
    python check_transcript_folders.py /path/to/parent

FFmpeg must be installed. Both linked models download automatically once to
~/.cache/baniguru-folder-check/. Existing local copies can be supplied:
    python check_transcript_folders.py /path/to/parent \
        --model /path/baniguru_offline_v1.nemo --lm /path/gurbani_3gram.bin

Outputs, in the supplied parent:
    mismatched_folders.txt  Absolute paths, one per folder with a failed section.
    unchecked_folders.txt  Absolute paths of folders with input/inference errors.
    mismatched_sections.txt  Folder basename, expected transcript, actual ASR, CER.
The TXT report is created at startup and flushed after each mismatch, so it
can be viewed during processing. It contains mismatches only and resets on
each run. Each block is folder_name / expected: / actual: / cer: / blank line.
Expected text comes only from the section's transcript field. The actual text
is the independent ASR output (3-gram or greedy) with the lower CER.
Heading numbers are expanded in expected text for display and comparison:
e.g. ਮਹਲਾ ੫ ਘਰੁ ੪ becomes ਮਹਲਾ ਪੰਜਵਾ ਘਰ ਚੌਥਾ. Original JSON is unchanged.
The folder lists update after each folder finishes. Inputs are never modified.
Errors are printed at folder level on stderr and are never counted as matches.
Exit codes: 0=all matched, 1=mismatches, 2=errors/incomplete, 130=interrupted.

Default matching uses normalized character error rate (CER), with --max-cer 20.
CER = character edit distance / normalized reference character count * 100;
lower is better. Insertions, deletions and substitutions each cost one edit.
Spaces, punctuation, verse counters, and final word sihari/onkar are ignored;
equivalent vowel-carrier spellings and the spoken form of ੴ are normalized.
Numbers after ਮਹਲਾ / ਮਃ / ਘਰੁ / ਘਰ are read as Punjabi ordinals (1-17),
including Gurmukhi or ASCII digits. Spoken heading ordinal variants with or
without a final nasal mark normalize alike; other verse counters stay ignored.
Gurmukhi vowel marks elsewhere still count as characters (Unicode code points).
This is normalized CER, not raw-text CER; insertions can make CER exceed 100%.
Raise --max-cer for a more forgiving check; lower it for a stricter check.
Accept if either independent CTC+3gram or greedy CTC agrees with the reference;
the latter prevents LM word omissions from creating unnecessary false flags.
The previous word check remains available using --metric words --min-match 0.75.
This is an ASR screening check, not proof that every word/timing is correct.

Only the checkpoint's preprocessor, encoder and Punjabi CTC head are loaded.
This avoids RNNT training dependencies and preserves the original Punjabi
language mask. The checkpoint weights are loaded strictly, without retraining.
"""

from __future__ import annotations

import argparse
import gc
import hashlib
import json
import math
import mmap
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
import time
import unicodedata
import urllib.request
from functools import lru_cache


MODEL_URL = 'https://huggingface.co/sukhpalsingh/baniguru_v1/resolve/main/baniguru_offline_v1.nemo?download=true'
LM_URL = 'https://huggingface.co/datasets/sukhpalsingh/speech_data_recordings/resolve/main/gurbani_3gram.bin?download=true'
MODEL_SHA256 = '0214688920a5a92854f76dd8e7116e0e7f64db4c2a715d03f0c6a18b900a11ef'
LM_SHA256 = '91d2a25db0cc5d8c2b292bd7b45eed241df5673f9b68331ed004f96a618e25c6'
SAMPLE_RATE = 16000


def note(message):
    print(message, file=sys.stderr, flush=True)


def sha256(path):
    h = hashlib.sha256()
    with path.open('rb') as f:
        for block in iter(lambda: f.read(8 * 1024 * 1024), b''):
            h.update(block)
    return h.hexdigest()


def get_asset(supplied, cache, filename, url, expected_hash):
    if supplied is not None:
        path = supplied.expanduser().resolve()
        if not path.is_file():
            raise ValueError(f'Model file does not exist: {path}')
        return path
    cache.mkdir(parents=True, exist_ok=True)
    target = cache / filename
    if target.is_file():
        if sha256(target) != expected_hash:
            raise ValueError(f'Cached file failed checksum: {target}; remove it and retry.')
        return target
    note(f'Downloading {filename} ...')
    fd, temporary = tempfile.mkstemp(prefix=filename + '.', suffix='.part', dir=cache)
    total, previous = 0, time.monotonic()
    try:
        with os.fdopen(fd, 'wb') as out, urllib.request.urlopen(url, timeout=120) as response:
            while True:
                chunk = response.read(4 * 1024 * 1024)
                if not chunk:
                    break
                out.write(chunk)
                total += len(chunk)
                if time.monotonic() - previous >= 5:
                    note(f'  {filename}: {total / 1048576:.1f} MiB')
                    previous = time.monotonic()
        temporary = Path(temporary)
        if sha256(temporary) != expected_hash:
            raise ValueError(f'Download checksum failed: {filename}')
        os.replace(temporary, target)
    finally:
        Path(temporary).unlink(missing_ok=True)
    return target


def lm_unigrams(path):
    """Read the stored vocabulary of the linked KenLM binary, not JSON text.

    PyCTCDecode cannot enumerate a binary's unigrams itself. Without this list
    it penalizes every partial word, which can cause unwanted word splitting.
    KenLM's default binary includes a NUL-separated UTF-8 vocabulary at EOF.
    Validate each recovered word against KenLM rather than trusting a marker.
    """
    import kenlm

    with path.open('rb') as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as data:
        marker = b'<unk>\0<s>\0</s>\0'
        position = data.rfind(marker)
        if position < 0:
            raise ValueError('LM binary has no stored vocabulary. Use the linked gurbani_3gram.bin.')
        payload = data[position + len(marker):].decode('utf-8')
    model = kenlm.Model(str(path))
    if model.order != 3:
        raise ValueError(f'Expected a 3-gram LM; supplied LM has order {model.order}.')
    vocabulary = sorted({w for w in payload.split('\0')
                         if w and not any(c.isspace() for c in w) and w in model})
    if not vocabulary:
        raise ValueError('Could not read the LM word vocabulary.')
    return vocabulary


HEADING_ORDINALS = {
    1: 'ਪਹਿਲਾ', 2: 'ਦੂਜਾ', 3: 'ਤੀਜਾ', 4: 'ਚੌਥਾ', 5: 'ਪੰਜਵਾ',
    6: 'ਛੇਵਾ', 7: 'ਸੱਤਵਾ', 8: 'ਅੱਠਵਾ', 9: 'ਨੌਵਾ', 10: 'ਦਸਵਾ',
    11: 'ਗਿਆਰਵਾ', 12: 'ਬਾਰਵਾ', 13: 'ਤੇਰਵਾ', 14: 'ਚੌਦਵਾ',
    15: 'ਪੰਦਰਵਾ', 16: 'ਸੋਲਵਾ', 17: 'ਸਤਾਰਵਾ',
}
HEADING_ORDINAL_ALIASES = {}
for _number, _ordinal in HEADING_ORDINALS.items():
    _variants = {_ordinal, _ordinal.replace('੍ਹ', '')}
    if _number == 1:
        _variants.add('ਪਹਲਾ')
    elif _number == 2:
        _variants.add('ਦੂਸਰਾ')
    elif _number == 3:
        _variants.add('ਤੀਸਰਾ')
    elif _number in (7, 8):
        _variants.add(_ordinal.replace('ੱ', ''))
    for _variant in _variants:
        HEADING_ORDINAL_ALIASES[_variant] = _ordinal
        if _number >= 5:
            HEADING_ORDINAL_ALIASES[_variant + 'ਂ'] = _ordinal

HEADING_NUMBER_PATTERN = re.compile(
    r'(?<![\w\u0a00-\u0a7f])(?P<label>ਮਹਲਾ|ਮਃ|ਘਰੁ|ਘਰ)\s*[:.,-]?\s*'
    r'(?P<value>[੦-੯0-9]+|'
    + '|'.join(re.escape(v) for v in sorted(HEADING_ORDINAL_ALIASES, key=len, reverse=True))
    + r')(?![\w\u0a00-\u0a7f])'
)
GURMUKHI_DIGITS = str.maketrans('੦੧੨੩੪੫੬੭੮੯', '0123456789')


def spoken_heading_text(text):
    """Expand only context-labelled heading numbers, before dropping counters.

    Apply identically to reference and ASR, independent of their contents.
    This never copies words from the reference into an ASR hypothesis.
    """
    def replace(match):
        value = match['value']
        if value.isdecimal():
            ordinal = HEADING_ORDINALS.get(int(value.translate(GURMUKHI_DIGITS)))
        else:
            ordinal = HEADING_ORDINAL_ALIASES.get(value)
        if ordinal is None:
            return match[0]
        label = 'ਮਹਲਾ' if match['label'] in ('ਮਹਲਾ', 'ਮਃ') else 'ਘਰ'
        return f'{label} {ordinal}'

    return HEADING_NUMBER_PATTERN.sub(replace, text)


def words(text):
    text = spoken_heading_text(text)
    text = text.replace('ੴ', ' ਇਕ ਓਅੰਕਾਰ ')
    # Equivalent old-style Unicode vowel-carrier spellings.
    for old, new in [('ੳੁ', 'ਉ'), ('ੳੂ', 'ਊ'), ('ੲਿ', 'ਇ'), ('ੲੀ', 'ਈ'),
                     ('ੲੇ', 'ਏ'), ('ਅਾ', 'ਆ'), ('ਅੈ', 'ਐ'), ('ਅੌ', 'ਔ')]:
        text = text.replace(old, new)
    text = unicodedata.normalize('NFC', text.lower())
    text = ''.join(c if unicodedata.category(c)[0] in 'LMN' else ' ' for c in text)
    # Remove verse counters, but keep the numeral within ਇਕ ਓਅੰਕਾਰ expansion.
    result = [w.rstrip('ੁਿ') or w for w in text.split() if not w.isnumeric()]
    text = ' '.join(result)
    text = re.sub(r'(?<!\S)(?:ਏਕ|ਇੱਕ|ਇਕ)\s*ਓ(?:ਅੰ|ੰ|ਂ)ਕਾਰ(?!\S)',
                  'ਇਕ ਓਅੰਕਾਰ', text)
    return text.split()


@lru_cache(maxsize=50000)
def similarity(a, b):
    """Normalized Levenshtein similarity; short words require an exact match."""
    if a == b:
        return 1.0
    if min(len(a), len(b)) <= 2:
        return 0.0
    previous = list(range(len(b) + 1))
    for i, ca in enumerate(a, 1):
        row = [i]
        for j, cb in enumerate(b, 1):
            row.append(min(row[-1] + 1, previous[j] + 1,
                           previous[j - 1] + (ca != cb)))
        previous = row
    return 1.0 - previous[-1] / max(len(a), len(b))


def compare(reference, prediction, min_match=0.75, word_similarity=0.72):
    """Ordered fuzzy alignment. A word occurrence cannot be reused.

    Maximize symmetric coverage, with quality as a tie-breaker. The function
    returns only aggregate values; it never produces a section report.
    """
    ref, hyp = words(reference), words(prediction)
    n, m = len(ref), len(hyp)
    if not n or not m:
        return False, 0.0
    # Cell = (reference words matched, hypothesis words matched, similarity sum).
    dp = [[(0, 0, 0.0) for _ in range(m + 1)] for _ in range(n + 1)]

    def rank(cell):
        r, h, quality = cell
        return min(r / n, h / m), r / n + h / m, quality

    for i in range(1, n + 1):
        for j in range(1, m + 1):
            candidates = [dp[i - 1][j], dp[i][j - 1]]
            for nr, nh in [(1, 1), (1, 2), (2, 1)]:
                if nr > i or nh > j:
                    continue
                a, b = ''.join(ref[i - nr:i]), ''.join(hyp[j - nh:j])
                threshold = word_similarity if nr == nh else max(0.88, word_similarity)
                score = similarity(a, b)
                if score >= threshold and (nr == nh or min(len(a), len(b)) >= 4):
                    r, h, q = dp[i - nr][j - nh]
                    candidates.append((r + nr, h + nh, q + score))
            dp[i][j] = max(candidates, key=rank)
    r, h, _ = dp[n][m]
    coverage = min(r / n, h / m)
    required = 1.0 if min(n, m) <= 3 else min_match
    return coverage + 1e-9 >= required, coverage


def character_error_rate(reference, prediction):
    """Return (CER percent, edits, reference length) after Gurbani normalization.

    Divide by reference length, not max(reference length, hypothesis length).
    This preserves the standard CER insertion penalty, including CER > 100%.
    """
    ref, hyp = ''.join(words(reference)), ''.join(words(prediction))
    if not ref:
        raise ValueError('Cannot calculate CER for an empty normalized reference.')
    previous = list(range(len(hyp) + 1))
    for i, a in enumerate(ref, 1):
        row = [i]
        for j, b in enumerate(hyp, 1):
            row.append(min(row[-1] + 1, previous[j] + 1,
                           previous[j - 1] + (a != b)))
        previous = row
    edits = previous[-1]
    return edits * 100.0 / len(ref), edits, len(ref)


def evaluate_prediction(reference, prediction, args):
    cer, edits, ref_length = character_error_rate(reference, prediction)
    result = {'cer_percent': cer, 'character_edits': edits,
              'reference_characters': ref_length}
    if args.metric == 'words':
        passed, score = compare(reference, prediction, args.min_match, args.word_similarity)
        required = 1.0 if min(len(words(reference)), len(words(prediction))) <= 3 else args.min_match
        result.update(passed=passed, word_match_percent=score * 100,
                      word_required_percent=required * 100)
    else:
        # Empty ASR must never pass, even with a very permissive CER threshold.
        result['passed'] = bool(words(prediction)) and cer <= args.max_cer + 1e-9
    return result


class Recognizer:
    def __init__(self, checkpoint, lm_path, args):
        # Imports are deferred so --help and matching unit tests need no NeMo.
        import numpy as np
        import torch
        import torch.nn.functional as functional
        from hydra.utils import instantiate
        from omegaconf import OmegaConf
        from pyctcdecode import build_ctcdecoder
        from nemo.utils import logging as nemo_logging

        nemo_logging.set_verbosity(nemo_logging.ERROR)
        self.np, self.torch, self.functional = np, torch, functional
        self.args = args
        self.device = ('cuda' if torch.cuda.is_available() else 'cpu') if args.device == 'auto' else args.device
        if self.device.startswith('cuda') and not torch.cuda.is_available():
            raise ValueError('CUDA requested but not available. Use --device cpu.')
        torch.set_num_threads(args.cpu_threads)
        note(f'Loading Punjabi CTC encoder on {self.device} ...')
        with tarfile.open(checkpoint, 'r:*') as archive:
            names = archive.getnames()
            config_name = next(n for n in names if Path(n).name == 'model_config.yaml')
            weights_name = next(n for n in names if Path(n).name == 'model_weights.ckpt')
            cfg = OmegaConf.create(archive.extractfile(config_name).read().decode('utf-8'))
            # The linked checkpoint is a plain tensor state dict; no pickle code
            # or archive extraction into arbitrary paths is needed.
            state = torch.load(archive.extractfile(weights_name), map_location='cpu', weights_only=True)
        if 'state_dict' in state:
            state = state['state_dict']
        if int(cfg.sample_rate) != SAMPLE_RATE:
            raise ValueError('This checker expects the linked 16 kHz model.')
        try:
            self.preprocessor = instantiate(cfg.preprocessor)
            self.encoder = instantiate(cfg.encoder)
        except Exception as e:
            cause = e
            while cause.__cause__ is not None:
                cause = cause.__cause__
            raise RuntimeError(f'Could not load NeMo components: {cause}') from e
        for prefix, module in [('preprocessor.', self.preprocessor), ('encoder.', self.encoder)]:
            part = {k[len(prefix):]: v for k, v in state.items() if k.startswith(prefix)}
            if not part:
                raise ValueError(f'Checkpoint is missing {prefix} weights.')
            module.load_state_dict(part, strict=True)
            module.eval().to(self.device)
        self.preprocessor.featurizer.dither = 0.0

        vocabulary = list(cfg.aux_ctc.decoder.vocabulary)
        language_keys = list(cfg.joint.get('language_keys', []))
        if cfg.tokenizer.type == 'multilingual':
            if 'pa' not in language_keys or len(vocabulary) % len(language_keys):
                raise ValueError('Cannot determine the Punjabi token range.')
            block = len(vocabulary) // len(language_keys)
            start = language_keys.index('pa') * block
            ids = list(range(start, start + block))
        else:
            ids = list(range(len(vocabulary)))
        labels = [vocabulary[i] for i in ids] + ['']
        if not any('\u0a00' <= c <= '\u0a7f' for label in labels for c in label):
            raise ValueError('Selected tokenizer has no Gurmukhi tokens.')
        # AI4Bharat masks logits BEFORE softmax; selecting these exact weight
        # rows plus the global CTC blank is algebraically the same operation.
        ids.append(len(vocabulary))
        weight = state['ctc_decoder.decoder_layers.0.weight']
        bias = state['ctc_decoder.decoder_layers.0.bias']
        if weight.shape[0] != len(vocabulary) + 1:
            raise ValueError('CTC vocabulary and checkpoint head disagree.')
        self.weight = weight[ids].contiguous().to(self.device)
        self.bias = bias[ids].contiguous().to(self.device)
        self.labels = labels
        self.blank = len(labels) - 1
        del state, weight, bias
        gc.collect()
        note(f'Loading 3-gram LM; {len(labels) - 1} Punjabi tokens, beam={args.beam_size} ...')
        unigrams = lm_unigrams(lm_path)
        self.decoder = build_ctcdecoder(labels=labels, kenlm_model_path=str(lm_path),
                                       unigrams=unigrams, alpha=args.lm_alpha, beta=args.lm_beta)

    def transcribe(self, clips):
        np, torch = self.np, self.torch
        lengths = torch.tensor([len(c) for c in clips], dtype=torch.long, device=self.device)
        batch = np.zeros((len(clips), max(map(len, clips))), dtype=np.float32)
        for i, clip in enumerate(clips):
            batch[i, :len(clip)] = clip
        with torch.inference_mode():
            features, feature_lengths = self.preprocessor(
                input_signal=torch.from_numpy(batch).to(self.device), length=lengths)
            encoded, encoded_lengths = self.encoder(audio_signal=features, length=feature_lengths)
            logits = self.functional.conv1d(encoded, self.weight, self.bias).transpose(1, 2)
            log_probs = logits.float().log_softmax(-1).cpu().numpy()
            encoded_lengths = encoded_lengths.cpu().tolist()
        results = []
        for probabilities, length in zip(log_probs, encoded_lengths):
            probabilities = probabilities[:length]
            if not np.isfinite(probabilities).all():
                raise RuntimeError('Non-finite model output; cannot verify this audio.')
            lm_text = self.decoder.decode(probabilities, beam_width=self.args.beam_size)
            greedy_ids, previous = [], None
            for token in probabilities.argmax(-1).tolist():
                if token != previous and token != self.blank:
                    greedy_ids.append(token)
                previous = token
            greedy_text = ''.join(self.labels[i] for i in greedy_ids).replace('▁', ' ')
            greedy_text = greedy_text.replace('<unk>', ' ').strip()
            results.append((lm_text, greedy_text))
        return results


def find_jsons(root, filename):
    found = []
    for directory, subdirs, files in os.walk(root, followlinks=False):
        subdirs[:] = sorted(n for n in subdirs if not n.startswith('.')
                            and not (Path(directory) / n).is_symlink())
        path = Path(directory) / filename
        # Include the supplied folder too, so a single recording can be tested.
        if filename in files and not path.is_symlink():
            found.append(path)
    return sorted(found)


def read_input(path, max_seconds):
    with path.open(encoding='utf-8-sig') as f:
        data = json.load(f)
    if not isinstance(data, dict) or not isinstance(data.get('sections'), list) or not data['sections']:
        raise ValueError('JSON must contain a non-empty sections array.')
    name = data.get('audio_file')
    if not isinstance(name, str) or not name.strip():
        raise ValueError('JSON audio_file is missing.')
    candidate = Path(name).expanduser()
    audio = candidate if candidate.is_absolute() else path.parent / candidate
    # A recording folder may have been moved from another machine.
    if not audio.is_file():
        audio = path.parent / Path(name.replace('\\', '/')).name
    if not audio.is_file():
        raise ValueError(f'Audio file not found: {name}')
    sections = []
    for index, section in enumerate(data['sections'], 1):
        if not isinstance(section, dict):
            raise ValueError('A section is not an object.')
        text = section.get('transcript')
        if not isinstance(text, str) or not words(text):
            raise ValueError('A section has an empty/invalid reference transcript.')
        try:
            start, end = float(section['start_time']), float(section['end_time'])
        except (KeyError, ValueError, TypeError) as e:
            raise ValueError('A section has missing/invalid timestamps.') from e
        if not math.isfinite(start) or not math.isfinite(end) or start < 0 or end <= start:
            raise ValueError('A section has invalid timestamps (seconds expected).')
        if end - start > max_seconds:
            raise ValueError(f'A section exceeds {max_seconds:g}s; adjust --max-section-seconds if intentional.')
        section_id = section.get('section_id')
        if section_id is None or not str(section_id).strip():
            section_id = f'section-{index}'
        sections.append((start, end, text, str(section_id)))
    return audio, sections


def write_lines(path, folders):
    path.parent.mkdir(parents=True, exist_ok=True)
    fd, temp = tempfile.mkstemp(prefix=path.name + '.', dir=path.parent)
    try:
        with os.fdopen(fd, 'w', encoding='utf-8') as f:
            for folder in sorted(set(folders)):
                f.write(str(folder) + '\n')
        os.replace(temp, path)
    finally:
        Path(temp).unlink(missing_ok=True)


def write_section_mismatch(stream, record):
    """Write the requested four-line block, using the best independent ASR."""
    def one_line(value):
        return ' '.join(str(value).split())

    stream.write(
        f'{one_line(Path(record["folder"]).name)}\n'
        f'expected: {one_line(spoken_heading_text(record["expected_transcript"]))}\n'
        f'actual: {one_line(record["actual_transcript"])}\n'
        f'cer: {record["cer_percent"]:.2f}%\n\n'
    )
    stream.flush()


def check_audio(audio, sections, recognizer, args, folder_number, folder_count,
                json_path, report_mismatch):
    np = recognizer.np
    with tempfile.TemporaryDirectory(prefix='baniguru-check-', dir=args.temp_dir) as scratch:
        raw = Path(scratch) / 'audio.s16le'
        # Decode once, on disk, rather than loading long recordings in RAM or
        # repeatedly seeking MP3 frame boundaries. Original timestamps remain.
        result = subprocess.run([
            'ffmpeg', '-nostdin', '-hide_banner', '-loglevel', 'error', '-y',
            '-i', str(audio), '-map', '0:a:0', '-ac', '1', '-ar', str(SAMPLE_RATE),
            '-c:a', 'pcm_s16le', '-f', 's16le', str(raw),
        ], capture_output=True, text=True)
        if result.returncode:
            raise RuntimeError('FFmpeg failed: ' + result.stderr.strip()[:400])
        if raw.stat().st_size == 0:
            raise ValueError('Audio is empty.')
        pcm = np.memmap(raw, dtype='<i2', mode='r')
        try:
            duration = len(pcm) / SAMPLE_RATE
            if any(end > duration + 0.02 for _, end, _, _ in sections):
                raise ValueError('A section extends beyond the audio duration.')
            mismatched = False
            for offset in range(0, len(sections), args.batch_size):
                selected = sections[offset:offset + args.batch_size]
                clips = []
                for start, end, _, _ in selected:
                    a, b = round(start * SAMPLE_RATE), min(len(pcm), round(end * SAMPLE_RATE))
                    if b <= a:
                        raise ValueError('A section has no audio samples.')
                    clips.append(np.array(pcm[a:b], dtype=np.float32) / 32768.0)
                predictions = recognizer.transcribe(clips)
                if len(predictions) != len(selected):
                    raise RuntimeError('ASR returned the wrong number of predictions.')
                for local_index, ((start, end, reference, section_id),
                                  (lm_text, greedy_text)) in enumerate(zip(selected, predictions)):
                    lm_result = evaluate_prediction(reference, lm_text, args)
                    greedy_result = evaluate_prediction(reference, greedy_text, args)
                    if not lm_result['passed'] and not greedy_result['passed']:
                        mismatched = True
                        best_text, best_result = ((lm_text, lm_result)
                                                 if lm_result['cer_percent'] <= greedy_result['cer_percent']
                                                 else (greedy_text, greedy_result))
                        record = {
                            'folder': str(json_path.parent.resolve()),
                            'json_file': str(json_path.resolve()),
                            'audio_file': str(audio.resolve()),
                            'section_index': offset + local_index + 1,
                            'section_id': section_id,
                            'start_time': start,
                            'end_time': end,
                            'expected_transcript': reference,
                            'asr_with_3gram': lm_text,
                            'asr_greedy': greedy_text,
                            'actual_transcript': best_text,
                            'cer_percent': best_result['cer_percent'],
                            'metric': args.metric,
                            'lm_cer_percent': round(lm_result['cer_percent'], 2),
                            'greedy_cer_percent': round(greedy_result['cer_percent'], 2),
                            'max_cer_percent': args.max_cer if args.metric == 'cer' else '',
                            'reference_characters': lm_result['reference_characters'],
                            'lm_character_edits': lm_result['character_edits'],
                            'greedy_character_edits': greedy_result['character_edits'],
                            'reason': ('Both ASR outputs are empty.' if not words(lm_text) and not words(greedy_text)
                                       else f'Both ASR outputs exceed the maximum normalized CER of {args.max_cer:g}%.'
                                       if args.metric == 'cer'
                                       else 'Neither ASR output meets the required ordered fuzzy-word coverage.'),
                        }
                        if args.metric == 'words':
                            record.update(
                                lm_match_percent=round(lm_result['word_match_percent'], 2),
                                greedy_match_percent=round(greedy_result['word_match_percent'], 2),
                                lm_required_percent=round(lm_result['word_required_percent'], 2),
                                greedy_required_percent=round(greedy_result['word_required_percent'], 2))
                        report_mismatch(record)
                        note(f'  MISMATCH {section_id}: LM CER {lm_result["cer_percent"]:.2f}%, '
                             f'greedy CER {greedy_result["cer_percent"]:.2f}%')
                done = offset + len(selected)
                note(f'  Folders {folder_number}/{folder_count}; sections {done}/{len(sections)}')
            return mismatched
        finally:
            del pcm


def parse_args(argv=None):
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument('parent', type=Path, help='Search this folder and all descendants.')
    p.add_argument('--json-name', default='aligned_transcript.json')
    p.add_argument('--model', type=Path, help='Existing .nemo file (no download).')
    p.add_argument('--lm', type=Path, help='Existing word-level KenLM .bin (no download).')
    p.add_argument('--cache-dir', type=Path, default=Path.home() / '.cache' / 'baniguru-folder-check')
    p.add_argument('--device', default='auto', help='auto, cpu, cuda or cuda:0')
    p.add_argument('--batch-size', type=int, default=4)
    p.add_argument('--cpu-threads', type=int, default=4)
    p.add_argument('--beam-size', type=int, default=64)
    p.add_argument('--lm-alpha', type=float, default=0.35, help='LM weight; default 0.35.')
    p.add_argument('--lm-beta', type=float, default=1.0, help='Word insertion bonus; default 1.0.')
    p.add_argument('--metric', choices=['cer', 'words'], default='cer', help='Default: cer.')
    p.add_argument('--max-cer', type=float, default=20.0,
                   help='Maximum normalized CER percentage; 20 means 20%% errors allowed. Lower is stricter.')
    p.add_argument('--min-match', type=float, help='For --metric words only; default 0.75.')
    p.add_argument('--word-similarity', type=float, help='For --metric words only; default 0.72.')
    p.add_argument('--max-section-seconds', type=float, default=30.0)
    p.add_argument('--output', type=Path, help='Default: PARENT/mismatched_folders.txt')
    p.add_argument('--errors-output', type=Path, help='Default: PARENT/unchecked_folders.txt')
    p.add_argument('--sections-output', type=Path, help='Default: PARENT/mismatched_sections.txt')
    p.add_argument('--temp-dir', type=Path, help='Disk directory for temporary 16 kHz mono PCM.')
    a = p.parse_args(argv)
    a.parent = a.parent.expanduser().resolve()
    if not a.parent.is_dir():
        p.error('parent must be an existing directory')
    if Path(a.json_name).name != a.json_name or a.json_name.startswith('.'):
        p.error('--json-name must be a plain, non-hidden filename')
    for key in ['batch_size', 'cpu_threads', 'beam_size', 'max_section_seconds']:
        value = getattr(a, key)
        if not math.isfinite(value) or value <= 0:
            p.error(f'--{key.replace("_", "-")} must be positive')
    if not math.isfinite(a.max_cer) or not 0 <= a.max_cer <= 100:
        p.error('--max-cer must be a percentage in [0, 100], e.g. 20 for 20%')
    if a.metric != 'words' and (a.min_match is not None or a.word_similarity is not None):
        p.error('Use --max-cer for CER; --min-match/--word-similarity require --metric words.')
    a.min_match = 0.75 if a.min_match is None else a.min_match
    a.word_similarity = 0.72 if a.word_similarity is None else a.word_similarity
    for key in ['min_match', 'word_similarity']:
        if not 0 < getattr(a, key) <= 1:
            p.error(f'--{key.replace("_", "-")} must be in (0, 1]')
    if not math.isfinite(a.lm_alpha) or a.lm_alpha <= 0 or not math.isfinite(a.lm_beta):
        p.error('LM weights must be finite, and --lm-alpha must be positive')
    a.output = (a.output or a.parent / 'mismatched_folders.txt').expanduser().resolve()
    a.errors_output = (a.errors_output or a.parent / 'unchecked_folders.txt').expanduser().resolve()
    a.sections_output = (a.sections_output or a.parent / 'mismatched_sections.txt').expanduser().resolve()
    if len({a.output, a.errors_output, a.sections_output}) != 3:
        p.error('all three output paths must differ')
    if a.temp_dir:
        a.temp_dir = a.temp_dir.expanduser().resolve()
        a.temp_dir.mkdir(parents=True, exist_ok=True)
    return a


def main(argv=None):
    args = parse_args(argv)
    if not shutil.which('ffmpeg'):
        note('ERROR: ffmpeg is required on PATH.')
        return 2
    paths = find_jsons(args.parent, args.json_name)
    if not paths:
        note(f'ERROR: No {args.json_name} files found under {args.parent}')
        return 2
    protected = {p.resolve() for p in paths}
    protected.add(Path(__file__).resolve())
    protected.update(p.resolve() for p in (args.model, args.lm) if p)
    for p in paths:
        try:
            audio, _ = read_input(p, args.max_section_seconds)
            protected.add(audio.resolve())
        except Exception:
            pass  # The normal folder loop records input errors.
    if any(path in protected for path in [args.output, args.errors_output, args.sections_output]):
        note('ERROR: An output path would overwrite an input file.')
        return 2
    mismatched, errors = [], []
    completed = 0
    interrupted = False
    report_stream = None
    try:
        args.sections_output.parent.mkdir(parents=True, exist_ok=True)
        report_stream = args.sections_output.open('w', encoding='utf-8', newline='\n')
        report_stream.flush()
        note(f'Comparison: maximum normalized CER {args.max_cer:g}% (lower is stricter).'
             if args.metric == 'cer' else f'Comparison: ordered fuzzy word coverage {args.min_match:.0%}.')

        def report_mismatch(record):
            write_section_mismatch(report_stream, record)

        model = get_asset(args.model, args.cache_dir, 'baniguru_offline_v1.nemo', MODEL_URL, MODEL_SHA256)
        lm = get_asset(args.lm, args.cache_dir, 'gurbani_3gram.bin', LM_URL, LM_SHA256)
        recognizer = Recognizer(model, lm, args)
        for index, json_path in enumerate(paths, 1):
            folder = json_path.parent.resolve()
            note(f'[{index}/{len(paths)}] {folder}')
            try:
                audio, sections = read_input(json_path, args.max_section_seconds)
                failed = check_audio(audio, sections, recognizer, args, index, len(paths),
                                     json_path, report_mismatch)
                if failed:
                    mismatched.append(folder)
                note('  MISMATCH' if failed else '  MATCH')
            except Exception as e:
                errors.append(folder)
                note(f'  UNCHECKED: {type(e).__name__}: {e}')
            completed = index
            write_lines(args.output, mismatched)
            write_lines(args.errors_output, errors)
    except KeyboardInterrupt:
        interrupted = True
        note('Interrupted; all remaining folders will be listed as unchecked.')
    except Exception as e:
        note(f'ERROR: {type(e).__name__}: {e}')
    finally:
        if report_stream is not None:
            report_stream.close()
        errors.extend(p.parent.resolve() for p in paths[completed:])
        write_lines(args.output, mismatched)
        write_lines(args.errors_output, errors)
    note(f'Finished: {completed}/{len(paths)} folders; {len(mismatched)} mismatched; '
         f'{len(set(errors))} unchecked.')
    note(f'Mismatches: {args.output}\nUnchecked: {args.errors_output}\nSection details: {args.sections_output}')
    return 130 if interrupted else 2 if errors else 1 if mismatched else 0


if __name__ == '__main__':
    sys.exit(main())