spájanie wiki a CRZP

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ján Pták 2026-11-20 11:23:12 +01:00
parent 7806ec85a5
commit a232f7be40
10 changed files with 1192 additions and 28 deletions

View File

@ -517,6 +517,11 @@ def test_a_count_of_a_supervisors_works_by_year_goes_to_crzp():
assert query.people[0].name == "Daniel Hládek" and query.people[0].role == "supervisor" and query.people[0].canonical
def test_a_bare_defence_question_stays_the_wikis_and_a_richer_one_asks_the_register():
assert C.crzp_plan("Obhájil Ján Holp diplomovú prácu?", "Ján Holp") is None
assert C.crzp_plan("V ktorom roku obhájil Martin Jancura diplomovú prácu a kto ju viedol?", "Martin Jancura") is not None
def test_technologies_of_a_person_only_crzp_knows(monkeypatch):
from tools.crzp.answering import answer as A
from tools.crzp.answering.understand import Person, understand

View File

@ -0,0 +1,112 @@
"""A wiki set joined with the register, every asked fact of a work, a false school premise, the same opponent."""
import pytest
from tools.answers.presentation import unified as U
from tools.answers.verification.context_policy import normalized
from tools.retrieval.person_names import name_token_variants
def _row(kind, year, title, author, supervisor="Hládek, Daniel", opponent="Staš, Ján",
school="Technická univerzita v Košiciach"):
return {"title": title, "year": year, "work_type": kind, "authors": [author], "supervisors": [supervisor],
"opponents": [opponent], "school": school, "url": f"https://opac.test/{title[:3]}"}
WORKS = {
"Ana Nová": [{"type": "bachelor_thesis", "year": 2025, "title": "Chatbot", "source": "wiki", "heading": "Bakalárska práca 2025",
"row": _row("bachelor_thesis", 2025, "Chatbot", "Nová, Ana", opponent="Pleva, Matúš")}],
"Ben Starý": [{"type": "bachelor_thesis", "year": 2024, "title": "Dialóg", "source": "wiki", "heading": "Bakalárska práca 2024",
"row": _row("bachelor_thesis", 2024, "Dialóg", "Starý, Ben")}],
"Cyril Malý": [{"type": "diploma_project", "year": 2027, "title": "Agent", "source": "wiki", "heading": "Diplomový projekt"}],
}
PAGES = [{"name": n, "url": f"https://zp.test/{n.split()[1]}", "kind": "student", "start_year": y, "tags": ["chatbot"],
"categories": []} for n, y in (("Ana Nová", 2022), ("Ben Starý", 2021), ("Cyril Malý", 2022))]
@pytest.fixture
def data(monkeypatch):
monkeypatch.setattr(U, "wiki_pages", lambda: PAGES)
monkeypatch.setattr(U, "person_works", lambda person, rows=None: [dict(w) for w in WORKS.get(person, [])])
monkeypatch.setattr(U, "catalog", lambda: {"people": {p["name"]: p for p in PAGES}, "works": WORKS})
monkeypatch.setattr("tools.answers.presentation.names.spelled", lambda name: name)
monkeypatch.setattr(U, "genitive", lambda name: name)
monkeypatch.setattr(U, "units", lambda person: [])
def test_a_tag_set_keeps_the_type_year_role_and_the_excluded_person(data):
listed = U.set_join("Ktorí študenti s tagom chatbot obhájili bakalársku prácu v roku 2025 a kto im robil oponenta?")
assert "1 z 3" in listed["text"] and "Ana Nová" in listed["text"] and "oponent: Matúš Pleva" in listed["text"]
assert "Ben Starý" not in listed["text"] and "https://opac.test/Cha" in listed["urls"]
counted = U.set_join("Koľko študentov s tagom chatbot má v CRZP obhájenú bakalársku prácu?")
assert "2 z 3" in counted["text"]
excluded = U.set_join("Ktorí študenti s tagom chatbot obhájili bakalársku prácu, pri ktorej oponentom nebol Matúš Pleva?")
assert "Ben Starý" in excluded["text"] and "Ana Nová —" not in excluded["text"] and "nebol Matúš Pleva," in excluded["text"]
none = U.set_join("Ktorí študenti s tagom chatbot obhájili bakalársku prácu v roku 2025, pri ktorej oponentom nebol Matúš Pleva?")
assert none["text"].startswith("Žiadny z 3") and "Ana Nová má takú prácu, ale oponentom bol Matúš Pleva" in none["text"]
assert "https://opac.test/Cha" in none["urls"]
started = U.set_join("Kto bol oponentom bakalárskej práce študenta, ktorý začal študovať v roku 2021 a má tag chatbot?")
assert "Ben Starý" in started["text"] and "Ján Staš" in started["text"] and "Ana" not in started["text"]
def test_a_set_question_without_register_facts_or_about_one_person_is_not_joined(data):
assert U.set_join("Ktorí študenti majú tag chatbot a kto je ich vedúci?") is None
assert U.set_join("Má Ana Nová tag chatbot a kto jej oponoval?", "Ana Nová") is None
def test_every_asked_fact_of_a_work_is_answered(data):
works = WORKS["Ana Nová"]
low = normalized("Pre Anu Novú: názov bakalárskej práce, vedúci, oponent, rok obhajoby a škola.")
text = U.work_card("Ana Nová", works, low)["text"]
for part in ("„Chatbot“", "Vedúci: Daniel Hládek", "Oponent: Matúš Pleva", "Rok: 2025",
"Škola: Technická univerzita v Košiciach"):
assert part in text
assert U.work_card("Ana Nová", works, normalized("Kto bol oponentom bakalárskej práce Any Novej?")) is None
assert U.work_card("Ana Nová", works, normalized("Kedy mala Ana Nová posledné stretnutie a aké boli výsledky?")) is None
def test_a_school_the_thesis_is_not_from_is_corrected(data):
out = U.school_premise("Ana Nová", WORKS["Ana Nová"], "Prečo Ana Nová obhájila bakalársku prácu na Žilinskej univerzite?")
assert out["text"].startswith("Predpoklad otázky nesedí") and "Technická univerzita v Košiciach" in out["text"]
assert U.school_premise("Ana Nová", WORKS["Ana Nová"],
"Obhájila Ana Nová bakalársku prácu na Technickej univerzite v Košiciach?") is None
def test_students_with_the_same_opponent(data):
out = U.same_opponent("Ben Starý", normalized("Ktorí študenti mali pri bakalárskej práci rovnakého oponenta ako Ben Starý?"))
assert "Ján Staš" in out["text"] and "Ana Nová" not in out["text"]
def test_an_adjectival_surname_has_its_case_forms():
assert {"lindvaiho", "lindvaimu", "lindvaim"} <= name_token_variants("lindvai")
assert "horaniho" in name_token_variants("horani")
def test_wiki_students_met_by_a_role_person_of_the_register(data):
out = U.wiki_student_role("Kto viedol bakalársku prácu študenta zo ZP Wiki, ktorému v roku 2025 oponoval Matúš Pleva?")
assert "Ana Nová" in out["text"] and "viedol Daniel Hládek" in out["text"] and "https://opac.test/Cha" in out["urls"]
members = U.wiki_members("Koľko bakalárskych prác viedol Daniel Hládek v roku 2024 a ktorí z jeho študentov sú v ZP Wiki?")
assert "Ben Starý" in members["text"] and "Ana" not in members["text"]
checked = U.defended_years("Ana Nová", "Obhájila Ana Nová bakalársku prácu v roku 2025 a diplomovú v roku 2027?")
assert checked["text"].startswith("Nie celkom.") and "v roku 2025" in checked["text"] and "v registri nemá" in checked["text"]
def test_one_thesis_in_two_records_and_a_project_defended_as_the_thesis(monkeypatch):
wiki = {"Eva Biela": [
{"type": "bachelor_thesis", "year": 2025, "title": None, "source": "wiki", "heading": "Bakalárska práca 2025"},
{"type": "bachelor_thesis", "year": 2024, "title": "Korekcia textu", "source": "wiki", "heading": "Bakalárska práca 2024"},
{"type": "research_project", "year": 2021, "title": "Dialógový systém pomocou RASA framework", "source": "wiki",
"heading": "Vedecký projekt 2021"}]}
rows = [_row("bachelor_thesis", 2024, "Korekcia textu", "Biela, Eva", opponent="Pleva, Matúš"),
_row("bachelor_thesis", 2025, "Korekcia textu", "Biela, Eva", opponent="Sopkovič, Kristián"),
_row("diploma_thesis", 2023, "Slovenský dialógový systém pomocou RASA frameworku", "Biela, Eva")]
monkeypatch.setattr(U, "catalog", lambda: {"people": {"Eva Biela": {"name": "Eva Biela"}}, "works": wiki})
monkeypatch.setattr(U, "registry_rows", lambda person: rows)
monkeypatch.setattr(U, "genitive", lambda name: name)
monkeypatch.setattr("tools.answers.presentation.names.spelled", lambda name: name)
works = U.person_works("Eva Biela")
opponent = U.roles("Eva Biela", works, normalized("Kto bol oponentom bakalárskej práce Evy Bielej?"))["text"]
assert "Kristián Sopkovič" in opponent and "(2025)" in opponent # the newer record, the register's year
thesis = U.roles("Eva Biela", works, normalized("Kto bol oponentom diplomovej práce Evy Bielej?"))["text"]
assert "Ján Staš" in thesis and "(2023)" in thesis
title = U.work_title("Eva Biela", works, normalized("Zhoduje sa názov diplomovej práce Evy Bielej v ZP Wiki s názvom v CRZP?"))
assert "v CRZP „Slovenský dialógový systém pomocou RASA frameworku“" in title["text"] and "nezhodujú" in title["text"]

72
test/rule_trace/report.py Normal file
View File

@ -0,0 +1,72 @@
"""Summary of a rule-trace run: pass rates and where the failures happen (place, branch, rule).
.venv/bin/python test/rule_trace/report.py RESULTS.jsonl [--md REPORT.md]
"""
from __future__ import annotations
import argparse
import collections
import json
import statistics
from pathlib import Path
def _rate(rows):
return f"{sum(r['pass'] for r in rows)}/{len(rows)} ({100 * sum(r['pass'] for r in rows) / max(1, len(rows)):.0f} %)"
def table(title: str, groups: dict, limit: int = 40) -> list[str]:
lines = [f"## {title}", "", "| skupina | prešlo | zlyhalo | príklady zlyhaní |", "|---|---|---|---|"]
for key, rows in sorted(groups.items(), key=lambda x: (-sum(not r["pass"] for r in x[1]), x[0]))[:limit]:
bad = [r["id"] for r in rows if not r["pass"]][:4]
lines.append(f"| {key} | {_rate(rows)} | {sum(not r['pass'] for r in rows)} | {', '.join(bad)} |")
return lines + [""]
def report(rows: list[dict]) -> str:
seconds = [r["seconds"] for r in rows if r.get("seconds")]
out = ["# Výsledok behu", "",
f"- otázok: {len(rows)}, prešlo: {_rate(rows)}",
f"- čas: medián {statistics.median(seconds) if seconds else 0} s, priemer "
f"{round(statistics.mean(seconds), 1) if seconds else 0} s, spolu {round(sum(seconds) / 3600, 2)} h", ""]
groups = {name: collections.defaultdict(list) for name in
("engine", "difficulty", "category", "template", "failure", "branch", "rule", "collision")}
for r in rows:
groups["engine"][r["engine"]].append(r)
groups["difficulty"][r.get("difficulty") or "-"].append(r)
groups["category"][r.get("category") or "-"].append(r)
groups["template"][r.get("template") or "-"].append(r)
if not r["pass"]:
place = (r.get("failure_point") or "?").split(":")[0]
groups["failure"][r.get("failure_point") or "?"].append(r)
groups["failure"]["(spolu) " + place].append(r)
groups["branch"][r.get("branch") or "-"].append(r)
for rule in (r.get("static") or {}).get("answer_type_rules") or []:
groups["rule"][rule].append(r)
groups["collision"]["kolízia 2+ pravidiel" if (r.get("static") or {}).get("collision") else "bez kolízie"].append(r)
out += table("Podľa nástroja", groups["engine"])
out += table("Podľa obťažnosti", groups["difficulty"])
out += table("Kde zlyhalo (miesto a dôvod)", {k: v for k, v in groups["failure"].items()}, limit=60)
out += table("Podľa vetvy, ktorá odpovedala", groups["branch"])
out += table("Podľa pravidla typu odpovede, ktoré na otázku sedí", groups["rule"])
out += table("Kolízie pravidiel", groups["collision"])
out += table("Podľa kategórie", groups["category"])
out += table("Podľa šablóny", groups["template"])
return "\n".join(out)
def main(argv=None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument("results")
parser.add_argument("--md")
args = parser.parse_args(argv)
rows = [json.loads(l) for l in Path(args.results).read_text(encoding="utf-8").splitlines() if l.strip()]
text = report(rows)
if args.md:
Path(args.md).write_text(text, encoding="utf-8")
print(text)
return 0
if __name__ == "__main__":
raise SystemExit(main())

132
test/rule_trace/run.py Normal file
View File

@ -0,0 +1,132 @@
"""Run a test set through the API and record, per question, the rules, the answer path and where it failed.
.venv/bin/python test/rule_trace/run.py --cases SET.json --out RESULTS.jsonl [--hours 4.25] [--resume]
[--only-failed OLD.jsonl] [--base http://localhost:8000]
Questions run one after another (nothing else may use the API meanwhile). Each row holds the static tags
(static_tags.py), the answer, the route of the backend (tools/answers/route_trace.py, read from
data/logs/answer_timings.jsonl), the checks and the failure point. The run stops after --hours and
continues with --resume.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import sys
import time
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
for path in (str(ROOT), str(Path(__file__).resolve().parent)):
if path not in sys.path:
sys.path.insert(0, path)
from scoring import check, failure_point, last_branch # noqa: E402
from static_tags import tags # noqa: E402
TIMINGS = ROOT / "data" / "logs" / "answer_timings.jsonl"
def _env(name: str) -> str:
from tools.evaluation.gold_set import _env as env
return env(name)
def ask(base: str, question: str, engine: str, token: str | None) -> dict:
body = {"query": question, "engine": engine, **({"context_token": token} if token else {})}
request = urllib.request.Request(base.rstrip("/") + "/answer", data=json.dumps(body, ensure_ascii=False).encode(),
headers={"Content-Type": "application/json", "X-API-Key": _env("SEARCH_API_KEY")})
with urllib.request.urlopen(request, timeout=300) as response:
return json.load(response)
def trace_of(question: str, offset: int) -> dict:
"""The timing record of this question: the last line written after `offset` with its hash."""
digest = hashlib.sha256(question.strip().encode()).hexdigest()[:12]
try:
with TIMINGS.open("rb") as handle:
handle.seek(offset)
lines = handle.read().decode("utf-8", "ignore").splitlines()
except OSError:
return {}
for line in reversed(lines):
try:
row = json.loads(line)
except ValueError:
continue
if row.get("q") == digest:
return row
return {}
def run_case(case: dict, base: str) -> dict:
token, result, steps = None, {}, []
started = time.time()
for question in [s.strip() for s in case["question"].split(" => ") if s.strip()]:
offset = TIMINGS.stat().st_size if TIMINGS.exists() else 0
t = time.time()
try:
result = ask(base, question, case["engine"], token)
except Exception as error: # a failed request is a failed case, never skipped
result = {"status": "request_error", "reason": repr(error)[:200], "answer": ""}
trace = trace_of(question, offset)
token = (result.get("conversation_context") or {}).get("token") or token
steps.append({"question": question, "status": result.get("status"), "reason": result.get("reason"),
"seconds": round(time.time() - t, 1), "route": trace.get("route") or [],
"notes": trace.get("notes") or {}, "parts": trace.get("steps") or {},
"model_calls": trace.get("model_calls"), "answer": (result.get("answer") or "")[:600]})
if result.get("status") == "request_error":
break
return {"result": result, "steps": steps, "seconds": round(time.time() - started, 1)}
def main(argv=None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--cases", required=True)
parser.add_argument("--out", required=True)
parser.add_argument("--base", default="http://localhost:8000")
parser.add_argument("--hours", type=float, default=4.25)
parser.add_argument("--resume", action="store_true")
parser.add_argument("--only-failed", help="results of an earlier run: ask again only its failed cases")
args = parser.parse_args(argv)
cases = json.loads(Path(args.cases).read_text(encoding="utf-8"))["cases"]
if args.only_failed:
failed = {json.loads(l)["id"] for l in Path(args.only_failed).read_text(encoding="utf-8").splitlines()
if l.strip() and not json.loads(l)["pass"]}
cases = [c for c in cases if c["id"] in failed]
out = Path(args.out)
done = set()
if args.resume and out.exists():
done = {json.loads(l)["id"] for l in out.read_text(encoding="utf-8").splitlines() if l.strip()}
deadline = time.time() + args.hours * 3600
todo = [c for c in cases if c["id"] not in done]
print(f"{len(todo)} otázok, limit {args.hours} h", flush=True)
with out.open("a" if args.resume else "w", encoding="utf-8") as handle:
for n, case in enumerate(todo, 1):
if time.time() > deadline:
print("Časový limit: zvyšok pokračuje s --resume.", flush=True)
break
static = tags(case["question"])
ran = run_case(case, args.base)
last = ran["steps"][-1] if ran["steps"] else {}
trace = {"route": last.get("route"), "notes": last.get("notes")}
checks = check(case, ran["result"])
point = failure_point(case, ran["result"], checks, trace)
row = {"id": case["id"], "engine": case["engine"], "category": case.get("category"),
"difficulty": case.get("difficulty"), "template": case.get("template"), "origin": case.get("origin"),
"question": case["question"], "pass": point is None, "failure_point": point,
"failed_checks": [k for k, v in checks.items() if not v], "branch": last_branch(last.get("route") or []),
"static": static, "seconds": ran["seconds"], "status": ran["result"].get("status"),
"reason": ran["result"].get("reason"), "answer": (ran["result"].get("answer") or "")[:2500],
"source_urls": (ran["result"].get("source_urls") or [])[:12], "steps": ran["steps"]}
handle.write(json.dumps(row, ensure_ascii=False) + "\n")
handle.flush()
print(f"{n:04d} {case['id']:<14} {case['engine']:<8} {'PASS' if row['pass'] else 'FAIL'} {ran['seconds']:>6}s "
f"{(point or '')[:70]}", flush=True)
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,78 @@
"""Checks of one answer and the place where it failed (planner, retrieval, check, source or content)."""
from __future__ import annotations
import re
import unicodedata
WIKI = "zp.kemt.fei.tuke.sk"
CRZP = "opac.crzp.sk"
BRANCH = re.compile(r"^(?:unified\.|combined\.|crzp\.answer|crzp\.part|wiki\.deliver)")
def fold(text: str | None) -> str:
return " ".join(unicodedata.normalize("NFKD", text or "").encode("ascii", "ignore").decode().lower().split())
def check(case: dict, result: dict) -> dict:
expect = case.get("expect") or {}
answer = result.get("answer") or ""
shown = answer + " " + " ".join(result.get("source_urls") or [])
text = fold(answer)
status = result.get("status")
allowed = expect.get("status") or ["ok"]
allowed = [allowed] if isinstance(allowed, str) else allowed
checks = {"status": status in allowed}
if expect.get("both_sources", True) and "ok" in allowed and status == "ok":
checks["zdroj ZP Wiki"] = WIKI in shown
checks["zdroj CRZP"] = CRZP in shown
for phrase in expect.get("all") or []:
checks[f"obsahuje: {phrase}"] = fold(phrase) in text
if expect.get("any"):
checks["obsahuje jedno z: " + " | ".join(expect["any"][:4])] = any(fold(p) in text for p in expect["any"])
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))
return checks
def failure_point(case: dict, result: dict, checks: dict, trace: dict) -> str | None:
"""The first place the answer went wrong, as a short label ("plánovač: ambiguous_work")."""
if all(checks.values()):
return None
route = trace.get("route") or []
notes = trace.get("notes") or {}
status, reason = result.get("status"), result.get("reason")
if status == "request_error":
return "spojenie: " + str(reason)[:60]
if not checks.get("status", True):
if status == "error":
fulfilment = notes.get("fulfilment") or {}
if reason == "answer_rejected" and fulfilment:
failed = [k for k in ("plan", "facts", "clear", "all_identified") if fulfilment.get(k) is False]
return "kontrola modelom: " + (",".join(failed) or "statuses=" + ",".join(fulfilment.get("statuses") or []))
return f"chyba: {reason}"
if status == "ambiguous":
return f"plánovač/upresnenie: {reason}"
if status == "no_answer":
return f"vyhľadávanie: {reason}"
return f"stav {status}: {reason}"
if checks.get("zdroj CRZP") is False:
plan = next((r for r in route if r.startswith("crzp.plan")), None)
return "CRZP nepoužité: " + (plan or "crzp.plan nevrátil plán (pravidlo ho vylúčilo)")
if checks.get("zdroj ZP Wiki") is False:
return "ZP Wiki nepoužitá: " + (last_branch(route) or "?")
return "obsah: " + (last_branch(route) or "?")
HELPERS = {"unified.person_works", "unified.supervisor_in"}
def last_branch(route: list[str]) -> str | None:
"""The branch that wrote the answer: a presentation branch first, then a combined branch, CRZP, the wiki."""
labels = [r.split("=")[0].split("!")[0] for r in route]
for prefix in ("unified.", "combined.", "crzp.answer", "crzp.part", "wiki.deliver"):
found = [l for l in labels if l.startswith(prefix) and l not in HELPERS]
if found:
return found[-1]
return None

View File

@ -0,0 +1,73 @@
"""Static tags of a question before it is asked: which rules (regexes) match it and what it contains.
The tags are attached to every case of a run, so a failure can be read next to the rules that
could have taken the question ("TITLE_Q and COMPARE both match: the title branch won").
"""
from __future__ import annotations
import re
import sys
from functools import lru_cache
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
# rules that each decide the type of the answer: two of them on one question are a collision
ANSWER_TYPE_RULES = {
"unified.TITLE_Q", "unified.COUNT_WORKS_Q", "unified.WHO_Q", "unified.DID_Q", "unified.WORKS_Q", "unified.ABOUT_Q",
"unified.TAG_Q", "unified.TOP_TOPICS_Q", "unified.STARTED_Q", "unified.TASKS_Q", "unified.METHODS_Q",
"combined.STUDY_START", "combined.CONTACT", "combined.SAME_SUPERVISOR", "combined.SUPERVISES", "combined.STUDENTS_OF",
"combined.EXPLAIN", "combined.NEWEST_OF", "combined.COMPARE", "combined.METHODS", "combined.WIKI_ONLY",
}
YEAR = re.compile(r"\b(?:19|20)\d{2}\b")
@lru_cache(maxsize=1)
def _rules() -> list[tuple[str, re.Pattern]]:
from tools.answers import combined
from tools.answers.presentation import unified
from tools.crzp.answering import understand
rules = []
for prefix, module in (("combined", combined), ("unified", unified), ("crzp", understand)):
for name, value in sorted(vars(module).items()):
if isinstance(value, re.Pattern) and name.isupper():
rules.append((f"{prefix}.{name}", value))
return rules
@lru_cache(maxsize=1)
def _catalog():
from tools.answers.planning.question_plan import planning_catalog
from tools.rag.common import DB_FILE
return planning_catalog(DB_FILE) or []
def tags(question: str) -> dict:
"""{"rules": [...], "answer_type_rules": [...], "collision": bool, "features": {...}} for one question
(a chain "a => b" is tagged by its last step, the earlier steps only add the chain length)."""
from tools.answers.presentation import unified
from tools.answers.verification.context_policy import normalized
from tools.retrieval.person_names import resolve_person_names
steps = [s.strip() for s in question.split(" => ") if s.strip()]
last = steps[-1] if steps else question
low = normalized(last)
hits = [name for name, rule in _rules() if rule.search(low) or rule.search(last)]
answer_type = sorted(h for h in hits if h in ANSWER_TYPE_RULES)
try:
resolution = resolve_person_names(" ".join(steps), _catalog())
people = sorted({m["name"] for m in resolution.get("matches") or []})
names_status = resolution.get("status")
except Exception:
people, names_status = [], "error"
features = {
"people": people, "names_status": names_status,
"years": sorted(set(YEAR.findall(" ".join(steps)))),
"work_types": unified.asked_types(normalized(" ".join(steps))),
"chain_steps": len(steps), "words": len(last.split()),
"count": bool(re.search(r"\bkolk\w*|\bpocet\b", low)),
"comparison": bool(re.search(r"\bporovn\w*|\brozdiel\w*", low)),
"condition": bool(re.search(r"\b(?:ak|okrem|nie\s+u|bez|ale\s+nie|zaroven|sucasne)\b", low)),
}
return {"rules": hits, "answer_type_rules": answer_type, "collision": len(answer_type) >= 2, "features": features}

View File

@ -66,11 +66,14 @@ EXPLICIT = re.compile(r"\b(?:crzp|registr\w*|register|celoslovensk\w*|na slovens
r"vsetkych|dalsich|slovensk\w+)\s+(?:vysok\w+\s+)?(?:skol|univerzit|fakult)\w*|mimo tuke|"
r"oponent\w*|oponoval\w*)\b")
NAMED_CRZP = re.compile(r"\b(?:crzp|registr\w*|register)\b") # the register itself is asked, not only opponents
NAMED_WIKI = re.compile(r"\b(?:zp\s*wiki|wiki\w*)\b") # the wiki asked too: "podľa registra a čo uvádza ZP Wiki"
METHODS = re.compile(r"\b(?:technolog\w*|nastroj\w*|metod\w*|pouziv\w*|pouzil\w*|vyuziv\w*|vyuzil\w*|framework\w*)\b")
ABOUT = re.compile(r"\b(?:o com|zhrn\w*|abstrakt\w*|ciel\w*)\b") # not "čomu sa venuje": the current work
# A question about a thesis (not "na čom pracuje", which CRZP's submitted works cannot answer).
THESIS = re.compile(r"\b(?:prac(?:a|e|u|i|ou|ach|ami)?|bakalar\w*|diplom\w*|dizerta\w*|habilita\w*|bp|dp|tem(?:a|u|y|ou)|"
r"oponent\w*|vedu\w*|skolitel\w*|abstrakt\w*|klucov\w*|tagy?)\b")
BARE_COMPLETION = re.compile(r"^(?:obhajil\w*|ukoncil\w*|dokoncil\w*)\s+(?:[^\W\d_]+\s+){1,3}"
r"(?:(?:bakalar|diplom|dizert)\w*\s+)?(?:prac\w*|bakalark\w*|diplomovk\w*)\W*$")
WIKI_CLARIFICATION_YIELDS = {"missing_subject", "unsupported_content_question", "unsupported_constraint",
"content_count_not_established"} # "the wiki cannot count this": CRZP counts it
# "Koľko prác obhájili na KEMT v roku 2024?": defended works of a school or department are CRZP's
@ -285,6 +288,7 @@ def named_back(question: str, previous: dict | None) -> str | None:
SUPERVISES = re.compile(r"\bkoho\s+(?:vedie|viedol|viedla|skoli\w*)|\bkomu\s+robi\s+veduc\w*|"
r"\b(?:akych|ktorych|kolkych|kolko)\s+studentov\b|\bstudent\w*\s+(?:pod\s+vedenim|ma|vedie)\b|"
r"\bpod\s+(?:sebou|vedenim)\b")
SAME_OPPONENT = re.compile(r"\b(?:rovnak\w*|toho\s+ist\w*|ten\s+ist\w*|spolocn\w*)\s+oponent\w*")
SAME_SUPERVISOR = re.compile(r"\b(?:rovnak\w*|toho\s+ist\w*|ten\s+ist\w*|spolocn\w*)\s+(?:veduc\w*|skolitel\w*)")
# "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")
@ -488,6 +492,22 @@ def wiki_profile(person: str) -> str:
# ------------------------------------------------------------------ CRZP part
def _canonical_person(query, person: str) -> None:
""""kto bol oponent bakalárky oleh poiansik": the wiki resolved the misspelled name, the register is searched
for the real one (a name read from the question that is close to the resolved person becomes that person)."""
from tools.retrieval.person_names import _distance, normalize as fold_name
target = fold_name(person).split()
def close(a, b):
return _distance(a, b) <= max(1, min(len(a), len(b)) // 3)
for item in query.people:
words = fold_name(item.name).split()
if words == target or len(words) != len(target):
continue
if all(close(a, b) for a, b in zip(words, target)) or all(close(a, b) for a, b in zip(words, target[::-1])):
item.name, item.canonical = person, True
def crzp_plan(question: str, person: str | None, complete=None, student: bool = True):
"""(mode, CrzpQuery) or None when CRZP adds nothing to this question."""
from tools.crzp.answering.understand import Person, understand
@ -496,7 +516,12 @@ def crzp_plan(question: str, person: str | None, complete=None, student: bool =
explicit = bool(EXPLICIT.search(low))
defended_scope = bool(DEFENDED.search(low) and not person and (
unit_in_question(question) or re.search(r"\b(?:univerzit\w*|fakult\w*|katedr\w*|skol\w*|tuke|stu|kemt|fei)\b", low)))
if WIKI_ONLY.search(low) and not explicit and not defended_scope:
# "V ktorom roku obhájil X diplomovú prácu?": the defence of a thesis is what the register records (a
# submitted, published thesis); the other wiki-only words (meetings, tasks, the start of studies) still keep CRZP out
# (the bare "Obhájil Ján Holp diplomovú prácu?" stays the wiki's: a record in the register is no proof of a defence)
gated = re.sub(r"\b(?:obhaj\w*|ukonc\w*|dokonc\w*|uspes\w*)\b", " ", low) if THESIS.search(low) \
and not BARE_COMPLETION.match(low) else low
if WIKI_ONLY.search(gated) and not explicit and not defended_scope:
return None
from tools.answers.presentation.unified import TAG_Q
if TAG_Q.search(low) and not RELATED.search(low): # a ZP Wiki tag or category, which CRZP does not have
@ -510,6 +535,12 @@ def crzp_plan(question: str, person: str | None, complete=None, student: bool =
other_school = query.school not in (None, "tuke") or explicit or bool(query.exclude_school)
if person and other_school and not query.from_model:
query = understand(question, complete=complete)
if person and query.people:
_canonical_person(query, person)
if query.target_role and len(query.people) > 1:
# "Kto bol naozaj oponentom …?": the asked role is unknown, a name given for it ("napíš, že oponentom bol
# Peter Novák") is a claim, never a search condition
query.people = [p for p in query.people if p.role != query.target_role] or query.people
if query.exclude_school and re.search(r"\baj\s+(?:na|v|vo|z|zo)\s+(?:inych|ostatnych|dalsich)\b", low) \
and re.search(r"\b(?:kemt\w*|tuke\w*|fei)\b", low):
query.exclude_school = None # "na KEMT a sú podobné práce aj na iných školách": both, not only the others
@ -656,7 +687,7 @@ def crzp_person_methods(question: str, query, complete=None) -> dict | None:
"intent": "methods", "person": name}
def crzp_comparison(query, complete=None, collaboration: bool = False) -> dict | None:
def crzp_comparison(query, complete=None, collaboration: bool = False, low: str = "") -> dict | None:
""""Porovnaj prácu Jána Ptáka a Samuela Furdu." when one of them is known only to CRZP: each person's
works as author (ZP Wiki works of a wiki person merged in), one table as for two wiki people."""
from tools.answers.presentation import unified as U
@ -675,7 +706,7 @@ def crzp_comparison(query, complete=None, collaboration: bool = False) -> dict |
name = known or display_name(rows[0]["authors"][0])
names.append(name)
rows_all.extend(rows)
out = U.comparison(names, collaboration=collaboration, crzp_rows=rows_all)
out = U.comparison(names, collaboration=collaboration, crzp_rows=rows_all, low=low)
if out is None:
return None
return {"mode": "explicit", "status": "ok", "text": out["text"] if isinstance(out, dict) else out,
@ -803,7 +834,7 @@ def _crzp_part(question: str, person: str | None, *, complete=None, student: boo
return related_part(query)
if mode == "explicit":
if COMPARE.search(low) and len(query.people) == 2 and not query.topics:
compared = crzp_comparison(query, complete, collaboration=bool(re.search(r"\bspolupr", low)))
compared = crzp_comparison(query, complete, collaboration=bool(re.search(r"\bspolupr", low)), low=low)
if compared is not None:
return compared
if (METHODS.search(low) and query.people and query.people[0].role in ("author", "any")
@ -812,6 +843,14 @@ def _crzp_part(question: str, person: str | None, *, complete=None, student: boo
methods = crzp_person_methods(question, query, complete)
if methods is not None:
return methods
if person and student and query.intent == "similar" and query.exclude_school == "tuke":
# "Kto na iných školách písal prácu na podobnú tému ako X?": X's own topics (not a namesake's work found
# outside TUKE), the works of the other schools
found = crzp_similar(person, complete=complete)
keep = [(i, r) for i, r in zip(found["items"], found["rows"]) if crzp.university(r) != TUKE] if found else []
if keep:
return {**found, "items": [i for i, _ in keep], "rows": [r for _, r in keep],
"urls": [r["url"] for _, r in keep if r.get("url")], "home_excluded": True}
result = crzp._answer_query(question, query, complete)
part = explicit_part(question, result)
if part is not None and query.people:
@ -1506,8 +1545,13 @@ def _subject_retry(question: str, result: dict, previous: dict | None) -> str |
person = previous.get("person") if isinstance(previous, dict) else None
if result.get("reason") != "missing_subject" or not person or previous.get("options") or _one_person(question):
return None
from tools.answers.presentation.unified import genitive
return re.sub(r"\s*\?*\s*$", "", question) + " " + genitive(person) + "?"
from tools.answers.presentation.unified import TYPES, asked_types, genitive
base = re.sub(r"\s*\?*\s*$", "", question)
kinds = [k for k in asked_types(normalized(previous.get("question") or "")) if k in TYPES]
if len(kinds) == 1 and not asked_types(normalized(question)):
# "… oponentom jeho diplomovky? => a kto bol vedúcim?": the work of the step before
return f"{base} {TYPES[kinds[0]][1]} {genitive(person)}?"
return base + " " + genitive(person) + "?"
LOST = {"missing_subject", "answer_rejected", "backend_timeout", "backend_unavailable", "model_unavailable",
@ -1628,6 +1672,13 @@ def _answer(question: str, *, engine: str, limit: int, context_token: str | None
if newest is not None: # "a ktorý z nich je najnovší?": chosen from the people just listed
return newest
from tools.answers.presentation import unified as U
joined = None if (previous or {}).get("options") else (
U.set_join(question, (named or {}).get("name")) or U.wiki_student_role(question)
or (U.defended_years(named["name"], question) if (named or {}).get("name") else None))
if joined: # "Ktorí študenti s tagom rag obhájili bakalársku prácu … a kto im robil oponenta?": the wiki set and
# the register's theses of its people, every condition of the question kept
text = joined["text"] + ("\n\nZdroje: " + ", ".join(joined["urls"]) if joined["urls"] else "")
return _with_token(_ok(question, engine, text, joined["urls"], {}), question=question)
supervisor = None if named else U.supervisor_in(question)
if supervisor and (U.WHO_Q.match(low) or bare_name(question, supervisor)):
# "Kto je Daniel Hládek?": a supervisor (no profile of his own), not a CRZP author or "unknown person"
@ -1955,7 +2006,8 @@ def _unified(asked, question, engine, wiki, wiki_ok, part, person, wiki_context,
question=question, page=page_id,
entities=[entity(item, i) for i, item in enumerate(shown, 1)])
# "Kto by mohol spolupracovať s X?", "Nájdi práce podobné práci X": the candidates, newest work first
if student and wiki_ok and (plan.get("intent") == "similar" or SIMILAR.search(low)) and not COMPARE_TWO(low):
if student and wiki_ok and (plan.get("intent") == "similar" or SIMILAR.search(low)) and not COMPARE_TWO(low) \
and not (part or {}).get("home_excluded"): # "na iných školách": the register's works, not the wiki's
body, urls = split_sources(wiki_text)
head, items, tail, general = wiki_items(body, urls or wiki.get("source_urls") or [])
if items:
@ -1978,6 +2030,14 @@ def _unified(asked, question, engine, wiki, wiki_ok, part, person, wiki_context,
if out:
return done(out)
supervising = re.search(r"\b(?:viedol|viedla|vedie|oponoval\w*|skolil\w*)\b", low)
card = None if (COMPARE.search(low) or SAME_SUPERVISOR.search(low) or SAME_OPPONENT.search(low) or METHODS.search(low)
or STUDY_START.search(low) or STUDENTS_OF.search(low) or SIMILAR.search(low)) \
else U.work_card(person, works, low, wiki_text)
if card: # "názov, vedúci, oponent a rok obhajoby": every asked fact, not the first rule's one
return done(card)
premise = U.school_premise(person, works, question)
if premise: # "Prečo X obhájil diplomovú prácu na Žilinskej univerzite?": the register's school instead
return done(premise)
if STUDY_START.search(low) and not re.search(r"\b(?:prac\w*|projekt\w*|nazov|tem\w*|veduc\w*)\b", low):
out = U.start_year(person) # only the start of studies; a compound question stays with the wiki answer
if out is None: # "Kedy začal študovať Maroš Harahus?": not recorded, said so (no other data instead)
@ -1990,6 +2050,8 @@ def _unified(asked, question, engine, wiki, wiki_ok, part, person, wiki_context,
elif plan.get("intent") == "meeting" or re.search(r"\bstretnut\w*", low) or U.TASKS_Q.search(low) and wiki_text:
text = U.meeting(person, wiki_text, low, follow_up=asked != question or bool(re.match(r"^\W*a\b", normalized(asked))))
out = {"text": text, "urls": wiki.get("source_urls") or U.work_urls(person, [])} if text else None
elif SAME_OPPONENT.search(low): # "… mali pri bakalárskej práci rovnakého oponenta ako Martin Šarišský?"
out = U.same_opponent(person, low)
elif SAME_SUPERVISOR.search(low): # "Ktorí študenti mali rovnakého vedúceho ako Dmytro Mural?"
out = U.same_supervisor(person)
elif U.asked_role(low) and not STUDENTS_OF.search(low) and (
@ -2042,7 +2104,7 @@ def _unified(asked, question, engine, wiki, wiki_ok, part, person, wiki_context,
body, urls = split_sources(wiki_text)
head, items, tail, general = wiki_items(body, urls)
if len(items) == 2:
out = U.comparison([items[0]["name"], items[1]["name"]], collaboration=bool(re.search(r"\bspolupr", low)))
out = U.comparison([items[0]["name"], items[1]["name"]], collaboration=bool(re.search(r"\bspolupr", low)), low=low)
if out:
return done(out)
return None
@ -2053,14 +2115,29 @@ def _compose(asked: str, question: str, engine: str, wiki: dict, part: dict | No
from tools.answers.presentation.finalize import finalize
low = normalized(question)
named_in_crzp = crzp_names_the_person(question, wiki, part)
if wiki.get("reason") in REFUSED or wiki.get("status") == "ambiguous" and not named_in_crzp and (
from tools.answers.presentation.unified import wiki_members
members = wiki_members(question, part.get("text") or "", part.get("rows")) if (
part is not None and part["mode"] == "explicit" and part.get("status") == "ok"
and wiki.get("reason") not in REFUSED) else None
if members: # "Koľko prác viedol X v roku 2025 a ktorí z jeho študentov sú v ZP Wiki?": the register's answer and
# the ZP Wiki students among those works (also when the wiki asks for a name: the register names the person)
body, urls = split_sources(part["text"])
urls = list(dict.fromkeys([*members["urls"], *urls, *part.get("urls", [])]))[:MAX_SOURCES]
text = body.rstrip() + "\n\n" + members["text"] + ("\n\nZdroje: " + ", ".join(urls) if urls else "")
return _with_token(_ok(question, engine, text, urls, {"index_version": wiki.get("index_version")}),
question=question, crzp=part.get("crzp_token"))
dropped_rows = []
compared = (part or {}).get("intent") == "compare" # two people compared from their records: no "which work?"
if wiki.get("reason") in REFUSED or wiki.get("status") == "ambiguous" and not named_in_crzp and not compared and (
person or wiki.get("reason") not in WIKI_CLARIFICATION_YIELDS):
part = None # refused/out of scope, or the wiki asks first (which person, which work): no CRZP
# refused/out of scope, or the wiki asks first (which person, which work): no CRZP part (its rows, with their
# links, still join the person's works below)
dropped_rows, part = (part or {}).get("rows") or [], None
wiki_ok = wiki.get("accepted_for_delivery") is True and wiki.get("status") == "ok"
if part is not None and part["mode"] == "explicit" and wiki.get("status") == "ambiguous":
wiki_ok = False
if part is not None and part["mode"] == "explicit" and part.get("intent") in ("count", "methods") \
and part.get("status") in ("ok", "ambiguous") and not part.get("addition") \
and part.get("status") in ("ok", "ambiguous") and not part.get("addition") and not NAMED_WIKI.search(low) \
or part is not None and part["mode"] == "explicit" and part.get("intent") == "relation" \
and part.get("status") == "ok" and re.search(r"\bkto\s+oponoval\w*|\boponent\w*\s+prac", low):
wiki_ok = False # a CRZP count (or the technologies of a CRZP work) is the answer; a wiki list is no count
@ -2069,10 +2146,12 @@ def _compose(asked: str, question: str, engine: str, wiki: dict, part: dict | No
wiki_context = wiki.get("conversation_context")
plan = wiki.pop("_plan", None) or {}
if (part is not None and part["mode"] == "explicit" and part.get("status") == "ok" and part.get("text")
and NAMED_CRZP.search(low) and not part.get("addition")):
wiki_ok = False # "… v CRZP?", "hľadaj v registri": what CRZP itself records is asked
and NAMED_CRZP.search(low) and not part.get("addition") and not NAMED_WIKI.search(low)):
wiki_ok = False # "… v CRZP?", "hľadaj v registri": what CRZP itself records is asked (not "… a čo uvádza ZP Wiki")
else:
special = _unified(asked, question, engine, wiki, wiki_ok, part, person, wiki_context, plan)
special = _unified(asked, question, engine, wiki, wiki_ok,
part if part is not None or not dropped_rows else {"rows": dropped_rows},
person, wiki_context, plan)
if special is not None:
return special
if part is None or wiki.get("status") == "ambiguous" and part["mode"] != "explicit":
@ -2129,7 +2208,12 @@ def _compose(asked: str, question: str, engine: str, wiki: dict, part: dict | No
if all(any(line.startswith(label + ":") for label in SIDE.values())
for line in wiki_body.split("\n") if line.strip()):
head, tail = [], [wiki_body] # only "Téma je len v zadaní …: X." – a closing note after the works
if not wiki_ok:
if not wiki_ok and part.get("home_excluded") and person: # the person's topic, the other schools' works
from tools.answers.presentation.unified import anchor_sentence, work_urls
anchor = anchor_sentence(person)
head = [(anchor + " " if anchor else "") + "Na iných školách sa podobnej téme venujú (od najbližších prác):"]
general = work_urls(person, [])
elif not wiki_ok:
head = ["V ZP Wiki k tomu nie je záznam. Práce na túto tému v CRZP (Centrálny register záverečných prác):"]
shown, rest = first_page(items, part["items"])
text, urls, page_id = compose_list(head, shown, rest, tail, general, mixed=True)
@ -2162,6 +2246,12 @@ def _compose(asked: str, question: str, engine: str, wiki: dict, part: dict | No
else:
text = "V ZP Wiki k tomu nie je záznam.\n\nV CRZP (Centrálny register záverečných prác):\n\n" + crzp_body
urls = list(dict.fromkeys([*wiki_urls, *crzp_urls]))
if not wiki_ok and person and part.get("person") and normalized(part["person"]) == normalized(person) \
and not part.get("home_excluded"):
# "… podľa registra CRZP": the register's answer about a ZP Wiki student links the student's profile too
from tools.answers.presentation.unified import catalog as wiki_catalog
profile = (wiki_catalog()["people"].get(person) or {}).get("url")
urls = list(dict.fromkeys([profile, *urls])) if profile else urls
if urls:
text += "\n\nZdroje: " + ", ".join(urls)
page = None
@ -2295,3 +2385,9 @@ def _answer_choice(question: str, chosen: dict, *, engine: str, limit: int, comp
def _key_of(row: dict) -> str:
from tools.crzp.answering import answer as crzp
return crzp.work_key(row)
# labels of the answer path (rewrite, plan, branch, source) in the timing log, for evaluation
from tools.answers import route_trace as _route_trace # noqa: E402
_route_trace.install()

View File

@ -224,7 +224,9 @@ def units(person: str) -> list[dict]:
def wiki_supervisor(person: str, heading: str | None) -> str | None:
"""The work's explicit supervisor line, else the profile's, else the profile author (local/AGENTS.md)."""
from tools.knowledge.sources import profile_authors
rows = [u for u in units(person) if u.get("kind") == "supervisor"]
# a supervisor line ("Vedúci: Ing. Daniel Hládek, PhD."), not a meeting note that mentions "vedúci"
rows = [u for u in units(person) if u.get("kind") == "supervisor" and not u.get("meeting_id")
and re.match(r"^[-*\s]*(?:Ved[uú]c\w*|Školite\w*|Skolite\w*)[^:.\n]{0,30}:", u["text"])]
for row in sorted(rows, key=lambda u: u.get("work_label") != heading):
match = re.search(rf"(?:(?:Ing|Mgr|doc|prof|Bc|RNDr|PhD)\.?\s*)*([{UPPER}][\w\-]+\s+[{UPPER}][\w\-]+)", row["text"].split(":", 1)[-1])
if match and (row.get("work_label") in (None, heading)):
@ -340,6 +342,8 @@ def person_works(person: str, crzp_rows: list[dict] | None = None) -> list[dict]
continue
item = crzp_work(row)
def same_work(w):
if w["type"] in THESES and item["type"] in THESES and w["type"] != item["type"]:
return False # a bachelor thesis is never the diploma thesis, whatever words their titles share
if _same_title(w.get("title"), item["title"]):
return True
if w["type"] != item["type"] or w["type"] not in THESES or not w.get("year") or not item.get("year"):
@ -347,11 +351,20 @@ def person_works(person: str, crzp_rows: list[dict] | None = None) -> list[dict]
# the same thesis: the same year, or a year apart (planned year vs. submission) when the wiki
# gives it no title of its own
return w["year"] == item["year"] or abs(w["year"] - item["year"]) <= 1 and not w.get("title")
twin = next((w for w in works if same_work(w)), None)
def closeness(w): # the closest of several candidates, not the first ("Generatívne modely …" 2023 vs 2024)
x, y = _stems(w.get("title")), _stems(item["title"])
return (normalized(w.get("title") or "") == normalized(item["title"] or ""), w["type"] == item["type"],
len(x & y) / max(1, len(x | y)), w.get("year") == item.get("year"), not w.get("row"))
twins = [w for w in works if same_work(w)]
twin = max(twins, key=closeness) if twins else None
if twin is not None:
if twin.get("row") and (twin["row"].get("year") or 0) >= (row.get("year") or 0):
continue # an older record of the same thesis: the newer one is the defended one (Pavlišin 2019, 2020)
twin["row"] = row
twin["title"] = twin.get("title") or item["title"]
twin.setdefault("urls", []).append(row.get("url"))
if twin["type"] not in THESES and item["type"] in THESES:
twin["thesis"] = item["type"] # the wiki's project the register holds as the defended thesis
else:
from tools.answers.combined import same_person_work
# (a person ZP Wiki does not know has no namesake there: the register's works are the person's)
@ -371,6 +384,28 @@ def person_works(person: str, crzp_rows: list[dict] | None = None) -> list[dict]
return works
def defended(work: dict):
"""The year a thesis was defended: the register's year (ZP Wiki gives the planned or submission year)."""
row = work.get("row") or {}
return row.get("year") if row.get("year") and work["type"] in THESES else work.get("year")
def register_title(work: dict) -> str | None:
"""The register's title of the work when it differs from the one in ZP Wiki."""
title, own = (work.get("row") or {}).get("title"), work.get("wiki_title", work.get("title"))
return title if title and own and normalized(title).rstrip(". ") != normalized(own).rstrip(". ") else None
def of_kind(works: list[dict], kinds) -> list[dict]:
"""The works of the asked types, newest first; a wiki project the register holds as that thesis ("Vedecký projekt
2021: Dialógový systém…" = the bachelor thesis 2022 in CRZP) is that thesis, with the register's year."""
kinds = [kinds] if isinstance(kinds, str) else list(kinds)
out = [w if w["type"] in kinds else {**w, "type": w["thesis"], "year": w["row"].get("year") or w.get("year"),
"title": w["row"].get("title") or w.get("title"), "wiki_title": w.get("title")}
for w in works if w["type"] in kinds or w.get("thesis") in kinds]
return sorted(out, key=lambda w: -(w.get("year") or 0))
def describe(work: dict, *, case: int = 0, title: bool = True) -> str:
""""bakalárska práca (2026) „Skórovací online systém…“" in the given case."""
names = TYPES.get(work["type"]) or (work.get("heading") or "práca",) * 3
@ -518,7 +553,9 @@ def roles(person: str, works: list[dict], low: str, wiki_text: str = "", role: s
def _role_part(person: str, works: list[dict], kind: str | None, role: str, low: str, wiki_text: str) -> dict | None:
"""The one work of that type (or the person's thesis) and who had the role in it."""
candidates = [w for w in works if (w["type"] == kind if kind else w["type"] in THESES)]
candidates = of_kind(works, kind) if kind else [w for w in works if w["type"] in THESES]
if kind: # two wiki records of one thesis (a planned title, then the defended one): the one the register knows
candidates.sort(key=lambda w: not w.get("row"))
chosen = [w for w in candidates if not w.get("unconfirmed")]
if not chosen and not kind:
chosen = [w for w in works if w["source"] == "wiki"][:1]
@ -547,7 +584,7 @@ def _role_sentence(person: str, role: str, low: str, parts: list[dict]) -> dict
work, people = part["work"], part["people"]
names = TYPES.get(work["type"]) or ("práca", "práce", "práci")
title = f" „{work['title'].rstrip('.')}“" if work.get("title") else ""
year = f" ({work['year']})" if work.get("year") else ""
year = f" ({defended(work)})" if defended(work) else ""
if not title and work.get("topic"): # the topic of the project the thesis continues
year = f" ({str(work['year']) + '; ' if work.get('year') else ''}téma: {work['topic'].rstrip('.')})"
urls += work_urls(person, [work])
@ -590,6 +627,113 @@ def supervisors(person: str, works: list[dict], low: str, wiki_text: str = "") -
_chunks: dict = {}
CARD_ASPECTS = [
("title", re.compile(r"\b(?:nazov|nazvom|nazvu|ako\s+sa\s+vola|nazyva\w*)\b")),
("supervisor", re.compile(r"\bved[uú]c\w*|\bskolitel\w*|\b(?:viedol|viedla)\b")),
("opponent", re.compile(r"\boponent\w*|\boponoval\w*|\boponovan\w*")),
("consultant", re.compile(r"\bkonzultant\w*|\bkonzultoval\w*")),
("year", re.compile(r"\bv\s+ktorom\s+roku|\bktoreho\s+roku|\bkedy\b|\brok\w*\s+(?:obhajob|odovzdan)\w*|\brok\b")),
("school", re.compile(r"\bskol[aueyo]\b|\bskolou\b|\buniverzit\w*|\bfakult\w*")),
("wiki", re.compile(r"\bzadani\w*|\bvysledk\w*|\buvadza\w*|\bciel\w*")),
]
CARD_LABEL = {"supervisor": "Vedúci", "opponent": "Oponent", "consultant": "Konzultant"}
def work_card(person: str, works: list[dict], low: str, wiki_text: str = "") -> dict | None:
""""Pre X: názov bakalárskej práce, vedúci, oponent, rok obhajoby, škola a čo k nej uvádza ZP Wiki": every
asked fact of the work (two or more asked at once), one line each, a fact the sources lack said so; with no
work type named, each thesis of the person (newest first)."""
asked = [name for name, pattern in CARD_ASPECTS if pattern.search(low)]
if len(asked) < 2 or re.search(r"\bstretnut\w*|\buloh\w*|\bzasobnik\w*|\bprogres\w*|\bpokrok\w*|\bstav\w*|"
r"\bposledn\w*|\btyzd\w*|\bteraz\b|\baktualn\w*", low):
return None # (a meeting, the tasks or the current state are the wiki's own answers)
kinds = [k for k in asked_types(low) if k in THESES]
every = [w for w in (of_kind(works, kinds) if kinds else works) if w["type"] in (kinds or THESES)]
pool = [w for w in every if not w.get("unconfirmed")]
if kinds: # one work of each named type: the one the register knows first (a namesake's only with the doubt)
pool = [next(iter(sorted((w for w in pool if w["type"] == k), key=lambda w: not w.get("row"))), None)
or next((w for w in every if w["type"] == k), None) for k in kinds]
missing = [k for k, w in zip(kinds, pool) if w is None]
pool = [w for w in pool if w is not None]
else:
missing, pool = [], pool[:3]
if not pool and not missing:
return None
blocks, urls = [], []
for work in pool:
names = TYPES.get(work["type"]) or ("práca", "práce", "práci")
row = work.get("row") or {}
title = f" „{work['title'].rstrip('.')}“" if work.get("title") else ""
lines = [f"{names[0][:1].upper() + names[0][1:]} {genitive(person)}{title}"
+ (f" ({defended(work)})" if defended(work) else "") + ":"]
for aspect in asked:
if aspect == "title": # (a known title already heads the block)
if not work.get("title"):
lines.append("- Názov: v podkladoch nie je")
elif register_title(work) and register_title(work) != work["title"]:
lines.append(f"- Názov v CRZP: „{register_title(work).rstrip('.')}“")
elif aspect in CARD_LABEL:
people = _role_people(person, work, aspect, wiki_text)
lines.append(f"- {CARD_LABEL[aspect]}: {join(people) if people else 'v podkladoch nie je uvedený'}")
elif aspect == "year":
lines.append(f"- Rok: {defended(work)}" if defended(work) else "- Rok: v podkladoch nie je")
elif aspect == "school":
school = row.get("school") or ("Technická univerzita v Košiciach" if work["source"] == "wiki" else None)
lines.append(f"- Škola: {school}" + (" (FEI, KEMT)" if work["source"] == "wiki" else "")
if school else "- Škola: v podkladoch nie je")
elif aspect == "wiki":
points = goals_of(person, work.get("heading"), 3) if work["source"] == "wiki" else []
done_points = results_of(person, work.get("heading"), 2) if work["source"] == "wiki" else []
if points:
lines.append("- Zadanie: " + "; ".join(p.rstrip(".") for p in points))
if done_points:
lines.append("- Výsledky: " + "; ".join(p.rstrip(".") for p in done_points))
if not points and not done_points:
lines.append("- Zadanie ani výsledky k tejto práci v ZP Wiki zaznamenané nie sú")
if work.get("unconfirmed"):
lines.append("- Nie je isté, že ide o tú istú osobu ako v profile študenta (iný vedúci a téma).")
blocks.append("\n".join(lines))
urls += work_urls(person, [work])
for kind in missing:
names = TYPES.get(kind) or ("práca", "práce", "práci")
blocks.append(f"{names[0][:1].upper() + names[0][1:]} {genitive(person)} v podkladoch nie je.")
return {"text": "\n\n".join(blocks), "urls": list(dict.fromkeys(urls or work_urls(person, [])))}
def school_premise(person: str, works: list[dict], question: str) -> dict | None:
""""Prečo Ján Holp obhájil diplomovú prácu na Žilinskej univerzite?": the register gives the school of the
person's thesis; another school in the question is a false premise, corrected with the thesis and its school."""
from tools.crzp.answering.understand import SCHOOLS
low = normalized(question)
if not re.search(r"\b(?:obhaj\w*|robil\w*|pisal\w*|napisal\w*|odovzdal\w*|studoval\w*)\b", low) \
or re.search(r"\b(?:kto|ktor\w*|podobn\w*|ak\w*\s+skol\w*)\b", low):
return None
words = [w[:5] for w in low.split()]
def named(part):
stems = [w[:5] for w in part.split() if len(w) > 2]
return bool(stems) and any(words[i:i + len(stems)] == stems for i in range(len(words) - len(stems) + 1))
asked = [key for key, (full, part) in SCHOOLS.items() if named(part) or re.search(rf"\b{key}\b", low)]
if not asked or "tuke" in asked:
return None
school = SCHOOLS[asked[0]][0]
kinds = [k for k in asked_types(low) if k in THESES] or sorted(THESES)
own = [w for w in works if w.get("row") and not w.get("unconfirmed")
and CRZP_TYPES.get(w["row"].get("work_type"), w["row"].get("work_type")) in kinds]
if not own or any(normalized(w["row"].get("school") or "") == normalized(school) for w in own):
return None # nothing to compare, or the premise holds
lines = []
for work in own[:2]:
names = TYPES.get(work["type"]) or ("práca", "práce", "práci")
title = f" „{work['title'].rstrip('.')}“" if work.get("title") else ""
lines.append(f"{names[0][:1].upper() + names[0][1:]} {genitive(person)}{title}"
+ (f" ({work['year']})" if work.get("year") else "") + f" je zo školy {work['row'].get('school')}.")
text = (f"Predpoklad otázky nesedí: {spelled(person)} nemá "
f"{ACCUSATIVE.get(kinds[0], 'záverečnú prácu') if len(kinds) == 1 else 'záverečnú prácu'} zo školy {school}. "
+ " ".join(lines))
return {"text": text, "urls": work_urls(person, own)}
def page_chunks(path: str) -> list[str]:
"""The texts of one wiki page as the RAG index split it (chunks.json, reread when it changes)."""
from tools.rag.common import DB_FILE
@ -736,7 +880,7 @@ def started_answer(question: str) -> dict | None:
year, more = int(match.group(1)), match.group(2) or ""
fits = (lambda y: y and y >= year) if more.startswith("nesk") else (lambda y: y and y <= year) if more else (
lambda y: y == year)
rows = [r for r in wiki_pages() if r["kind"] == "student" and fits(r.get("start_year"))]
rows = [r for r in wiki_pages() if r["kind"] == "student" and fits(_year(r.get("start_year")))]
kinds = [k for k in asked_types(low) if k in TYPES]
lines = []
for r in sorted(rows, key=lambda r: normalized(r["name"])):
@ -755,6 +899,280 @@ def started_answer(question: str) -> dict | None:
return {"text": text, "urls": [r["url"] for r in rows[:10] if r.get("url")]}
# ------------------------------------------------------------------ a wiki set joined with the register
# what only the register holds (a defended thesis, its opponent); a supervisor alone is the wiki's ("a kto je ich vedúci?")
SET_CRZP = re.compile(r"\b(?:crzp|registr\w*|register|obhaj\w*|obhajen\w*|oponent\w*|oponoval\w*)\b")
NOT_ROLE = re.compile(r"\b(?:nebol[ai]?|neboli|okrem|nie\s+(?:je|bol[ai]?))\s+(?:oponent\w*\s+|ved[uú]c\w*\s+)?"
r"([a-z]+(?:\s+[a-z]+)?)")
SET_RANKING = re.compile(r"\bnajcast\w*|\bnajviac\w*|\bopakuj\w*")
ACCUSATIVE = {"bachelor_thesis": "bakalársku prácu", "diploma_thesis": "diplomovú prácu",
"doctoral_thesis": "dizertačnú prácu", "habilitation_thesis": "habilitačnú prácu",
"rigorous_thesis": "rigoróznu prácu"}
LOCATIVE_PLURAL = {"bachelor_thesis": "bakalárskych prácach", "diploma_thesis": "diplomových prácach",
"doctoral_thesis": "dizertačných prácach"}
ROLE_NOUN = {"opponent": ("oponent", "oponentom"), "supervisor": ("vedúci", "vedúcim"),
"consultant": ("konzultant", "konzultantom")}
def _year(value) -> int | None:
try:
return int(value)
except (TypeError, ValueError):
return None
def _excluded(low: str) -> str | None:
match = NOT_ROLE.search(low)
return match.group(1) if match else None
def _is(name: str, words: str) -> bool:
return set(words.split()) <= set(normalized(name).split())
def set_join(question: str, person: str | None = None) -> dict | None:
""""Ktorí študenti s tagom rag obhájili bakalársku prácu v roku 2025 a kto im robil oponenta?", "Koľko študentov
s tagom nlp má v CRZP obhájenú bakalársku prácu?", "Kto bol oponentom bakalárskej práce študenta, ktorý začal
študovať v roku 2016 a má tag nmt?": the wiki profiles of the tag (category, start of studies) joined with their
theses in the register (the local cache, no request), every condition kept: type, year, role, "nebol X"."""
from collections import Counter
from tools.crzp.source.parse import display_name
low = normalized(question)
tag, started = TAG_Q.search(low), STARTED_Q.search(low)
if not (tag or started) or not SET_CRZP.search(low) or re.search(r"\b(?:suvis\w*|pribuzn\w*)\b", low):
return None
excluded = _excluded(low)
if person and not (excluded and _is(person, excluded)):
return None # a question about one named person is not a question about the set
pages, label = wiki_pages(), []
if tag:
field = "categories" if tag.group(1).startswith("kategori") else "tags"
pages = [r for r in pages if tag.group(2) in r[field]]
label.append(f"{'kategóriou' if field == 'categories' else 'tagom'} {tag.group(2)}")
rest = low
if started:
first, more = int(started.group(1)), started.group(2) or ""
fits = (lambda y: y and y >= first) if more.startswith("nesk") else (lambda y: y and y <= first) if more else (
lambda y: y == first)
pages = [r for r in pages if r["kind"] == "student" and fits(_year(r.get("start_year")))]
label.append(f"začiatkom štúdia v roku {first}")
rest = low[:started.start()] + " " + low[started.end():]
year = next((int(y) for y in re.findall(r"\b((?:19|20)\d{2})\b", rest)), None)
kinds = [k for k in asked_types(low) if k in THESES] or sorted(THESES)
role = asked_role(low)
group = "študentov ZP Wiki s " + " a ".join(label)
what = ACCUSATIVE[kinds[0]] if len(kinds) == 1 else "záverečnú prácu"
when = f" v roku {year}" if year else ""
if not pages:
return {"text": f"V ZP Wiki nie je žiadny študent s {' a '.join(label)}.", "urls": []}
found, dropped = [], []
for page in pages:
seen = set()
for work in person_works(page["name"]):
row = work.get("row")
if not row or work.get("unconfirmed"):
continue
kind = CRZP_TYPES.get(row.get("work_type"), row.get("work_type"))
key = (normalized(row.get("title") or ""), row.get("year"))
if kind not in kinds or year and row.get("year") != year or key in seen:
continue
seen.add(key)
people = {r: [display_name(n) for n in row.get(ROLES[r]["field"], [])] for r in ROLES}
if excluded and any(_is(n, excluded) for r in ([role] if role else list(ROLES)) for n in people[r]):
dropped.append({"page": page, "row": row})
continue
found.append({"page": page, "row": row, "type": kind, "people": people})
found.sort(key=lambda f: (-(f["row"].get("year") or 0), normalized(f["page"]["name"])))
urls = list(dict.fromkeys(u for f in found for u in (f["page"].get("url"), f["row"].get("url")) if u))[:24] or [
r["url"] for r in pages[:10] if r.get("url")]
names = list(dict.fromkeys(f["page"]["name"] for f in found))
if excluded:
noun = ROLE_NOUN[role or "opponent"][1]
words, folded = re.findall(r"[^\W_]+", question), excluded.split()
at = next((i for i in range(len(words)) if [normalized(w) for w in words[i:i + len(folded)]] == folded), None)
shown_name = " ".join(words[at:at + len(folded)]) if at is not None else excluded.title()
not_x = f", pri ktorej {noun} nebol {shown_name},"
else:
not_x = ""
if not found:
text = f"Žiadny z {len(pages)} {group} nemá obhájenú {what}{when}{not_x.rstrip(',')}."
if dropped: # the theses the condition removed are the evidence of "none"
held = _people_sentence(list(dict.fromkeys(spelled(d["page"]["name"]) for d in dropped)))
text += f" {held} {'má' if len({d['page']['name'] for d in dropped}) == 1 else 'majú'} takú prácu, ale {noun} bol {shown_name}."
urls = list(dict.fromkeys([u for d in dropped for u in (d["page"].get("url"), d["row"].get("url")) if u]
+ urls))[:24]
return {"text": text, "urls": urls}
if SET_RANKING.search(low) and not re.search(r"\bkolk\w*|\bpocet\b", low):
asked = role or "opponent"
counts = Counter(n for f in found for n in f["people"][asked])
if counts:
(top, n), *_ = counts.most_common()
where = LOCATIVE_PLURAL.get(kinds[0], "záverečných prácach") if len(kinds) == 1 else "záverečných prácach"
lines = [f"- {name}: {c}×" for name, c in counts.most_common(10)]
return {"text": f"Najčastejším {ROLE_NOUN[asked][1]} pri {where} {group} je {top} ({n}×).\n\n"
+ "\n".join(lines), "urls": urls}
if re.search(r"\bkolk\w*|\bpocet\b", low):
return {"text": f"Obhájenú {what}{when}{not_x} má {len(names)} z {len(pages)} {group}: "
f"{_people_sentence(names)}.", "urls": urls}
shown = [role] if role else ["supervisor", "opponent"]
lines = []
for f in found[:40]:
work = crzp_work(f["row"])
facts = "; ".join(f"{ROLE_NOUN[r][0]}: {', '.join(f['people'][r])}" for r in shown if f["people"][r])
lines.append(f"- {spelled(f['page']['name'])} — {describe(work)}" + (f"; {facts}" if facts else ""))
head = f"Obhájenú {what}{when}{not_x} má {len(names)} z {len(pages)} {group}"
return {"text": head + ":\n\n" + "\n".join(lines), "urls": urls}
UPPER = "A-ZÁÄČĎÉÍĽĹŇÓÔŔŠŤÚÝŽ"
ROLE_PERSON = re.compile(rf"\b(oponoval\w*|viedol|viedla|konzultoval\w*)\s+((?:[{UPPER}][^\W\d_]+\s+)[{UPPER}][^\W\d_]+)")
WIKI_STUDENT = re.compile(r"\bstudent\w*\s+(?:zo|z|v)\s+zp\s*wiki\b")
WIKI_MEMBERS = re.compile(r"\bktor\w*\s+(?:z\s+)?(?:jeho|jej|ich|tych)\s+student\w*\s+(?:su|je|boli)\s+(?:aj\s+)?(?:v|vo)\s+zp\s*wiki")
def register_students(question: str, role: str | None = None, name: str | None = None) -> dict | None:
"""The ZP Wiki students whose theses in the register (the local cache) meet the question's role person
("ktorému v roku 2025 oponoval Stanislav Ondáš", "viedol Daniel Hládek"), year and thesis type."""
from tools.crzp.source.parse import display_name
if name is None:
match = ROLE_PERSON.search(question)
if not match:
return None
verb = normalized(match.group(1))
role = "opponent" if verb.startswith("opon") else "consultant" if verb.startswith("konz") else "supervisor"
name = match.group(2)
folded = normalized(name)
low = normalized(question)
year = next((int(y) for y in re.findall(r"\b((?:19|20)\d{2})\b", low)), None)
kinds = [k for k in asked_types(low) if k in THESES] or sorted(THESES)
found, doubtful, seen = [], [], set()
for page in wiki_pages():
if page["kind"] != "student":
continue
for work in person_works(page["name"]):
row = work.get("row")
if not row:
continue
kind = CRZP_TYPES.get(row.get("work_type"), row.get("work_type"))
key = (page["name"], normalized(row.get("title") or ""))
if kind not in kinds or year and row.get("year") != year or key in seen:
continue
if any(_is(display_name(n), folded) for n in row.get(ROLES[role]["field"], [])):
seen.add(key)
(doubtful if work.get("unconfirmed") else found).append({"page": page, "row": row, "type": kind})
found.sort(key=lambda f: (-(f["row"].get("year") or 0), normalized(f["page"]["name"])))
return {"role": role, "name": name, "year": year, "kinds": kinds, "found": found, "doubtful": doubtful}
def _found_urls(found: list[dict]) -> list[str]:
return list(dict.fromkeys(u for f in found for u in (f["page"].get("url"), f["row"].get("url")) if u))[:24]
def wiki_student_role(question: str) -> dict | None:
""""Kto viedol bakalársku prácu študenta zo ZP Wiki, ktorému v roku 2025 oponoval Stanislav Ondáš?": the wiki
students meeting the condition in the register, and who had the asked role in their thesis."""
from tools.crzp.source.parse import display_name
low = normalized(question)
if not WIKI_STUDENT.search(low) or WIKI_MEMBERS.search(low):
return None
asked = "supervisor" if re.search(r"\bkto\s+(?:viedol|viedla|bol\w*\s+veduc\w*|je\s+veduc\w*)", low) else \
"opponent" if re.search(r"\bkto\s+(?:oponoval\w*|bol\w*\s+oponent\w*)", low) else None
joined = register_students(question)
if joined is None or asked is None or asked == joined["role"]:
return None
what = ACCUSATIVE[joined["kinds"][0]] if len(joined["kinds"]) == 1 else "záverečnú prácu"
verb = {"opponent": "oponoval", "supervisor": "viedol", "consultant": "konzultoval"}[joined["role"]]
when = f" v roku {joined['year']}" if joined["year"] else ""
if not joined["found"]:
noun = TYPES[joined["kinds"][0]][0] if len(joined["kinds"]) == 1 else "záverečná práca"
text = f"V registri nie je {noun} študenta ZP Wiki, ktorú{when} {verb} {joined['name']}."
for f in joined["doubtful"][:3]: # a namesake of a wiki student: said with the doubt
people = [display_name(n) for n in f["row"].get(ROLES[asked]["field"], [])]
text += (f" Je tam {describe(crzp_work(f['row']))} autora s menom {spelled(f['page']['name'])} "
f"({ROLE_NOUN[asked][0]}: {', '.join(people) or 'neuvedený'}); nie je isté, že ide o študenta ZP Wiki.")
return {"text": text, "urls": _found_urls(joined["doubtful"][:3])}
lines = []
for f in joined["found"]:
people = [display_name(n) for n in f["row"].get(ROLES[asked]["field"], [])]
lines.append(f"- {spelled(f['page']['name'])} — {describe(crzp_work(f['row']))}; "
f"{ROLE_NOUN[asked][0]}: {', '.join(people) or 'neuvedený'}")
if len(joined["found"]) == 1:
f = joined["found"][0]
people = [display_name(n) for n in f["row"].get(ROLES[asked]["field"], [])]
head = (f"{what[:1].upper() + what[1:]} študenta ZP Wiki {genitive(f['page']['name'])}, ktorú{when} {verb} "
f"{joined['name']}, {'viedol' if asked == 'supervisor' else 'oponoval'} {', '.join(people) or 'neuvedený'}: "
f"{describe(crzp_work(f['row']))}.")
return {"text": head, "urls": _found_urls(joined["found"])}
head = f"Študenti ZP Wiki, ktorých {what}{when} {verb} {joined['name']}:"
return {"text": head + "\n\n" + "\n".join(lines), "urls": _found_urls(joined["found"])}
def wiki_members(question: str, part_text: str = "", part_rows: list[dict] | None = None) -> dict | None:
""""Koľko bakalárskych prác viedol Daniel Hládek v roku 2025 a ktorí z jeho študentov sú v ZP Wiki?",
"Kto viedol najviac prác o téme RAG a ktorí jeho študenti sú v ZP Wiki?": the sentence added to the register's
answer, the ZP Wiki students among those works."""
low = normalized(question)
if not WIKI_MEMBERS.search(low):
return None
joined = register_students(question)
if joined is None: # the person is the register's answer: "Najviac prác … viedol Daniel Hládek (TUKE)"
top = re.search(rf"\bviedol\w*\s+((?:[{UPPER}][^\W\d_]+\s+)[{UPPER}][^\W\d_]+)", part_text)
if not top:
return None
joined = register_students(re.sub(r"\b(?:19|20)\d{2}\b", " ", question), "supervisor", top.group(1))
keys = {(normalized(r.get("title") or ""), r.get("year")) for r in part_rows or []}
among = [f for f in joined["found"] if (normalized(f["row"].get("title") or ""), f["row"].get("year")) in keys]
names = list(dict.fromkeys(spelled(f["page"]["name"]) for f in among))
if names:
return {"text": f"V ZP Wiki z autorov týchto prác {'je' if len(names) == 1 else 'sú'}: {_people_sentence(names)}.",
"urls": _found_urls(among)}
everyone = list(dict.fromkeys(spelled(f["page"]["name"]) for f in joined["found"]))
if not everyone:
return {"text": f"{joined['name']} nemá v ZP Wiki študentov s prácou v registri.", "urls": []}
more = f" a ďalší ({len(everyone) - 15})" if len(everyone) > 15 else ""
return {"text": f"Študentov ZP Wiki, ktorých prácu v registri viedol {joined['name']} (na rôzne témy), je "
f"{len(everyone)}: {_people_sentence(everyone[:15])}{more}.", "urls": _found_urls(joined["found"])}
names = list(dict.fromkeys(spelled(f["page"]["name"]) for f in joined["found"]))
who = joined["name"]
if not names:
return {"text": f"Študentov ZP Wiki s prácou v registri, ktorú {'viedol' if joined['role'] == 'supervisor' else 'oponoval'} "
f"{who}{' v roku ' + str(joined['year']) if joined['year'] else ''}, v podkladoch nie je.", "urls": []}
shown = names[:15]
more = f" a ďalší ({len(names) - 15})" if len(names) > 15 else ""
return {"text": f"V ZP Wiki z nich {'je' if len(names) == 1 else 'sú'} {len(names)}: {_people_sentence(shown)}{more}.",
"urls": _found_urls(joined["found"])}
def defended_years(person: str, question: str) -> dict | None:
""""Obhájil Martin Jancura bakalársku prácu v roku 2021 a diplomovú v roku 2023?": each named thesis and its year
checked against the register (yes, or the year it was defended, or not in the register)."""
low = normalized(question)
pairs = re.findall(r"\b(bakal\w*|diplom\w*|dizert\w*)\D{0,40}?\bv\s+roku\s+((?:19|20)\d{2})\b", low)
if not re.search(r"\bobhaj\w*", low) or len(pairs) < 2 or re.search(r"\b(?:kto|ktor\w*|kolk\w*)\b", low):
return None
kinds = {"bakal": "bachelor_thesis", "diplo": "diploma_thesis", "dizer": "doctoral_thesis"}
works = person_works(person)
clauses, urls, right = [], [], []
for word, year in pairs:
kind = kinds[word[:5]]
pool = sorted((w for w in of_kind(works, kind) if not w.get("unconfirmed")), key=lambda w: not w.get("row"))
noun = ACCUSATIVE[kind]
if not pool or not pool[0].get("row"):
clauses.append(f"{noun} v registri nemá")
right.append(False)
continue
work = pool[0]
title = f" „{work['title'].rstrip('.')}“" if work.get("title") else ""
right.append(defended(work) == int(year))
clauses.append(f"{noun}{title} obhájil{ending(person)} v roku {defended(work)}"
+ ("" if right[-1] else f" (nie v roku {year})"))
urls += work_urls(person, [work])
lead = "Áno." if all(right) else "Nie." if not any(right) else "Nie celkom."
text = f"{lead} {spelled(person)} " + " a ".join(clauses) + "."
return {"text": text, "urls": list(dict.fromkeys(u for u in urls if u))}
def supervisor_students() -> dict[str, list[str]]:
"""Supervisor (the profile author, KEMT convention) -> the students whose profiles they wrote."""
from tools.knowledge.sources import profile_authors
@ -796,6 +1214,43 @@ def same_supervisor(person: str) -> dict | None:
return {"text": text, "urls": [u for u in [*work_urls(person, []), *urls] if u]}
def same_opponent(person: str, low: str) -> dict | None:
""""Ktorí študenti zo ZP Wiki mali pri bakalárskej práci rovnakého oponenta ako Martin Šarišský?": the opponent of
the person's thesis in the register and the other wiki students whose thesis (of that type) he or she reviewed."""
from tools.crzp.source.parse import display_name
kinds = [k for k in asked_types(low) if k in THESES] or sorted(THESES)
own = [w for w in person_works(person) if w.get("row") and not w.get("unconfirmed")
and CRZP_TYPES.get(w["row"].get("work_type"), w["row"].get("work_type")) in kinds]
if not own:
return None
opponents = {display_name(n) for w in own for n in w["row"].get("opponents", [])}
if not opponents:
return None
found = []
for page in wiki_pages():
if page["name"] == person:
continue
for work in person_works(page["name"]):
row = work.get("row")
if not row or work.get("unconfirmed"):
continue
kind = CRZP_TYPES.get(row.get("work_type"), row.get("work_type"))
names = {display_name(n) for n in row.get("opponents", [])}
if kind in kinds and names & opponents:
found.append((page, crzp_work(row), sorted(names & opponents)))
found.sort(key=lambda f: (-(f[1].get("year") or 0), normalized(f[0]["name"])))
what = TYPES[kinds[0]][2] if len(kinds) == 1 else "záverečnej práci"
lead = f"Oponentom {TYPES[own[0]['type']][1] if own[0]['type'] in TYPES else 'práce'} {genitive(person)} bol " \
f"{join(sorted(opponents))}."
urls = work_urls(person, own)
if not found:
return {"text": lead + f" Iný študent ZP Wiki ho pri {what} ako oponenta nemal.", "urls": urls}
lines = [f"- {spelled(p['name'])} — {describe(w)}; oponent: {join(o)}" for p, w, o in found[:40]]
urls += [u for p, w, o in found[:10] for u in (p.get("url"), w.get("url"))]
return {"text": lead + f" Rovnakého oponenta pri {what} mali aj ({len(found)}):\n\n" + "\n".join(lines),
"urls": list(dict.fromkeys(u for u in urls if u))}
def supervisor_overview(name: str) -> dict:
""""Kto je Daniel Hládek?": a supervisor of ZP Wiki, how many students, the newest works of them."""
students = supervisor_students().get(name, [])
@ -867,7 +1322,7 @@ def work_title(person: str, works: list[dict], low: str) -> dict | None:
""""Aký je názov bakalárskej práce X?": the title of the asked work, from ZP Wiki or the same work in CRZP."""
kinds = [k for k in asked_types(low) if k in TYPES]
# no type asked: every recorded work counts (a current diploma project of ZP Wiki next to a defended BP)
pool = [w for w in works if not w.get("unconfirmed") and (w["type"] in kinds if kinds else w["type"] in TYPES)]
pool = [w for w in (of_kind(works, kinds) if kinds else works) if not w.get("unconfirmed") and w["type"] in (kinds or TYPES)]
if not pool:
return None
if len(pool) > 1 and not kinds:
@ -875,11 +1330,20 @@ def work_title(person: str, works: list[dict], low: str) -> dict | None:
label = "záverečné práce" if all(w["type"] in THESES for w in pool) else "práce"
return {"text": f"{spelled(person)} má tieto {label} (od najnovšej):\n\n" + "\n".join(lines),
"urls": work_urls(person, pool)}
if kinds: # two wiki records of one thesis (a planned title, then the defended one): the one the register knows
pool.sort(key=lambda w: not w.get("row"))
work = pool[0]
name = TYPES.get(work["type"], ("práca", "práce", "práci"))[1]
year = f" ({work['year']})" if work.get("year") else ""
if work.get("title"):
text = f"Názov {name} {genitive(person)}{year} je „{work['title'].rstrip('.')}“."
year = f" ({defended(work)})" if defended(work) else ""
compare = re.search(r"\b(?:zhod\w*|rovnak\w*|lis\w*|odlis\w*|zhodn\w*)\b", low)
other = register_title(work)
if other:
text = (f"Názov {name} {genitive(person)}{year} je v CRZP „{other.rstrip('.')}“, v ZP Wiki je uvedený ako "
f"„{work.get('wiki_title', work['title']).rstrip('.')}“." + (" Názvy sa nezhodujú." if compare else ""))
elif work.get("title"):
both = compare and (work.get("row") or {}).get("title") and work["source"] == "wiki"
text = (f"Názov {name} {genitive(person)}{year} je „{work['title'].rstrip('.')}“"
+ (" v ZP Wiki aj v CRZP, názvy sa zhodujú." if both else "."))
else:
text = f"Názov {name} {genitive(person)}{year} v podkladoch nie je uvedený."
return {"text": text, "urls": work_urls(person, [work])}
@ -929,15 +1393,19 @@ def works_list(person: str, works: list[dict]) -> dict | None:
def about(person: str, works: list[dict], low: str, complete=None) -> dict | None:
kind = asked_type(low)
pool = [w for w in works if w["type"] == kind] if kind else [w for w in works if w["type"] in THESES] or works
pool = of_kind(works, kind) if kind else [w for w in works if w["type"] in THESES] or works
if not pool:
return None
if kind: # two wiki records of one thesis: the one the register knows
pool.sort(key=lambda w: not w.get("row"))
work = pool[0]
title = f" „{work['title'].rstrip('.')}“" if work.get("title") else ""
if register_title(work) and register_title(work) != work.get("title"):
title += f" (v CRZP „{register_title(work).rstrip('.')}“)"
names = TYPES.get(work["type"]) or ("práca", "práce", "práci")
lines = []
if work["source"] == "wiki":
head = f"{names[0][:1].upper() + names[0][1:]} {genitive(person)}" + (f" ({work['year']})" if work.get("year") else "")
head = f"{names[0][:1].upper() + names[0][1:]} {genitive(person)}" + (f" ({defended(work)})" if defended(work) else "")
lines.append(head + (f" sa volá{title}." if title else " nemá v podkladoch uvedený názov."))
goals = goals_of(person, work.get("heading"))
if goals:
@ -1123,10 +1591,17 @@ def meeting(person: str, text: str, low: str, follow_up: bool) -> str | None:
return "\n".join(out)
def comparison(names: list[str], collaboration: bool = False, crzp_rows: list[dict] | None = None) -> dict | None:
def comparison(names: list[str], collaboration: bool = False, crzp_rows: list[dict] | None = None,
low: str = "") -> dict | None:
"""A table of two students: their main work, focus, results and tools; shared points below
(crzp_rows: the register's works of a person ZP Wiki does not know)."""
(crzp_rows: the register's works of a person ZP Wiki does not know). Asked for the roles or years of the
works ("kto ich viedol, kto bol oponent a kedy ich obhájili"): those facts of each person's work."""
from tools.answers.combined import comparison_block
if low and any(p.search(low) for n, p in CARD_ASPECTS if n in CARD_LABEL or n == "year"):
cards = [work_card(n, person_works(n, crzp_rows), low + " nazov") for n in names]
if all(cards):
return {"text": "\n\n".join(c["text"] for c in cards),
"urls": list(dict.fromkeys(u for c in cards for u in c["urls"]))}
data = []
for name in names:
merged = [w for w in person_works(name, crzp_rows) if not w.get("unconfirmed")]

View File

@ -0,0 +1,118 @@
"""The path of one answer in the timing log: which rewrite, plan, branch and source produced it.
Every traced function that returns something adds a short label to the answer's timing record
("unified.work_title", "crzp.find=12", "plan=meeting/ambiguous_work"), so an evaluation can tell
where a question failed. Labels only, never user text; the answer itself is unchanged.
ANSWER_ROUTE_TRACE=0 turns it off.
"""
from __future__ import annotations
import functools
import os
import sys
from tools.answers import timing
LIMIT = 80
# module -> (function, label); a missing function is skipped
TRACED = {
"tools.answers.combined": [
("ellipsis", "rewrite.ellipsis"), ("again", "rewrite.again"), ("named_back", "rewrite.named_back"),
("with_subject", "rewrite.with_subject"), ("_subject_retry", "rewrite.subject_retry"),
("_back_to_person", "rewrite.back_to_person"), ("_newest_of", "combined.newest_of"),
("_future_defences", "combined.future_defences"), ("_schools_answer", "combined.schools"),
("_next_page", "combined.next_page"), ("_crzp_work_answer", "combined.crzp_work"),
("_reference", "combined.reference"), ("_answer_choice", "combined.choice"), ("_return_to", "combined.return_to"),
("_ask_choice", "combined.ask_choice"), ("_with_people", "combined.with_people"),
("crzp_plan", "crzp.plan"), ("_crzp_part", "crzp.part"), ("_unified", "unified"),
],
"tools.answers.presentation.unified": [
("person_works", "unified.person_works"), ("work_title", "unified.work_title"),
("work_count", "unified.work_count"), ("roles", "unified.roles"), ("who", "unified.who"),
("works_list", "unified.works_list"), ("comparison", "unified.comparison"), ("methods", "unified.methods"),
("meeting", "unified.meeting"), ("start_year", "unified.start_year"), ("same_supervisor", "unified.same_supervisor"),
("supervisor_overview", "unified.supervisor_overview"), ("intern_overview", "unified.intern_overview"),
("tag_answer", "unified.tag_answer"), ("top_topics", "unified.top_topics"), ("started_answer", "unified.started"),
("supervisor_in", "unified.supervisor_in"),
],
"tools.crzp.answering.answer": [("find", "crzp.find"), ("topical", "crzp.topical"), ("answer", "crzp.answer")],
"tools.answers.planning.question_plan": [("build_question_plan", "plan")],
"tools.answers.planning.question_catalog": [("classify", "catalog"), ("route_for", "catalog.route")],
"tools.answers.answer_delivery": [("deliver_answer", "wiki.deliver")],
"app.routes": [("deliver_answer", "wiki.deliver")],
}
def mark(label: str) -> None:
record = timing._current.get()
if record is None:
return
with record["_lock"]:
trail = record.setdefault("route", [])
if len(trail) < LIMIT:
trail.append(label[:90])
def summary(result) -> str:
"""A short machine description of a returned value."""
if isinstance(result, str):
return ""
if isinstance(result, dict):
parts = [str(result.get(k)) for k in ("status", "reason") if result.get(k)]
return "/".join(parts)
if isinstance(result, (list, tuple)):
if isinstance(result, tuple) and result and isinstance(result[0], str):
mode = result[0]
query = result[1] if len(result) > 1 else None
intent = getattr(query, "intent", None)
roles = ",".join(p.role for p in getattr(query, "people", []) or [])
topics = len(getattr(query, "topics", []) or [])
return f"{mode}/{intent}/people:{roles or '-'}/topics:{topics}"
if isinstance(result, tuple):
return "/".join(str(len(x)) if isinstance(x, list) else type(x).__name__ for x in result[:2])
return str(len(result))
spec = getattr(result, "spec", None)
if spec is not None or hasattr(result, "reason"):
return "/".join(str(v) for v in (getattr(spec, "intent", None), getattr(result, "reason", None),
getattr(result, "origin", None)) if v)
kind = getattr(result, "type", None)
return str(kind) if kind else type(result).__name__
def _wrap(module, name: str, label: str) -> None:
original = getattr(module, name, None)
if original is None or not callable(original) or getattr(original, "_route_traced", False):
return
@functools.wraps(original)
def traced(*args, **kwargs):
try:
result = original(*args, **kwargs)
except Exception as error:
mark(f"{label}!{type(error).__name__}")
raise
if result is not None and result is not False and result != "":
detail = summary(result)
mark(label + (f"={detail}" if detail else ""))
return result
traced._route_traced = True
setattr(module, name, traced)
def install() -> None:
if os.getenv("ANSWER_ROUTE_TRACE", "1") == "0":
return
import importlib
for module_name, functions in TRACED.items():
module = sys.modules.get(module_name)
if module is None and module_name != "app.routes":
try:
module = importlib.import_module(module_name)
except Exception:
continue
if module is None:
continue
for name, label in functions:
_wrap(module, name, label)

View File

@ -33,6 +33,9 @@ def name_token_variants(token: str) -> set[str]:
variants.update(irregular.get(token, ()))
if token.endswith(('ii', 'yi')):
variants.add(token + 'ho')
elif token.endswith('i') and len(token) >= 4:
# an adjectival surname: Lindvai -> Lindvaiho, Lindvaimu, Lindvaim; Horáni -> Horániho
variants.update(token + s for s in ('ho', 'mu', 'm'))
if token.endswith("ova"):
variants.update(token[:-1] + s for s in ("ej", "u", "ou"))
elif token.endswith("y"):