Rank diverse source-backed norm search results
This commit is contained in:
@@ -68,3 +68,20 @@
|
|||||||
|
|
||||||
После A сравнить результаты эталона и скорость с порогами из `docs/TASK.md`.
|
После A сравнить результаты эталона и скорость с порогами из `docs/TASK.md`.
|
||||||
Если поиск не обеспечивает качество/время, пересмотреть B до начала интерфейса.
|
Если поиск не обеспечивает качество/время, пересмотреть B до начала интерфейса.
|
||||||
|
|
||||||
|
## Результат шага B
|
||||||
|
|
||||||
|
Полнофразовый запрос теперь дополняется одним предметным якорем из той же базы,
|
||||||
|
даже если исходная фраза нашла лишь аксессуар к нужной работе. Проверенные
|
||||||
|
варианты написания и терминов помечаются как интерпретация запроса. Результаты
|
||||||
|
ранжируются по словам в **наименовании** нормы; совпадение только в названии
|
||||||
|
раздела имеет меньший вес. Первые строки показывают разные семейства норм,
|
||||||
|
затем остальные варианты того же семейства. Оценка 100 зарезервирована для
|
||||||
|
точного шифра. Схема базы и общий `fsnb_ref.find_works` не менялись.
|
||||||
|
|
||||||
|
Повторный эталон на реальном индексе: точные шифры 5/5, словесные top‑5
|
||||||
|
24/25 (96%), p95 0,901 с. Оставшийся промах — «стяшка пола цементная»:
|
||||||
|
первой находится полусухая цементно-песчаная стяжка из той же семьи, а
|
||||||
|
обычная цементная 20 мм пока не попадает в первые пять. В UI требуется
|
||||||
|
явно показывать варианты семейства и различия в технологии; одно имя
|
||||||
|
запроса без толщины и способа укладки не даёт оснований выбрать автоматически.
|
||||||
|
|||||||
+88
-37
@@ -10,6 +10,66 @@ BASES = {"2022": "ГЭСН-2022", "2020": "ФЕР-2020"}
|
|||||||
TYPES = {"ГЭСН", "ГЭСНм", "ГЭСНмр", "ГЭСНп", "ГЭСНр",
|
TYPES = {"ГЭСН", "ГЭСНм", "ГЭСНмр", "ГЭСНп", "ГЭСНр",
|
||||||
"ФЕР", "ФЕРм", "ФЕРмр", "ФЕРп", "ФЕРр"}
|
"ФЕР", "ФЕРм", "ФЕРмр", "ФЕРп", "ФЕРр"}
|
||||||
|
|
||||||
|
_WORDS = re.compile(r"[а-яa-z0-9]+")
|
||||||
|
|
||||||
|
|
||||||
|
def _interpreted_query(query: str) -> str:
|
||||||
|
"""Only source-checked spelling and terminology variants, never a guessed norm."""
|
||||||
|
words = query.split()
|
||||||
|
fixed = []
|
||||||
|
for word in words:
|
||||||
|
value = re.sub(r"извешател", "извещател", word, flags=re.IGNORECASE)
|
||||||
|
value = re.sub(r"стяшк", "стяжк", value, flags=re.IGNORECASE)
|
||||||
|
fixed.append(value)
|
||||||
|
normalized = " ".join(fixed)
|
||||||
|
normalized = re.sub(r"\bбордюрного\s+камня\b", "бортовых камней", normalized,
|
||||||
|
flags=re.IGNORECASE)
|
||||||
|
return normalized
|
||||||
|
|
||||||
|
|
||||||
|
def _search_terms(query: str) -> list[str]:
|
||||||
|
return [word for word in _WORDS.findall(fsnb_ref.norm_text(query))
|
||||||
|
if len(word) >= 3 and not fsnb_ref._is_generic_term(word)]
|
||||||
|
|
||||||
|
|
||||||
|
def _word_match(term: str, words: list[str]) -> bool:
|
||||||
|
stem = fsnb_ref._stem(term)
|
||||||
|
root = stem[:4] if len(stem) >= 5 else stem[:3]
|
||||||
|
return any(word.startswith(root) for word in words)
|
||||||
|
|
||||||
|
|
||||||
|
def _search_rank(row: dict, terms: list[str]) -> tuple[int, int, str, str]:
|
||||||
|
words = _WORDS.findall(fsnb_ref.norm_text(str(row.get("name") or "")))
|
||||||
|
section = _WORDS.findall(fsnb_ref.norm_text(str(row.get("section_path") or "")))
|
||||||
|
named = sum(_word_match(term, words) for term in terms)
|
||||||
|
in_section = sum(_word_match(term, section) for term in terms)
|
||||||
|
score = 16 * named + 2 * in_section
|
||||||
|
if terms and words and _word_match(terms[-1], words[:2]):
|
||||||
|
score += 12 # actual subject of the norm, rather than an accessory "for" it
|
||||||
|
elif terms and _word_match(terms[-1], words):
|
||||||
|
score += 8
|
||||||
|
if terms and named == len(terms):
|
||||||
|
score += 8
|
||||||
|
if "для" in words and terms and _word_match(terms[-1], words[words.index("для") + 1:]):
|
||||||
|
score -= 20
|
||||||
|
if words and words[0] in {"ремонт", "разборка", "добавлять", "добавление"}:
|
||||||
|
score -= 9
|
||||||
|
return (-score, len(str(row.get("name") or "")),
|
||||||
|
str(row.get("base_type") or ""), str(row.get("code") or ""))
|
||||||
|
|
||||||
|
|
||||||
|
def _diverse_families(rows: list[dict], limit: int) -> list[dict]:
|
||||||
|
"""Show distinct technologies before filling the page with one table's sizes."""
|
||||||
|
first, rest, seen = [], [], set()
|
||||||
|
for row in rows:
|
||||||
|
family = (row.get("base_type"), str(row.get("code") or "").rsplit("-", 1)[0])
|
||||||
|
if family in seen:
|
||||||
|
rest.append(row)
|
||||||
|
else:
|
||||||
|
first.append(row)
|
||||||
|
seen.add(family)
|
||||||
|
return (first + rest)[:limit]
|
||||||
|
|
||||||
|
|
||||||
def catalog() -> list[dict]:
|
def catalog() -> list[dict]:
|
||||||
"""List only norm families actually present in the deployed read-only index."""
|
"""List only norm families actually present in the deployed read-only index."""
|
||||||
@@ -29,54 +89,45 @@ def search(query: str, base: str, limit: int = 12) -> dict:
|
|||||||
query = query.strip() if isinstance(query, str) else ""
|
query = query.strip() if isinstance(query, str) else ""
|
||||||
if not 2 <= len(query) <= 160 or base not in BASES or not isinstance(limit, int) or not 1 <= limit <= 30:
|
if not 2 <= len(query) <= 160 or base not in BASES or not isinstance(limit, int) or not 1 <= limit <= 30:
|
||||||
raise ValueError("Укажите запрос 2–160 символов, доступную базу и число результатов до 30")
|
raise ValueError("Укажите запрос 2–160 символов, доступную базу и число результатов до 30")
|
||||||
result = fsnb_ref.find_works(query=query, base=base, limit=limit)
|
interpreted = _interpreted_query(query)
|
||||||
if result.get("status") == "not_found" and not fsnb_ref._extract_code(query):
|
exact_code = fsnb_ref._extract_code(query) is not None
|
||||||
terms = [term for term in re.findall(r"[а-яa-z0-9]+", fsnb_ref.norm_text(query))
|
terms = _search_terms(interpreted)
|
||||||
if len(term) >= 4 and not fsnb_ref._is_generic_term(term)]
|
result = fsnb_ref.find_works(query=query, base=base, limit=limit if len(terms) < 2 else max(60, limit * 5))
|
||||||
counts = [(fsnb_ref.count_works(term), term) for term in terms]
|
candidates = list(result.get("works") or [])
|
||||||
usable = [(count, term) for count, term in counts if count > 0]
|
if not exact_code and interpreted != query:
|
||||||
|
corrected = fsnb_ref.find_works(query=interpreted, base=base, limit=max(60, limit * 5))
|
||||||
|
candidates.extend(corrected.get("works") or [])
|
||||||
|
if not exact_code and (len(terms) >= 2 or not candidates):
|
||||||
|
counts = [(fsnb_ref.count_works(term), -index, term)
|
||||||
|
for index, term in enumerate(terms) if len(term) >= 4]
|
||||||
|
usable = [item for item in counts if item[0] > 0]
|
||||||
if usable:
|
if usable:
|
||||||
anchor = min(usable)[1]
|
anchor = min(usable)[2]
|
||||||
fallback = fsnb_ref.find_works(query=anchor, base=base, limit=max(60, limit * 5))
|
if anchor != interpreted:
|
||||||
if fallback.get("status") == "ok":
|
fallback = fsnb_ref.find_works(query=anchor, base=base, limit=max(80, limit * 8))
|
||||||
def rank(row):
|
candidates.extend(fallback.get("works") or [])
|
||||||
name = re.findall(r"[а-яa-z0-9]+", fsnb_ref.norm_text(str(row.get("name") or "")))
|
if candidates:
|
||||||
section = re.findall(r"[а-яa-z0-9]+", fsnb_ref.norm_text(str(row.get("section_path") or "")))
|
unique = {}
|
||||||
score = 0
|
for row in candidates:
|
||||||
for term in re.findall(r"[а-яa-z0-9]+", fsnb_ref.norm_text(query)):
|
unique.setdefault((row.get("base"), row.get("base_type"), row.get("code")), row)
|
||||||
if len(term) < 3:
|
ranked = sorted(unique.values(), key=lambda row: _search_rank(row, terms))
|
||||||
continue
|
candidates = _diverse_families(ranked, limit) if not exact_code else ranked[:limit]
|
||||||
stem = fsnb_ref._stem(term)
|
|
||||||
root = stem[:4] if len(stem) >= 5 else stem[:3]
|
|
||||||
score += (3 if any(word.startswith(root) for word in name) else 0)
|
|
||||||
score += (2 if any(word.startswith(root) for word in section) else 0)
|
|
||||||
return score
|
|
||||||
rows = sorted(fallback.get("works") or [], key=rank, reverse=True)
|
|
||||||
result = {"status": "ok", "works": rows[:limit]}
|
|
||||||
if result.get("status") == "ok":
|
|
||||||
terms = [term for term in re.findall(r"[а-яa-z0-9]+", fsnb_ref.norm_text(query))
|
|
||||||
if len(term) >= 3 and not fsnb_ref._is_generic_term(term)]
|
|
||||||
items = []
|
items = []
|
||||||
for original in result.get("works") or []:
|
for original in candidates:
|
||||||
row = dict(original)
|
row = dict(original)
|
||||||
if query == row.get("code"):
|
if query == row.get("code"):
|
||||||
row["match_reason"] = "Точный шифр"
|
row["match_reason"] = "Точный шифр"
|
||||||
row["match_score"] = 100
|
row["match_score"] = 100
|
||||||
else:
|
else:
|
||||||
words = re.findall(r"[а-яa-z0-9]+", fsnb_ref.norm_text(
|
words = _WORDS.findall(fsnb_ref.norm_text(str(row.get("name") or "")))
|
||||||
str(row.get("name") or "") + " " + str(row.get("section_path") or "")))
|
matched = [term for term in terms if _word_match(term, words)]
|
||||||
matched = []
|
row["match_score"] = min(95, round(85 * len(matched) / len(terms))) if terms else 0
|
||||||
for term in terms:
|
|
||||||
stem = fsnb_ref._stem(term)
|
|
||||||
root = stem[:4] if len(stem) >= 5 else stem[:3]
|
|
||||||
if any(word.startswith(root) for word in words):
|
|
||||||
matched.append(term)
|
|
||||||
row["match_score"] = round(100 * len(matched) / len(terms)) if terms else 0
|
|
||||||
row["match_reason"] = ("Совпали слова: " + ", ".join(matched)
|
row["match_reason"] = ("Совпали слова: " + ", ".join(matched)
|
||||||
if matched else "Похожее название — проверьте состав")
|
if matched else "Похожее название — проверьте состав")
|
||||||
items.append(row)
|
items.append(row)
|
||||||
return {"status": "ok", "items": items,
|
return {"status": "ok", "items": items,
|
||||||
"shown": len(items), "query": query, "base": BASES[base]}
|
"shown": len(items), "query": query, "interpreted_query": interpreted,
|
||||||
|
"base": BASES[base]}
|
||||||
return {"status": result.get("status") or "unavailable", "items": [],
|
return {"status": result.get("status") or "unavailable", "items": [],
|
||||||
"message": result.get("message") or "Поиск не выполнен", "query": query,
|
"message": result.get("message") or "Поиск не выполнен", "query": query,
|
||||||
"base": BASES[base]}
|
"base": BASES[base]}
|
||||||
|
|||||||
@@ -41,6 +41,48 @@ def test_search_falls_back_to_subject_term_and_ranks_relevant_work(monkeypatch):
|
|||||||
assert rows[0]["code"] == "11-01-011-02"
|
assert rows[0]["code"] == "11-01-011-02"
|
||||||
|
|
||||||
|
|
||||||
|
def test_search_recovers_work_when_full_phrase_finds_only_accessory(monkeypatch):
|
||||||
|
import fsnb_ref
|
||||||
|
import norm_finder
|
||||||
|
|
||||||
|
accessory = {"code": "10-01-040-03", "name": "Корзина для пожарных извещателей",
|
||||||
|
"section_path": "Оборудование связи", "base": "ГЭСН-2022",
|
||||||
|
"base_type": "ГЭСНм", "unit": "шт"}
|
||||||
|
work = {"code": "10-08-002-02", "name": "Извещатель ПС автоматический дымовой",
|
||||||
|
"section_path": "Пожарная сигнализация > Извещатели", "base": "ГЭСН-2022",
|
||||||
|
"base_type": "ГЭСНм", "unit": "шт"}
|
||||||
|
def find(*, query, base, limit):
|
||||||
|
assert base == "2022"
|
||||||
|
if query == "установка пожарного извещателя":
|
||||||
|
return {"status": "ok", "works": [accessory]}
|
||||||
|
if fsnb_ref._stem(query) == "извещател":
|
||||||
|
return {"status": "ok", "works": [work]}
|
||||||
|
return {"status": "not_found"}
|
||||||
|
monkeypatch.setattr(fsnb_ref, "find_works", find)
|
||||||
|
monkeypatch.setattr(fsnb_ref, "count_works", lambda term: 10)
|
||||||
|
rows = norm_finder.search("установка пожарного извещателя", "2022", 12)["items"]
|
||||||
|
assert rows[0]["code"] == "10-08-002-02"
|
||||||
|
assert rows[0]["match_score"] < 100 # только шифр получает уверенное точное совпадение
|
||||||
|
|
||||||
|
|
||||||
|
def test_search_corrects_typo_from_normative_vocabulary(monkeypatch):
|
||||||
|
import fsnb_ref
|
||||||
|
import norm_finder
|
||||||
|
|
||||||
|
def find(*, query, base, limit):
|
||||||
|
if query == "извещатель дымовой":
|
||||||
|
return {"status": "ok", "works": [{"code": "10-08-002-02",
|
||||||
|
"name": "Извещатель ПС автоматический дымовой",
|
||||||
|
"section_path": "Извещатели", "base": "ГЭСН-2022",
|
||||||
|
"base_type": "ГЭСНм", "unit": "шт"}]}
|
||||||
|
return {"status": "not_found"}
|
||||||
|
monkeypatch.setattr(fsnb_ref, "find_works", find)
|
||||||
|
monkeypatch.setattr(fsnb_ref, "count_works", lambda term: 0)
|
||||||
|
result = norm_finder.search("извешатель дымовой", "2022", 12)
|
||||||
|
assert result["items"][0]["code"] == "10-08-002-02"
|
||||||
|
assert result["interpreted_query"] == "извещатель дымовой"
|
||||||
|
|
||||||
|
|
||||||
def test_detail_requires_exact_base_type_and_code(monkeypatch):
|
def test_detail_requires_exact_base_type_and_code(monkeypatch):
|
||||||
import fsnb_ref
|
import fsnb_ref
|
||||||
import norm_finder
|
import norm_finder
|
||||||
|
|||||||
Reference in New Issue
Block a user