File size: 6,174 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
"""Locate and call the canonical entity matcher.

The reported numbers depend entirely on this file, so the harness refuses to
score without it rather than silently substituting a weaker rule.

Resolution order:
  1. --matcher module:callable, if given
  2. a module named matcher_v5 on sys.path or next to this file
  3. a file passed as --matcher-path

The matcher is called as fn(entity, hypothesis_text) -> truthy. Older
signatures fn(hypothesis, entity) are detected by a probe at load time.
"""

from __future__ import annotations

import importlib
import importlib.util
import inspect
import os
import sys
from typing import Callable

CANDIDATE_NAMES = [
    "hit",
    "match_entity",
    "entity_match",
    "entity_hit",
    "is_match",
    "matches",
    "match",
    "score_entity",
]
CANDIDATE_CLASSES = ["MatcherV5", "Matcher", "EntityMatcher"]


class MatcherNotFound(RuntimeError):
    pass


def _import_path(path: str):
    name = os.path.splitext(os.path.basename(path))[0]
    spec = importlib.util.spec_from_file_location(name, path)
    if spec is None or spec.loader is None:
        raise MatcherNotFound(f"cannot import {path}")
    module = importlib.util.module_from_spec(spec)
    sys.modules[name] = module
    spec.loader.exec_module(module)
    return module


def _pick_callable(module) -> tuple[Callable, str]:
    for name in CANDIDATE_NAMES:
        fn = getattr(module, name, None)
        if callable(fn):
            return fn, name
    for cls_name in CANDIDATE_CLASSES:
        cls = getattr(module, cls_name, None)
        if cls is None:
            continue
        instance = cls()
        for name in CANDIDATE_NAMES:
            fn = getattr(instance, name, None)
            if callable(fn):
                return fn, f"{cls_name}.{name}"
    public = [n for n in dir(module) if not n.startswith("_") and callable(getattr(module, n))]
    raise MatcherNotFound(
        f"no recognised matcher entry point in {module.__name__}. "
        f"Public callables: {public}\n"
        f"Pass --matcher {module.__name__}:<name> to point at the right one."
    )


def _orient(fn: Callable, label: str) -> Callable[[str, str], bool]:
    """Work out whether the callable is fn(entity, hyp) or fn(hyp, entity)."""
    try:
        params = list(inspect.signature(fn).parameters)
    except (TypeError, ValueError):
        params = []
    named = [p.lower() for p in params[:2]]
    swapped = bool(named) and any(
        k in named[0] for k in ("hyp", "pred", "transcript", "text", "candidate")
    )

    probe_entity, probe_hyp = "Addenbrooke's Hospital", "she works at addenbrookes hospital in cambridge"
    if not swapped:
        try:
            forward = bool(fn(probe_entity, probe_hyp))
            reverse = bool(fn(probe_hyp, probe_entity))
            if reverse and not forward:
                swapped = True
        except Exception:
            pass

    if swapped:
        return lambda entity, hyp: bool(fn(hyp, entity))
    return lambda entity, hyp: bool(fn(entity, hyp))


def load_matcher(spec: str | None = None, path: str | None = None):
    """Returns (callable(entity, hypothesis) -> bool, description)."""
    if spec:
        mod_name, _, fn_name = spec.partition(":")
        module = _import_path(mod_name) if mod_name.endswith(".py") else importlib.import_module(mod_name)
        if not fn_name:
            fn, label = _pick_callable(module)
        else:
            fn, label = getattr(module, fn_name), fn_name
        return _orient(fn, label), f"{spec} ({label})"

    if path:
        module = _import_path(path)
        fn, label = _pick_callable(module)
        return _orient(fn, label), f"{path} ({label})"

    here = os.path.dirname(os.path.abspath(__file__))
    for candidate in (os.path.join(here, "matcher_v5.py"), os.path.join(os.getcwd(), "matcher_v5.py")):
        if os.path.exists(candidate):
            module = _import_path(candidate)
            fn, label = _pick_callable(module)
            return _orient(fn, label), f"{candidate} ({label})"
    try:
        module = importlib.import_module("matcher_v5")
    except ImportError:
        raise MatcherNotFound(
            "matcher_v5.py not found. It defines the match rule and therefore the "
            "reported numbers.\nDownload it from the dataset repo:\n"
            "  huggingface-cli download modulate/entity-transcription-benchmark "
            "matcher_v5.py --repo-type dataset --local-dir .\n"
            "or point at a local copy with --matcher-path /path/to/matcher_v5.py"
        )
    fn, label = _pick_callable(module)
    return _orient(fn, label), f"matcher_v5 ({label})"


def self_test(matcher_module_path: str | None = None) -> tuple[int, int]:
    """Run the matcher's own self-test if it exposes one. Returns (passed, total).

    (0, 0) means the module does not expose one -- scoring proceeds ungated.
    Never calls main(); that would parse the caller's argv.
    """
    module = None
    if matcher_module_path and os.path.exists(matcher_module_path):
        module = _import_path(matcher_module_path)
    else:
        for candidate in (
            os.path.join(os.path.dirname(os.path.abspath(__file__)), "matcher_v5.py"),
            os.path.join(os.getcwd(), "matcher_v5.py"),
        ):
            if os.path.exists(candidate):
                module = _import_path(candidate)
                break
        if module is None:
            try:
                module = importlib.import_module("matcher_v5")
            except ImportError:
                return (0, 0)

    total = len(getattr(module, "CASES", []) or [])
    for name in ("validate", "self_test", "run_self_test", "_self_test"):
        fn = getattr(module, name, None)
        if not callable(fn):
            continue
        try:
            result = fn(verbose=False)
        except TypeError:
            result = fn()
        if isinstance(result, tuple) and len(result) == 2:
            return result
        if isinstance(result, bool):
            # validate() returns True when every case passes
            return (total, total) if result else (0, total or 1)
        return (0, 0)
    return (0, 0)