"""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__}: 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)