neevidované údaje, odpovede zo záznamu profilu, odkazy CRZP, zamietnutá wiki, preklep v krstnom mene

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ján Pták 2026-11-24 13:24:20 +01:00
parent 73e895af41
commit 44deacf0e8
7 changed files with 544 additions and 12 deletions

View File

@ -736,3 +736,82 @@ def test_a_misspelled_name_the_register_corrected_is_the_person_the_question_nam
part = {"mode": "explicit", "status": "ok", "person": "Jakub Smetanka", "corrected": "jakub smetnaka"}
assert C.crzp_names_the_person(question, wiki, part)
assert not C.crzp_names_the_person(question, wiki, {**part, "corrected": None}) # an uncorrected other name
@pytest.mark.parametrize("question, label", [
("Koľko zarába Ján Pták po skončení štúdia?", "Údaje o plate ani príjme osoby Ján Pták v podkladoch nie sú"),
("Kde býva Ján Pták?", "Adresa ani bydlisko osoby Ján Pták v podkladoch nie sú"),
("Akú známku dostal Ján Pták za diplomovú prácu?", "Známka, body, miestnosť ani protokol obhajoby osoby Ján Pták"),
("Koľko bodov získal Ján Pták pri obhajobe svojej záverečnej práce?", "Známka, body, miestnosť ani protokol obhajoby"),
("V akej miestnosti prebiehala obhajoba záverečnej práce osoby Ján Pták?", "Známka, body, miestnosť ani protokol"),
])
def test_data_the_records_never_hold_are_said_to_be_missing_without_a_work_list(combo, monkeypatch, question, label):
monkeypatch.setattr(C, "_one_person", _named_ptak)
asked = []
combo["deliver"] = lambda q, **kw: (asked.append(q), dict(WIKI))[1]
result = ask(combo, question)
assert result["status"] == "ok" and result["answer"].startswith(label) and not asked
@pytest.mark.parametrize("question", [
"Akú platformu použil Ján Pták?", "Kde býva uložený dataset Jána Ptáka?", "Aký model GPU používal Ján Pták?",
"Aká IP adresa bola použitá pre systém Jána Ptáka?", "Kto bol vedúci diplomovej práce Jána Ptáka?"])
def test_questions_about_the_work_are_not_refused_as_personal_data(question):
low = C.normalized(question)
assert not any(pattern.search(low) for pattern, _ in C.NOT_RECORDED)
REJECTED = {"status": "error", "reason": "answer_rejected", "accepted_for_delivery": False, "index_version": {"version": "v"},
"answer": "Odpoveď sa nepodarilo spoľahlivo overiť podľa podkladov.", "source_urls": [], "claims": [],
"delivery_check": {"layer": "fulfilment", "code": "request_not_fulfilled", "request_fingerprint": "x"}}
PERSON_LIST = {"mode": "person", "text": "- bakalárska práca 2025 „IoT“ — vedúci Pavol Galajda; oponent Daniel Hládek",
"rows": [], "urls": ["https://opac.test/1"], "people": [], "works": []}
@pytest.mark.parametrize("question, expected", [
("Aké výsledky dosiahol Ján Pták?", "Zaznamenané výsledky"), # the wiki's records, by code
("Na čom všetkom pracoval Ján Pták?", "Ján Pták má"), # the works list
("Akú architektúru trénoval Ján Pták?", None), # the failure, not the register's list
])
def test_a_rejected_wiki_answer_is_not_replaced_by_the_registers_work_list(combo, monkeypatch, question, expected):
from tools.answers.presentation import unified as U
monkeypatch.setattr(C, "_one_person", _named_ptak)
monkeypatch.setattr(U, "person_works", lambda person, rows=None: [
{"type": "diploma_thesis", "year": 2027, "title": "Znalostné grafy", "source": "wiki", "heading": "Diplomová práca 2027"}])
monkeypatch.setattr(U, "results_of", lambda person, heading, limit=2: ["Implementovaný RAG nad Neo4j."])
monkeypatch.setattr(U, "work_urls", lambda person, works: ["https://zp.test/jan"])
monkeypatch.setattr(U, "catalog", lambda: {"people": {"Ján Pták": {"person_kind": "student"}}, "works": {}})
combo["part"] = dict(PERSON_LIST)
combo["deliver"] = lambda q, **kw: dict(REJECTED)
result = C.compose(question, question, "rag", dict(REJECTED), dict(PERSON_LIST), "Ján Pták")
if expected:
assert result["status"] == "ok" and result["answer"].startswith(expected) and "Galajda" not in result["answer"]
else:
assert result["status"] == "error" and "Galajda" not in (result.get("answer") or "")
def test_a_question_the_work_list_answers_still_gets_it_after_a_rejected_wiki_answer():
for question in ("Kto viedol bakalársku prácu Jána Ptáka?", "Ako sa volá bakalárska práca Jána Ptáka?",
"Aké práce robil Ján Pták?", "O čom je bakalárska práca Jána Ptáka?", "Aké zdroje máš k práci Jána Ptáka?"):
assert C.LISTED_FACTS.search(C.normalized(question)), question
assert not C.LISTED_FACTS.search(C.normalized("Aké výsledky dosiahol Ján Pták?"))
def test_a_supervisor_is_no_student_whose_rejected_answer_is_kept(combo, monkeypatch):
from tools.answers.presentation import unified as U
monkeypatch.setattr(U, "catalog", lambda: {"people": {"Daniel Hládek": {"person_kind": None}}, "works": {}})
question = "Ktoré práce o vyhľadávaní viedol Daniel Hládek a čo z nich vzniklo?"
result = C.compose(question, question, "rag", dict(REJECTED), dict(PERSON_LIST), "Daniel Hládek")
assert "Galajda" in result["answer"] # not a student: the register's list stays the answer
def test_a_rejected_answer_about_a_student_the_register_does_not_know_is_answered_from_the_records(combo, monkeypatch):
from tools.answers.presentation import unified as U
monkeypatch.setattr(U, "person_works", lambda person, rows=None: [
{"type": "bachelor_thesis", "year": 2026, "title": "Orchestrácia", "source": "wiki", "heading": "Bakalárska práca 2026"}])
monkeypatch.setattr(U, "catalog", lambda: {"people": {"Ján Pták": {"person_kind": "student"}}, "works": {}})
question = "Na čom všetkom pracoval Ján Pták?"
result = C.compose(question, question, "rag", dict(REJECTED), None, "Ján Pták")
assert result["status"] == "ok" and "Orchestrácia" in result["answer"]
other = C.compose("Akú architektúru trénoval Ján Pták?", "Akú architektúru trénoval Ján Pták?", "rag", dict(REJECTED), None, "Ján Pták")
assert other["status"] == "error"

View File

@ -0,0 +1,101 @@
"""Questions a ZP Wiki profile answers alone: the record's page, a topic in it, keyword (tag) conditions, two people."""
import pytest
from tools.answers import combined as C
from tools.answers.presentation import unified as U
PAGES = [
{"name": "Ana Nová", "url": "https://zp.test/ana", "kind": "student", "start_year": 2022, "tags": ["nlp", "rag"],
"categories": ["bp2025"], "person_kind": "student", "source_document": "ana.md"},
{"name": "Ben Starý", "url": "https://zp.test/ben", "kind": "student", "start_year": 2021, "tags": ["nlp"],
"categories": ["bp2024"], "person_kind": "student", "source_document": "ben.md"},
{"name": "Eva Biela", "url": "https://zp.test/eva", "kind": "intern", "start_year": None, "tags": ["hatespeech"],
"categories": ["iaeste"], "person_kind": "intern", "source_document": "eva.md"},
]
TEXTS = {"ana.md": "# Bakalárska práca 2025\nStav:\n- Implementovaný PageRank v [Elasticsearch](https://es.test).\n"
"- Použité PyTorch modely.\n",
"ben.md": "# Bakalárska práca 2024\nStav:\n- Hotový chatbot.\n",
"eva.md": "Goal: Help with the [Hate Speech Project](/topics/hatespeech)\n"}
WORKS = {"Ana Nová": [{"type": "bachelor_thesis", "year": 2025, "title": "Vyhľadávanie", "source": "wiki"}],
"Ben Starý": [{"type": "bachelor_thesis", "year": 2024, "title": "Chatbot", "source": "wiki"}]}
@pytest.fixture
def data(monkeypatch):
monkeypatch.setattr(U, "wiki_pages", lambda: PAGES)
monkeypatch.setattr(U, "catalog", lambda: {"people": {p["name"]: p for p in PAGES}, "works": WORKS})
monkeypatch.setattr(U, "page_chunks", lambda path: [TEXTS.get(path, "")])
monkeypatch.setattr(U, "person_works", lambda person, rows=None: [dict(w) for w in WORKS.get(person, [])])
monkeypatch.setattr(U, "spelled", lambda name: name)
names = [p["name"] for p in PAGES]
monkeypatch.setattr(C, "_people", lambda q: [n for n in names if n.split()[0][:3] in q])
return names
def answer(question):
named = [n for n in ("Ana Nová", "Ben Starý", "Eva Biela") if n.split()[0][:3] in question]
return C.record_answer(question, {"name": named[0]} if len(named) == 1 else None)
def test_where_the_record_of_a_person_is(data):
out = answer("Kde v ZP Wiki nájdem záznam o osobe Ana Nová?")
assert "https://zp.test/ana" in out["text"] and out["urls"] == ["https://zp.test/ana"]
assert "(stážistka v ZP Wiki)" in answer("Nájdi dokument o osobe Eva Biela.")["text"]
assert "(študentka v ZP Wiki)" in out["text"]
def test_the_lines_of_a_record_that_name_a_topic(data):
out = answer("Ktorý záznam v ZP Wiki spája osobu Ana Nová s témou „PageRank“?")
assert "Bakalárska práca 2025" in out["text"] and "„Implementovaný PageRank v Elasticsearch.“" in out["text"]
assert "PyTorch" in answer("Ktorý dokument alebo študent súvisí s témou PyTorch a osobou Ana Nová?")["text"]
assert "Hate Speech Project" in answer("Ktorá stáž osoby Eva Biela súvisela s témou Hate Speech?")["text"]
assert "sa téma „Docker“ nespomína" in answer("Ktorý dokument alebo študent súvisí s témou Docker a osobou Ana Nová?")["text"]
def test_a_keyword_condition_of_a_title_is_checked(data):
assert "„Vyhľadávanie“" in answer("Uveď názov práce osoby Ana Nová v roku 2025 s kľúčovým slovom nlp.")["text"]
missing = answer("Aký je názov práce osoby Ana Nová, ak jej dokument zároveň obsahuje kľúčové slovo Raspberry Pi?")
assert "kľúčové slovo „Raspberry Pi“ nemá" in missing["text"] and "Vyhľadávanie" not in missing["text"]
assert "prácu z roku 2019 však v zázname nemá" in answer("Uveď názov práce osoby Ana Nová v roku 2019 s kľúčovým slovom nlp.")["text"]
def test_two_people_keywords_and_study_starts(data):
assert answer("Majú osoby Ana Nová a Ben Starý spoločné kľúčové slovo nlp?")["text"].startswith("Áno")
no = answer("Over spoločné kľúčové slovo rag pri osobách Ana Nová a Ben Starý.")["text"]
assert no.startswith("Nie") and "má ho len Ana Nová" in no
which = answer("Ktorá z osôb Ana Nová a Ben Starý má kľúčové slovo nlp a jej práca je z roku 2024?")["text"]
assert which.startswith("Podmienky spĺňa") and "Ben Starý: bakalárska práca (2024)" in which and "Ana Nová nemá prácu z roku 2024" in which
start = answer("Aký spoločný rok začiatku štúdia majú osoby Ana Nová a Ben Starý?")["text"]
assert start.startswith("Nie, spoločný rok začiatku štúdia nemajú") and "2022" in start and "2021" in start
@pytest.mark.parametrize("question", [
"Kto je vedúci diplomovej práce Ana Nová?", "Na čom pracovala Ana Nová?", "Porovnaj výsledky Ana Nová a Ben Starý.",
"Kto robil s PageRank?", "Aký je názov bakalárskej práce Ana Nová?"])
def test_other_questions_are_left_to_the_usual_answers(data, question):
assert answer(question) is None
def test_a_misspelled_topic_word_still_finds_its_lines(data):
out = answer("Ktorý dokument alebo študent súvisí s témou PagReank a osobou Ana Nová?")
assert "PageRank" in out["text"] and "nespomína" not in out["text"]
assert "nespomína" in answer("Ktorý dokument alebo študent súvisí s témou Pagr a osobou Ana Nová?")["text"] # short: exact only
def test_a_study_start_both_people_are_linked_by(data):
out = answer("Cez ktorý rok začiatku štúdia sú prepojené osoby Ana Nová a Ben Starý?")
assert out and "2022" in out["text"] and "2021" in out["text"]
def test_an_intern_goal_written_on_one_line(monkeypatch, data):
TEXTS["eva.md"] = "Eva Biela\n\nIAESTE Intern Summer 2023, two months\n\nGoal: Help with the [Hate Speech Project](/topics/hs)\n"
out = U.intern_overview("Eva Biela")
assert "pobyt IAESTE Intern Summer 2023" in out["text"] and "- Help with the Hate Speech Project" in out["text"]
def test_a_work_read_twice_keeps_the_copy_with_the_register_link():
old = {"title": "A", "year": 2024, "url": None, "opponents": ["Malý, Igor"]}
new = {"title": "A", "year": 2024, "url": "https://opac.test/a", "opponents": []}
assert U._better_copy(old, new) == {"title": "A", "year": 2024, "url": "https://opac.test/a", "opponents": ["Malý, Igor"]}
assert U._better_copy(new, old)["url"] == "https://opac.test/a"
assert U._better_copy(None, old) is old

View File

@ -22,7 +22,8 @@ BRANCH = re.compile(r"^(?:unified\.|combined\.|crzp\.answer|crzp\.part|wiki\.del
REFUSAL = re.compile(r"nie je uveden|nie je v podkladoch|v podkladoch nie|taky udaj nie je|nenasl|nemam|nepodarilo|"
r"neexist|nie je zaznamenan|nie su zaznamenan|nemozem|neviem|ziadn|nie je dostupn|upresn|ktor\w+ mysli|"
r"nie je mozne|nepotvrdzujem|neuvadza|nie je zname|nie je evidovan|odpovedam len|nie je doloz|"
r"skontroluj meno|uved cele meno|nie je isté|nie je iste|nema v podkladoch|nemaju v podkladoch")
r"skontroluj meno|uved cele meno|nie je isté|nie je iste|nema v podkladoch|nemaju v podkladoch|"
r"klucove slovo [^.;]{1,60}? nema\b|\bnemaju\b|nespomina|nesplna|v podkladoch nie su")
def fold(text: str | None) -> str:
@ -60,7 +61,7 @@ def check(case: dict, result: dict) -> dict:
for phrase in expect.get("none") or []:
checks[f"neobsahuje: {phrase}"] = fold(phrase) not in text
if expect.get("number") is not None:
checks[f"číslo {expect['number']}"] = bool(re.search(rf"(?<![\d.,]){expect['number']}(?![\d.,])", answer))
checks[f"číslo {expect['number']}"] = bool(re.search(rf"(?<![\d.,]){expect['number']}(?![\d]|[.,]\d)", answer))
return checks

View File

@ -247,6 +247,42 @@ def _one_person(question: str) -> dict | None:
return {"name": matches[0]["name"], "input": matches[0].get("input") or matches[0]["name"]}
def _people(question: str) -> list[str]:
"""The ZP Wiki people a question names (several), in their order."""
from tools.answers.planning.question_plan import planning_catalog
from tools.rag.common import DB_FILE
from tools.retrieval.person_names import resolve_person_names
try:
resolution = resolve_person_names(question, planning_catalog(DB_FILE) or [])
except Exception:
return []
if resolution.get("status") != "ok":
return []
return list(dict.fromkeys(m["name"] for m in resolution.get("matches") or []))
def record_answer(question: str, named: dict | None) -> dict | None:
"""Questions a ZP Wiki profile answers alone, by code (tools/answers/presentation/unified.py): where the
person's record is, which lines of it name a topic, a keyword (tag) condition of a work title, and two people's
keywords or study starts."""
from tools.answers.presentation import unified as U
low = normalized(question)
if named:
person = named["name"]
if not (U.catalog()["people"].get(person) or {}).get("url"):
return None
if U.PERSON_TOPIC_Q.search(low):
return U.person_topic(person, question)
if U.PROFILE_Q.search(low):
return U.profile(person)
if U.KEYWORD_Q.search(low) and U.TITLE_Q.search(low):
return U.keyword_title(person, question)
return None
if U.SHARED_KEYWORD_Q.search(low) or U.WHICH_OF_Q.search(low) or U.SHARED_START_Q.search(low):
return U.pair_answer(question, _people(question))
return None
def ellipsis(question: str, previous: dict | None) -> str | None:
"""The full question behind a short follow-up about another person: "a Ján Pták?" after
"Kto je vedúci práce Jakuba Schwarca?" -> "Kto je vedúci práce Ján Pták?"; "a Ján Pták by mohol?"
@ -294,6 +330,27 @@ SAME_SUPERVISOR = re.compile(r"\b(?:rovnak\w*|toho\s+ist\w*|ten\s+ist\w*|spolocn
# "práce študentov, ktorých viedol X": X as the supervisor of others, not X's own theses
STUDENTS_OF = re.compile(r"\bstudent\w*\b[^?]*\bktor\w*\s+(?:viedol|viedla|vedie|vedu)\b")
CONTACT = re.compile(r"\b(?:e[\s-]?mail\w*|mailov\w*\s+adres\w*|telefon\w*|tel\.?\s+cisl\w*|kontaktn\w*|kontakt\s+na)\b")
# Other data about a person the records never hold ("Koľko zarába X?", "Kde býva X?", "Akú známku dostal X?", "Koľko
# bodov získal X pri obhajobe?", "V akej miestnosti prebiehala obhajoba X?"): the wiki and the register describe works
# only. Technical facts of a work (GPU, RAM, an IP address) may be recorded and are not refused here.
NOT_RECORDED = [
(re.compile(r"\b(?:zarab\w*|zarobi\w*|plat|platu|platom|platy|platov|mzd\w*|vyplat\w*)\b"),
"Údaje o plate ani príjme"),
(re.compile(r"\bkde\s+(?:byva|byval\w*|zije|zil|zila|byvaju)\b(?!\s+(?:ulozen|umiestnen|nasaden|zverejnen|dostupn|spusten)\w*)|\bbydlisk\w*|\btrval\w*\s+pobyt\w*|"
r"\badres\w*\s+(?:bydlisk\w*|trval\w*|domov\w*)"), "Adresa ani bydlisko"),
(re.compile(r"\bznamk\w*|\bbod(?:y|ov|mi)?\s+(?:pri|za|z|na)\s+obhaj\w*|\b(?:kolko|ake|aky)\s+bod\w*[^?]*\bobhaj\w*|"
r"\bmiestnost\w*[^?]*\bobhaj\w*|\bobhaj\w*[^?]*\bmiestnost\w*|\bprotokol\w*[^?]*\bobhaj\w*|"
r"\bcisl\w*\s+protokol\w*"), "Známka, body, miestnosť ani protokol obhajoby"),
]
# What the register's list of a person's works answers (works, titles, topics, years, school, roles, sources)
LISTED_FACTS = re.compile(r"\b(?:ake|ktore)\s+(?:prace|projekty|zaverecne\s+prace)\b|\bprace\s+(?:robil|robila|ma|mal|mala)\b|"
r"\b(?:nazov|nazvom|nazvu|nazyva\w*|vola)\b|\bo\s+com\b|\b(?:tem\w*|zdroj\w*|odkaz\w*|kedy|rok\w*|student\w*|"
r"skol\w*|univerzit\w*|fakult\w*|obhaj\w*|ukonc\w*|typ\w*|ved\w*|vied\w*|opon\w*|konzult\w*|skolitel\w*)\b")
# "Aké výsledky dosiahol X?", "Čo dosiahol X?"
RESULTS_Q = re.compile(r"\bvysledk\w*\b[^?]*\b(?:dosiah\w*|ma|mal|mala|mali)\b|\b(?:dosiah\w*)\b[^?]*\bvysledk\w*|"
r"^\W*(?:a\s+)?co\s+dosiah\w*")
# "Na čom všetkom pracoval X?", "Čo všetko robil X?"
ALL_WORKS_Q = re.compile(r"\bna\s+com\s+(?:vsetkom\s+)?(?:pracoval\w*|robil\w*|pracuje|robi)\b|\bco\s+vsetko\s+(?:robil\w*|riesil\w*)")
# A meeting is asked: "stretnutie", "naposledy sa stretol s vedúcim"
MEETING_Q = re.compile(r"\b(?:stretnut\w*|stret(?:ol|la|li|lo)\w*|stretav\w*)\b")
LATEST_Q = re.compile(r"\b(?:posledn\w*|naposledy|najnov\w*)\b")
@ -1741,6 +1798,10 @@ def _answer(question: str, *, engine: str, limit: int, context_token: str | None
both = _two_answers(question, parts, engine=engine, limit=limit, complete=complete, deliver=deliver)
if both is not None:
return both
record = None if (previous or {}).get("options") else record_answer(question, named)
if record: # "Kde v ZP Wiki nájdem záznam o osobe X?", "Majú osoby A a B spoločné kľúčové slovo nlp?"
text = record["text"] + ("\n\nZdroje: " + ", ".join(record["urls"]) if record.get("urls") else "")
return _with_token(_ok(question, engine, text, record.get("urls") or [], {}), question=question)
newest = _newest_of(question, low, previous, engine)
if newest is not None: # "a ktorý z nich je najnovší?": chosen from the people just listed
return newest
@ -1763,6 +1824,12 @@ def _answer(question: str, *, engine: str, limit: int, context_token: str | None
who = U.spelled((named or {}).get("name") or supervisor)
return _with_token(_ok(question, engine, f"Kontaktné údaje osoby {who} v podkladoch nie sú; ZP Wiki a "
"register záverečných prác uvádzajú len údaje o prácach.", [], {}), question=question)
unrecorded = next((label for pattern, label in NOT_RECORDED if pattern.search(low)), None) \
if named or supervisor else None
if unrecorded: # "Koľko zarába X?", "Akú známku dostal X?": not in the records (no work list instead)
who = U.spelled((named or {}).get("name") or supervisor)
return _with_token(_ok(question, engine, f"{unrecorded} osoby {who} v podkladoch nie sú; ZP Wiki a register "
"záverečných prác uvádzajú len údaje o prácach.", [], {}), question=question)
if not named and not supervisor and not (previous or {}).get("options"):
# tags, categories, the most common topics and the start of studies come from the wiki's own metadata:
# complete, counted by code, and never sent to CRZP (CRZP has no ZP Wiki tags)
@ -2030,6 +2097,28 @@ def compose(asked: str, question: str, engine: str, wiki: dict, part: dict | Non
return result
def _rejected_student(low: str, wiki: dict, person: str | None) -> bool:
"""The wiki's answer about a ZP Wiki student was rejected and the question is not one the register's work list
answers (works, titles, years, roles, sources)."""
from tools.answers.presentation import unified as U
return bool(person and wiki.get("status") == "error" and not LISTED_FACTS.search(low)
and (U.catalog()["people"].get(person) or {}).get("person_kind") in ("student", "intern"))
def _from_records(question: str, engine: str, low: str, wiki: dict, part: dict | None, person: str) -> dict | None:
""""Aké výsledky dosiahol X?", "Na čom všetkom pracoval X?" after a rejected wiki answer: the wiki's own records,
by code (no model); None for any other question."""
from tools.answers.presentation import unified as U
works = U.person_works(person, (part or {}).get("rows"))
out = (U.results_overview(person, works) if RESULTS_Q.search(low)
else U.works_list(person, works) if ALL_WORKS_Q.search(low) else None)
if not out:
return None
text = out["text"] + ("\n\nZdroje: " + ", ".join(out["urls"]) if out.get("urls") else "")
return _with_token(_ok(question, engine, text, out.get("urls") or [], {"index_version": wiki.get("index_version")}),
question=question)
def _unified(asked, question, engine, wiki, wiki_ok, part, person, wiki_context, plan) -> dict | None:
"""The answer of a question about one person, a supervisor's students or two people, built from the
records of both sources (tools/answers/presentation/unified.py); None leaves the general composition."""
@ -2231,7 +2320,8 @@ def _compose(asked: str, question: str, engine: str, wiki: dict, part: dict | No
if part is None or wiki.get("status") == "ambiguous" and part["mode"] != "explicit":
# (a wiki clarification such as "Uveď meno študenta" yields to a question CRZP answers as a whole)
if wiki.get("accepted_for_delivery") is not True:
return wiki
return (_from_records(question, engine, low, wiki, part, person) if _rejected_student(low, wiki, person)
else None) or wiki
if wiki_ok:
body, urls = split_sources(wiki["answer"])
head, items, tail, general = wiki_items(body, urls or wiki.get("source_urls") or [])
@ -2243,6 +2333,10 @@ def _compose(asked: str, question: str, engine: str, wiki: dict, part: dict | No
return _with_token(result, wiki_context=wiki_context, question=question, page=page_id,
entities=[entity(item, i) for i, item in enumerate(shown, 1)])
return _with_token(wiki, wiki_context=wiki_context, question=question)
if part is not None and part["mode"] == "person" and _rejected_student(low, wiki, person):
# The wiki's answer was rejected ("Aké výsledky dosiahol X?", a detail of the work): the register's list of the
# person's works answers another question. The wiki's own records answer some by code; else the failure.
return _from_records(question, engine, low, wiki, part, person) or wiki
# Different works in the two sources and the question names none: ask which one.
if person and part["mode"] == "person" and (METHODS.search(low) or ABOUT.search(low)):
options = _work_options(person, part, low)

View File

@ -252,6 +252,21 @@ def results_of(person: str, heading: str | None, limit: int = 2) -> list[str]:
return out
def results_overview(person: str, works: list[dict], limit: int = 3) -> dict | None:
""""Aké výsledky dosiahol X?": the newest recorded results of each of the person's wiki works, newest work first
(the records' own points, no model)."""
blocks = []
for work in [w for w in works if w.get("source", "wiki") == "wiki" and w.get("heading")][:4]:
points = results_of(person, work["heading"], limit=limit)
if points:
blocks.append(f"**{work['heading']}**" + (f" „{work['title']}“" if work.get("title") else "") + ":\n"
+ "\n".join(f"- {p}" for p in points))
if not blocks:
return None
return {"text": f"Zaznamenané výsledky osoby {spelled(person)} (od najnovšej práce):\n\n" + "\n\n".join(blocks),
"urls": work_urls(person, works)}
def goals_of(person: str, heading: str | None, limit: int = 4) -> list[str]:
"""The work's goals: its assignment, else the points under a "Ciele…:"/"Zadanie:" label, else the
undated tasks before the first meeting ("Predbežné úlohy:")."""
@ -301,6 +316,15 @@ def crzp_work(row: dict) -> dict:
_registry: dict = {"stamp": 0.0, "by_author": {}}
def _better_copy(old: dict | None, new: dict) -> dict:
"""One work read in several searches: the copy with the record's link (a search with links stored it), its empty
fields filled from the other copy, so an answer from the local cache cites the register's record."""
if old is None:
return new
first, second = (new, old) if new.get("url") and not old.get("url") else (old, new)
return {**second, **{k: v for k, v in first.items() if v not in (None, "", [])}}
def registry_rows(person: str) -> list[dict]:
"""Works of the person at Technická univerzita v Košiciach already read from the register (local
cache, no request): every answer about a student joins them, also when this question did not
@ -316,8 +340,9 @@ def registry_rows(person: str) -> list[dict]:
if "technick" not in school or "kosiciach" not in school:
continue
for author in row.get("authors", []):
by_author.setdefault(" ".join(fold(display_name(author)).split()), {})[
(fold(row.get("title") or ""), row.get("year"))] = row
works = by_author.setdefault(" ".join(fold(display_name(author)).split()), {})
key = (fold(row.get("title") or ""), row.get("year"))
works[key] = _better_copy(works.get(key), row)
except Exception:
by_author = {}
_registry.update(stamp=time.time(), by_author=by_author)
@ -760,8 +785,9 @@ def intern_overview(person: str) -> dict | None:
return None
def section(*labels):
match = re.search(r"(?im)^\s*(?:" + "|".join(labels) + r")\s*:\s*\n+((?:\s*[-*].+\n?|[^\n#:]+\n?){1,6})", text)
if not match:
return []
if not match: # "Goal: Help with the [Hate Speech Project](/topics/hatespeech)" on one line
inline = re.search(r"(?im)^\s*(?:" + "|".join(labels) + r")\s*:[ \t]*(\S[^\n]*)$", text)
return [re.sub(r"\[([^\]]+)\]\([^)]*\)", r"\1", inline.group(1)).strip()] if inline else []
lines = [re.sub(r"^\s*[-*]\s*", "", l).strip() for l in match.group(1).splitlines()]
return list(dict.fromkeys(l for l in lines if l))[:4]
stay = re.search(r"(?i)\b(ERASMUS|IAESTE)[^\n]*", text)
@ -1751,3 +1777,210 @@ def anchor_sentence(person: str) -> str | None:
works = [w for w in person_works(person) if not w.get("unconfirmed")]
main = next((w for w in works if w["type"] in THESES), works[0] if works else None)
return f"{spelled(person)} pracuje na {describe(main, case=2)}." if main else None
# ------------------------------------------------------------------ a person's record, topics and keywords (tags)
# "Kde v ZP Wiki nájdem záznam o osobe X?", "Nájdi dokument o osobe X."
PROFILE_Q = re.compile(r"\bkde\b[^?]*\b(?:najdem|najst|najdes)\b[^?]*\b(?:zaznam|dokument|profil|strank)\w*"
r"|\b(?:najdi|vyhladaj|ukaz)\w*\s+(?:mi\s+)?(?:zaznam|dokument|profil|strank)\w*\s+(?:o\s+)?osob\w*")
# "Ktorý záznam v ZP Wiki spája osobu X s témou „Y“?", "Ktorý dokument alebo študent súvisí s témou Y a osobou X?",
# "Ktorá stáž osoby X súvisela s témou Y?"
PERSON_TOPIC_Q = re.compile(r"\bspaja\s+osob\w*\b[^?]*\bs\s+temou\b|\bsuvis\w*\s+s\s+temou\b[^?]*\bosob\w*"
r"|\bstaz\w*\s+osob\w*[^?]*\bsuvis\w*\s+s\s+temou\b")
TOPIC_IN_Q = re.compile(r"\bs\s+temou\s+(?P<topic>.+?)(?=\s+a\s+osob\w*\b|\s*[?.!]?\s*$)")
# "kľúčové slovo nlp", "s kľúčovým slovom Raspberry Pi", "spoločné kľúčové slovo ir"
KEYWORD_Q = re.compile(r"\bklucov\w*\s+slov\w*\s+(?P<kw>.+?)(?=\s+(?:pri|a|v\s+roku|s|u)\s|\s*[?.!,;:]|\s*$)")
def _folded_slice(text: str, pattern: re.Pattern, group: str) -> str | None:
"""The original words of a pattern matched on the folded text ("Hate Speech" for "s temou hate speech")."""
from tools.answers.planning.noise import fold_chars
match = pattern.search(fold_chars(text))
if not match:
return None
return text[match.start(group):match.end(group)].strip(" „“\"'")
def asked_keyword(question: str) -> str | None:
return _folded_slice(question, KEYWORD_Q, "kw")
def page_text(person: str) -> str:
info = catalog()["people"].get(person) or {}
return "\n".join(page_chunks(info.get("source_document") or ""))
def tags_of(person: str) -> list[str]:
return next((p["tags"] for p in wiki_pages() if p["name"] == person), [])
def has_keyword(person: str, keyword: str) -> bool:
"""A tag of the profile is the keyword (case, diacritics, spaces and hyphens aside): "hate speech" is "hatespeech"."""
key = re.sub(r"[\s\-_]+", "", normalized(keyword))
return bool(key) and any(re.sub(r"[\s\-_]+", "", normalized(t)) == key for t in tags_of(person))
def _word_fits(asked: str, word: str) -> bool:
"""The same word up to its case, or (six letters or more) one misspelled letter ("PagReank", "infomrácií")."""
from tools.retrieval.person_names import _distance
return (word == asked or len(asked) >= 5 and word.startswith(asked) or len(asked) >= 6 and word.startswith(asked[:-2])
or len(asked) >= 6 and abs(len(word) - len(asked)) <= 1 and _distance(asked, word) <= 1)
def topic_lines(person: str, topic: str, limit: int = 3) -> list[tuple[str | None, str]]:
"""(work heading, line) of the profile lines that name the topic, in the order of the page."""
asked = normalized(topic).split()
if not asked:
return []
found, heading = [], None
for raw in page_text(person).splitlines():
line = raw.strip()
head = re.match(r"^#+\s*(.+?)\s*#*$", line)
if head:
heading = head.group(1).strip()
continue
words = normalized(line).split()
if any(all(_word_fits(a, w) for a, w in zip(asked, words[i:i + len(asked)]))
for i in range(len(words) - len(asked) + 1)):
shown = re.sub(r"\[([^\]]+)\]\([^)]*\)", r"\1", line).lstrip("-*# []x").strip()
if shown and all(shown != s for _, s in found):
found.append((heading, shown[:220]))
if len(found) >= limit:
break
return found
def profile(person: str) -> dict | None:
""""Kde v ZP Wiki nájdem záznam o osobe X?": the profile page."""
info = catalog()["people"].get(person) or {}
if not info.get("url"):
return None
kind = "stážist" + ("ka" if female(spelled(person)) else "a") if info.get("person_kind") == "intern" \
else "študent" + ("ka" if female(spelled(person)) else "")
return {"text": f"Záznam o osobe {spelled(person)} ({kind} v ZP Wiki) je na stránke {info['url']}.",
"urls": [info["url"]]}
def person_topic(person: str, question: str) -> dict | None:
""""Ktorý záznam spája osobu X s témou Y?": the profile lines naming the topic, or that it names none."""
topic = _folded_slice(question, TOPIC_IN_Q, "topic")
info = catalog()["people"].get(person) or {}
if not topic or not info.get("url"):
return None
lines = topic_lines(person, topic)
tagged = has_keyword(person, topic)
if not lines and not tagged:
return {"text": f"V zázname osoby {spelled(person)} v ZP Wiki sa téma „{topic}“ nespomína.", "urls": [info["url"]]}
heads = list(dict.fromkeys(h for h, _ in lines if h))
where = f" v zázname {join(heads)}" if heads else ""
text = f"Téma „{topic}“ sa v ZP Wiki spája s osobou {spelled(person)}{where}"
text += " (je aj medzi kľúčovými slovami profilu)" if tagged else ""
text += ":" if lines else "."
if lines:
text += "\n\n" + "\n".join(f"- „{line}“" for _, line in lines)
return {"text": text, "urls": [info["url"]]}
def work_years(person: str) -> dict[int, list[dict]]:
by_year: dict = {}
for work in person_works(person):
if work.get("year") and not work.get("unconfirmed"):
by_year.setdefault(work["year"], []).append(work)
return by_year
def _title_line(work: dict) -> str:
kind = (TYPES.get(work["type"]) or (work.get("heading") or "práca",))[0]
return kind + (f" ({work['year']})" if work.get("year") else "") + (f" „{work['title']}“" if work.get("title") else "")
def keyword_title(person: str, question: str) -> dict | None:
""""Aký je názov práce X, ak jej dokument obsahuje kľúčové slovo K?", "… v roku 2026 s kľúčovým slovom nlp":
the condition is checked; a work only of the asked year."""
keyword = asked_keyword(question)
info = catalog()["people"].get(person) or {}
if not keyword or not info.get("url"):
return None
urls = [info["url"]]
if not has_keyword(person, keyword):
tags = tags_of(person)
return {"text": f"Profil osoby {spelled(person)} kľúčové slovo „{keyword}“ nemá"
+ (f"; jeho kľúčové slová sú: {', '.join(tags)}." if tags else "."), "urls": urls}
years = [int(y) for y in re.findall(r"\b((?:19|20)\d{2})\b", question)]
works = [w for w in person_works(person) if not w.get("unconfirmed") and w.get("title")]
chosen = [w for w in works if not years or w.get("year") in years]
if not chosen:
listed = "; ".join(_title_line(w) for w in works) or "bez názvu"
return {"text": f"Kľúčové slovo „{keyword}“ profil osoby {spelled(person)} má, prácu z roku "
f"{join([str(y) for y in years])} však v zázname nemá. Jej práce: {listed}.", "urls": urls}
lines = "\n".join(f"- {_title_line(w)}" for w in chosen)
return {"text": f"Profil osoby {spelled(person)} má kľúčové slovo „{keyword}“. "
+ ("Práca" if len(chosen) == 1 else "Práce") + (f" z roku {join([str(y) for y in years])}" if years else "")
+ f":\n\n{lines}", "urls": urls}
# Two people: "Majú osoby A a B spoločné kľúčové slovo nlp?", "Ktorá z osôb A a B má kľúčové slovo K a prácu z roku Y?",
# "Aký spoločný rok začiatku štúdia majú osoby A a B?"
SHARED_KEYWORD_Q = re.compile(r"\b(?:spolocn|rovnak)\w*\s+klucov\w*\s+slov\w*")
WHICH_OF_Q = re.compile(r"\bktor\w*\s+z\s+(?:osob|nich|tychto\s+osob)\b")
SHARED_START_Q = re.compile(r"\b(?:spolocn|rovnak)\w*\s+rok\w*\s+zaciat\w*\s+stud\w*"
r"|\brok\w*\s+zaciat\w*\s+stud\w*[^?]*\bprepojen\w*")
def pair_answer(question: str, names: list[str]) -> dict | None:
"""Two ZP Wiki people compared on their keywords (tags), work years or study start, by code."""
low = normalized(question)
people = [n for n in names if (catalog()["people"].get(n) or {}).get("url")]
if len(people) != 2 or len(set(people)) != 2:
return None
a, b = people
urls = [catalog()["people"][n]["url"] for n in people]
keyword = asked_keyword(question)
if SHARED_KEYWORD_Q.search(low):
if not keyword or re.search(r"\b(?:ake|ktore)\s+(?:spolocn|rovnak)\w*\s+klucov", low):
shared = [t for t in tags_of(a) if any(normalized(t) == normalized(u) for u in tags_of(b))]
text = (f"Spoločné kľúčové slová osôb {spelled(a)} a {spelled(b)}: {', '.join(shared)}." if shared
else f"Osoby {spelled(a)} a {spelled(b)} nemajú spoločné kľúčové slovo.")
return {"text": text, "urls": urls}
has = {n: has_keyword(n, keyword) for n in people}
if all(has.values()):
text = f"Áno, kľúčové slovo „{keyword}“ majú obe osoby: {spelled(a)} aj {spelled(b)}."
elif any(has.values()):
yes, no = (a, b) if has[a] else (b, a)
text = (f"Nie, spoločné kľúčové slovo „{keyword}“ nemajú: má ho len {spelled(yes)}; {spelled(no)} ho nemá"
f" (kľúčové slová: {', '.join(tags_of(no)) or 'žiadne'}).")
else:
text = f"Nie, kľúčové slovo „{keyword}“ nemá ani {spelled(a)}, ani {spelled(b)}."
return {"text": text, "urls": urls}
if WHICH_OF_Q.search(low) and keyword:
years = [int(y) for y in re.findall(r"\b((?:19|20)\d{2})\b", low)]
fits, notes = [], []
for n in people:
tagged = has_keyword(n, keyword)
dated = [w for y in years for w in work_years(n).get(y, [])] if years else []
if tagged and (dated or not years):
fits.append((n, dated))
else:
missing = [] if tagged else [f"nemá kľúčové slovo „{keyword}“"]
if years and not dated:
missing.append(f"nemá prácu z roku {join([str(y) for y in years])}")
notes.append(f"{spelled(n)} {' a '.join(missing)}")
cond = f"kľúčové slovo „{keyword}“" + (f" a práca z roku {join([str(y) for y in years])}" if years else "")
if not fits:
return {"text": f"Žiadna z osôb {spelled(a)} a {spelled(b)} nespĺňa obe podmienky ({cond}): "
+ "; ".join(notes) + ".", "urls": urls}
lines = [f"{spelled(n)}" + (": " + "; ".join(_title_line(w) for w in dated) if dated else "") for n, dated in fits]
head = "Obe osoby spĺňajú" if len(fits) == 2 else "Podmienky spĺňa"
text = f"{head} podmienky ({cond}): " + ", ".join(lines) + "."
return {"text": text + (" " + "; ".join(notes) + "." if notes else ""), "urls": urls}
if SHARED_START_Q.search(low):
years = {n: (catalog()["people"].get(n) or {}).get("start_year") for n in people}
missing = [n for n in people if not years[n]]
if missing:
return {"text": " ".join(f"Rok začiatku štúdia osoby {spelled(n)} v podkladoch nie je uvedený." for n in missing),
"urls": urls}
if str(years[a]) == str(years[b]):
return {"text": f"Áno, {spelled(a)} aj {spelled(b)} začali študovať v roku {years[a]}.", "urls": urls}
return {"text": f"Nie, spoločný rok začiatku štúdia nemajú: {spelled(a)} začal{ending(a)} študovať v roku "
f"{years[a]}, {spelled(b)} v roku {years[b]}.", "urls": urls}
return None

View File

@ -145,7 +145,7 @@ def name_variants(name: str) -> list[str]:
# 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 = {"stamp": 0.0, "by_first": {}, "first_of": {}, "by_last": {}}
_known_lock = threading.Lock()
KNOWN_REFRESH = 1800
MAX_KNOWN = 3
@ -158,7 +158,7 @@ def _known_index() -> tuple[dict, dict]:
if time.time() - _known["stamp"] > KNOWN_REFRESH:
with _known_lock:
if time.time() - _known["stamp"] > KNOWN_REFRESH:
by_first, first_of, seen = {}, {}, set()
by_first, first_of, by_last, seen = {}, {}, {}, set()
try:
from tools.crzp.fetch import store
from tools.crzp.source.parse import display_name
@ -172,15 +172,22 @@ def _known_index() -> tuple[dict, dict]:
continue
seen.add(key)
by_first.setdefault(words[0], []).append((words, shown))
by_last.setdefault(words[-1], []).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)
by_first, first_of, by_last = {}, {}, {}
_known.update(stamp=time.time(), by_first=by_first, first_of=first_of, by_last=by_last)
return _known["by_first"], _known["first_of"]
def _known_surnames() -> dict:
"""{folded surname: [(folded words, display name)]} of the same cache (built with _known_index)."""
_known_index()
return _known["by_last"]
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."""
@ -226,6 +233,17 @@ def known_names(typed: str) -> dict:
key = " ".join(known)
if key not in scored or score < scored[key][0]:
scored[key] = (score, shown)
if not scored:
# "jakb smetanka": the surname (or a case of it) is known and the first name is one letter away
from tools.retrieval.person_names import _distance, name_token_variants, normalize as fold_name
surnames = {last, *(" ".join(fold_name(f).split()) for f in word_forms(last))}
for surname in surnames:
for known, shown in _known_surnames().get(surname, ()):
if len(known) != len(words) or known[1:-1] != words[1:-1] or len(words[0]) < 4:
continue
if min((_distance(words[0], f) for f in name_token_variants(known[0])
if abs(len(f) - len(words[0])) <= 1), default=2) == 1:
scored.setdefault(" ".join(known), (10, shown))
if not scored:
return empty
best = min(score for score, _ in scored.values())

View File

@ -141,6 +141,7 @@ def crzp(monkeypatch):
monkeypatch.setattr(A.graph, "project", lambda rows: False)
from tools.crzp.answering import names as N
monkeypatch.setattr(N, "_known_index", lambda: ({}, {})) # no local register cache unless a test gives one
monkeypatch.setattr(N, "_known_surnames", lambda: {})
A._cache.clear()
state["no_model"] = lambda messages, **kw: (_ for _ in ()).throw(RuntimeError("no model"))
return state
@ -1010,13 +1011,15 @@ def _known(monkeypatch, *shown):
"""A local register cache holding these names (names.known_names)."""
from tools.crzp.answering import names as N
from tools.retrieval.person_names import name_token_variants, normalize
by_first, first_of = {}, {}
by_first, first_of, by_last = {}, {}, {}
for name in shown:
words = normalize(name).split()
by_first.setdefault(words[0], []).append((words, name))
by_last.setdefault(words[-1], []).append((words, name))
for form in name_token_variants(words[0]):
first_of.setdefault(form, set()).add(words[0])
monkeypatch.setattr(N, "_known_index", lambda: (by_first, first_of))
monkeypatch.setattr(N, "_known_surnames", lambda: by_last)
def test_known_names_read_cases_and_one_misspelled_word(monkeypatch):
@ -1029,6 +1032,9 @@ def test_known_names_read_cases_and_one_misspelled_word(monkeypatch):
assert known_names("jan nocia")["typos"] == ["Ján Nociak", "Ján Nociar"] # two equally close names: both
assert known_names("Peter Smetnaka") == {"exact": False, "forms": [], "typos": []} # the first name must fit
assert known_names("Jakub Smetnakova")["typos"] == [] # never two changed things at once
assert known_names("jakb smetanka")["typos"] == ["Jakub Smetanka"] # the first name one letter away
assert known_names("Jakuba Smetanku")["forms"] == ["Jakub Smetanka"]
assert known_names("jakb smetnaka")["typos"] == [] # both words misspelled: no guess
def test_a_case_the_rules_miss_is_searched_under_the_known_name(crzp, monkeypatch):