"""One answer from ZP Wiki and CRZP, written as plain sentences. tools/answers/combined.py asks both sources; this module decides how the answer reads, for every kind of question the same way: - one answer, never one part per source: a work found in both sources is one work (its facts from both), the text never says where a fact was found (the links are in "Zdroje:" at the end); - the first sentence answers the question ("Ronald Zalačko začal študovať v roku 2023."), details follow as points, nothing that was not asked; - no internal labels ("Zaznamenaný výsledok:", "Priebežný stav:") and no "Osoba — Práca" headings for a question about one person; - lists of works, students and candidates go from the newest to the oldest. Everything is built from source records (the wiki's works and titles as the graph build reads them, the profile records, the CRZP rows); nothing is generated by a model here. """ from __future__ import annotations import json import re import threading from pathlib import Path from tools.answers.verification.context_policy import normalized TYPES = { # work type -> (nominative, genitive, locative) "bachelor_thesis": ("bakalárska práca", "bakalárskej práce", "bakalárskej práci"), "diploma_thesis": ("diplomová práca", "diplomovej práce", "diplomovej práci"), "doctoral_thesis": ("dizertačná práca", "dizertačnej práce", "dizertačnej práci"), "habilitation_thesis": ("habilitačná práca", "habilitačnej práce", "habilitačnej práci"), "rigorous_thesis": ("rigorózna práca", "rigoróznej práce", "rigoróznej práci"), "bachelor_project": ("bakalársky projekt", "bakalárskeho projektu", "bakalárskom projekte"), "diploma_project": ("diplomový projekt", "diplomového projektu", "diplomovom projekte"), "team_project": ("tímový projekt", "tímového projektu", "tímovom projekte"), "research_project": ("vedecký projekt", "vedeckého projektu", "vedeckom projekte"), } SHOWN_TOOLS = 8 # technologies listed at once; the rest on request THESES = {"bachelor_thesis", "diploma_thesis", "doctoral_thesis", "habilitation_thesis", "rigorous_thesis"} CRZP_TYPES = {"dissertation": "doctoral_thesis", "doctoral_thesis": "rigorous_thesis"} # CRZP names -> wiki names ASKED_TYPE = [(r"\bbakalar\w*\s+prac\w*|\bbakalark\w*|\bbakalarsk\w*\b(?!\s+projekt)|\bbp\b", "bachelor_thesis"), (r"\bdiplomov\w*\s+prac\w*|\bdiplomov\w*\b(?!\s+projekt)|\bdp\b", "diploma_thesis"), (r"\bdizertac\w*|\bdisertac\w*|\bdoktorand\w*|\bphd\b", "doctoral_thesis"), (r"\bbakalar\w*\s+projekt\w*", "bachelor_project"), (r"\bdiplomov\w*\s+projekt\w*", "diploma_project"), (r"\btimov\w*\s+projekt\w*", "team_project")] UPPER = "A-ZÁÄČĎÉÍĹĽŇÓÔŔŠŤÚÝŽ" LABELS = re.compile(r"^\s*(?:[-*]\s*)?(?:Zaznamenan\w+ výsled\w+|Priebežn\w+ stav|Úloha zo stretnutia|Zadanie|" r"Záznam|Plánovan\w+ úloh\w*|Zaznamenaný priebeh|Zameranie)\s*(?:\([^)]*\))?\s*:\s*", re.I) STUDY_START = re.compile(r"\b(?:zaciat\w*\s+stud\w*|zacal\w*\s+stud\w*)\b") SUPERVISOR_Q = re.compile(r"\b(?:kto\s+(?:je|bol|bola)\s+(?:ved[uú]c|skolitel)\w*|ved[uú]c\w*\s+(?:prac|projekt)\w*|" r"kto\s+(?:vedie|viedol|viedla|skoli|skolil))\b") WORKS_Q = re.compile(r"\b(?:ake|ktore)\s+(?:prace|projekty|zaverecne prace)\b|\bprace\s+(?:robil|robila|ma|mal|mala)\b") ABOUT_Q = re.compile(r"\bo\s+com\s+(?:je|bola|bude)\b|\bco\s+(?:robil|robila|riesil|riesila)\b(?:\s+\w+){0,4}?\s+(?:v|vo)\s+" r"(?:svojej\s+)?(?:bakalar|diplom|dizerta|praci|projekt)") # "Čo robil Kristián Sopkovič?" without a time or meeting: an overview of the person's works DID_Q = re.compile(r"^\W*(?:a\s+)?(?:co|na\s+com)\s+(?:robil|robila|robi|pracoval|pracovala|pracuje)\b(?!.*\b(?:v|na|vo)\s)") BOTH_TYPES = re.compile(r"\b(?:bakal\w*|diplom\w*|bp|dp)(?:\s+prac\w*)?\s+(?:a|aj|i|ako\s+aj)\s+(?:(?:v|vo|u|pri)\s+)?" r"(?:jeho\s+|jej\s+|svojej\s+)?(?:bakal\w*|diplom\w*|bp|dp)\b") # "Kto je Matej Ščišľak?", "Ján Holp" (only the name): who the person is, the works newest first WHO_Q = re.compile(r"^\W*(?:a\s+)?(?:kto\s+(?:je|bol|bola|je\s+to)|povedz\s+mi\s+(?:nieco\s+)?o|predstav\s+mi)\s+\S") # "Koľko záverečných prác má X?", "Má X jednu alebo dve diplomové práce?" (not a supervisor's count) COUNT_WORKS_Q = re.compile(r"\bkolk\w*\b[^?]*\bprac\w*|\bjednu\s+alebo\s+dve\b|\bkolko\s+(?:bakalar|diplom|zaverec)\w*") TITLE_Q = re.compile(r"\b(?:nazov|nazvom|nazvu|ako\s+sa\s+vola|nazyva\w*)\b") METHODS_Q = re.compile(r"\b(?:technolog\w*|nastroj\w*|metod\w*|pouziv\w*|vyuziv\w*|framework\w*)\b") TASKS_Q = re.compile(r"\b(?:uloh\w*|dostal\w*|zadal\w*|ma\s+urobit|treba\s+urobit)\b") COUNT_STUDENTS_Q = re.compile(r"\bkolk\w*\s+(?:studentov|student\w*|ludi|osob)\b") ROSTER_Q = re.compile(r"\b(?:koho\s+vedie|koho\s+viedol|koho\s+viedla|ktor\w*\s+studentov\s+vedie|studenti\s+(?:ktorych|ktore)\s+vedie)\b") _lock = threading.Lock() _catalog: dict = {} # ------------------------------------------------------------------ names and words def female(name: str) -> bool: from tools.answers.presentation import names return names.female(name) def rule_female(name: str) -> bool: words = name.split() return bool(words) and (words[-1].endswith(("ová", "á")) or words[0].endswith("a") and words[0] not in {"Nikita", "Luca"}) def ending(name: str) -> str: """"a" for a woman ("začala"), "" for a man.""" return "a" if female(name) else "" def genitive(name: str) -> str: """"Ronalda Zalačka", "Andriiho Pervashova": the checked forms of tools/answers/presentation/names.py.""" from tools.answers.presentation import names return names.case(name, "genitive") def spelled(name: str) -> str: from tools.answers.presentation import names return names.spelled(name) def rule_genitive(name: str) -> str: """"Ronalda Zalačka", "Simony Bobrovčanovej", "Kristiána Sokolského" (common Slovak patterns).""" words = name.split() if not words or len(words) > 4: return name out = [] for i, word in enumerate(words): last = i == len(words) - 1 if rule_female(name): if word.endswith("ová"): word = word[:-1] + "ej" elif last and word.endswith("á"): word = word[:-1] + "ej" elif word.endswith("a"): word = word[:-1] + ("y" if not word[-2:-1] in "kgh" else "y") else: if word.endswith(("ý", "y")) and len(word) > 3 and last: word = word[:-1] + "ého" elif word.endswith("ek") and len(word) > 4: word = word[:-2] + "ka" elif word.endswith("o"): word = word[:-1] + "a" elif word.endswith("a"): word = word[:-1] + "u" elif word.endswith("i"): word = word + "ho" elif word[-1:].isalpha() and word[-1] not in "aeiouyáéíóúý": word = word + "a" out.append(word) return " ".join(out) def day(value: str | None) -> str: """"2026-10-16" -> "16.10.2026", as the wiki writes dates (other forms unchanged).""" match = re.fullmatch(r"(\d{4})-(\d{2})-(\d{2})", value or "") return f"{int(match[3])}.{int(match[2])}.{match[1]}" if match else (value or "") def plural_students(count: int) -> str: return f"{count} študenta" if count == 1 else f"{count} študentov" def join(names: list[str]) -> str: names = [n for n in names if n] return names[0] if len(names) == 1 else ", ".join(names[:-1]) + " a " + names[-1] if names else "" def asked_type(low: str) -> str | None: return next((kind for pattern, kind in ASKED_TYPE if re.search(pattern, low)), None) def asked_types(low: str) -> list[str]: """Every work type the question names, in its order ("u bp … a u dp" -> bachelor, diploma).""" found = [] for pattern, kind in ASKED_TYPE: match = re.search(pattern, low) if match and kind not in (k for _, k in found): found.append((match.start(), kind)) return [kind for _, kind in sorted(found)] def clean_point(text: str) -> str: """One record as a point: no list marker, label, checkbox or trailing colon.""" text = re.sub(r"^\s*(?:[-*+]|\d+[.)])\s+", "", text.strip()) text = re.sub(r"\[([^\]]+)\]\([^)]*\)", r"\1", text) # a Markdown link: its words text = LABELS.sub("", text) text = re.sub(r"^\[[xX]\]\s*", "", text) text = re.sub(r"^\[\s\]\s*", "", text) text = re.sub(r"\s+", " ", text).strip() return text[:1].upper() + text[1:] if text else text # ------------------------------------------------------------------ wiki works (as the graph build reads them) def catalog() -> dict: """{"people": {name: {...}}, "works": {name: [work, ...]}} from documents.json/chunks.json, rebuilt only when the published files change (the same reading as the GraphRAG graph).""" from tools.rag.common import DB_FILE folder = Path(DB_FILE).parent try: key = tuple((folder / f).stat().st_mtime_ns for f in ("documents.json", "chunks.json")) except OSError: return {"people": {}, "works": {}} with _lock: if _catalog.get("key") == key: return _catalog["value"] from tools.graphrag.graphrag import build_graph_payload try: payload = build_graph_payload(json.loads((folder / "documents.json").read_text(encoding="utf-8")), json.loads((folder / "chunks.json").read_text(encoding="utf-8"))) except (OSError, ValueError): return {"people": {}, "works": {}} docs = {d["path"]: d for d in payload["documents"]} people = {p["id"]: p for p in payload["people"]} records = {r["id"]: r for r in [*payload["theses"], *payload["works"]]} works: dict = {} for relation in [*payload["person_theses"], *payload["person_works"]]: person = people.get(relation["person_id"]) record = records.get(relation.get("thesis_id") or relation.get("work_id")) if not person or not record: continue works.setdefault(person["name"], []).append({ "type": record.get("thesis_type") or record.get("work_type"), "heading": record.get("heading"), "title": record.get("title"), "year": record.get("year"), "source": "wiki", "url": (docs.get(record.get("source_document")) or {}).get("source_url"), "path": record.get("source_document")}) texts: dict = {} for chunk in sorted(json.loads((folder / "chunks.json").read_text(encoding="utf-8")), key=lambda c: (c.get("document_path"), c.get("chunk_index", 0))): texts.setdefault(chunk.get("document_path"), []).append(chunk.get("text") or "") value = {"people": {p["name"]: {**p, "url": (docs.get(p.get("source_document")) or {}).get("source_url")} for p in payload["people"]}, "works": works, "texts": {path: "\n\n".join(parts) for path, parts in texts.items()}} _catalog.update(key=key, value=value) return value def units(person: str) -> list[dict]: from tools.answers.combined import wiki_units return wiki_units(person) 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 # 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)): return match.group(1) paths = {u["source_path"] for u in units(person)} return next((profile_authors().get(p) for p in paths if profile_authors().get(p)), None) def results_of(person: str, heading: str | None, limit: int = 2) -> list[str]: """The newest recorded results of one work (short), checked tasks last.""" rows = [u for u in units(person) if u.get("work_label") == heading and u.get("phase") in {"result", "progress"}] rows.sort(key=lambda u: (u["text"].lstrip("- ").startswith("[x]"), u.get("phase") != "result", -(int((u.get("record_date") or "0").replace("-", "") or 0)))) out = [] for row in rows: point = clean_point(row["text"]) if re.match(r"(?i)(?:prečítan|preštudovan|naštudovan|nie je posun|progres zatiaľ|bez posunu|urobené poznámky)", point): continue # reading or "no progress": no result of the work if 12 <= len(point) <= 220 and point not in out and not point.endswith((":", "?")): out.append(point) if len(out) >= limit: break 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:").""" rows = sorted((u for u in units(person) if u.get("work_label") == heading), key=lambda u: u.get("line", 0)) groups = {"goal": [], "task": []} label = None for row in rows: text = row["text"].strip() if row.get("kind") == "meeting" or row.get("meeting_id"): break # the meetings follow; their tasks are no goals of the work if text.endswith(":") and not text.startswith(("-", "*")): low = normalized(text) label = "goal" if re.search(r"\bciel|\bzadani|\bnavrh na zadanie", low) else \ "task" if re.search(r"\buloh|\bzasobnik", low) else None continue if row.get("phase") == "assignment": groups["goal"].append(row) elif label and text.startswith(("-", "*")) and row.get("phase") != "administrative": groups[label].append(row) out = [] for row in groups["goal"] if len(groups["goal"]) >= 2 else [*groups["goal"], *groups["task"]]: point = clean_point(row["text"]) if len(point) >= 12 and not point.endswith(":") and point not in out: out.append(point) if len(out) >= limit: break return out # ------------------------------------------------------------------ one list of works from both sources def _stems(text: str) -> set: return {w[:5] for w in normalized(text or "").split() if len(w) > 3} def _same_title(a: str | None, b: str | None) -> bool: x, y = _stems(a), _stems(b) return bool(x and y) and len(x & y) >= max(1, (min(len(x), len(y)) + 1) // 2) def crzp_work(row: dict) -> dict: kind = CRZP_TYPES.get(row.get("work_type"), row.get("work_type")) return {"type": kind, "heading": None, "title": row.get("title"), "year": row.get("year"), "source": "crzp", "url": row.get("url"), "row": row} _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 ask the register.""" import time from tools.crzp.source.parse import display_name, fold if time.time() - _registry["stamp"] > 1800: by_author: dict = {} try: from tools.crzp.fetch import store for row in store().cached_rows(): school = fold(row.get("school") or "") if "technick" not in school or "kosiciach" not in school: continue for author in row.get("authors", []): 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) return list((_registry["by_author"].get(" ".join(fold(person).split())) or {}).values()) def person_works(person: str, crzp_rows: list[dict] | None = None) -> list[dict]: """The person's works, newest first: a CRZP work that is a wiki work (same title, or the same thesis type and year) is one work with the facts of both. The register's works come from this question's CRZP part and from the local cache of the register.""" from tools.crzp.answering import answer as crzp works = [dict(w) for w in catalog()["works"].get(person, [])] wiki_known = bool(works or catalog()["people"].get(person)) rows, seen = [], set() for row in [*(crzp_rows or []), *registry_rows(person)]: key = (normalized(row.get("title") or ""), row.get("year")) if key not in seen: seen.add(key) rows.append(row) for row in rows: if not crzp.people_in_role(row, person, "author"): 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"): return False # 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") 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) item["unconfirmed"] = wiki_known and not ( same_person_work(person, row) or fits_studies(person, row, item, works)) works.append(item) # A thesis without a title continues the project of its level ("Diplomový projekt 2026: # Inštrukčné dotrénovanie jazykového modelu" -> the diploma thesis 2027): that topic is shown. level = {"diploma_thesis": "diploma_project", "bachelor_thesis": "bachelor_project"} for work in works: if not work.get("title") and work["type"] in level: project = max((w for w in works if w["type"] == level[work["type"]] and w.get("title")), key=lambda w: w.get("year") or 0, default=None) if project: work["topic"] = project["title"] works.sort(key=lambda w: (-(w.get("year") or 0), w["type"] not in THESES)) 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 year_note(work: dict) -> str: """" (v ZP Wiki je pri práci uvedený rok 2020)" when the register's year of a thesis is another than the wiki's.""" own = work.get("wiki_year", work.get("year") if work.get("source") == "wiki" else None) shown = defended(work) if work["type"] not in THESES or not own or not shown or own == shown: return "" return f" (v ZP Wiki je pri práci uvedený rok {own})" 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"), "wiki_year": w.get("year") if w.get("source") == "wiki" else None} 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 text = names[case] + (f" ({work['year']})" if work.get("year") else "") if title and work.get("title"): text += f" „{work['title'].rstrip('.')}“" elif title and work.get("topic"): text += f", téma: {work['topic'].rstrip('.')}" return text def work_urls(person: str, works: list[dict]) -> list[str]: urls = [(catalog()["people"].get(person) or {}).get("url")] for work in works: urls += [work.get("url"), *(work.get("urls") or []), (work.get("row") or {}).get("url")] return list(dict.fromkeys(u for u in urls if u)) # ------------------------------------------------------------------ answers by kind of question STUDY_YEARS = {"bachelor_thesis": (2, 4), "diploma_thesis": (4, 6)} # years after the start of studies (3 and 5, ±1) def fits_studies(person: str, row: dict, item: dict, works: list[dict]) -> bool: """A TUKE thesis of the person's whole name whose year fits the studies recorded in ZP Wiki (bachelor ~3, diploma ~5 years after the start) and of a type the wiki has no other work of: the same student, even with another supervisor and topic (the wiki profile often starts with the diploma thesis).""" from tools.crzp.answering import answer as crzp from tools.crzp.source.parse import display_name start = (catalog()["people"].get(person) or {}).get("start_year") span = STUDY_YEARS.get(item.get("type")) if not start or not span or not item.get("year") or crzp.university(row) != "Technická univerzita v Košiciach": return False try: start = int(start) except (TypeError, ValueError): return False whole = any(normalized(display_name(a)) == normalized(person) for a in row.get("authors", [])) other = any(w["source"] == "wiki" and w["type"] == item["type"] for w in works) return whole and not other and span[0] <= item["year"] - start <= span[1] def start_year(person: str) -> dict | None: year = (catalog()["people"].get(person) or {}).get("start_year") if not year: match = next((re.search(r"\b([12]\d{3})\b", u["text"]) for u in units(person) if normalized(u["text"]).startswith(("rok zaciatku studia", "beginning of the study"))), None) year = match.group(1) if match else None if not year: return None return {"text": f"{spelled(person)} začal{ending(person)} študovať v roku {year}.", "urls": work_urls(person, [])} # Roles at a work: the question words, the register's field and the words of the answer # (instrumental for one man / one woman / several people, the accusative asked for in a choice). ROLES = { "supervisor": {"field": "supervisors", "one": ("Vedúcim", "Vedúcou", "Vedúcimi"), "ask": "vedúceho"}, "opponent": {"field": "opponents", "one": ("Oponentom", "Oponentkou", "Oponentmi"), "ask": "oponenta"}, "consultant": {"field": "consultants", "one": ("Konzultantom", "Konzultantkou", "Konzultantmi"), "ask": "konzultanta"}, } ROLE_Q = [("opponent", re.compile(r"\boponent\w*|\boponoval\w*|\boponovan\w*")), ("consultant", re.compile(r"\bkonzultant\w*|\bkonzultoval\w*")), ("supervisor", re.compile(r"\bved[uú]c\w*|\bskolitel\w*|\bkto\s+(?:vedie|viedol|viedla|skoli|skolil)\b"))] def asked_role(low: str) -> str | None: """"Kto je vedúci / školiteľ / oponent / konzultant práce X?" -> the role asked for.""" return next((role for role, pattern in ROLE_Q if pattern.search(low)), None) def work_options(person: str, works: list[dict], low: str) -> list[dict] | None: """The person's theses when there are two or more and the question names none (which one?).""" if asked_type(low): return None theses = [w for w in works if w["type"] in THESES and not w.get("unconfirmed")] if len(theses) < 2: return None return [{"source": w["source"], "label": describe(w), "type": w["type"], **({"work": w.get("heading") or describe(w, title=False)} if w["source"] == "wiki" else {"key": f"{normalized(w['title'] or '')}|{w.get('year')}"})} for w in theses[:4]] def options_text(person: str, options: list[dict], what: str) -> str: return (f"{spelled(person)} má {len(options)} záverečné práce:\n\n" + "\n".join(f"{i}. {o['label']}" for i, o in enumerate(options, 1)) + f"\n\n{what}") def _role_people(person: str, work: dict, role: str, wiki_text: str) -> list[str]: """Who has the role at this work: the wiki's own statement (the profile's supervisor line or author, the consultant line), else the register; both the same person -> one name.""" from tools.crzp.source.parse import display_name row = work.get("row") or {} registry = [display_name(s) for s in row.get(ROLES[role]["field"], [])] own = [] if work["source"] == "wiki" and role == "supervisor": stated = re.findall(r"Vedúc\w*[^:\n]*:\s*(?:(?:Ing|Mgr|doc|prof|Bc|RNDr)\.?\s*)*([^.,(\n]+?)(?:,?\s*PhD)?\.?\s*$", wiki_text or "", re.M) found = stated[0].strip() if stated else wiki_supervisor(person, work.get("heading")) own = [found] if found else [] elif work["source"] == "wiki" and role == "consultant": for unit in units(person): if unit.get("kind") == "consultant" and unit.get("work_label") in (None, work.get("heading")): match = re.search(rf"(?:(?:Ing|Mgr|doc|prof|Bc|RNDr|PhD)\.?\s*)*([{UPPER}][\w\-]+\s+[{UPPER}][\w\-]+)", unit["text"]) if match: own.append(match.group(1)) if not own: return registry # the register names the opponents, consultants and the supervisors of its works def same(a, b): return set(normalized(a).split()) <= set(normalized(b).split()) people = [spelled(n) for n in own] if registry and not any(same(r, people[0]) for r in registry): # the two sources disagree: say both people[0] += f" (v registri záverečných prác je uvedený {registry[0]})" return people def roles(person: str, works: list[dict], low: str, wiki_text: str = "", role: str | None = None) -> dict | None: """"Vedúcim bakalárskej práce Ronalda Zalacka „…“ (2026) je Matúš Pleva." for one work; the question naming two theses ("u bp … a u dp") gets one sentence for both; two or more theses and no named one: {"options": …} (the answer asks which one); the same for opponents and consultants.""" role = role or asked_role(low) or "supervisor" named = [k for k in asked_types(low) if k in THESES] if len(named) >= 2: # "Kto bol vedúcim jeho bakalárky a kto je teraz pri diplomovke?" parts = [_role_part(person, works, k, role, low, wiki_text) for k in named] return _role_sentence(person, role, low, [p for p in parts if p]) if not asked_type(low) and CURRENT_WORK_Q.search(low): # "Kto je vedúci práce, ktorú robí X?": the work X is doing now, the newest thesis X has in ZP Wiki current = sorted((w for w in works if w["source"] == "wiki" and w["type"] in THESES and not w.get("unconfirmed")), key=lambda w: -(w.get("year") or 0)) people = _role_people(person, current[0], role, wiki_text) if current else [] if people: return _role_sentence(person, role, low, [{"work": current[0], "people": people}]) options = work_options(person, works, low) if options: same = same_role_people(person, works, role) if same: # "Kto je vedúci práce, ktorú robí X?" and every thesis had the same supervisor: no "which one?" return _role_sentence(person, role, low, same) word = "školiteľa" if re.search(r"\bskolitel", low) else ROLES[role]["ask"] # the word the question used return {"options": options, "text": options_text(person, options, f"Pri ktorej práci chceš vedieť {word}?")} kind = asked_type(low) part = _role_part(person, works, kind, role, low, wiki_text) if part and part.get("work") and not kind: # the thesis answered and a newer running work of ZP Wiki (the diploma project after a bachelor thesis): # "Kto je vedúci?" also asks who leads now, so both, the newest first year = part["work"].get("year") or 0 later = sorted((w for w in works if w["source"] == "wiki" and w["type"] not in THESES and (w.get("year") or 0) > year), key=lambda w: -(w.get("year") or 0)) if later: now = {"work": later[0], "people": _role_people(person, later[0], role, wiki_text)} if now["people"]: return _role_sentence(person, role, low, [now, part]) return _role_sentence(person, role, low, [part]) if part else None # "práce, ktorú robí X", "práca, na ktorej pracuje X": the work in progress, in the present tense CURRENT_WORK_Q = re.compile(r"\b(?:prac\w*|projekt\w*)\s*,?\s*(?:ktoru|ktory|na\s+ktorej|na\s+ktorom)\s+" r"(?:teraz\s+|prave\s+|aktualne\s+)?(?:robi|pise|pracuje|riesi|vypracuva)\b") def _stated_role(person: str, work: dict, role: str) -> list[str]: """The role at this work only from a record of the work itself: the register's row, or (supervisor) the work's own "Vedúci:" line in the wiki; never the profile's author or another work's line.""" from tools.crzp.source.parse import display_name row = work.get("row") or {} if row.get(ROLES[role]["field"]): return [display_name(s) for s in row[ROLES[role]["field"]]] if role == "supervisor" and work["source"] == "wiki": for unit in units(person): if (unit.get("kind") == "supervisor" and not unit.get("meeting_id") and unit.get("work_label") == work.get("heading") and re.match(r"^[-*\s]*(?:Ved[uú]c\w*|Školite\w*|Skolite\w*)[^:.\n]{0,30}:", unit["text"])): match = re.search(rf"(?:(?:Ing|Mgr|doc|prof|Bc|RNDr|PhD)\.?\s*)*([{UPPER}][\w\-]+\s+[{UPPER}][\w\-]+)", unit["text"].split(":", 1)[-1]) if match: return [match.group(1)] return [] def same_role_people(person: str, works: list[dict], role: str) -> list[dict] | None: """[{"work", "people"}] of every thesis when each has the role recorded at the work itself and it is the same person(s) at all of them; None otherwise (the answer asks which thesis).""" theses = [w for w in works if w["type"] in THESES and not w.get("unconfirmed")] if len(theses) < 2: return None parts = [{"work": w, "people": _stated_role(person, w, role)} for w in theses] keys = [frozenset(normalized(n) for n in p["people"]) for p in parts] if not all(keys) or len(set(keys)) != 1: return None return [{"work": p["work"], "people": [spelled(n) for n in p["people"]]} for p in parts] 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 = 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] chosen = (chosen or candidates)[:1] if not chosen: return {"missing": kind} if kind else None work = chosen[0] return {"work": work, "people": _role_people(person, work, role, wiki_text)} def _role_sentence(person: str, role: str, low: str, parts: list[dict]) -> dict | None: """One sentence: "Vedúcim bakalárskej práce X „…“ (2025) bol A a vedúcim jeho diplomovej práce „…“ (2027) je B."; a work the sources lack or whose role they do not record gets its own short sentence.""" import datetime if not parts: return None his = "jej" if female(person) else "jeho" words = ("Školiteľom", "Školiteľkou", "Školiteľmi") if role == "supervisor" and re.search(r"\bskolitel", low) \ else ROLES[role]["one"] clauses, extra, urls, doubtful = [], [], [], [] for part in parts: if part.get("missing"): names = TYPES.get(part["missing"]) or ("práca", "práce", "práci") extra.append(f"{names[0][:1].upper() + names[0][1:]} {genitive(person)} v podkladoch nie je.") continue 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" ({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]) if work.get("unconfirmed"): doubtful.append(names[2]) again = bool(clauses or extra) # the person was named in an earlier part: "jeho/jej" owner = his if again else genitive(person) if not people: later = (work.get("year") or 0) > datetime.date.today().year work_name = f"{his[:1].upper() + his[1:]} {names[0]}" if again else \ f"{names[0][:1].upper() + names[0][1:]} {genitive(person)}" if role == "opponent" and later: # not submitted yet: the opponent is named at the submission extra.append(f"{work_name}{title}{year} ešte nebola odovzdaná, oponent sa určuje až pri odovzdaní.") else: at = f"{his} {names[2]}" if again else f"{names[2]} {genitive(person)}" extra.append(f"Pri {at}{title}{year} {ROLES[role]['ask']} podklady neuvádzajú.") continue plain = [p.split(" (")[0] for p in people] lead = words[2] if len(people) > 1 else words[1] if female(plain[0]) else words[0] # an opponent reviews a submitted work (past); a supervisor or consultant of a running work "je" current = role != "opponent" and (work.get("year") or 0) >= datetime.date.today().year verb = ("sú" if current else "boli") if len(people) > 1 else "je" if current else ("bola" if female(plain[0]) else "bol") if clauses: # the second work: "a vedúcim jeho diplomovej práce …" clauses.append(f"{lead[:1].lower() + lead[1:]} {owner} {names[1]}{title}{year} {verb} {join(people)}") else: clauses.append(f"{lead} {names[1]} {owner}{title}{year} {verb} {join(people)}") text = (" a ".join(clauses) + ".") if clauses else "" text = " ".join(t for t in [text, *extra] if t) if doubtful: text += (f" Pri {' a '.join(doubtful)} nie je isté, že ide o tú istú osobu ako v profile študenta " "(iný vedúci a téma)." if len(parts) > 1 else " Nie je isté, že ide o tú istú osobu ako v profile študenta (iný vedúci a téma).") return {"text": text, "urls": list(dict.fromkeys(urls))} if text else None def supervisors(person: str, works: list[dict], low: str, wiki_text: str = "") -> dict | None: return roles(person, works, low, wiki_text, "supervisor") _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)}{year_note(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 file = Path(DB_FILE).parent / "chunks.json" try: stamp = file.stat().st_mtime_ns except OSError: return [] with _lock: if _chunks.get("stamp") != stamp: by_path: dict = {} for chunk in json.loads(file.read_text(encoding="utf-8")): by_path.setdefault(chunk.get("document_path"), []).append(chunk) _chunks.update(stamp=stamp, by_path=by_path) rows = sorted(_chunks["by_path"].get(path, []), key=lambda c: c.get("chunk_index") or 0) return [re.sub(r"^Dokument:[^\n]*\n+", "", c.get("text") or "") for c in rows] def intern_overview(person: str) -> dict | None: """An intern's page has no thesis headings: its topic, goals and outputs as written ("Topic:", "Goal:", "Outputs:").""" info = catalog()["people"].get(person) or {} text = "\n".join(page_chunks(info.get("source_document") or "")) if not text.strip(): 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: # "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) topic = section("Topic", "Téma") goals, outputs = section("Goal", "Goals", "Ciele", "Cieľ"), section("Outputs?", "Outupus", "Results", "Výsledky") lead = f"{spelled(person)} je stážist{'ka' if female(spelled(person)) else 'a'} v ZP Wiki" + ( f", pobyt {stay.group(0).strip()}" if stay else "") + "." parts = [lead] if topic: parts.append("Téma: " + topic[0] + ".") if goals: parts.append("Ciele:\n" + "\n".join("- " + g for g in goals)) if outputs: parts.append("Výstupy:\n" + "\n".join("- " + o for o in outputs)) if len(parts) == 1: return None return {"text": "\n\n".join(parts), "urls": [info["url"]] if info.get("url") else []} _pages: dict = {} def wiki_pages() -> list[dict]: """Profiles of ZP Wiki (students and interns) with their tags and categories (documents.json).""" import ast from tools.rag.common import DB_FILE file = Path(DB_FILE).parent / "documents.json" try: stamp = file.stat().st_mtime_ns except OSError: return [] with _lock: if _pages.get("stamp") == stamp: return _pages["rows"] by_path = {p.get("source_document"): (name, p) for name, p in catalog()["people"].items()} rows = [] for doc in json.loads(file.read_text(encoding="utf-8")): if doc.get("path") not in by_path: continue name, person = by_path[doc["path"]] taxonomy = doc.get("taxonomy") if isinstance(taxonomy, str): try: taxonomy = ast.literal_eval(taxonomy) except (ValueError, SyntaxError): taxonomy = {} taxonomy = taxonomy if isinstance(taxonomy, dict) else {} rows.append({"name": name, "url": person.get("url"), "kind": person.get("person_kind"), "start_year": person.get("start_year"), "tags": [str(t).lower() for t in taxonomy.get("tag") or []], "categories": [str(c).lower() for c in taxonomy.get("category") or []]}) with _lock: _pages.update(stamp=stamp, rows=rows) return rows def _people_sentence(names: list[str], limit: int = 40) -> str: shown = [spelled(n) for n in names[:limit]] return ", ".join(shown) + (f" a ďalší ({len(names) - limit})" if len(names) > limit else "") TAG_Q = re.compile(r"\b(tag(?:om|u|y|mi|ov)?|kategori\w*)\s+([a-z0-9][a-z0-9\-]{1,30})\b") # The tag as written ("mind-maps", "c++"): normalized() drops the hyphen and the plus, the question's own text keeps them TAG_RAW = re.compile(r"\b(tag(?:om|u|y|mi|ov)?|kategori\w*)\s+([a-z0-9][a-z0-9\-+#.]{0,30}[a-z0-9+#])") def asked_tag(question: str) -> str | None: """The tag or category value of a tag question, with its hyphens and pluses.""" from tools.answers.planning.noise import fold_chars match = TAG_RAW.search(fold_chars(question)) return match.group(2) if match else None TOP_TOPICS_Q = re.compile(r"\bnajcast\w*\b[^?]*\b(?:tem\w*|tag\w*|oblast\w*)|\b(?:tem\w*|tag\w*|oblast\w*)\b[^?]*\bnajcast\w*") def tag_answer(question: str) -> dict | None: """"Ktorí študenti majú tag hatespeech?", "Koľko študentov má kategóriu dp2027?": every profile with it.""" low = normalized(question) match = TAG_Q.search(low) if not match: return None field = "categories" if match.group(1).startswith("kategori") else "tags" value = match.group(2) raw = asked_tag(question) if raw and raw != value and normalized(raw).replace(" ", "").startswith(value): value = raw # "mind-maps" (normalized: "mind maps", read as the tag "mind") rows = [r for r in wiki_pages() if value in r[field]] label = "Kategóriu" if field == "categories" else "Tag" if not rows: return {"text": f"{label} **{value}** v ZP Wiki nemá žiadny profil.", "urls": []} rows.sort(key=lambda r: (-(r.get("start_year") or 0), normalized(r["name"]))) names = [r["name"] for r in rows] n = len(names) who = "osoba" if n == 1 else "osoby" if n <= 4 else "osôb" verb = "má" if n == 1 else "majú" if re.search(r"\bkolk\w*|\bpocet\b", low): text = f"{label} **{value}** {verb} v ZP Wiki {n} {who}: {_people_sentence(names)}." else: lines = [] for r in rows[:40]: theses = [w for w in catalog()["works"].get(r["name"], []) if w.get("type") in THESES and w.get("title")] theses.sort(key=lambda w: -(w.get("year") or 0)) lines.append(f"- {spelled(r['name'])}" + (f" — {describe(theses[0])}" if theses else "")) text = f"{label} **{value}** {verb} v ZP Wiki {n} {who}:\n\n" + "\n".join(lines) if n > 40: text += f"\n\nZobrazených je 40 z {n}." return {"text": text, "urls": [r["url"] for r in rows[:10] if r.get("url")]} def top_topics() -> dict: """"Ktoré témy sú v ZP Wiki najčastejšie?": the tags of the profiles by how many profiles have them.""" from collections import Counter counts = Counter(t for r in wiki_pages() for t in set(r["tags"])) top = counts.most_common(12) lines = [f"- {t}: {n} {'profil' if n == 1 else 'profily' if n <= 4 else 'profilov'}" for t, n in top] return {"text": "Najčastejšie tagy profilov v ZP Wiki:\n\n" + "\n".join(lines), "urls": []} STARTED_Q = re.compile(r"\bzac\w*\s+(?:studovat|studium|studia|studovali|studoval\w*)\s+(?:v\s+)?(?:roku\s+)?((?:19|20)\d{2})" r"(?:\s+(?:alebo|a)\s+(neskor\w*|skor\w*|neskôr))?") def started_answer(question: str) -> dict | None: """"Ktorí študenti, čo začali študovať v roku 2022, robia diplomovú prácu?": the start of studies, not a work year.""" low = normalized(question) match = STARTED_Q.search(low) if not match: return 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(_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"])): works = [w for w in catalog()["works"].get(r["name"], []) if not kinds or w.get("type") in kinds] if kinds and not works: continue works.sort(key=lambda w: -(w.get("year") or 0)) lines.append(f"- {spelled(r['name'])}" + (f" — {describe(works[0])}" if works else "")) when = f"v roku {year}" + (" alebo neskôr" if more.startswith("nesk") else " alebo skôr" if more else "") accusative = " ".join(w[:-1] + "ú" if w.endswith("á") else w[:-1] + "u" if w.endswith("a") else w for w in TYPES[kinds[0]][0].split()) if len(kinds) == 1 else "" what = f" a majú {accusative}" if accusative else "" if not lines: return {"text": f"V podkladoch nie je študent, ktorý začal študovať {when}{what}.", "urls": []} text = f"Študenti, ktorí začali študovať {when}{what} ({len(lines)}):\n\n" + "\n".join(lines) 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" raw = asked_tag(question) value = raw if raw and normalized(raw).replace(" ", "").startswith(tag.group(2)) else tag.group(2) pages = [r for r in pages if value in r[field]] label.append(f"{'kategóriou' if field == 'categories' else 'tagom'} {value}") 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 by_path = {p.get("source_document"): name for name, p in catalog()["people"].items()} result: dict = {} for path, author in profile_authors().items(): if author and by_path.get(path): result.setdefault(author, []).append(by_path[path]) return result def supervisor_in(question: str) -> str | None: """A supervisor named in the question in any form ("Daniela Hládka", "Hládek", "Harahusa"): every word of the name, or the surname alone when no other supervisor has it.""" from tools.retrieval.person_names import name_token_variants words = set(re.findall(r"[a-z0-9]+", normalized(question))) found = [] for name in supervisor_students(): parts = normalized(name).split() hits = [any(v in words for v in name_token_variants(part)) for part in parts] if all(hits): return name if hits and hits[-1]: found.append(name) return found[0] if len(found) == 1 else None def same_supervisor(person: str) -> dict | None: """"Ktorí študenti mali rovnakého vedúceho ako Dmytro Mural?": the person's supervisor and his other students.""" supervisor = next((s for s, students in supervisor_students().items() if person in students), None) if not supervisor: return None others = [s for s in supervisor_students()[supervisor] if s != person] lead = f"Vedúcim {genitive(person)} je {spelled(supervisor)}." if not others: return {"text": lead + " Iných študentov s rovnakým vedúcim ZP Wiki neuvádza.", "urls": work_urls(person, [])} text = lead + f" Rovnakého vedúceho majú aj: {_people_sentence(sorted(others, key=normalized))}." urls = [catalog()["people"].get(s, {}).get("url") for s in others[:10]] 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, []) works = [] for student in students: for work in catalog()["works"].get(student, []): if work.get("type") in THESES and work.get("year"): works.append((work["year"], student, work)) works.sort(key=lambda w: (-w[0], w[1])) shown = spelled(name) lines = [f"{shown} je vedúci záverečných prác v ZP Wiki; vedie {len(students)} " f"{'študenta' if len(students) == 1 else 'študentov' if len(students) >= 5 else 'študentov'}."] if works: lines.append("Najnovšie záverečné práce jeho študentov:") lines += [f"- {spelled(s)} — {describe(w)}" for _, s, w in works[:6]] urls = [catalog()["people"].get(s, {}).get("url") for _, s, _ in works[:6]] return {"text": "\n".join(lines[:1]) + ("\n\n" + "\n".join(lines[1:]) if len(lines) > 1 else ""), "urls": [u for u in dict.fromkeys(urls) if u]} def _one_work(group: list[dict]) -> str: work = group[0] years = sorted({w.get("year") for w in group if w.get("year")}) text = describe(work) if len(years) > 1: text += f", záznamy z rokov {', '.join(map(str, years))}" return text def work_count(person: str, works: list[dict], low: str) -> dict | None: """"Koľko záverečných prác má Tomáš Kuchárik?": the person's works of the asked type, one entry per work (records of the same work in two years are one work; a namesake's CRZP work is not counted).""" kinds = asked_types(low) pool = [w for w in works if not w.get("unconfirmed")] if kinds: pool = [w for w in pool if w["type"] in kinds] elif re.search(r"\bzaverec\w*", low): pool = [w for w in pool if w["type"] in THESES] if not pool and not kinds: return None groups: dict = {} for work in sorted(pool, key=lambda w: -(w.get("year") or 0)): title = normalized(work.get("title") or "") key = (work["type"], title if title else f"#{work.get('year')}") groups.setdefault(key, []).append(work) n = len(groups) kind = TYPES[kinds[0]][0] if len(kinds) == 1 and kinds[0] in TYPES else ( "záverečná práca" if re.search(r"\bzaverec\w*", low) else "práca") words = kind.split() form = (lambda w: w[:-1] + ("é" if w.endswith("á") else "e")) if 2 <= n <= 4 else ( lambda w: w[:-1] + ("ých" if w.endswith("á") else "") if w.endswith("á") else w[:-1]) if n == 1: noun = " ".join([w[:-1] + "ú" if w.endswith("á") else w[:-1] + "u" if w.endswith("a") else w for w in words]) elif 2 <= n <= 4: noun = " ".join([form(w) for w in words[:-1]] + ["práce"]) else: noun = " ".join([w[:-1] + "ých" if w.endswith("á") else w for w in words[:-1]] + ["prác"]) if not n: return {"text": f"{spelled(person)} nemá v podkladoch žiadnu {kind}.", "urls": work_urls(person, [])} text = f"{spelled(person)} má v podkladoch {n} {noun}:\n\n" + "\n".join(f"- {_one_work(g)}" for g in groups.values()) same_kind = [k for k in {k for k, _ in groups} if k in THESES and sum(1 for t, _ in groups if t == k) > 1] if same_kind: # two diploma theses of one student: say what it may be text += ("\n\nDva záznamy toho istého typu záverečnej práce sú nezvyčajné; môže ísť o pokračovanie alebo " "premenovanie tej istej práce v ďalšom roku.") return {"text": text, "urls": work_urls(person, [w for g in groups.values() for w in g])} 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 (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: lines = [f"- {describe(w)}" for w in pool] 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" ({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])} def who(person: str, works: list[dict]) -> dict | None: """"Kto je X?": one lead sentence (a student of ZP Wiki, the study start) and the works, newest first.""" listed = works_list(person, works) if listed is None: return None start = start_year(person) year = re.search(r"(\d{4})", start["text"]).group(1) if start else None lead = (f"{spelled(person)} je študent{'ka' if female(spelled(person)) else ''} v ZP Wiki" + (f", štúdium začal{ending(person)} v roku {year}" if year else "") + ".") body = re.sub(r"^.+?(?:má tieto práce|má túto prácu):", "Práce od najnovšej:" if len(works) > 1 else "Práca:", listed["text"], count=1) return {**listed, "text": lead + " " + body} def works_list(person: str, works: list[dict]) -> dict | None: if not works: return None lines = [f"{spelled(person)} má tieto práce:" if len(works) > 1 else f"{spelled(person)} má túto prácu:", ""] from collections import Counter twice = Counter((w["type"], w.get("year")) for w in works) for work in works: names = TYPES.get(work["type"]) or (work.get("heading") or "Práca",) label = names[0][:1].upper() + names[0][1:] if twice[(work["type"], work.get("year"))] > 1 and work.get("heading"): # "Diplomový projekt 1" and "… 2" label = re.sub(r"\s*\b(?:19|20)\d{2}(?:/\d{2})?\b", "", work["heading"]).strip() or label head = f"- **{label}" + (f" ({work['year']})" if work.get("year") else "") + "**" if work.get("title"): head += f": {work['title'].rstrip('.')}" details = results_of(person, work.get("heading")) if work["source"] == "wiki" else [] if not work.get("year") and not work.get("title") and not details: continue # a heading without year, title or record says nothing lines.append(head) row = work.get("row") or {} if not details and row.get("supervisors"): from tools.crzp.source.parse import display_name details = [f"Vedúci: {display_name(row['supervisors'][0])}"] if work.get("unconfirmed"): details.append("Nie je isté, že ide o tú istú osobu (iný vedúci a téma).") lines += [f" - {d}" for d in details] return {"text": "\n".join(lines), "urls": work_urls(person, works)} def about(person: str, works: list[dict], low: str, complete=None) -> dict | None: kind = asked_type(low) 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" ({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: lines += ["", "Ciele práce:", *[f"- {g}" for g in goals]] done = results_of(person, work.get("heading"), limit=3) if done: lines += ["", "Doteraz urobil" + ending(person) + ":", *[f"- {d}" for d in done]] else: from tools.crzp.answering import answer as crzp row = work["row"] detail = crzp.fetch.detail(row["sid"]) if row.get("sid") else None summary = crzp.summary(detail, complete)[1] if detail else "" lines.append(f"{spelled(person)} v {names[2]}{title}" + (f" ({work['year']})" if work.get("year") else "") + ":") if summary: lines += ["", summary] if work.get("unconfirmed"): lines += ["", "Nie je isté, že ide o tú istú osobu ako v profile študenta (iný vedúci a téma)."] if len(lines) <= 1 and work["source"] == "wiki" and not title: return None return {"text": "\n".join(lines), "urls": work_urls(person, [work])} def methods(person: str, works: list[dict], wiki_text: str, crzp_text: str, low: str = "") -> dict | None: """One sentence per work with the tools of both sources (each tool once); only the asked work type.""" found: dict = {} # "v bakalárskej a v diplomovej práci": both; a follow-up joined to the previous question ("… v nej … a v # bakalárke?") names one type, the first one asked_type() finds kinds = asked_types(low) if BOTH_TYPES.search(low) else [k for k in [asked_type(low)] if k] official = {} for source, text in (("wiki", wiki_text), ("crzp", crzp_text)): for sentence in re.finditer(r"vo svojej ([^„\n]+?)\s*„([^“]+)“[^:\n]*?využíva:\s*([^\n]+?)\.\s*$", text or "", re.M): if kinds and normalized(sentence.group(1)) not in {normalized(TYPES[k][2]) for k in kinds if k in TYPES}: continue tools = [t.strip() for t in sentence.group(3).split(",") if t.strip()] found.setdefault(sentence.group(2), {"kind": sentence.group(1), "tools": []})["tools"] += tools if source == "crzp": official.update({normalized(t): t for t in tools}) if not found: return None lines = [] for title, entry in found.items(): merged = [] for tool in entry["tools"]: key = normalized(re.sub(r"\s*\([^)]*\)", "", tool)) same = next((i for i, t in enumerate(merged) if normalized(re.sub(r"\s*\([^)]*\)", "", t)) == key), None) if same is None: merged.append(tool) elif "(" in merged[same] and "(" not in tool: merged[same] = tool # a plain use wins over "(začína)" / "(v zadaní)" elif merged[same].islower() and not tool.islower() and "(" not in tool: merged[same] = tool # the name as its authors write it ("Streamlit", not "streamlit") merged = [official.get(normalized(t), t) if "(" not in t else t for t in merged] # "Neo4j", not "neo4J" twin = next((t for t in found if t != title and _same_title(t, title)), None) if twin and any(l.endswith(f"„{twin}“ využíva: ") for l in lines): continue lines.append((f"{spelled(person)} vo svojej {entry['kind']} „{title}“ využíva: ", merged)) # works of both sources with the same title: one sentence; at most SHOWN_TOOLS each, the rest offered unique, seen, rest, rest_lead = [], [], [], "" for lead, tools in lines: title = re.search(r"„([^“]+)“", lead).group(1) if any(_same_title(title, s) for s in seen): continue seen.append(title) unique.append(lead + ", ".join(tools[:SHOWN_TOOLS]) + ".") if len(tools) > SHOWN_TOOLS and not rest: rest = tools[SHOWN_TOOLS:] rest_lead = lead.replace(" využíva: ", " využíva aj: ") unique[-1] = unique[-1][:-1] + f" (uvedených {SHOWN_TOOLS} z {len(tools)})." missing = [] if len(kinds) >= 2: # a named work without recorded tools is said so, not left out said = {normalized(e["kind"]) for e in found.values()} for k in kinds: if k in TYPES and normalized(TYPES[k][2]) not in said: work = next((w for w in works if w.get("type") == k), None) if work: title = f" „{work['title']}“" if work.get("title") else "" year = f" ({work['year']})" if work.get("year") else "" unique.append(f"Pri {TYPES[k][2]}{title}{year} technológie v podkladoch zapísané nie sú.") missing.append((k, unique[-1])) out = {"text": "\n\n".join(unique), "urls": work_urls(person, works), "missing": missing} if rest: out.update(rest=rest, rest_lead=rest_lead, offer=f"Ďalších technológií a metód je ešte {len(rest)}. Chceš vidieť aj zvyšné?") return out def backlog_of(person: str, when: str) -> list[str]: """The points under "Zásobník úloh:" of the meeting of that date (meeting_section).""" return meeting_section(person, when, r"Zásobník úloh[^:\n]*") def tasks_of(person: str, when: str) -> list[str]: """The points under "Úlohy:" of the meeting of that date, as the profile writes them (never the "Stav:" points, which are the progress, and never the backlog).""" return meeting_section(person, when, r"Úlohy(?:\s*\([^)\n]*\))?") def meeting_section(person: str, when: str, label: str) -> list[str]: """The points under a section label in the record of the meeting of that date: the profile text from "Stretnutie 27.10.2026" to the next meeting or heading; [] when that meeting has no such section.""" match = re.fullmatch(r"(\d{1,2})\.(\d{1,2})\.(\d{4})", when) if not match: return [] iso = f"{match[3]}-{int(match[2]):02}-{int(match[1]):02}" marker = next((u for u in units(person) if u.get("kind") == "meeting" and (u.get("record_date") or u.get("date")) == iso), None) text = (catalog().get("texts") or {}).get((marker or {}).get("source_path"), "") start = text.find(marker["text"].strip()) if marker else -1 if start < 0: return [] rest = text[start + len(marker["text"].strip()):] stop = re.search(r"\n\s*(?:(?:Virtuálne\s+)?[Ss]tretnutie\b|#)", rest) block = rest[:stop.start()] if stop else rest points = [] # the index text joins overlapping chunks: a section may be cut in one and whole in the next for section in re.finditer(r"(?m)^\s*" + label + r":\s*\n((?:\s*[-*+].*(?:\n|$)|\s*\n)+)", block): for line in section.group(1).splitlines(): if line.strip().startswith(("-", "*", "+")): point = clean_point(line) if point and point not in points: points.append(point) return points def meeting(person: str, text: str, low: str, follow_up: bool) -> str | None: """A meeting record: "X na poslednom stretnutí 16. 10. 2026 riešil:" and its points.""" date = re.search(r"(?:Posledný záznam s úplným dátumom|Podľa zápisu zo stretnutia|Úlohy zo stretnutia|" r"stretnutia|stretnutie)\s*:?\s*(\d{4}-\d{2}-\d{2}|\d{1,2}\.\s*\d{1,2}\.\s*(?:\d{4})?)", text) if date: when = day(date.group(1).strip()) elif TASKS_Q.search(low) or re.search(r"\b(?:posledn\w*|naposledy)\b", low): # the wiki text names no date: the newest meeting dates = sorted((u.get("record_date") or u.get("date") or "") for u in units(person) if u.get("kind") == "meeting") dates = [d for d in dates if re.fullmatch(r"\d{4}-\d{2}-\d{2}", d)] if not dates: return None when = day(dates[-1]) if TASKS_Q.search(low) and (tasks_of(person, when) or backlog_of(person, when)): text = "" # the record's own sections answer it (below) else: return None if re.match(r"^\W*(?:a\s+)?kedy\b", low) and not re.search(r"\b(?:co|riesil\w*|robil\w*|uloh\w*)\b", low): # "Kedy sa naposledy stretol X s vedúcim?": the date is the answer, also of a meeting without recorded points return f"Posledné stretnutie {genitive(person)} bolo {when}." if re.search(r"\b(?:posledn|naposledy)", low) \ else f"Stretnutie {genitive(person)} bolo {when}." done, todo = [], [] section = None for raw in text.splitlines(): line = raw.strip() if not line or line.startswith("**") or re.match(r"(?:Posledný záznam|Podľa zápisu|Zdroj)", line): continue if re.match(r"(?i)^(?:stav|zaznamenan\w+ (?:výsledky|priebeh))\s*(?:\([^)]*\))?:$", line): section = "done"; continue if re.match(r"(?i)^(?:úlohy|plánované úlohy|úlohy zo stretnutia[^:]*)\s*(?:\([^)]*\))?:$", line): section = "todo"; continue if not line.startswith(("-", "*")): continue is_task = bool(re.match(r"^[-*]\s*(?:Úloha zo stretnutia|Plánovan\w+ úloh\w*)\s*:", line, re.I)) or section == "todo" point = clean_point(line) if point: (todo if is_task else done).append(point) if not done and not todo and not (TASKS_Q.search(low) and (tasks_of(person, when) or backlog_of(person, when))): return None if re.match(r"^\W*(?:a\s+)?kedy\b", low) and not re.search(r"\b(?:co|riesil\w*|robil\w*|uloh\w*)\b", low): return f"Posledné stretnutie {genitive(person)} bolo {when}." if re.search(r"\b(?:posledn|naposledy)", low) \ else f"Stretnutie {genitive(person)} bolo {when}." if re.search(r"\bzasobnik\w*", low) and not re.search(r"\b(?:ulohy|uloh)\b(?!\s*$)", low.replace("zasobnik uloh", "")): backlog = backlog_of(person, when) # "a čo zásobník úloh?": the backlog only return (f"Do zásobníka úloh zo stretnutia {when} patrí:\n\n" + "\n".join(f"- {p}" for p in backlog)) if backlog \ else f"Pri stretnutí {when} nie je zapísaný zásobník úloh." tasks_only = bool(TASKS_Q.search(low)) and not re.search(r"\b(?:riesil\w*|robil\w*|urobil\w*|stihol\w*)\b", low) last = "poslednom " if re.search(r"\bposledn\w*", low) or follow_up else "" backlog = backlog_of(person, when) stack = ("\n\n" + f"Do zásobníka úloh zo stretnutia {when} patrí:\n\n" + "\n".join(f"- {p}" for p in backlog)) if backlog else "" todo = tasks_of(person, when) or todo # the record's own "Úlohy:" points first if tasks_only: if not todo: # the progress ("Stav:") is never given out as tasks none = f"Pri stretnutí {when} nie sú zapísané úlohy." return none + stack if stack else none head = (f"Na stretnutí {when} dostal{ending(person)} tieto úlohy:" if follow_up else f"{spelled(person)} dostal{ending(person)} na {last}stretnutí {when} tieto úlohy:") return head + "\n\n" + "\n".join(f"- {p}" for p in todo) + stack out = [f"{spelled(person)} na {last}stretnutí {when} riešil{ending(person)}:", "", *[f"- {p}" for p in done]] if todo and not done: out = [f"Na {last}stretnutí {when} dostal{ending(person)} {spelled(person)} tieto úlohy:", "", *[f"- {p}" for p in todo]] elif todo and not re.search(r"\b(?:riesil\w*|robil\w*)\b", low): out += ["", "Úlohy na ďalšie stretnutie:", *[f"- {p}" for p in todo]] return "\n".join(out) + stack return "\n".join(out) 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). 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")] works = [w for w in merged if w["type"] in THESES] or merged if not works: return None work = works[0] newer = merged[0] # a newer project with recorded goals or results beats an older thesis without them if newer is not work and (newer.get("year") or 0) > (work.get("year") or 0) and newer.get("heading") and ( results_of(name, newer.get("heading"), 1) or goals_of(name, newer.get("heading"), 1)) and not ( results_of(name, work.get("heading"), 1)): work = newer data.append({"work": work, "goals": goals_of(name, work.get("heading"), 2), "results": results_of(name, work.get("heading"), 3)}) known = all(catalog()["people"].get(n) for n in names) block = (comparison_block(names) or "") if known else "" shared = re.search(r"- Spoločné: (.+)", block) only = [re.search(rf"- Len {re.escape(n)}: (.+)", block) for n in names] if not known: # a person only the register knows: the keywords of each main work, the shared ones below words = [list(dict.fromkeys((d["work"].get("row") or {}).get("keywords") or [])) for d in data] common = [w for w in words[0] if fold_word(w) in {fold_word(v) for v in words[1]}] only = [_Fixed(", ".join([w for w in ws if w not in common][:8])) if ws else None for ws in words] shared = _Fixed(", ".join(common[:8]) + ".") if common else None def cell(values): return "
".join(v.replace("|", "/") for v in values) if values else "–" rows = [("Práca", [describe(d["work"]) for d in data]), ("Zameranie", [cell(d["goals"]) for d in data]), ("Výsledky", [cell(d["results"]) for d in data]), ("Vlastné nástroje a pojmy", [o.group(1).rstrip(".") if o else "–" for o in only])] table = [f"| | {spelled(names[0])} | {spelled(names[1])} |", "|---|---|---|"] table += [f"| {label} | {a} | {b} |" for label, (a, b) in rows] lead = (f"Či by mohli spolupracovať {spelled(names[0])} a {spelled(names[1])}, ukazuje porovnanie ich prác:" if collaboration else f"Porovnanie prác {genitive(names[0])} a {genitive(names[1])}:") text = lead + "\n\n" + "\n".join(table) if shared: text += f"\n\nSpoločné majú: {shared.group(1)}" elif collaboration: text += "\n\nSpoločné pojmy v ich záznamoch nie sú; ich práce sa tematicky neprekrývajú." urls = list(dict.fromkeys(u for n, d in zip(names, data) for u in work_urls(n, [d["work"]]))) return {"text": text, "urls": urls} class _Fixed: """A ready text where comparison() reads a regex match (group(1)).""" def __init__(self, text: str): self.text = text def group(self, _): return self.text def fold_word(text: str) -> str: return normalized(text or "").strip() def roster_items(supervisor: str, wiki_items: list[dict], crzp_rows: list[dict]) -> list[dict]: """The students of a supervisor, newest work first, each once: name — work (year): title.""" from tools.crzp.answering import answer as crzp from tools.crzp.source.parse import display_name items = {} for item in wiki_items: works = person_works(item["name"]) main = next((w for w in works if w["type"] in THESES), works[0] if works else None) text = describe(main) if main else "práca bez uvedeného názvu" if main and not main.get("title"): goal = goals_of(item["name"], main.get("heading"), 1) if goal: text += f" — {goal[0][:120]}" items[normalized(item["name"])] = {**item, "name": spelled(item["name"]), "source": "line", "text": text, "year": max((w.get("year") or 0 for w in works), default=0)} for row in crzp_rows: if not crzp.people_in_role(row, supervisor, "supervisor"): continue name = display_name((row.get("authors") or [""])[0]) if not name or normalized(name) in items: existing = items.get(normalized(name)) if existing is not None and row.get("url"): existing.setdefault("urls", []).append(row["url"]) continue work = crzp_work(row) items[normalized(name)] = {"name": name, "source": "line", "school": crzp.university(row), "text": describe(work), "urls": [row["url"]] if row.get("url") else [], "year": row.get("year") or 0} return sorted(items.values(), key=lambda i: -(i.get("year") or 0)) def recency(name: str) -> str: """The newest record date of a wiki person ("" when none): for lists of people, newest first.""" dates = [u.get("record_date") or "" for u in units(name)] years = [str(w.get("year") or "") for w in catalog()["works"].get(name, [])] return max([*dates, *years, ""]) def strip_sources(text: str) -> str: """No "V CRZP …:" / "V ZP Wiki k tomu nie je záznam." / "(ZP Wiki)" in an answer.""" text = re.sub(r"(?m)^V ZP Wiki k tomu nie je záznam\.?\s*(?:Práce na túto tému v CRZP \(Centrálny register záverečných prác\):)?\s*$", "", text) text = re.sub(r"(?m)^V CRZP \(Centrálny register záverečných prác\):\s*$", "", text) text = re.sub(r"(?m)^Práce, ktoré (.+?) viedol alebo oponoval, v CRZP \(TUKE\):\s*$", r"Práce, ktoré \1 viedol alebo oponoval:", text) text = text.replace(" (ZP Wiki)", "").replace(" (CRZP)", "") # the register is the source of these facts; the answer names facts, its links are in "Zdroje:" for old, new in [(r" \(súhrnný počet z CRZP\)", ""), (r"\bV CRZP som nenašiel\b", "Nenašiel som"), (r"\bV CRZP som našiel\b", "Našiel som"), (r"\bCRZP pri tejto práci abstrakt neuvádza\.", "Pri tejto práci nie je uvedený abstrakt."), (r"\bCRZP (?:ich|ho|ju|to)? ?neuvádza\b", "nie je uvedené"), (r"\(CRZP ich nerozlišuje", "(nerozlišujú sa"), (r"\bpodľa CRZP\s+", ""), (r"\s+v CRZP\b", ""), (r"\s+z CRZP\b", ""), (r"\(návrh, nie overené synonymum\)", "(príbuzný výraz)")]: text = re.sub(old, new, text) text = re.sub(r"(?m)^Spolu (\d+) prác v CRZP na TUKE; zobrazených je (\d+) najnovších\.", r"Spolu \1 prác; zobrazených je \2 najnovších.", text) # "· [CRZP](odkaz)" in a line: the link goes to "Zdroje:" like every other source links = re.findall(r"\s*·\s*\[CRZP\]\((https?://[^)\s]+)\)", text) if links: text = re.sub(r"\s*·\s*\[CRZP\]\((https?://[^)\s]+)\)", "", text) line = re.search(r"(?m)^Zdroje?:\s*(.+)$", text) known = re.findall(r"https?://[^\s,]+", line.group(1)) if line else [] extra = [u for u in dict.fromkeys(links) if u not in known] if line: text = text[:line.end()] + (", " if extra else "") + ", ".join(extra) + text[line.end():] else: text = text.rstrip() + "\n\nZdroje: " + ", ".join(extra) return re.sub(r"\n{3,}", "\n\n", text).strip() def similar_items(wiki_items: list[dict]) -> list[dict]: """Candidates of a "similar work / collaboration" answer: one line each with the candidate's work, the shared points and one record that shows them (not every record of the candidate).""" out = [] for item in wiki_items: text = item["text"].split("Podklady k porovnávanej osobe")[0] shared = re.search(r"Spoločné doložené pojmy:\s*(.+?)\.?\s*$", text, re.M) record = next((m.group(1) for m in re.finditer(r"(?m)^\s*-\s*[^:\n]{3,60}?(?:\([^)]*\))?:\s*(.+)$", text) if len(m.group(1)) > 15 and not m.group(1).rstrip().endswith("?")), None) works = [w for w in person_works(item["name"]) if not w.get("unconfirmed")] main = next((w for w in works if w["type"] in THESES), works[0] if works else None) line = describe(main) if main else "práca bez uvedeného názvu" details = [] if shared: details.append(f"Spoločné: {shared.group(1)}") if record: details.append(f"Napríklad: {clean_point(record)[:220]}") out.append({**item, "name": spelled(item["name"]), "source": "line", "text": line + "".join(f"\n - {d}" for d in details), "urls": item.get("urls", [])}) return out def anchor_sentence(person: str) -> str | None: """"Jakub Schwarc pracuje na diplomovej práci (2027), téma: …" — what the candidates are similar to.""" 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.+?)(?=\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.+?)(?=\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 # ------------------------------------------------------------------ a claimed role, a work year, interns, topic pages # "Viem, že vedúcim X je Peter Novák, len mi to potvrď.", "Potvrď, že oponentom práce X bol Ján Staš." CLAIM_Q = re.compile(r"\b(?:viem|myslim|tusim|pocul\w*|vraj|som\s+si\s+ist\w*|je\s+pravda|potvrd\w*|over\w*)\b[^?]*?\bze\s+" r"(?Pveduc\w*|skolitel\w*|oponent\w*|konzultant\w*)\b[^?]*?\b(?:je|bol|bola|bude)\s+" r"(?P[^\W\d_]+(?:\s+[^\W\d_]+){1,2})(?=\s*[,.?!]|\s+(?:a|len|tak|ci|alebo)\b|\s*$)") CLAIM_CUE = re.compile(r"\b(?:potvrd\w*|over\w*|je\s+to\s+tak|mam\s+pravdu|pravda)\b") def claimed_role(person: str, question: str) -> dict | None: """"Viem, že vedúcim X je Peter Novák, len mi to potvrď.": the claim is checked against the records of X's theses, never confirmed only because the question says so.""" from tools.answers.planning.noise import fold_chars folded = fold_chars(question) match = CLAIM_Q.search(folded) if not match or not CLAIM_CUE.search(folded): return None claimed = question[match.start("claimed"):match.end("claimed")].strip() if _is(person, claimed) or normalized(claimed).split()[0] in normalized(person).split(): return None # the claimed name is the student's own name: not a claim about the role word = match.group("role") role = "opponent" if word.startswith("opon") else "consultant" if word.startswith("konz") else "supervisor" works = person_works(person) theses = [w for w in works if w["type"] in THESES and not w.get("unconfirmed")] or \ [w for w in works if w["source"] == "wiki"][:1] parts = [{"work": w, "people": _role_people(person, w, role, "")} for w in theses] parts = [p for p in parts if p["people"]] if not parts: return None label = {"supervisor": "vedúci", "opponent": "oponent", "consultant": "konzultant"}[role] told = _role_sentence(person, role, normalized(question), parts) if not told: return None named = any(_is(claimed, n) or set(normalized(claimed).split()) <= set(normalized(n).split()) for p in parts for n in p["people"]) lead = (f"Áno, podľa záznamov to sedí." if named else f"Nie, {spelled(claimed)} v záznamoch nie je uvedený ako {label}.") return {"text": lead + " " + told["text"], "urls": told.get("urls") or work_urls(person, works)} YEAR_IN_Q = re.compile(r"\b(?:v|z|pre|zo)\s+roku\s+((?:18|19|20)\d{2})\b|\b((?:18|19|20)\d{2})\b") def year_title(person: str, question: str) -> dict | None: """"Aký názov práce má X v roku 2018?", "Uveď názov práce X a rok práce pre rok 2019.": only works of that year (and of the named type); none -> said so, with the person's works.""" low = normalized(question) years = sorted({int(a or b) for a, b in YEAR_IN_Q.findall(low)}) info = catalog()["people"].get(person) or {} if not years or not info.get("url"): return None kinds = asked_types(low) works = [w for w in person_works(person) if not w.get("unconfirmed")] candidates = [w for w in works if not kinds or w["type"] in kinds] chosen = [w for w in candidates if w.get("year") in years or (w.get("row") or {}).get("year") in years] if chosen and len(chosen) == len(candidates): return None # the year leaves out nothing: the usual title answer (with the register's title) when = join([str(y) for y in years]) if not chosen and any((w.get("year") in years or (w.get("row") or {}).get("year") in years) and (not kinds or w["type"] in kinds) for w in person_works(person) if w.get("unconfirmed")): return None # a register's work of that year, perhaps a namesake's: the usual answer says so if not chosen: listed = "; ".join(_title_line(w) for w in works) or "žiadne" what = TYPES[kinds[0]][0] if len(kinds) == 1 and kinds[0] in TYPES else "práca" return {"text": f"{what[:1].upper() + what[1:]} osoby {spelled(person)} z roku {when} v zázname nie je uvedená. " f"Práce osoby: {listed}.", "urls": work_urls(person, works)} lines = "\n".join(f"- {_title_line(w)}" for w in chosen) return {"text": f"Práca osoby {spelled(person)} z roku {when}:\n\n{lines}" if len(chosen) == 1 else f"Práce osoby {spelled(person)} z roku {when}:\n\n{lines}", "urls": work_urls(person, chosen)} INTERN_YEAR_Q = re.compile(r"\b(?:v\s+ktorom\s+roku|kedy|ktory\s+rok)\b[^?]*\bstaz\w*|\bstaz\w*[^?]*\b(?:v\s+ktorom\s+roku|kedy)\b") INTERN_TOPIC_Q = re.compile(r"\btem\w*\s+(?:jeho\s+|jej\s+)?staz\w*|\bstaz\w*[^?]*\b(?:tem\w*|zameran\w*)\b") def intern_answer(person: str, question: str) -> dict | None: """An intern: the year and topic of the stay as the page writes them; a thesis an intern does not have.""" info = catalog()["people"].get(person) or {} if info.get("person_kind") != "intern" or not info.get("url"): return None low = normalized(question) text = page_text(person) urls = [info["url"]] stay = re.search(r"(?i)\b(?:ERASMUS|IAESTE)[^\n]*", text) or re.search(r"(?im)^\s*Intern\b[^\n]*", text) if INTERN_YEAR_Q.search(low): years = sorted(set(re.findall(r"\b(20\d{2})\b", stay.group(0)))) if stay else [] if not years: return {"text": f"Rok stáže osoby {spelled(person)} v zázname nie je uvedený.", "urls": urls} return {"text": f"Stáž osoby {spelled(person)} prebiehala v roku {join(years)} ({stay.group(0).strip().rstrip('.')}).", "urls": urls} if INTERN_TOPIC_Q.search(low): topic = re.search(r"(?im)^\s*(?:Topic|Téma)\s*:\s*(\S[^\n]*)$", text) or re.search(r"(?im)^\s*(?:Goals?|Ciele?|Cieľ)\s*:\s*(\S[^\n]*)$", text) if topic: shown = re.sub(r"\[([^\]]+)\]\([^)]*\)", r"\1", topic.group(1)).strip() return {"text": f"Téma stáže osoby {spelled(person)}: {shown}", "urls": urls} return None kinds = [k for k in asked_types(low) if k in THESES] if kinds: # "Kto bol oponentom dizertačnej práce stážistu X?" what = TYPES[kinds[0]][0] return {"text": f"{spelled(person)} je v ZP Wiki stážist{'ka' if female(spelled(person)) else 'a'}; " f"{what} osoby v podkladoch nie je uvedená.", "urls": urls} return None # "Nájdi projektovú alebo informačnú stránku „Anotácia textových dát“.", "Ktorý dokument v ZP Wiki sa priamo venuje téme „X“?" TOPIC_PAGE_Q = re.compile(r"\b(?:projektov\w*|informacn\w*|navodov\w*|temov\w*)\s+(?:alebo\s+\w+\s+)?strank\w*" r"|\b(?:najdi|ukaz|kde\s+je)\s+(?:mi\s+)?strank\w*|\bktory\s+dokument\b[^?]*\bvenuje\s+tem\w*") _topic_pages: dict = {} def topic_pages() -> list[dict]: """The wiki's topic and guide pages (documents.json): their titles and links.""" from tools.rag.common import DB_FILE from tools.rag.search_utils import make_source_url file = Path(DB_FILE).parent / "documents.json" try: stamp = file.stat().st_mtime_ns except OSError: return [] if _topic_pages.get("stamp") != stamp: rows = [{"title": d.get("title") or "", "path": d["path"], "url": make_source_url(d["path"])} for d in json.loads(file.read_text(encoding="utf-8")) if "/topics/" in (d.get("path") or "") and d.get("title")] _topic_pages.update(stamp=stamp, rows=rows) return _topic_pages["rows"] def topic_page(question: str) -> dict | None: """The topic page whose title the question names (quoted, as written); None when no title matches.""" quoted = re.search(r"[„\"“]([^„“\"]{3,120})[“\"”]", question) if not quoted: return None asked = normalized(quoted.group(1)).split() for page in topic_pages(): words = normalized(page["title"]).split() if len(words) == len(asked) and all(_word_fits(a, w) for a, w in zip(asked, words)): return {"text": f"Stránka „{page['title']}“ je v ZP Wiki na adrese {page['url']}.", "urls": [page["url"]]} return None