Rank diverse source-backed norm search results

This commit is contained in:
anor
2026-12-04 05:19:58 +10:00
parent 92754d3b5a
commit c5332fcaaa
3 changed files with 147 additions and 37 deletions
+88 -37
View File
@@ -10,6 +10,66 @@ BASES = {"2022": "ГЭСН-2022", "2020": "ФЕР-2020"}
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]:
"""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 ""
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")
result = fsnb_ref.find_works(query=query, base=base, limit=limit)
if result.get("status") == "not_found" and not fsnb_ref._extract_code(query):
terms = [term for term in re.findall(r"[а-яa-z0-9]+", fsnb_ref.norm_text(query))
if len(term) >= 4 and not fsnb_ref._is_generic_term(term)]
counts = [(fsnb_ref.count_works(term), term) for term in terms]
usable = [(count, term) for count, term in counts if count > 0]
interpreted = _interpreted_query(query)
exact_code = fsnb_ref._extract_code(query) is not None
terms = _search_terms(interpreted)
result = fsnb_ref.find_works(query=query, base=base, limit=limit if len(terms) < 2 else max(60, limit * 5))
candidates = list(result.get("works") or [])
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:
anchor = min(usable)[1]
fallback = fsnb_ref.find_works(query=anchor, base=base, limit=max(60, limit * 5))
if fallback.get("status") == "ok":
def rank(row):
name = re.findall(r"[а-яa-z0-9]+", fsnb_ref.norm_text(str(row.get("name") or "")))
section = re.findall(r"[а-яa-z0-9]+", fsnb_ref.norm_text(str(row.get("section_path") or "")))
score = 0
for term in re.findall(r"[а-яa-z0-9]+", fsnb_ref.norm_text(query)):
if len(term) < 3:
continue
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)]
anchor = min(usable)[2]
if anchor != interpreted:
fallback = fsnb_ref.find_works(query=anchor, base=base, limit=max(80, limit * 8))
candidates.extend(fallback.get("works") or [])
if candidates:
unique = {}
for row in candidates:
unique.setdefault((row.get("base"), row.get("base_type"), row.get("code")), row)
ranked = sorted(unique.values(), key=lambda row: _search_rank(row, terms))
candidates = _diverse_families(ranked, limit) if not exact_code else ranked[:limit]
items = []
for original in result.get("works") or []:
for original in candidates:
row = dict(original)
if query == row.get("code"):
row["match_reason"] = "Точный шифр"
row["match_score"] = 100
else:
words = re.findall(r"[а-яa-z0-9]+", fsnb_ref.norm_text(
str(row.get("name") or "") + " " + str(row.get("section_path") or "")))
matched = []
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
words = _WORDS.findall(fsnb_ref.norm_text(str(row.get("name") or "")))
matched = [term for term in terms if _word_match(term, words)]
row["match_score"] = min(95, round(85 * len(matched) / len(terms))) if terms else 0
row["match_reason"] = ("Совпали слова: " + ", ".join(matched)
if matched else "Похожее название — проверьте состав")
items.append(row)
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": [],
"message": result.get("message") or "Поиск не выполнен", "query": query,
"base": BASES[base]}