File size: 23,914 Bytes
0041cfd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
702
703
704
705
706
707
708
709
#!/usr/bin/env python3
"""
matcher_v5.py — merged entity matcher. Replaces voicepii_benchmark's `hit` and
matcher_final's `is_hit`, fixing real bugs found in BOTH.

WHY A MERGE
-----------
On the PHI set the two matchers disagreed on 93 clips (308 vs 353 for vfast).
Auditing the disagreements showed each was wrong in a different direction:

  matcher_v4/voicepii_benchmark MISSED (too strict)
    - compound numbers: 'seventy-seven' -> 707 instead of 77
    - 'eight o two o three' -> no 'o'->0 mapping, so 80203 never matched
    - abbreviations inside longer golds

  matcher_final PASSED things it should not (too loose)
    - `gold_digits in re.sub(r'\\D','',normalize_alnum(transcript))` searches the
      ENTIRE transcript's concatenated digit stream, so digits scattered across
      unrelated clauses can satisfy a gold ID.
    - That is why PN-01 still fires: gold 555-201-4478 vs
      'five five five two o L one four four seven eight'. The stray 'l' is a
      real transcription error, but the digit-stream test skips right over it.
      PN-01 was one of the three clips manually excluded as a false positive in
      July; it is still firing.

THE FIX: CONTIGUOUS-TOKEN MATCHING
----------------------------------
The transcript is compiled into an ordered token stream where each token is
either a letter-chunk, a digit-chunk (from a spoken number run), or a word. A
gold value matches only if its canonical form equals the concatenation of
ADJACENT tokens. Nothing may be skipped.

  'l nine nine zero two three four one'  -> ['l']['9902341']  -> L9902341  HIT
  'five five five two o l one four four seven eight'
        -> ['55520']['l']['14478']  -> 5552014478 requires skipping 'l'  MISS

This bounds the search structurally instead of by a heuristic window, so it
fixes the false positive without hand-tuning a threshold.

AMBIGUOUS NUMBER RUNS
---------------------
'twenty three nine four eight five' can be read as 23-9-4-8-5 (239485) or
20-3-9-4-8-5 (2039485). Text alone cannot resolve it; only the audio can. Both
readings are generated and either may match. This is deliberately permissive on
a genuinely ambiguous case, and it is flagged per-clip by which_path() so you
can audit how often it fires.

  python3 matcher_v5.py --selftest
  python3 matcher_v5.py --in entity_hits.csv --by-category
  python3 matcher_v5.py --compare voicepii_benchmark,matcher_final --in ...
"""

import argparse
import csv
import re
import sys
import unicodedata

# ============================================================ #
#                        NORMALIZATION                         #
# ============================================================ #


def canon(s):
    # Fold diacritics to ASCII first. Stripping them outright turns
    # 'Chisinau' into 'chinu', which can never match a correct transcript.
    s = unicodedata.normalize("NFKD", str(s))
    s = "".join(c for c in s if not unicodedata.combining(c))
    s = s.replace("\u0142", "l").replace("\u0141", "L")
    s = s.replace("\u00f8", "o").replace("\u00e6", "ae").replace("\u00df", "ss")
    return re.sub(r"[^a-z0-9]", "", s.lower())


UNITS = {
    "zero": 0,
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4,
    "five": 5,
    "six": 6,
    "seven": 7,
    "eight": 8,
    "nine": 9,
}
TEENS = {
    "ten": 10,
    "eleven": 11,
    "twelve": 12,
    "thirteen": 13,
    "fourteen": 14,
    "fifteen": 15,
    "sixteen": 16,
    "seventeen": 17,
    "eighteen": 18,
    "nineteen": 19,
}
TENS = {
    "twenty": 20,
    "thirty": 30,
    "forty": 40,
    "fourty": 40,
    "fifty": 50,
    "sixty": 60,
    "seventy": 70,
    "eighty": 80,
    "ninety": 90,
}
ZEROISH = {"o", "oh", "nought"}
SCALES = {"hundred", "thousand", "million"}
GLUE = {"and", "point", "dash", "hyphen"}

ORDINAL_TO_CARD = {
    "first": "one",
    "second": "two",
    "third": "three",
    "fourth": "four",
    "fifth": "five",
    "sixth": "six",
    "seventh": "seven",
    "eighth": "eight",
    "ninth": "nine",
    "tenth": "ten",
    "eleventh": "eleven",
    "twelfth": "twelve",
    "thirteenth": "thirteen",
    "fourteenth": "fourteen",
    "fifteenth": "fifteen",
    "sixteenth": "sixteen",
    "seventeenth": "seventeen",
    "eighteenth": "eighteen",
    "nineteenth": "nineteen",
    "twentieth": "twenty",
    "thirtieth": "thirty",
    "fortieth": "forty",
    "fiftieth": "fifty",
    "sixtieth": "sixty",
    "seventieth": "seventy",
    "eightieth": "eighty",
    "ninetieth": "ninety",
}

SYMWORDS = {
    "dot": ".",
    "period": ".",
    "at": "@",
    "underscore": "_",
    "slash": "/",
    "colon": ":",
    "plus": "+",
}
# Spoken separators that vanish under canon() in the gold value.
SEPWORDS = {"dash", "hyphen", "space"}

MONTHS = {
    "january": 1,
    "february": 2,
    "march": 3,
    "april": 4,
    "may": 5,
    "june": 6,
    "july": 7,
    "august": 8,
    "september": 9,
    "october": 10,
    "november": 11,
    "december": 12,
}


def is_numword(w):
    return w in UNITS or w in TEENS or w in TENS or w in ZEROISH or w in SCALES


def tokenize(text):
    """Split into lowercase words, expanding hyphenated compounds."""
    raw = re.findall(r"[a-z0-9]+(?:['’][a-z]+)?|[0-9]+", str(text).lower())
    out = []
    for w in re.split(r"[\s\-–—/]+", str(text).lower()):
        w = re.sub(r"[^a-z0-9'’.@_:]+", "", w)
        if w:
            out.append(w)
    return out or raw


# ============================================================ #
#                     SPOKEN NUMBER RUNS                       #
# ============================================================ #


def _run_readings(run):
    """Return candidate digit-strings for one run of number words.

    Two readings are produced where they differ:
      merged   : tens + following unit combine  ('twenty' 'three' -> 23)
      unmerged : every token stands alone       ('twenty' 'three' -> 20,3)
    Scale words and glue are dropped; 'o'/'oh' become 0.
    """
    toks = [t for t in run if t not in SCALES and t not in GLUE]
    if not toks:
        return set()

    def emit(merge):
        parts = []
        i = 0
        while i < len(toks):
            w = toks[i]
            if w in ZEROISH:
                parts.append("0")
                i += 1
            elif w in TENS:
                if (
                    merge
                    and i + 1 < len(toks)
                    and toks[i + 1] in UNITS
                    and toks[i + 1] != "zero"
                ):
                    parts.append(str(TENS[w] + UNITS[toks[i + 1]]))
                    i += 2
                else:
                    parts.append(str(TENS[w]))
                    i += 1
            elif w in TEENS:
                parts.append(str(TEENS[w]))
                i += 1
            elif w in UNITS:
                parts.append(str(UNITS[w]))
                i += 1
            elif w.isdigit():
                parts.append(w)
                i += 1
            else:
                i += 1
        return "".join(parts)

    return {r for r in (emit(True), emit(False)) if r}


def compile_tokens(text):
    """Compile a transcript into an ordered list of token-alternative sets.

    Each element is a set of strings that token could contribute. Words map to
    themselves (canonicalized); number runs map to their digit readings; symbol
    words map to their symbol. Adjacent elements may be concatenated when
    testing a gold value -- nothing may be skipped.
    """
    words = tokenize(text)
    # normalize ordinals so '15th'/'fifteenth' behave like 'fifteen'
    words = [ORDINAL_TO_CARD.get(w, w) for w in words]
    words = [re.sub(r"^(\d+)(st|nd|rd|th)$", r"\1", w) for w in words]

    toks = []
    i = 0
    n = len(words)
    while i < n:
        w = words[i]
        if is_numword(w) or w.isdigit():
            j = i
            run = []
            real = 0
            while j < n and (
                is_numword(words[j]) or words[j].isdigit() or words[j] in GLUE
            ):
                if words[j] not in GLUE:
                    run.append(words[j])
                    if words[j] not in ZEROISH:
                        real += 1
                else:
                    run.append(words[j])
                j += 1
            while run and run[-1] in GLUE:
                run.pop()
                j -= 1
            # a lone 'o'/'oh' with no numeric neighbour is the letter O
            if real == 0:
                toks.append({canon(w)})
                i += 1
                continue
            readings = _run_readings(run)
            if readings:
                toks.append(readings)
            i = j
        elif w in SEPWORDS:
            # a spoken separator canon()s away in the gold, so allow skipping
            toks.append({"", canon(w)})
            i += 1
        elif w in SYMWORDS:
            toks.append({SYMWORDS[w], canon(w)})
            i += 1
        else:
            c = canon(w)
            if c:
                toks.append({c})
            i += 1
    return toks


def contiguous_match(gold_canon, toks, max_span=24):
    """True if gold equals the concatenation of some ADJACENT token window."""
    if not gold_canon:
        return False
    n = len(toks)
    for start in range(n):
        frontier = {""}
        for k in range(start, min(n, start + max_span)):
            nxt = set()
            for pre in frontier:
                for alt in toks[k]:
                    cand = pre + canon(alt)
                    if cand == gold_canon:
                        return True
                    if gold_canon.startswith(cand):
                        nxt.add(cand)
            if not nxt:
                break
            frontier = nxt
    return False


# ============================================================ #
#                     ABBREVIATION / ALIASES                   #
# ============================================================ #

ALIAS = [
    ("street", "st"),
    ("avenue", "ave"),
    ("road", "rd"),
    ("boulevard", "blvd"),
    ("drive", "dr"),
    ("lane", "ln"),
    ("court", "ct"),
    ("apartment", "apt"),
    ("suite", "ste"),
    ("doctor", "dr"),
    ("mister", "mr"),
    ("missus", "mrs"),
    ("saint", "st"),
    ("mount", "mt"),
    ("fort", "ft"),
    ("junior", "jr"),
    ("senior", "sr"),
    ("post office box", "po box"),
    ("and", "&"),
    ("medical record number", "mrn"),
    ("social security number", "ssn"),
    ("date of birth", "dob"),
    ("percent", "%"),
    ("dollars", "$"),
]


def alias_variants(gold):
    """Expand a gold value into equivalent surface forms."""
    out = {canon(gold)}
    g = str(gold).lower()
    for long, short in ALIAS:
        if long in g:
            out.add(canon(g.replace(long, short)))
        if short in g:
            out.add(canon(g.replace(short, long)))
    return {v for v in out if v}


# ============================================================ #
#                          MASTER TEST                         #
# ============================================================ #


def hit(gold, transcript):
    g = str(gold).strip()
    t = str(transcript).strip()
    if not g or not t:
        return False

    gc = canon(g)
    tc = canon(t)
    if gc and gc in tc:  # plain surface match
        return True

    for v in alias_variants(g):  # abbreviation equivalence
        if v and v in tc:
            return True

    toks = compile_tokens(t)
    if contiguous_match(gc, toks):  # spoken-form match
        return True
    for v in alias_variants(g):
        if v != gc and contiguous_match(v, toks):
            return True

    if date_hit(g, t):
        return True
    return False


_DATE_GOLD = re.compile(r"^(\d{1,2})[/\-.](\d{1,2})[/\-.](\d{2,4})$")


def spoken_years(words):
    """4-digit years from spoken forms: 'nineteen eighty five', 'two thousand twelve'."""
    ys = set()
    for i, w in enumerate(words):
        if w.isdigit() and len(w) == 4:
            ys.add(int(w))
        # 'nineteen/twenty' + tens[+unit]
        if w in TEENS and 10 <= TEENS[w] <= 20:
            head = TEENS[w]
            j, tail = i + 1, None
            if j < len(words) and words[j] in TENS:
                tail = TENS[words[j]]
                if j + 1 < len(words) and words[j + 1] in UNITS:
                    tail += UNITS[words[j + 1]]
            elif j < len(words) and words[j] in TEENS:
                tail = TEENS[words[j]]
            if tail is not None and tail < 100:
                ys.add(head * 100 + tail)
        if w in TENS and TENS[w] == 20:
            j = i + 1
            if j < len(words) and words[j] in TENS:
                t = TENS[words[j]]
                if j + 1 < len(words) and words[j + 1] in UNITS:
                    t += UNITS[words[j + 1]]
                ys.add(2000 + t)
        # 'two thousand [and] twelve'
        if w in UNITS and i + 1 < len(words) and words[i + 1] == "thousand":
            base = UNITS[w] * 1000
            j = i + 2
            if j < len(words) and words[j] == "and":
                j += 1
            rest = 0
            if j < len(words) and words[j] in TEENS:
                rest = TEENS[words[j]]
            elif j < len(words) and words[j] in TENS:
                rest = TENS[words[j]]
                if j + 1 < len(words) and words[j + 1] in UNITS:
                    rest += UNITS[words[j + 1]]
            elif j < len(words) and words[j] in UNITS:
                rest = UNITS[words[j]]
            ys.add(base + rest)
    return ys


def spoken_days(words):
    """Day-of-month values from ordinals or plain numbers."""
    ds = set()
    for i, w in enumerate(words):
        if w.isdigit() and 1 <= int(w) <= 31:
            ds.add(int(w))
        if w in UNITS:
            ds.add(UNITS[w])
        if w in TEENS:
            ds.add(TEENS[w])
        if w in TENS:
            ds.add(TENS[w])
            if i + 1 < len(words) and words[i + 1] in UNITS:
                ds.add(TENS[w] + UNITS[words[i + 1]])
    return ds


def date_hit(gold, transcript):
    """Numeric date gold vs spoken month-name form."""
    m = _DATE_GOLD.match(str(gold).strip())
    if not m:
        return False
    mm, dd, yy = int(m.group(1)), int(m.group(2)), int(m.group(3))
    if yy < 100:
        yy += 1900 if yy > 30 else 2000
    words = [ORDINAL_TO_CARD.get(w, w) for w in tokenize(transcript)]
    text = " ".join(words)
    month_ok = (
        any(MONTHS.get(w) == mm for w in words)
        or re.search(rf"\b0?{mm}\b", text) is not None
    )
    day_ok = dd in spoken_days(words)
    year_ok = yy in spoken_years(words) or str(yy) in text
    return bool(month_ok and day_ok and year_ok)


def which_path(gold, transcript):
    g, t = str(gold), str(transcript)
    gc = canon(g)
    if gc and gc in canon(t):
        return "exact"
    for v in alias_variants(g):
        if v and v in canon(t):
            return "alias"
    toks = compile_tokens(t)
    if contiguous_match(gc, toks):
        return "spoken"
    for v in alias_variants(g):
        if v != gc and contiguous_match(v, toks):
            return "spoken+alias"
    if date_hit(g, t):
        return "date"
    return "miss"


# ============================================================ #
#                        VALIDATION SET                        #
# ============================================================ #
# Positives from both prior suites, plus every disagreement audited by hand.

CASES = [
    # ---- plain ----
    ("Michael Thompson", "i spoke with michael thompson yesterday", True),
    ("NVIDIA", "the nvidia earnings call is tomorrow", True),
    ("Julian O'Brien", "this is julian o'brien calling about a bill", True),
    # ---- compound numbers (matcher_v4 MISSED these) ----
    ("77 Harbor View Drive", "i still live at seventy-seven harbor view drive", True),
    ("356 Maple Terrace", "my new address is three fifty-six maple terrace", True),
    ("94 Fairview Road", "delivery should go to ninety-four fairview road", True),
    ("27609", "the zip code is twenty-seven six-oh-nine", True),
    ("80203", "the zip code should be eight o two o three", True),
    ("712", "my credit score is showing a seven hundred and twelve", True),
    ("648", "my credit score is six hundred and forty-eight", True),
    ("1274", "i'd like to update my pin to twelve seventy-four", True),
    ("6690", "let me give you the pin it's sixty-six ninety", True),
    ("482", "my security code is four eighty two", True),
    ("739", "my security code is seven thirty-nine", True),
    ("20-30-45", "my sort code is twenty thirty forty-five", True),
    ("10-88-23", "the sort code on file is ten eighty-eight twenty-three", True),
    ("11/25", "the expiration date is eleven twenty-five", True),
    ("06/26", "i'd like to update my expiration date to oh six twenty-six", True),
    (
        "$4,281.53",
        "the balance is four thousand two hundred and eighty-one fifty three",
        True,
    ),
    (
        "987654321",
        "my tax file number is nine eight seven six five four three two one",
        True,
    ),
    (
        "123 456 782",
        "my tax file number is one hundred and twenty-three four five six seven eight two",
        True,
    ),
    ("527 748 190", "it's five twenty-seven seven four eight one nine oh", True),
    ("9081726", "the license number is nine o eight one seven two six", True),
    # ---- alphanumeric IDs ----
    ("L9902341", "my national id number is l nine nine zero two three four one", True),
    ("MRN-88231", "the record is m r n dash eight eight two three one", True),
    ("M2233445", "update my license to m two two three three four four five", True),
    (
        "192.168.1.1",
        "the gateway is one nine two dot one six eight dot one dot one",
        True,
    ),
    # ---- email / address / abbreviation ----
    (
        "michael.thompson82@gmail.com",
        "send it to michael dot thompson eighty two at gmail dot com",
        True,
    ),
    ("sarah.alvarez@yahoo.com", "my email is sarah dot alvarez yahoo dot com", True),
    (
        "PO Box 118, Austin, TX 78704",
        "my mailing address is p o box one eighteen austin t x seven eight seven o four",
        True,
    ),
    ("Dr.", "please make sure my title uh doctor is on the paperwork", True),
    ("Jr.", "could you add junior after my name on the account", True),
    ("482 Willowbrook Street", "mail it to 482 willowbrook st", True),
    # ---- dates ----
    ("03/14/1985", "her date of birth is march fourteenth nineteen eighty five", True),
    ("12/25/2012", "it was december twenty-fifth two thousand twelve", True),
    ("03/14/1985", "her date of birth is march fourteenth nineteen eighty six", False),
    # ---- FALSE POSITIVES matcher_final accepted; must be MISSES ----
    # PN-01: stray 'l' inside the digit span is a real error.
    (
        "555-201-4478",
        "you can reach me at five five five two o l one four four seven eight",
        False,
    ),
    # digits scattered across unrelated clauses must not satisfy a gold ID
    ("4471", "i have four cats and four hundred and seventy one dollars", False),
    ("617-555-0142", "call six one seven five five five zero one four three", False),
    ("A7X-42B", "policy a seven x dash four two d", False),
    # ---- hard negatives, both suites ----
    ("Osei", "my maiden name is osay that's how i spell it", False),
    ("Fischer", "doctor fisher signed the chart", False),
    ("Rowe", "mister roe called back", False),
    ("Devon Chen", "devin chen arrived early", False),
    ("Groq", "we tested grok on the same workload", False),
    ("tubal ligation", "she had a two ball ligation in twenty ten", False),
    ("O negative", "the patient is o positive", False),
    (
        "sarah.jones@yahoo.com",
        "send it to michael dot thompson at gmail dot com",
        False,
    ),
    ("482 Willowbrook Lane", "mail it to five eight two willowbrook lane", False),
]


def validate(verbose=True):
    fails = []
    for gold, hyp, expect in CASES:
        got = hit(gold, hyp)
        if got != expect:
            fails.append((gold, hyp, expect, got, which_path(gold, hyp)))
    if verbose:
        print(f"matcher_v5 self-test: {len(CASES)-len(fails)}/{len(CASES)} pass")
        for gold, hyp, exp, got, path in fails:
            print(f"  FAIL gold={gold!r} expected={exp} got={got} via={path}")
            print(f"       hyp={hyp!r}")
    return not fails


# ============================================================ #
#                            SCORER                            #
# ============================================================ #


def score(path, by_category=False, dump=None):
    rows = list(csv.DictReader(open(path, newline="", encoding="utf-8")))
    if not rows:
        print("no rows")
        return
    systems = [c[:-5] for c in rows[0] if c.endswith("_text")]
    n = len(rows)
    tot = {s: 0 for s in systems}
    cats = {}
    out = []
    for r in rows:
        g = r.get("pii_value", "")
        cat = r.get("category", "") or "(none)"
        b = cats.setdefault(cat, {s: 0 for s in systems})
        b["_n"] = b.get("_n", 0) + 1
        rec = {"script_id": r.get("script_id", ""), "category": cat, "pii_value": g}
        for s in systems:
            h = hit(g, r.get(f"{s}_text", ""))
            tot[s] += h
            b[s] += h
            rec[s] = int(h)
            rec[f"{s}_path"] = which_path(g, r.get(f"{s}_text", ""))
            rec[f"{s}_text"] = r.get(f"{s}_text", "")
        out.append(rec)

    print(f"\n=== entity transcription accuracy — {n} clips — {path} ===")
    for s in systems:
        print(f"  {s:<12} {tot[s]:>5}/{n} = {tot[s]/n:6.1%}")
    if by_category:
        print(f"\n{'category':<28}{'n':>5}" + "".join(f"{s:>16}" for s in systems))
        for c in sorted(cats):
            b = cats[c]
            cn = b["_n"]
            line = f"{c[:27]:<28}{cn:>5}"
            for s in systems:
                line += f"{b[s]}/{cn} ({b[s]/cn:.0%})".rjust(16)
            print(line)
    if dump:
        with open(dump, "w", newline="", encoding="utf-8") as f:
            w = csv.DictWriter(f, fieldnames=list(out[0].keys()))
            w.writeheader()
            w.writerows(out)
        print(f"\nwrote {dump}")


def compare(path, mods):
    """Score the same file under several matcher modules and diff them."""
    import importlib

    sys.path.insert(0, ".")
    fns = {"v5": hit}
    for m in mods:
        mod = importlib.import_module(m)
        f = getattr(mod, "hit", None) or getattr(mod, "is_hit", None)
        if f:
            fns[m] = f
    rows = list(csv.DictReader(open(path, newline="", encoding="utf-8")))
    systems = [c[:-5] for c in rows[0] if c.endswith("_text")]
    print(f"\n{'matcher':<28}" + "".join(f"{s:>16}" for s in systems))
    for name, f in fns.items():
        line = f"{name[:27]:<28}"
        for s in systems:
            k = sum(bool(f(r["pii_value"], r.get(f"{s}_text", ""))) for r in rows)
            line += f"{k}/{len(rows)} ({k/len(rows):.1%})".rjust(16)
        print(line)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--in", dest="inp")
    ap.add_argument("--selftest", action="store_true")
    ap.add_argument("--by-category", action="store_true")
    ap.add_argument("--dump", default=None)
    ap.add_argument(
        "--compare",
        default=None,
        help="comma list of other matcher modules to diff against",
    )
    a = ap.parse_args()

    if a.selftest:
        sys.exit(0 if validate() else 1)
    if not validate():
        sys.exit("SELF-TEST FAILED — refusing to score")
    if not a.inp:
        sys.exit("--in required")
    if a.compare:
        compare(a.inp, [m.strip() for m in a.compare.split(",")])
    score(a.inp, a.by_category, a.dump)


if __name__ == "__main__":
    main()