dp-zp-agent/tools/crzp/answering/names.py
jp170na 73e895af41 oprava mien CRZP, čistenie šumu, spoločné stop-slová, stretnutia
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 04:18:10 +01:00

236 lines
12 KiB
Python

"""Base forms of inflected Slovak names, used only without the model.
CRZP matches whole words, so "Jána Ptáka" cannot be found as written. Without
the model only the surname is searched, in a few candidate nominatives (most
likely first); the caller keeps the first candidate whose rows really contain
the asked person, because the row filter compares the stems of all asked
words (first name included). A wrong guess therefore finds nothing.
"""
from __future__ import annotations
from tools.crzp.source.parse import fold
import threading
# ending -> nominative replacements in order of preference (lowercase).
_RULES = [
("ovej", ["ová"]), ("ovou", ["ová"]), ("ovú", ["ová"]), # Novákovej -> Nováková
("skej", ["ská"]), ("ckej", ["cká"]), ("skou", ["ská"]), # Hronskej -> Hronská
("ského", ["ský"]), ("ckého", ["cký"]), ("ého", ["ý"]), ("ému", ["ý"]), ("ým", ["ý"]), # Malého -> Malý
("ovi", ["", "a"]), ("om", ["", "a"]), ("ou", ["a"]), # Ptákovi -> Pták, Plevom -> Pleva
("a", [""]), ("u", ["a", ""]), ("y", ["a"]), ("e", ["a", ""]), # Ptáka -> Pták, Galajdu -> Galajda
]
MAX_CANDIDATES = 3
def word_forms(word: str) -> list[str]:
"""Candidate nominatives of one name word, most likely first, the word itself last."""
low, forms = word.lower(), []
for ending, replacements in _RULES:
if low.endswith(ending) and len(low) - len(ending) >= 2:
for replacement in replacements:
base = low[: len(low) - len(ending)] + replacement
if replacement == "" and len(base) >= 3 and base[-1] in "kcrl" and base[-2] not in "aeiouyáéíóúýô":
forms += [base[:-1] + "e" + base[-1], base[:-1] + "o" + base[-1]] # Hládka -> Hládek, Pavla -> Pavol
forms.append(base)
break
forms.append(low)
seen, result = set(), []
for form in forms:
if len(form) >= 2 and fold(form) not in seen:
seen.add(fold(form))
result.append(form[:1].upper() + form[1:] if word[:1].isupper() else form)
return result
def surname_variants(name: str) -> list[str]:
"""Search candidates for the surname of an inflected name: "Daniela Hládka" -> ["Hládek", ...]."""
words = name.split()
return word_forms(words[-1])[:MAX_CANDIDATES] if words else []
# Common Slovak nicknames (folded nominative) -> the first names CRZP records write.
NICKNAMES = {
"samo": ["Samuel"], "jano": ["Ján"], "janko": ["Ján"], "jozo": ["Jozef"], "jozko": ["Jozef"],
"peto": ["Peter"], "mato": ["Matej", "Martin"], "miro": ["Miroslav"], "miso": ["Michal"], "tomi": ["Tomáš"],
"majo": ["Marián", "Mário"], "palo": ["Pavol"], "fero": ["František"], "duro": ["Juraj"], "juro": ["Juraj"],
"dano": ["Daniel"], "danko": ["Daniel"], "rado": ["Radoslav", "Radovan"], "stano": ["Stanislav"],
"vlado": ["Vladimír"], "laco": ["Ladislav"], "riso": ["Richard"], "robo": ["Róbert"], "kubo": ["Jakub"],
"filo": ["Filip"], "ondro": ["Ondrej"], "adko": ["Adam"], "lubo": ["Ľubomír", "Ľuboš"], "maros": ["Maroš"],
"samko": ["Samuel"], "petko": ["Peter"], "matko": ["Matej", "Martin"], "misko": ["Michal"], "jurko": ["Juraj"],
"ferko": ["František"], "palko": ["Pavol"], "tomasko": ["Tomáš"], "lukasko": ["Lukáš"],
"zuzka": ["Zuzana"], "katka": ["Katarína"], "janka": ["Jana"], "evka": ["Eva"], "majka": ["Mária"],
"danka": ["Daniela"], "lucka": ["Lucia"], "miska": ["Michaela"], "baska": ["Barbora"], "tana": ["Tatiana"],
"sasa": ["Alexandra", "Alexander"], "nika": ["Nikola", "Veronika"], "peta": ["Petra"],
}
# Case endings a nickname takes after its stem ("Sama", "Samovi", "Samom"; "Zuzky", "Zuzkou").
_NICK_ENDINGS = {"", "o", "a", "u", "y", "e", "i", "ou", "om", "ovi"}
MAX_FULL_NAMES = 4 # full-name searches of one asked person
MAX_SURNAME_ONLY = 2 # surname-only searches (first name checked in the rows) as the last resort
def nickname_names(word: str) -> list[str]:
""""Samo"/"Sama" -> ["Samuel"], "Zuzky" -> ["Zuzana"]; [] for a word that is no nickname."""
folded = fold(word)
names = []
for nick, full in NICKNAMES.items():
stem = nick[:-1]
if folded == nick or folded.startswith(stem) and folded[len(stem):] in _NICK_ENDINGS:
names += full
return list(dict.fromkeys(names))
def _capital(name: str) -> str:
""""samuel furda" -> "Samuel Furda" (the question may be typed in lower case)."""
return " ".join(w[:1].upper() + w[1:] for w in name.split())
def name_candidates(model_name: str | None, typed: str) -> tuple[list[str], list[str]]:
"""Search candidates of an asked person whose name is written in the question:
(full names, most likely first; surnames alone, the last resort).
The model's base form comes first ("Samuel Feranc"), then the rule base forms of the
typed words ("Samuela Furdy" -> "Samuel Furda", also when the model wrote "Samuel Furd"),
then the full first names of a nickname ("Samo Furda" -> "Samuel Furda")."""
words = typed.split()
full = [_capital(model_name)] if model_name else []
if len(words) < 2: # one word: the model's form, then the surname candidates
return _unique(full)[:1], _unique([_capital(s) for s in word_forms(typed)])[:MAX_SURNAME_ONLY]
model_words = model_name.split() if model_name and len(model_name.split()) >= 2 else []
# The rule forms assume an inflected name; a name the model kept as typed is already the nominative.
inflected = not model_words or fold(typed) != fold(model_name)
rule_surname = _capital(surname_variants(typed)[0])
rule_first = _capital(word_forms(words[0])[0])
middle = _capital(" ".join(words[1:-1]))
join = lambda first, last: " ".join(p for p in (first, middle, last) if p)
surname = _capital(model_words[-1]) if model_words else rule_surname
# A nickname: the model writes the nominative ("Samo"); the typed form may be inflected ("Sama", which
# the model may wrongly shorten to "Sam") and is read too when the model changed it.
nicknames = nickname_names(model_words[0]) if model_words else []
if not model_words or fold(model_words[0]) != fold(words[0]):
nicknames = list(dict.fromkeys([*nicknames, *nickname_names(words[0])]))
if surname.lower().endswith("á") or fold(surname).endswith("ova"): # a woman: "Jana Nováková" is no "Jano"
nicknames = [n for n in nicknames if fold(n).endswith("a")]
surnames = [surname, *([rule_surname] if inflected else [])]
candidates = [*full, *([join(rule_first, rule_surname)] if inflected else []),
*[join(n, s) for n in nicknames for s in _unique(surnames)]]
return (_unique(candidates)[:MAX_FULL_NAMES],
[s for s in _unique(surnames) if len(fold(s)) >= 3][:MAX_SURNAME_ONLY])
def _unique(names: list[str]) -> list[str]:
seen, result = set(), []
for name in names:
if name and fold(name) not in seen:
seen.add(fold(name))
result.append(name)
return result
def name_variants(name: str) -> list[str]:
"""Search texts for an inflected name, most likely first: the likeliest first
name with each surname candidate, then each surname candidate alone (the
first name is still checked in the rows, e.g. "Pavla" matches "Pavol")."""
words = name.split()
surnames = surname_variants(name)
if len(words) < 2:
return surnames
first = word_forms(words[0])[0]
return list(dict.fromkeys([f"{first} {s}" for s in surnames] + surnames))
# ------------------------------------------------------------------ known names (local register cache)
# CRZP matches whole words, so a misspelled surname ("jakub smetnaka") or a case the rules above do not
# derive ("Tomáša Murcka" is Murcko, not Murcek) finds nothing. The names already read from the register
# (the local cache: authors, supervisors, opponents) are compared with the typed name the other way round:
# every case form of a known name is generated (person_names.name_token_variants), and at most one word may
# differ by one letter (two in words of eight letters or more), never the first name and the surname both
# (person_names._score). Only names of the cache are proposed; a name is never invented.
_known = {"stamp": 0.0, "by_first": {}, "first_of": {}}
_known_lock = threading.Lock()
KNOWN_REFRESH = 1800
MAX_KNOWN = 3
def _known_index() -> tuple[dict, dict]:
"""{folded first name: [(folded words, display name)]} and {case form of a first name: {folded first names}}."""
import time
from tools.retrieval.person_names import name_token_variants, normalize
if time.time() - _known["stamp"] > KNOWN_REFRESH:
with _known_lock:
if time.time() - _known["stamp"] > KNOWN_REFRESH:
by_first, first_of, seen = {}, {}, set()
try:
from tools.crzp.fetch import store
from tools.crzp.source.parse import display_name
for row in store().cached_rows():
for field in ("authors", "supervisors", "opponents"):
for raw in row.get(field) or []:
shown = display_name(raw)
words = normalize(shown).split()
key = " ".join(words)
if len(words) < 2 or key in seen:
continue
seen.add(key)
by_first.setdefault(words[0], []).append((words, shown))
for first in by_first:
for form in name_token_variants(first):
first_of.setdefault(form, set()).add(first)
except Exception:
by_first, first_of = {}, {}
_known.update(stamp=time.time(), by_first=by_first, first_of=first_of)
return _known["by_first"], _known["first_of"]
def _known_score(words: list[str], known: list[str]) -> int | None:
"""0 the same words, 1 per word in another case, 10 a surname one letter (or two swapped letters) away
from one of its case forms; None otherwise. Only the surname may be misspelled."""
from tools.retrieval.person_names import _distance, name_token_variants
score = 0
for position, (typed, name) in enumerate(zip(words, known)):
if typed == name:
continue
forms = name_token_variants(name)
if typed in forms:
score += 1
elif position == len(words) - 1 and len(typed) >= 4 and min(
(_distance(typed, form) for form in forms if abs(len(typed) - len(form)) <= 1), default=2) == 1:
score += 10
else:
return None
return score
def known_names(typed: str) -> dict:
"""Names of the local register cache the typed name may mean:
{"exact": the name as typed is known, "forms": known names of which the typed words are a case
("Tomáša Murcka" -> Tomáš Murcko), "typos": known names whose surname is one letter (or two swapped
letters) away ("jakub smetnaka" -> Jakub Smetanka)}. The first name must be the typed one up to its case;
several equally close names are all returned (the caller asks which one is meant)."""
from tools.retrieval.person_names import normalize
words = normalize(typed).split()
empty = {"exact": False, "forms": [], "typos": []}
if len(words) < 2 or not all(w.isalpha() for w in words):
return empty
by_first, first_of = _known_index()
scored = {}
last = words[-1]
for first in first_of.get(words[0], ()):
for known, shown in by_first.get(first, ()):
if len(known) != len(words):
continue
surname = known[-1]
if surname[:1] != last[:1] or abs(len(surname) - len(last)) > 4:
continue # a misspelled surname keeps its first letter; a case adds at most a few letters
score = _known_score(words, known)
if score is not None:
key = " ".join(known)
if key not in scored or score < scored[key][0]:
scored[key] = (score, shown)
if not scored:
return empty
best = min(score for score, _ in scored.values())
if best == 0:
return {**empty, "exact": True}
names = sorted((shown for score, shown in scored.values() if score == best), key=fold)[:MAX_KNOWN]
return {**empty, "forms": names} if best < 10 else {**empty, "typos": names}