dp-zp-agent/tools/answers/unified.py
2026-11-17 00:39:55 +01:00

803 lines
43 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""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.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*", "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)")
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 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/names.py."""
from tools.answers import names
return names.case(name, "genitive")
def spelled(name: str) -> str:
from tools.answers 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 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
rows = [u for u in units(person) if u.get("kind") == "supervisor"]
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 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 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", []):
by_author.setdefault(" ".join(fold(display_name(author)).split()), {})[
(fold(row.get("title") or ""), row.get("year"))] = 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, [])]
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 _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")
twin = next((w for w in works if same_work(w)), None)
if twin is not None:
twin["row"] = row
twin["title"] = twin.get("title") or item["title"]
twin.setdefault("urls", []).append(row.get("url"))
else:
from tools.answers.combined import same_person_work
item["unconfirmed"] = not same_person_work(person, row)
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 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
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; for two or more
theses and no named one: {"options": …} (the answer asks which one); the same for opponents and
consultants."""
import datetime
role = role or asked_role(low) or "supervisor"
kind = asked_type(low)
options = work_options(person, works, low)
if options:
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}?")}
candidates = [w for w in works if (w["type"] == kind if kind else w["type"] in THESES)]
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 None
work = chosen[0]
people = _role_people(person, work, role, wiki_text)
names = TYPES.get(work["type"]) or ("práca", "práce", "práci")
title = f" „{work['title'].rstrip('.')}“" if work.get("title") else ""
year = f" ({work['year']})" if work.get("year") else ""
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('.')})"
if not people:
text = f"Pri {names[2]} {genitive(person)}{title}{year} {ROLES[role]['ask']} podklady neuvádzajú."
return {"text": text, "urls": work_urls(person, [work])}
plain = [p.split(" (")[0] for p in people]
words = ("Školiteľom", "Školiteľkou", "Školiteľmi") if role == "supervisor" and re.search(r"\bskolitel", low) \
else ROLES[role]["one"]
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")
text = f"{lead} {names[1]} {genitive(person)}{title}{year} {verb} {join(people)}."
if work.get("unconfirmed"):
text += " Nie je isté, že ide o tú istú osobu ako v profile študenta (iný vedúci a téma)."
return {"text": text, "urls": work_urls(person, [work])}
def supervisors(person: str, works: list[dict], low: str, wiki_text: str = "") -> dict | None:
return roles(person, works, low, wiki_text, "supervisor")
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:", ""]
for work in works:
names = TYPES.get(work["type"]) or (work.get("heading") or "Práca",)
head = f"- **{names[0][:1].upper() + names[0][1:]}" + (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 = [w for w in works if w["type"] == kind] if kind else [w for w in works if w["type"] in THESES] or works
if not pool:
return None
work = pool[0]
title = f" „{work['title'].rstrip('.')}“" if work.get("title") else ""
names = TYPES.get(work["type"]) or ("práca", "práce", "práci")
lines = []
if work["source"] == "wiki":
head = f"{names[0][:1].upper() + names[0][1:]} {genitive(person)}" + (f" ({work['year']})" if work.get("year") else "")
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 = {}
kind = asked_type(low)
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 kind and normalized(sentence.group(1)) != normalized(TYPES[kind][2]):
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)})."
out = {"text": "\n\n".join(unique), "urls": work_urls(person, works)}
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:" 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 none."""
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
section = re.search(r"Zásobník úloh[^:\n]*:\s*\n((?:\s*[-*+].*(?:\n|$)|\s*\n)+)", block)
if not section:
return []
points = []
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 not date:
return None
when = day(date.group(1).strip())
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:
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"\bposledn", low) \
else f"Stretnutie {genitive(person)} bolo {when}."
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 ""
if tasks_only:
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:")
points = todo or done
return head + "\n\n" + "\n".join(f"- {p}" for p in points) + 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) -> dict | None:
"""A table of two students: their main work, focus, results and tools; shared points below."""
from tools.answers.combined import comparison_block
data = []
for name in names:
merged = [w for w in person_works(name) 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]
data.append({"work": work, "goals": goals_of(name, work.get("heading"), 2),
"results": results_of(name, work.get("heading"), 3)})
block = comparison_block(names) or ""
shared = re.search(r"- Spoločné: (.+)", block)
only = [re.search(rf"- Len {re.escape(n)}: (.+)", block) for n in names]
def cell(values):
return "<br>".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 in names for u in work_urls(n, [])))
return {"text": text, "urls": urls}
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