hranicne pripady

This commit is contained in:
Ján Pták 2026-11-17 00:39:55 +01:00
parent 7a3a10f149
commit a9fbd1c81e
3 changed files with 248 additions and 78 deletions

View File

@ -140,3 +140,43 @@ def test_a_respelled_or_undeclined_name_is_rejected():
assert not names.valid("Jakub Schwarc", names.NameForms(genitive="Jakuba Schwarca", instrumental="Jakubom Schwarzom", **base))
assert not names.valid("Jakub Schwarc", names.NameForms(genitive="Jakub Schwarc", instrumental="Jakubom Schwarcom", **base))
assert names.fits("Hládek", "Hládka") and names.fits("Zalačko", "Zalačka") and not names.fits("Andrii", "Andrija")
def test_two_theses_are_offered_before_naming_the_supervisor_and_one_is_answered(data):
works = [{"type": "diploma_thesis", "heading": "Diplomová práca 2026", "year": 2026, "title": "Znalostné grafy",
"source": "wiki", "url": PROFILE},
{"type": "bachelor_thesis", "heading": "Bakalárska práca 2024", "year": 2024, "title": "Dialógový systém",
"source": "wiki", "url": PROFILE}]
asked = U.roles("Ronald Zalacko", works, normalized("Kto je vedúci práce Ronalda Zalačka?"))
assert [o["type"] for o in asked["options"]] == ["diploma_thesis", "bachelor_thesis"]
assert asked["text"].endswith("Pri ktorej práci chceš vedieť vedúceho?") and "1. diplomová práca (2026)" in asked["text"]
one = U.roles("Ronald Zalacko", works, normalized("Kto je vedúci diplomovej práce Ronalda Zalačka?"))
assert one["text"].startswith("Vedúcim diplomovej práce Ronalda Zalacka „Znalostné grafy“ (2026)")
def test_the_opponent_comes_from_the_register_in_one_sentence(data):
works = U.person_works("Ronald Zalacko", [CRZP_ROW])
out = U.roles("Ronald Zalacko", works, normalized("Kto bol oponentom bakalárskej práce Ronalda Zalačka?"))
assert "Oponentkou bakalárskej práce Ronalda Zalacka „Skórovací online systém pre robotické súťaže“ (2026)" in out["text"]
assert out["text"].endswith("Eva Kupcová.")
def test_the_backlog_of_the_meeting_is_listed_with_its_tasks(monkeypatch):
profile = ("Stretnutie 27.10.2026\n\nÚlohy:\n\n- Porozprávajte sa s Olehom.\n\nZásobník úloh:\n\n- Preložte dataset do "
"slovenčiny.\n\nStretnutie 2.10.2026\n\nZásobník úloh:\n\n- Iná staršia úloha.\n")
path = "pages/students/2022/x/README.md"
monkeypatch.setattr(U, "catalog", lambda: {"people": {}, "works": {}, "texts": {path: profile}})
monkeypatch.setattr(U, "units", lambda person: [{"kind": "meeting", "record_date": "2026-10-27", "line": 1,
"text": "Stretnutie 27.10.2026", "source_path": path}])
assert U.backlog_of("Valerii Kutsenko", "27.10.2026") == ["Preložte dataset do slovenčiny."]
wiki = "Úlohy zo stretnutia 2026-10-27:\n- Porozprávajte sa s Olehom."
text = U.meeting("Valerii Kutsenko", wiki, normalized("a aké úlohy dostal?"), True)
assert text.endswith("Do zásobníka úloh zo stretnutia 27.10.2026 patrí:\n\n- Preložte dataset do slovenčiny.")
assert "Iná staršia úloha" not in text # the backlog of another meeting
def test_at_most_eight_tools_and_the_rest_on_request(data):
tools = ", ".join(f"Nástroj{i}" for i in range(11))
out = U.methods("Ronald Zalacko", [], f"X vo svojej bakalárskej práci „Systém“ využíva: {tools}.", "")
assert out["text"].endswith("Nástroj7 (uvedených 8 z 11).") and out["rest"] == ["Nástroj8", "Nástroj9", "Nástroj10"]
assert out["offer"] == "Ďalších technológií a metód je ešte 3. Chceš vidieť aj zvyšné?"

View File

@ -411,6 +411,13 @@ def _work(row) -> str:
return f"{_kind(row)} {row.get('year') or ''}".strip() + f" „{row['title']}“"
# Keywords that name no technology or method of a work (everything else of the author's keywords counts:
# "vývoj a testovanie četbotov", "Rasa", "Python").
METHOD_STOP = {"analyza", "navrh", "system", "systemy", "aplikacia", "implementacia", "model", "modelovanie", "metoda",
"metody", "data", "udaje", "vyvoj", "softver", "hardver", "riesenie", "praca", "teoria", "prehlad",
"vyskum", "studia", "experiment", "experimenty", "vysledky", "porovnanie", "testovanie"}
def crzp_methods(person: str, row: dict, detail: dict | None) -> str:
""""Ján Pták vo svojej bakalárskej práci „…“ (2025) využíva: ESP32, MQTT, InfluxDB, Home Assistant." —
the work's keywords and the tools its abstract names."""
@ -418,10 +425,10 @@ def crzp_methods(person: str, row: dict, detail: dict | None) -> str:
record = detail or row
abstract = record.get("abstract") or ""
found = []
for keyword in record.get("keywords", []):
for keyword in record.get("keywords", []): # the author's own keywords: technologies and methods of the work
spelled = re.search(r"(?i)(?<!\w)" + re.escape(keyword) + r"(?!\w)", abstract)
name = spelled.group(0) if spelled else keyword
if named_tools(name) or re.search(r"[A-Z]", name[1:] if spelled else name): # "Home Assistant", not "časová značka"
name = (spelled.group(0) if spelled else keyword).strip()
if name and normalized(name) not in METHOD_STOP:
found.append(name)
found += [t.rstrip(".,;:") for t in named_tools(abstract)]
tools = []
@ -432,7 +439,7 @@ def crzp_methods(person: str, row: dict, detail: dict | None) -> str:
tools.append(name)
where = {"bachelor_thesis": "vo svojej bakalárskej práci", "diploma_thesis": "vo svojej diplomovej práci",
"dissertation": "vo svojej dizertačnej práci"}.get(row.get("work_type"), "vo svojej práci")
return f"{person} {where} „{row['title']}“ ({row.get('year')}) využíva: {', '.join(tools[:12])}."
return f"{person} {where} „{row['title']}“ ({row.get('year')}) využíva: {', '.join(tools)}."
def remember(rows: list[dict]) -> None:
@ -845,13 +852,14 @@ def _with_token(result: dict, *, wiki_context=None, entities=(), options=(), que
return result
NEXT_PAGE = re.compile(r"\b(?:dalsi\w*|dalej|viac|ostatn\w*|zvysn\w*|pokracuj\w*|zvysok)\b")
NEXT_PAGE = re.compile(r"\b(?:dalsi\w*|dalej|viac|ostatn\w*|zvysn\w*|pokracuj\w*|zvysok|vsetk\w*)\b")
# Words of a paging reply ("áno, ukáž ďalších", "pokračuj"): a message with any other word is a new question
# ("a čo robil ďalej?", "povedz viac o jeho práci").
PAGER_WORDS = {"a", "ano", "aj", "jasne", "ok", "okej", "hej", "chcem", "daj", "ukaz", "zobraz", "vypis", "prosim",
"urcite", "samozrejme", "mi", "ich", "ho", "este", "dalsich", "dalsie", "dalsi", "dalej", "viac", "ostatnych",
"ostatne", "zvysnych", "zvysne", "zvysok", "pokracuj", "pokracovat", "vidiet", "chcel", "chcela", "by", "som",
"tych", "ty", "tie", "osoby", "ludi", "studentov", "temy", "prace", "polozky", "stranu", "dalsiu", "zoznam"}
"tych", "ty", "tie", "osoby", "ludi", "studentov", "temy", "prace", "polozky", "stranu", "dalsiu", "zoznam",
"vsetky", "vsetko", "vsetkych", "technologie", "technologii", "nastroje", "metody", "aj"}
# A question starting like a new one is never a choice reply ("Kto robil RAG?" while a work choice is pending).
NEW_QUESTION = re.compile(r"^\W*(?:kto|co|ako|kedy|kde|ktor\w*|kolk\w*|ak[eyaou]\w*|preco|najdi|porovnaj|vypis|ukaz)\b")
YES = re.compile(r"^\W*(?:ano|jasne|ok|okej|hej|chcem|daj|ukaz|prosim|urcite|samozrejme)(?:\s+(?:ano|prosim|daj|ukaz|ich|mi|ho|aj))*\W*$")
@ -923,6 +931,10 @@ def _next_page(question: str, engine: str, previous: dict) -> dict:
return _ok(question, engine, "Ďalšie položky predchádzajúcej odpovede už nie sú k dispozícii; zopakuj otázku.",
[], {})
items, mixed = stored["items"], stored["meta"].get("mixed", False)
if stored["meta"].get("kind") == "tools": # the rest of a list of technologies: all of it, once
text = stored["meta"]["lead"] + ", ".join(i["name"] for i in items) + "."
return _with_token(_ok(question, engine, text, [], {}), entities=entities, question=question,
crzp=previous.get("crzp"), primary=previous.get("primary", "wiki"))
start = max((e.get("n", 0) for e in entities), default=0) + 1
text, urls, page_id = compose_list([], items[:PAGE], items[PAGE:], [], [], start=start, mixed=mixed)
shown = entities + [entity(item, start + i) for i, item in enumerate(items[:PAGE])]
@ -976,6 +988,10 @@ def _answer(question: str, *, engine: str, limit: int, context_token: str | None
return failure
wiki_token = previous.get("wiki") if previous else context_token
low = normalized(question)
words = re.findall(r"[a-z0-9]+", low)
wants_more = bool(YES.match(low) or NEXT_PAGE.search(low) and words and all(w in PAGER_WORDS for w in words))
if previous and previous.get("page") and wants_more: # "áno" to "Chceš vidieť ďalšie/zvyšné?" comes first
return _next_page(question, engine, previous)
if previous and previous.get("options"): # "Ktorú prácu myslíš?" was asked
chosen = _choice(low, previous["options"])
if chosen is not None:
@ -983,16 +999,19 @@ def _answer(question: str, *, engine: str, limit: int, context_token: str | None
deliver=deliver_answer)
result["_asked_as"] = [previous["question"], *result.pop("_asked_as", [])]
if result.get("accepted_for_delivery") is True and result.get("status") == "ok":
# the offer stays: "a tú druhú?" / "1" after "2" answers the same question for the other work
result = _with_token(result, wiki_context=result.get("conversation_context"),
options=previous["options"], question=previous["question"])
# the offer stays: "a tú druhú?" / "1" after "2" answers the same question for the other work;
# the answer's own context (wiki token, shown people, the rest of a list) stays with it
context = result.get("conversation_context") or {}
inner = unseal(context.get("token")) or {}
if inner.get("error"):
inner = {}
wiki_context = {**context, "token": inner.get("wiki")} if inner else context
result = _with_token(result, wiki_context=wiki_context, options=previous["options"],
question=previous["question"], entities=inner.get("entities") or [],
page=inner.get("page"), crzp=inner.get("crzp"), primary=inner.get("primary", "wiki"))
return result
if len(low.split()) <= 3 and not wiki_person(question) and not NEW_QUESTION.match(low):
return _ask_choice(question, engine, previous)
words = re.findall(r"[a-z0-9]+", low)
wants_more = bool(YES.match(low) or NEXT_PAGE.search(low) and words and all(w in PAGER_WORDS for w in words))
if previous and previous.get("page") and wants_more:
return _next_page(question, engine, previous)
if previous and previous.get("entities") and wants_more: # nothing more was offered
return _with_token(_ok(question, engine, "Všetko nájdené už je v predchádzajúcej odpovedi.", [], {}),
entities=previous["entities"], question=question, crzp=previous.get("crzp"),
@ -1086,6 +1105,13 @@ def _unified(asked, question, engine, wiki, wiki_ok, part, person, wiki_context,
def done(out, **token):
text = out["text"] + ("\n\nZdroje: " + ", ".join(out["urls"]) if out.get("urls") else "")
if out.get("rest"): # "Chceš vidieť aj zvyšné?": the rest is kept like the next page of a list
from tools.answers import pages
page = pages.put([{"name": t, "source": "tool", "text": ""} for t in out["rest"]],
{"kind": "tools", "lead": out["rest_lead"]})
if page:
text += "\n\n" + out["offer"]
token["page"] = page
return _with_token(_ok(question, engine, text, out.get("urls") or [], base), wiki_context=wiki_context,
question=question, **token)
if person is None and wiki.get("resolved_query"): # "a aké úlohy dostal?": the person of the resolved question
@ -1137,14 +1163,18 @@ def _unified(asked, question, engine, wiki, wiki_ok, part, person, wiki_context,
elif plan.get("intent") == "meeting" or re.search(r"\bstretnut\w*", low) or U.TASKS_Q.search(low) and wiki_text:
text = U.meeting(person, wiki_text, low, follow_up=asked != question or bool(re.match(r"^\W*a\b", normalized(asked))))
out = {"text": text, "urls": wiki.get("source_urls") or U.work_urls(person, [])} if text else None
elif U.SUPERVISOR_Q.search(low):
out = U.supervisors(person, works, low, wiki_text)
elif U.asked_role(low) and re.search(r"\b(?:kto|ktor\w*|ako\s+sa\s+vola|meno)\b", low):
out = U.roles(person, works, low, wiki_text)
if out and out.get("options"): # two or more theses: which one?
result = _ok(question, engine, out["text"], [], base)
result.update(status="ambiguous", reason="clarification_required",
delivery_check={"layer": "planning", "code": "clarification_required",
"request_fingerprint": fingerprint(question, engine)})
return _with_token(result, wiki_context=wiki_context, options=out["options"], question=question)
elif U.METHODS_Q.search(low):
options = U.thesis_options(person, works, low)
options = U.work_options(person, works, low)
if options:
text = (f"{U.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))
+ "\n\nZ ktorej chceš vedieť, aké technológie využíva?")
text = U.options_text(person, options, "Z ktorej chceš vedieť, aké technológie využíva?")
result = _ok(question, engine, text, [], base)
result.update(status="ambiguous", reason="clarification_required",
delivery_check={"layer": "planning", "code": "clarification_required",
@ -1323,7 +1353,13 @@ def _answer_choice(question: str, chosen: dict, *, engine: str, limit: int, comp
deliver_answer = deliver
if chosen.get("type"): # one of the person's theses: the same question about that thesis
from tools.answers.unified import TYPES
asked = question.rstrip(" ?.") + f" v {TYPES[chosen['type']][2]}?"
nominative, genitive_, locative = TYPES[chosen["type"]]
if re.search(r"\bpráce\b", question):
asked = re.sub(r"\bpráce\b", genitive_, question, count=1)
elif re.search(r"\bpráci\b", question):
asked = re.sub(r"\bpráci\b", locative, question, count=1)
else:
asked = question.rstrip(" ?.") + f" v {locative}?"
result = _answer(asked, engine=engine, limit=limit, context_token=None, complete=complete, deliver=deliver)
return {**result, "_asked_as": [asked, *result.pop("_asked_as", [])]}
from tools.crzp.answering.wiki_bridge import wiki_person

View File

@ -35,9 +35,10 @@ TYPES = { # work type -> (nominative, genitive, locative)
"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*|\bbp\b", "bachelor_thesis"),
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"),
@ -187,8 +188,13 @@ def catalog() -> dict:
"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}
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
@ -377,45 +383,112 @@ def start_year(person: str) -> dict | None:
"urls": work_urls(person, [])}
def supervisors(person: str, works: list[dict], low: str, wiki_text: str = "") -> dict | None:
# 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)]
# 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
chosen = (chosen or candidates)[:1]
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])}
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:
@ -505,34 +578,52 @@ def methods(person: str, works: list[dict], wiki_text: str, crzp_text: str, low:
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)
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(line)
return {"text": "\n\n".join(unique), "urls": work_urls(person, works)}
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 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 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:
@ -565,16 +656,19 @@ def meeting(person: str, text: str, low: str, follow_up: bool) -> str | None:
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)
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)