709 lines
37 KiB
Python
709 lines
37 KiB
Python
"""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"),
|
||
}
|
||
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*|\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")})
|
||
value = {"people": {p["name"]: {**p, "url": (docs.get(p.get("source_document")) or {}).get("source_url")}
|
||
for p in payload["people"]}, "works": works}
|
||
_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, [])}
|
||
|
||
|
||
def supervisors(person: str, works: list[dict], low: str, wiki_text: str = "") -> dict | None:
|
||
kind = asked_type(low)
|
||
candidates = [w for w in works if (w["type"] == kind if kind else w["type"] in THESES)]
|
||
# a work of the register that may be a namesake's is no answer while the wiki has a work of the person
|
||
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
|
||
if not chosen:
|
||
return None
|
||
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)
|
||
lines = []
|
||
for work in chosen:
|
||
row = work.get("row") or {}
|
||
from tools.crzp.source.parse import display_name
|
||
registry = [display_name(s) for s in row.get("supervisors", [])]
|
||
own = (stated[0].strip() if stated else wiki_supervisor(person, work.get("heading"))) if work["source"] == "wiki" else None
|
||
name = spelled(own) if own else (registry[0] if registry else None) # "Daniel Hládek", as the register writes him
|
||
if not name:
|
||
continue
|
||
if registry and own and normalized(registry[0]) != normalized(own) and not set(normalized(registry[0]).split()) <= set(normalized(own).split()):
|
||
name = f"{own} (v registri záverečných prác je uvedený {registry[0]})"
|
||
if work.get("unconfirmed"):
|
||
name += " (nie je isté, že ide o tú istú osobu — iný vedúci a téma)"
|
||
lines.append((work, name))
|
||
if not lines:
|
||
return None
|
||
if len(lines) == 1:
|
||
work, name = lines[0]
|
||
role = "Vedúcou" if female(name.split(" (")[0]) else "Vedúcim"
|
||
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('.')})"
|
||
text = f"{role} {names[1]} {genitive(person)}{title}{year} je {name}."
|
||
else:
|
||
text = f"Vedúci prác {genitive(person)}:\n\n" + "\n".join(f"- {describe(w)}: {n}" for w, n in lines)
|
||
return {"text": text, "urls": work_urls(person, [w for w, _ in lines])}
|
||
|
||
|
||
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: {', '.join(merged)}.")
|
||
# works of both sources with the same title: one sentence
|
||
unique, seen = [], []
|
||
for line in lines:
|
||
title = re.search(r"„([^“]+)“", line).group(1)
|
||
if any(_same_title(title, s) for s in seen):
|
||
continue
|
||
seen.append(title)
|
||
unique.append(line)
|
||
return {"text": "\n\n".join(unique), "urls": work_urls(person, works)}
|
||
|
||
|
||
def thesis_options(person: str, works: list[dict], low: str) -> list[dict] | None:
|
||
"""Two or more theses and the question names none: which one?"""
|
||
if asked_type(low):
|
||
return None
|
||
theses = [w for w in works if w["type"] in THESES]
|
||
if len(theses) < 2:
|
||
return None
|
||
options = []
|
||
for work in theses[:4]:
|
||
option = {"source": work["source"], "label": describe(work), "type": work["type"]}
|
||
if work["source"] == "wiki":
|
||
option["work"] = work.get("heading") or describe(work, title=False)
|
||
else:
|
||
option["key"] = f"{normalized(work['title'] or '')}|{work.get('year')}"
|
||
options.append(option)
|
||
return options
|
||
|
||
|
||
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 ""
|
||
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)
|
||
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)
|
||
|
||
|
||
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
|