perf(search): кэш полной базы ГЭСН (181K) по mtime вместо re-parse на запрос
_search_gesn_extra на КАЖДЫЙ запрос заново json.loads-ил все gesn_*.json (181K норм) — секунды блокировки event loop на каждое сметное слово (Fable audit). Вынесен предпарсенный индекс _gesn_extra_index() с инвалидацией по (mtime_ns,size) набора файлов; диск читается только после pull-обновления базы. Поиск/вывод байт-в-байт прежние (имя в оригинальном регистре сохранено). Битый файл больше не роняет весь поиск. Финальная проверка — test_search_engine на dev (нужен pymorphy2). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
+44
-17
@@ -118,34 +118,61 @@ def _search_fssc(query: str, top_k: int = 5) -> str:
|
||||
|
||||
# === ГЭСН extra (181K norms) ===
|
||||
|
||||
def _search_gesn_extra(query: str, top_k: int = 5) -> str:
|
||||
"""Search in full 181K GESN norms (gesn_extra JSON files)."""
|
||||
_gesn_extra_cache: list[tuple[str, str, str, str]] = [] # (code, name, name_lower, unit)
|
||||
_gesn_extra_sig: tuple = () # (имя, mtime_ns, size)* — инвалидация
|
||||
|
||||
|
||||
def _gesn_extra_index() -> list[tuple[str, str, str, str]]:
|
||||
"""Предпарсенный индекс полной базы ГЭСН с кэшем по mtime/size файлов.
|
||||
|
||||
Раньше _search_gesn_extra на КАЖДЫЙ запрос заново json.loads-ил все gesn_*.json
|
||||
(181K норм, секунды блокировки event loop на сообщение — Fable audit). Теперь
|
||||
диск читается только когда набор файлов изменился (напр. после pull-обновления)."""
|
||||
global _gesn_extra_cache, _gesn_extra_sig
|
||||
gesn_dir = SMETA_DIR / "data" / "gesn_extra"
|
||||
if not gesn_dir.exists():
|
||||
return ""
|
||||
|
||||
query_lower = query.lower()
|
||||
terms = [_normalize(t) for t in query_lower.split() if len(t) > 2]
|
||||
results = []
|
||||
|
||||
for f in gesn_dir.glob("gesn_*.json"):
|
||||
data = json.loads(f.read_text(encoding="utf-8"))
|
||||
return []
|
||||
files = sorted(gesn_dir.glob("gesn_*.json"))
|
||||
sig = tuple((f.name, f.stat().st_mtime_ns, f.stat().st_size) for f in files)
|
||||
if sig == _gesn_extra_sig and _gesn_extra_cache:
|
||||
return _gesn_extra_cache
|
||||
index: list[tuple[str, str, str, str]] = []
|
||||
for f in files:
|
||||
try:
|
||||
data = json.loads(f.read_text(encoding="utf-8"))
|
||||
except Exception: # noqa: BLE001 — битый файл не должен ронять весь поиск
|
||||
continue
|
||||
for code, info in data.items():
|
||||
if not isinstance(info, dict) or "error" in info:
|
||||
continue
|
||||
name = info.get("name", "").lower()
|
||||
score = sum(1 for t in terms if t in name)
|
||||
if score >= 2 or (score == 1 and len(terms) == 1):
|
||||
results.append((score, code, info))
|
||||
name = info.get("name", "")
|
||||
index.append((code, name, name.lower(), info.get("unit", "")))
|
||||
_gesn_extra_cache = index
|
||||
_gesn_extra_sig = sig
|
||||
return index
|
||||
|
||||
|
||||
def _search_gesn_extra(query: str, top_k: int = 5) -> str:
|
||||
"""Search in full 181K GESN norms (gesn_extra JSON files)."""
|
||||
index = _gesn_extra_index()
|
||||
if not index:
|
||||
return ""
|
||||
|
||||
terms = [_normalize(t) for t in query.lower().split() if len(t) > 2]
|
||||
if not terms:
|
||||
return ""
|
||||
results = []
|
||||
for code, name, name_lower, unit in index:
|
||||
score = sum(1 for t in terms if t in name_lower)
|
||||
if score >= 2 or (score == 1 and len(terms) == 1):
|
||||
results.append((score, code, name, unit))
|
||||
|
||||
results.sort(reverse=True, key=lambda x: x[0])
|
||||
if not results:
|
||||
return ""
|
||||
|
||||
lines = ["Расценки из полной базы ГЭСН (181 000+ норм):"]
|
||||
for score, code, info in results[:top_k]:
|
||||
name = info.get("name", "")
|
||||
unit = info.get("unit", "")
|
||||
for score, code, name, unit in results[:top_k]:
|
||||
lines.append(f"- ГЭСН {code}: {name} [{unit}]")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user