94 lines
3.4 KiB
Python
94 lines
3.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Measure source-backed norm search on the deployed, read-only FSNB index.
|
|
|
|
Run with the same FSNB_REF_PATH/EXT_SNAPSHOT_DIR as the app. No user data is read.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import math
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT))
|
|
|
|
import fsnb_ref # noqa: E402
|
|
import norm_finder # noqa: E402
|
|
|
|
|
|
def _expected_exists(con, case: dict) -> bool:
|
|
code = case.get("code")
|
|
prefix = case.get("prefix")
|
|
if bool(code) == bool(prefix):
|
|
raise ValueError(f"Эталон должен иметь ровно code или prefix: {case['q']}")
|
|
if code:
|
|
clause, value = "code=?", code
|
|
else:
|
|
clause, value = "code LIKE ?", prefix + "%"
|
|
row = con.execute(
|
|
"SELECT 1 FROM works WHERE base=? AND base_type=? AND " + clause + " LIMIT 1",
|
|
(norm_finder.BASES[case.get("base", "2022")], case["type"], value),
|
|
).fetchone()
|
|
return row is not None
|
|
|
|
|
|
def _matches(item: dict, case: dict) -> bool:
|
|
return (item.get("base_type") == case["type"]
|
|
and (item.get("code") == case["code"] if case.get("code")
|
|
else str(item.get("code") or "").startswith(case["prefix"])))
|
|
|
|
|
|
def run(cases: list[dict]) -> dict:
|
|
con = fsnb_ref._connect()
|
|
if con is None:
|
|
raise RuntimeError("Индекс ФСНБ недоступен: укажите FSNB_REF_PATH или EXT_SNAPSHOT_DIR")
|
|
try:
|
|
for case in cases:
|
|
if not _expected_exists(con, case):
|
|
raise ValueError(f"Эталон отсутствует в базе: {case['q']}")
|
|
finally:
|
|
con.close()
|
|
times, misses = [], []
|
|
exact_total = exact_hits = natural_total = natural_hits = 0
|
|
for case in cases:
|
|
start = time.perf_counter()
|
|
response = norm_finder.search(case["q"], case.get("base", "2022"), 12)
|
|
times.append(time.perf_counter() - start)
|
|
items = response.get("items") or []
|
|
if case.get("exact"):
|
|
exact_total += 1
|
|
hit = bool(items and _matches(items[0], case))
|
|
exact_hits += hit
|
|
else:
|
|
natural_total += 1
|
|
hit = any(_matches(item, case) for item in items[:5])
|
|
natural_hits += hit
|
|
if not hit:
|
|
misses.append({"q": case["q"], "top5": [
|
|
item.get("base_type", "") + " " + item.get("code", "") for item in items[:5]]})
|
|
p95 = sorted(times)[math.ceil(0.95 * len(times)) - 1]
|
|
return {"cases": len(cases), "exact": [exact_hits, exact_total],
|
|
"top5": [natural_hits, natural_total], "p95_s": round(p95, 3),
|
|
"misses": misses}
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--enforce", action="store_true", help="fail below the acceptance thresholds")
|
|
args = parser.parse_args()
|
|
cases = json.loads((ROOT / "tests/fixtures/norm_finder_queries.json").read_text())
|
|
result = run(cases)
|
|
print(json.dumps(result, ensure_ascii=False, indent=2))
|
|
exact_hits, exact_total = result["exact"]
|
|
natural_hits, natural_total = result["top5"]
|
|
meets = (exact_hits == exact_total and natural_hits / natural_total >= 0.9
|
|
and result["p95_s"] <= 2)
|
|
return 0 if meets or not args.enforce else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|