From e3fa2be4f46a2e7710d7151254d366ddb8501365 Mon Sep 17 00:00:00 2001 From: jp170na Date: Thu, 19 Nov 2026 19:21:06 +0100 Subject: [PATCH] opravy zo sady Co-Authored-By: Claude Opus 5.5 --- test/presentation/test_combined_answers.py | 53 +++- test/presentation/test_unified_answers.py | 9 + tools/answers/combined.py | 277 +++++++++++++++++++-- tools/answers/planning/question_catalog.py | 10 + tools/answers/planning/question_plan.py | 8 +- tools/answers/presentation/finalize.py | 17 ++ tools/answers/presentation/unified.py | 88 ++++++- tools/crzp/answering/answer.py | 150 +++++++++-- tools/crzp/answering/relevance.py | 12 +- tools/crzp/answering/understand.py | 12 +- tools/crzp/answering/units.py | 6 +- tools/crzp/tests/test_crzp.py | 24 +- tools/knowledge/roster.py | 23 +- tools/retrieval/person_names.py | 9 +- tools/retrieval/synonyms.py | 3 +- 15 files changed, 635 insertions(+), 66 deletions(-) diff --git a/test/presentation/test_combined_answers.py b/test/presentation/test_combined_answers.py index 5fa3f48..cd2d520 100644 --- a/test/presentation/test_combined_answers.py +++ b/test/presentation/test_combined_answers.py @@ -204,7 +204,8 @@ def test_a_person_in_both_sources_is_listed_once(): "urls": ["https://opac.test/m"]}, {"name": "Eva Malá", "school": "Iná", "source": "crzp", "text": "Iná: „X“", "urls": []}] rest = C.merge_people(wiki, crzp) - assert [i["name"] for i in rest] == ["Eva Malá"] and "V CRZP: „Anotácia“" in wiki[0]["text"] + assert [i["name"] for i in rest] == ["Eva Malá"] and "- Diplomová práca 2021: „Anotácia“" in wiki[0]["text"] + assert "V CRZP" not in wiki[0]["text"] # no source labels in an answer assert wiki[0]["urls"] == ["https://opac.test/m"] @@ -564,3 +565,53 @@ def test_a_thesis_choice_is_asked_again_with_the_person_named(): assert C.pending_question("A kto je jeho vedúci?", {"resolved_query": "Kto je vedúci Jána Holpa?"}, "Ján Holp") == "Kto je vedúci Jána Holpa?" assert C.pending_question("Kto je vedúci Jána Ptáka?", {}, "Ján Pták") == "Kto je vedúci Jána Ptáka?" + + +def test_suite_fixes_question_rules(): + """Rules added after the 120-question suite (19. 11. 2026).""" + low = C.normalized + # "na slovenských školách" names every school; "Vypíš …" starts a topic list + assert C.EXPLICIT.search(low("Vypíš všetky práce o strojovom učení na slovenských školách.")) + assert C.TOPIC_LIST.search(low("Vypíš práce o chatbotoch")) + # a topic of a supervisor's count is a topic only after a cue ("na tému", "o …"), never "o koľko" + assert C.TOPIC_CUE.search(low("Koľko prác na tému blockchain viedol Juraj Sipko?")) + assert not C.TOPIC_CUE.search(low("o kolko viac viedol hladek v 2025 ako 2024")) + assert C.supervisor_count("Viedol Daniel Hládek v roku 2025 viac bakalárskych prác ako v roku 2024?") + # defences of a year to come are unknown, a past year is counted + future = C._future_defences("Koľko diplomových prác obhájia na KEMT v roku 2030?", + low("Koľko diplomových prác obhájia na KEMT v roku 2030?")) + assert "2030" in future and "nie je známy" in future + assert C._future_defences("Koľko prác obhájili v roku 2024?", low("Koľko prác obhájili v roku 2024?")) == "" + # "prečo si myslíš / na základe čoho tvrdíš, že …": the claim itself is checked + assert C.EXPLAIN.match("Prečo si myslíš, že Andrii Pervashov vyhodnocoval WER? Odkiaľ to vieš?").group(1) == \ + "Andrii Pervashov vyhodnocoval WER" + assert not C.EXPLAIN.match("Prečo je to tak?") + # only the name is a "who is" question + assert C.bare_name("Ján Holp", "Ján Holp") and not C.bare_name("Ján Holp vedúci", "Ján Holp") + # English twins of Slovak keywords are left out, names and abbreviations stay + assert C.one_language(["simulation", "PPO", "reinforcement learning", "simulácia", "posilňované učenie"]) == \ + ["PPO", "simulácia", "posilňované učenie"] + assert C.one_language(["IoT", "MQTT", "časová značka"]) == ["IoT", "MQTT", "časová značka"] + + +def test_a_crzp_work_joins_a_wiki_person_without_a_source_label(): + wiki = [{"name": "Eva Nová", "school": C.WIKI_SCHOOL, "source": "wiki", "text": "**Eva Nová**", "urls": []}] + crzp = [{"name": "Eva Nová", "school": C.TUKE, "source": "crzp", "text": f"{C.TUKE}: „Graf“ (bakalárska práca, 2026)", + "urls": []}] + C.merge_people(wiki, crzp) + assert wiki[0]["text"].endswith("- Bakalárska práca 2026: „Graf“") + + +def test_a_work_pointed_at_gets_the_person_of_the_previous_question(monkeypatch): + monkeypatch.setattr(C, "_one_person", lambda q: {"name": "Ján Pták", "input": "Ján Pták"} if "Pták" in q else None) + previous = {"question": "Aké technológie využíva Ján Pták v bakalárke?"} + assert C.named_back("kto bol oponentom tej bakalárky?", previous) == "kto bol oponentom bakalárky Ján Pták?" + assert C.named_back("kto bol oponentom?", previous) is None # no work pointed at + assert C.named_back("tú bakalársku", {**previous, "options": [{}]}) is None # a choice reply + + +def test_the_wiki_is_asked_without_the_other_schools_clause(): + assert C.home_only("Kto pracoval s GraphRAG na KEMT aj na iných školách?") == "Kto pracoval s GraphRAG na KEMT?" + assert C.home_only("Kto robil s Whisper na KEMT a sú podobné práce aj na iných školách?") == "Kto robil s Whisper na KEMT?" + assert C.home_only("Aké práce viedol Hládek na iných školách?") == "Aké práce viedol Hládek na iných školách?" + assert C.home_only("Sú podobné práce aj na iných školách?") == "Sú podobné práce aj na iných školách?" diff --git a/test/presentation/test_unified_answers.py b/test/presentation/test_unified_answers.py index 0902a83..02e5555 100644 --- a/test/presentation/test_unified_answers.py +++ b/test/presentation/test_unified_answers.py @@ -248,3 +248,12 @@ def test_one_thesis_and_a_newer_running_project_both_answer_who_leads(monkeypatc out = U.roles("Ján Malinovský", works, normalized("Kto je vedúci práce Jána Malinovského?")) assert out["text"] == ("Vedúcim diplomového projektu Jána Malinovského „Grafové vyhľadávanie“ (2026) je Daniel Hládek a " "vedúcim jeho bakalárskej práce „5G“ (2025) bol Ľubomír Doboš.") + + +def test_one_category_of_several_people_is_one_sentence_and_roster_rows_are_clean(): + from tools.answers.presentation.finalize import same_category + from tools.knowledge.roster import _no_topic, _shown + text = same_category("A B: uvedená kategória je **dp2027**.\nC D: uvedená kategória je **dp2027**.") + assert text == "Kategóriu **dp2027** majú: A B, C D." + assert _no_topic("18.2.2022") and _no_topic("Návrh na zadanie bakalárskej práce:") and not _no_topic("Neurónový NER") + assert _shown("1. [ ] Použite [TUKE Cloud](https://cloud.tuke.sk/).") == "Použite TUKE Cloud." diff --git a/tools/answers/combined.py b/tools/answers/combined.py index 01f7bb4..db551d2 100644 --- a/tools/answers/combined.py +++ b/tools/answers/combined.py @@ -49,6 +49,8 @@ LIFETIME = 24 * 3600 PREFIX = "zc1." # plain JSON body (still read) PREFIX2 = "zc2." # zlib-compressed JSON body (still read; issued with ANSWER_CONTEXT_STORE=0) PREFIX3 = "zc3." # the id of a step kept on the server (tools/answers/context_store.py) and its signature +# crzp_plan dropped the wiki person of "… a koľko podobných prác je na iných školách?": the CRZP part is an addition +_addition: contextvars.ContextVar[bool] = contextvars.ContextVar("crzp_addition", default=False) _parent: contextvars.ContextVar[str | None] = contextvars.ContextVar("answer_parent_step", default=None) TUKE = "Technická univerzita v Košiciach" WIKI_SCHOOL = "Technická univerzita v Košiciach (KEMT FEI)" @@ -57,7 +59,8 @@ WIKI_ONLY = re.compile(r"\b(?:stretnut\w*|pokrok\w*|progres\w*|uloh\w*|zadan\w*| r"repozitar\w*|git\w*|stav\w*|poznam\w*|konzult\w*|zaciat\w*|studi\w*|obhaj\w*|ukonc\w*|" r"dokonc\w*|uspes\w*|statnic\w*|hodnot\w*|znamk\w*|problem\w*|vtedy|posledn\w*)\b") EXPLICIT = re.compile(r"\b(?:crzp|registr\w*|register|celoslovensk\w*|na slovensku|(?:inych|inej|inom|ostatnych|" - r"vsetkych|dalsich)\s+(?:vysok\w+\s+)?(?:skol|univerzit|fakult)\w*|mimo tuke|oponent\w*|oponoval\w*)\b") + r"vsetkych|dalsich|slovensk\w+)\s+(?:vysok\w+\s+)?(?:skol|univerzit|fakult)\w*|mimo tuke|" + r"oponent\w*|oponoval\w*)\b") NAMED_CRZP = re.compile(r"\b(?:crzp|registr\w*|register)\b") # the register itself is asked, not only opponents METHODS = re.compile(r"\b(?:technolog\w*|nastroj\w*|metod\w*|pouziv\w*|pouzil\w*|vyuziv\w*|vyuzil\w*|framework\w*)\b") ABOUT = re.compile(r"\b(?:o com|zhrn\w*|abstrakt\w*|ciel\w*)\b") # not "čomu sa venuje": the current work @@ -68,6 +71,12 @@ WIKI_CLARIFICATION_YIELDS = {"missing_subject", "unsupported_content_question", "content_count_not_established"} # "the wiki cannot count this": CRZP counts it # "Koľko prác obhájili na KEMT v roku 2024?": defended works of a school or department are CRZP's # published works, not a wiki question about one student's defence. +# "Prečo si myslíš, že …?", "Odkiaľ vieš, že …?", "Na základe čoho tvrdíš, že …?" (+ "Odkiaľ to vieš?") +EXPLAIN = re.compile(r"^\W*(?:pre[čc]o|odkia[ľl]|ako|na\s+z[áa]klade\s+[čc]oho)\s+(?:si\s+mysl[íi][šs]|vie[šs]|tvrd[íi][šs])" + r"\s*,?\s*(?:že|ze)\s+(.+?)\s*\?(?:\s*(?:odkia[ľl]|ako|pre[čc]o)\s+to\s+(?:vie[šs]|tvrd[íi][šs])\s*\?)?\s*$", + re.I) +# A topic named in a count ("na tému blockchain", "o rozpoznávaní reči", "s LLM"; not "o koľko") +TOPIC_CUE = re.compile(r"\b(?:na\s+temu|tem\w*|o(?!\s+kolk)|ohladom|s|so|v\s+oblasti)\s+[a-z0-9]{2,}") DEFENDED = re.compile(r"\b(?:obhaj\w*|obhajen\w*|obhajil\w*|uspesn\w*)\b") TOPIC_MIN_SCORE = float(os.getenv("CRZP_TOPIC_MIN_SCORE", "0")) PAGE = int(os.getenv("ANSWER_PAGE_SIZE", "6")) @@ -76,7 +85,7 @@ WIKI_FIRST = 4 # a mixed list shows at most this many ZP Wiki people before the REFUSED = {"request_out_of_scope", "irrelevant", "unsupported_request", "out_of_scope"} RELATED = re.compile(r"\b(?:suvis\w*|pribuzn\w*)\b") SIMILAR = re.compile(r"\b(?:podobn\w*|suvisiac\w*|pribuzn\w*|spolupra\w*|rovnak\w* tem\w*)\b") -TOPIC_LIST = re.compile(r"^\W*(?:kto|ktor\w*|ak\w*)\b") +TOPIC_LIST = re.compile(r"^\W*(?:kto|ktor\w*|ak\w*|vypis\w*|ukaz\w*|daj\s+mi)\b") SCHOOLS = re.compile(r"\b(?:z|zo|na) (?:akych|akej|ktorych|ktorej) (?:skol|univerzit|fakult)\w*|\bkde (?:studoval\w*|studuj\w*)" r"|\b(?:ktor|ak)\w* (?:skol|univerzit)\w*") CHOICE_WIKI = re.compile(r"\b(?:wiki|diplom\w*|dp)\b") @@ -251,6 +260,22 @@ def ellipsis(question: str, previous: dict | None) -> str | None: return None +BACK_WORK = re.compile(r"(?i)\b(?:tej|tejto|tom|tomto|tú|tu|túto|tuto|jeho|jej|svojej)\s+" + r"((?:bakal|diplom|dizerta|záverečn|zaverecn|prác|prac|projekt)\w*)") + + +def named_back(question: str, previous: dict | None) -> str | None: + """"kto bol oponentom tej bakalárky?" after a question about one person, naming no one: the person of the + previous question is put in ("… bakalárky Ján Pták?"), so the roles of that person's work are read.""" + if not previous or not previous.get("question") or previous.get("options") or _one_person(question): + return None + match = BACK_WORK.search(question) + old = _one_person(previous["question"]) if match else None + if not old: + return None + return question[:match.start()] + match.group(1) + " " + old["name"] + question[match.end():] + + AGAIN_FILLERS = {"a", "ale", "no", "tak", "teda", "este", "presne", "vlastne", "konkretne", "mi", "povedz", "napis", "prosim"} @@ -398,13 +423,32 @@ def crzp_plan(question: str, person: str | None, complete=None, student: bool = other_school = query.school not in (None, "tuke") or explicit or bool(query.exclude_school) if person and other_school and not query.from_model: query = understand(question, complete=complete) + if query.exclude_school and re.search(r"\baj\s+(?:na|v|vo|z|zo)\s+(?:inych|ostatnych|dalsich)\b", low) \ + and re.search(r"\b(?:kemt\w*|tuke\w*|fei)\b", low): + query.exclude_school = None # "na KEMT a sú podobné práce aj na iných školách": both, not only the others + if query.intent == "similar" and query.topics and not query.title and not query.sids and not (query.people and not person): + query.intent = "list" # "sú podobné práce aj na iných školách?" names no work to compare: works of the topic + if not query.people and not query.exclude_school and query.school in (None, "tuke"): + query.school, query.unit = None, None + return "topic", query # "Kto robil s Whisper na KEMT a sú podobné práce aj inde?": one list with the wiki + if (query.topics and not query.people and not query.exclude_school and not query.title + and re.search(r"\baj\s+(?:na|v|vo|z|zo)\s+(?:inych|ostatnych|dalsich|inej)\b", low)): + query.school, query.unit = None, None # "Kto robil s Whisper na KEMT a sú podobné práce aj na iných školách?" + return "topic", query # both: one list of the wiki people and the register's works of the topic + if query.exclude_school and query.topics and query.people and re.search(r"\bpodobn\w*", low) \ + and query.intent in ("count", "list"): + # "Ktorí študenti Hládka robili s LLM … a koľko podobných prác je na iných školách?": the other + # schools' works of the topic, not the person's (the wiki answers about the person's students) + query.people = [] + _addition.set(True) if person and not student and not other_school and supervisor_count(question): # "Koľko bakalárok viedol Hládek v roku 2024 a 2025?": CRZP counts the submitted works per year and type # (the wiki lists students, not counts); a future year stays with the wiki (CRZP has no such works yet) query.people = [Person(name=person, role="opponent" if re.search(r"\bopon\w*", low) else "supervisor", typed=person, canonical=True)] query.intent, query.school, query.unit, query.from_model, query.title = "count", "tuke", None, True, None - query.topics, query.alternatives = [], [] + if not TOPIC_CUE.search(low): # rule words of a plain count are no topic ("robilo", "viac") + query.topics, query.alternatives, query.phrases, query.surface = [], [], [], [] return "explicit", query if person and not other_school: if SIMILAR.search(low) and student: @@ -436,13 +480,56 @@ def crzp_plan(question: str, person: str | None, complete=None, student: bool = return None +def _crzp_follow_up_methods(question: str, low: str, previous: dict, engine: str, complete) -> dict | None: + """"a aké technológie použila?" after a CRZP answer about one person: that person's technologies + (crzp_person_methods: one work -> a sentence, two or more -> which one?).""" + if not METHODS.search(low): + return None + from tools.crzp.answering import context as crzp_context + try: + query = crzp_context.restore(previous["crzp"])["query"] + except Exception: + return None + if not query.people: + return None + from tools.crzp.answering.understand import WORK_CUES + query.work_types = [t for t, cue in WORK_CUES.items() if re.search(cue, question.lower())] or query.work_types + query.intent, query.sids, query.topics, query.alternatives = "list", [], [], [] + part = crzp_person_methods(question, query, complete) + if part is None: + return None + result = _ok(question, engine, part["text"] + ("\n\nZdroje: " + ", ".join(part["urls"]) if part["urls"] else ""), + part["urls"], {}) + if part["status"] == "ambiguous": + result.update(status="ambiguous", reason="clarification_required", + delivery_check={"layer": "planning", "code": "clarification_required", + "request_fingerprint": fingerprint(question, engine)}) + return _with_token(result, options=part["options"], question=f"Aké technológie využíva {part['person']}?", + crzp=previous.get("crzp"), primary="crzp") + return _with_token(result, question=question, crzp=previous.get("crzp"), primary="crzp") + + +def _future_defences(question: str, low: str) -> str: + """The count of defences in a year that has not come yet: unknown (ZP Wiki plans theses by category, + e.g. dp2027, but a defence is recorded only after it).""" + from tools.crzp.answering.understand import years_in + years = years_in(question) + now = time.localtime().tm_year + if not years or min(years) <= now or not DEFENDED.search(low) or not re.search(r"\bkolk\w*|\bpocet\b", low): + return "" + when = f"v roku {years[0]}" if len(years) == 1 else f"v rokoch {min(years)}–{max(years)}" + return (f"Počet prác obhájených {when} zatiaľ nie je známy: obhajoba sa zaznamená až po nej a v registri " + f"záverečných prác sú práce najviac z roku {now}. V ZP Wiki môžu byť pripravované práce študentov s " + f"kategóriou podľa roku obhajoby (napr. dp{now + 1}).") + + def supervisor_count(question: str) -> bool: """A count of a supervisor's works in a year or of a type, of past years only.""" from tools.crzp.answering.understand import WORK_CUES, years_in low = normalized(question) years = years_in(question) - return bool(re.search(r"\bkolk\w*|\bpocet\b", low) - and (years or any(re.search(cue, question.lower()) for cue in WORK_CUES.values())) + counted = re.search(r"\bkolk\w*|\bpocet\b", low) or len(years) >= 2 and re.search(r"\b(?:viac|menej)\b", low) + return bool(counted and (years or any(re.search(cue, question.lower()) for cue in WORK_CUES.values())) and all(y <= time.localtime().tm_year for y in years)) @@ -476,6 +563,34 @@ def crzp_person_methods(question: str, query, complete=None) -> dict | None: "intent": "methods", "person": name} +def crzp_comparison(query, complete=None, collaboration: bool = False) -> dict | None: + """"Porovnaj prácu Jána Ptáka a Samuela Furdu." when one of them is known only to CRZP: each person's + works as author (ZP Wiki works of a wiki person merged in), one table as for two wiki people.""" + from tools.answers.presentation import unified as U + from tools.crzp.answering import answer as crzp + from tools.crzp.answering.understand import Person + from tools.crzp.source.parse import display_name + names, rows_all = [], [] + for person in query.people: + known = U.catalog()["works"].get(person.name) and person.name + single = query.model_copy(update={"people": [Person(name=person.name, role="author", typed=person.typed)], + "intent": "list", "work_types": [], "years": []}, deep=True) + _, rows = crzp.find(single) + rows = [r for r in crzp.resubmissions(rows) if crzp.people_in_role(r, person.name, "author")] + if not rows and not known: + return None # not a person of either source: the general answer says so + name = known or display_name(rows[0]["authors"][0]) + names.append(name) + rows_all.extend(rows) + out = U.comparison(names, collaboration=collaboration, crzp_rows=rows_all) + if out is None: + return None + return {"mode": "explicit", "status": "ok", "text": out["text"] if isinstance(out, dict) else out, + "rows": rows_all[:10], "urls": list(dict.fromkeys( + [*(out.get("urls", []) if isinstance(out, dict) else []), *[r["url"] for r in rows_all if r.get("url")]]))[:10], + "crzp_token": None, "entities": [], "intent": "compare", "person": None} + + def clean_crzp(text: str) -> str: """CRZP answer text inside a combined answer: its own source lines go to the common "Zdroje CRZP" line.""" lines = [l for l in text.split("\n") if not re.match(r"^\s*(?:-\s*)?Zdroj:\s", l)] @@ -522,6 +637,20 @@ METHOD_STOP = {"analyza", "navrh", "system", "systemy", "aplikacia", "implementa "vyskum", "studia", "experiment", "experimenty", "vysledky", "porovnanie", "testovanie"} +SK_LETTERS = re.compile(r"[áäčďéíĺľňóôŕšťúýž]", re.I) + + +def one_language(keywords: list[str]) -> list[str]: + """CRZP keywords often come twice, in English and in Slovak ("reinforcement learning", "posilňované učenie"): + with about as many plain lower-case English phrases as Slovak ones, the English ones are left out. Names + and abbreviations ("PPO", "Gymnasium", "IoT") stay.""" + english = [k for k in keywords if k.isascii() and k == k.lower() and re.search(r"[a-z]{4}", k)] + slovak = [k for k in keywords if SK_LETTERS.search(k)] + if len(slovak) >= 2 and len(english) >= 2 and abs(len(english) - len(slovak)) <= 1: + return [k for k in keywords if k not in english] + return keywords + + 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.""" @@ -529,7 +658,7 @@ 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", []): # the author's own keywords: technologies and methods of the work + for keyword in one_language(record.get("keywords", [])): # the author's own keywords: technologies and methods spelled = re.search(r"(?i)(? 8 else "" - return {"mode": mode, "text": f"Práce, ktoré {person} viedol alebo oponoval, v CRZP (TUKE):\n\n" + return {"mode": mode, "text": supervisor_header(person, query, rows) + "\n\n" + "\n".join(lines) + more, "rows": rows[:8], "urls": [r["url"] for r in rows[:8] if r.get("url")]} lines, details = [], {} for row in rows[:3]: @@ -887,6 +1025,29 @@ def render_item(number: int, item: dict, mixed: bool) -> str: return f"**{number}. {title}**" + ("\n" + rest if rest else "") +def bare_name(question: str, person: str) -> bool: + """The question is only the person's name ("Ján Holp", "Matej Scislak?").""" + words = re.findall(r"[a-z0-9]+", normalized(question)) + return bool(words) and 2 <= len(words) <= 3 and set(words) <= set(re.findall(r"[a-z0-9]+", normalized(person))) + + +def supervisor_header(person: str, query, rows: list[dict]) -> str: + """"Bakalárske práce, ktoré viedol Daniel Hládek v rokoch 2024–2025:" — the name as the register writes it + (with diacritics), the role, type and years the question asked.""" + from tools.crzp.answering import answer as crzp + from tools.crzp.source.parse import display_name + from tools.answers.presentation.unified import female + role = query.people[0].role if query.people and query.people[0].role in ("supervisor", "opponent") else "supervisor" + spelled = next((display_name(n) for r in rows for n in r.get(crzp.ROLE_FIELD[role], []) + if crzp.name_matches(person, n)), person) + verb = crzp.VERBS[role][1 if female(spelled) else 0] + kinds = [crzp.WORK_TYPE_PLURAL.get(crzp.WORK_TYPE_LABELS.get(t, ""), "") for t in query.work_types] + lead = (kinds[0].capitalize() + " práce") if len(kinds) == 1 and kinds[0] else "Práce" + years = sorted(set(query.years)) + when = (f" v roku {years[0]}" if len(years) == 1 else f" v rokoch {years[0]}–{years[-1]}") if years else "" + return f"{lead}, ktoré {verb} {spelled}{when}:" + + def merge_people(wiki: list[dict], crzp_items: list[dict]) -> list[dict]: """A CRZP work of a person already in the ZP Wiki list joins that person's item (no person twice).""" by_name = {normalized(item["name"]): item for item in wiki} @@ -894,7 +1055,10 @@ def merge_people(wiki: list[dict], crzp_items: list[dict]) -> list[dict]: for item in crzp_items: owner = by_name.get(normalized(item["name"])) if owner is not None and item.get("school") == TUKE: - owner["text"] += f"\n- V CRZP: {item['text'].split(': ', 1)[-1]}" + work = item["text"].split(": ", 1)[-1] # "„Názov“ (bakalárska práca, 2026)" -> "Bakalárska práca 2026: „Názov“" + shaped = re.match(r"^(„[^“]+“)\s*\(([^,()]+),\s*(\d{4})\)\s*$", work) + owner["text"] += (f"\n- {shaped.group(2)[:1].upper()}{shaped.group(2)[1:]} {shaped.group(3)}: {shaped.group(1)}" + if shaped else f"\n- Záverečná práca: {work}") owner.setdefault("urls", []).extend(item.get("urls", [])) else: rest.append(item) @@ -1311,11 +1475,28 @@ def _answer(question: str, *, engine: str, limit: int, context_token: str | None wiki_token = previous.get("wiki") if previous else context_token low = normalized(question) words = re.findall(r"[a-z0-9]+", low) + explained = EXPLAIN.match(question) + if explained: # "Prečo si myslíš, že X robil Y? Odkiaľ to vieš?": the claim checked again, with its records + claim = explained.group(1).strip() + asked = (re.sub(r"^(?:[A-ZÁČĎÉÍĽĹŇÓÔŔŠŤÚÝŽ][\w-]+\s+){1,3}", "Kto ", claim) + if re.search(r"\bnajviac\b", claim) else claim) + "?" + result = _answer(asked, engine=engine, limit=limit, context_token=context_token, complete=complete, + deliver=deliver) + inner = result.pop("_asked_as", []) + if result.get("accepted_for_delivery") is True and result.get("status") == "ok" and result.get("source_urls"): + result = {**result, "answer": "Vychádzam zo záznamov v podkladoch, ktoré sú uvedené v zdrojoch:\n\n" + + result["answer"]} + return {**result, "_asked_as": [asked, *inner]} + future = _future_defences(question, low) + if future: # "Koľko prác obhájia v roku 2030?": no record can hold it yet + return _with_token(_ok(question, engine, future, [], {}), question=question) 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"]) + # "kto bol oponentom tej bakalárky?" is a new question, not the choice "bakalárku" + own_question = bool(NEW_QUESTION.match(low) and len(words) > 2 and not re.fullmatch(r"\W*\d+\W*", low)) + chosen = None if own_question else _choice(low, previous["options"]) if chosen is not None and chosen.get("source") == "step": # "Ktorú otázku myslíš?" (a return to an older one) return _return_to(previous["question"], chosen["step"], engine=engine, limit=limit, complete=complete, deliver=deliver) @@ -1355,7 +1536,7 @@ def _answer(question: str, *, engine: str, limit: int, context_token: str | None if entities and SCHOOLS.search(low) and not wiki_person(question) and not THESIS.search(low) and len(words) <= 8: return _schools_answer(question, engine, previous) asked = question - full = ellipsis(question, previous) or again(question, previous) + full = ellipsis(question, previous) or again(question, previous) or named_back(question, previous) if full: # "a Ján Pták?": the previous question about this person; "ale čo robil?": that question again return {**_answer(full, engine=engine, limit=limit, context_token=None, complete=complete, deliver=deliver), "_asked_as": [full]} @@ -1364,6 +1545,12 @@ def _answer(question: str, *, engine: str, limit: int, context_token: str | None match, chosen = reference if chosen.get("source") == "crzp" and chosen.get("sid"): return _crzp_work_answer(question, engine, chosen, complete) + if chosen.get("source") == "crzp" and chosen.get("role") in ("supervisor", "opponent"): + # a supervisor of a CRZP ranking ("a čo robil druhý z nich?"): the works he or she led, from CRZP + verb = "oponoval" if chosen["role"] == "opponent" else "viedol" + asked = f"Aké práce {verb} {chosen['name']} v CRZP?" + return {**_answer(asked, engine=engine, limit=limit, context_token=None, complete=complete, + deliver=deliver), "_asked_as": [asked]} question = (question[:match.start()] + chosen["name"] + question[match.end():]).strip() low, wiki_token, previous = normalized(question), None, None # a question about that person now return {**_answer(question, engine=engine, limit=limit, context_token=None, complete=complete, @@ -1376,6 +1563,9 @@ def _answer(question: str, *, engine: str, limit: int, context_token: str | None # The last answer came from CRZP ("O čom je práca Jána Nováka?" -> "2", "a kto bol oponent?", # "aké napr.", "rozdeľ to podľa rokov", "málo zdrojov"). from tools.crzp.answering import answer as crzp + methods = _crzp_follow_up_methods(question, low, previous, engine, complete) + if methods is not None: + return methods followed = crzp._answer(question, complete, context_token=previous["crzp"]) followed.pop("_shown", None), followed.pop("_asked", None), followed.pop("_options", None) shown = followed.pop("_entities", None) or [] @@ -1409,7 +1599,8 @@ def _answer(question: str, *, engine: str, limit: int, context_token: str | None finally: timing.step(name, time.monotonic() - began) - wiki_future = pool.submit(contextvars.copy_context().run, timed, "wiki", deliver_answer, question, engine=engine, + home = home_only(question) if enabled() else question # the other schools are CRZP's part of the question + wiki_future = pool.submit(contextvars.copy_context().run, timed, "wiki", deliver_answer, home, engine=engine, limit=limit, **({"context_token": wiki_token} if wiki_token else {})) crzp_future, probe = _crzp_future(pool, timed, question, person, complete, student) if enabled() else (None, {}) @@ -1417,7 +1608,7 @@ def _answer(question: str, *, engine: str, limit: int, context_token: str | None if wiki_token and wiki.get("reason") in ("stale_context", "expired_context"): # the wiki's own context of an older step is too old (24 hours) or the wiki data changed: the # question goes to the wiki without it (people, works and the CRZP question of the step stay) - wiki = deliver_answer(question, engine=engine, limit=limit) + wiki = deliver_answer(home, engine=engine, limit=limit) part = None if crzp_future is not None: try: @@ -1436,7 +1627,31 @@ def _answer(question: str, *, engine: str, limit: int, context_token: str | None if (part is None and crzp_future is not None and crzp_future.done() and crzp_future.exception() is None and probe.get("mode") == "explicit" and not probe.get("failed")): wiki = searched_both(wiki) # CRZP was searched for the person too and has nothing - return compose(asked, question, engine, wiki, part, person) + result = compose(asked, question, engine, wiki, part, person) + return {**result, "_asked_as": [home, *result.pop("_asked_as", [])]} if home != question else result + + +# "… aj na iných školách", "a sú podobné práce aj na iných školách", "a koľko podobných prác je na iných školách +# podľa CRZP": ZP Wiki (KEMT) is not asked about other schools (its audit would rightly find that part missing) +OTHER_SCHOOLS_CLAUSE = re.compile( + r",?\s*(?:(?:a|aj)\s+)?(?:(?:su|je|bolo|boli|existuju)\s+)?(?:kolko\s+(?:je\s+)?)?(?:podobn\w+\s+(?:prac\w*|tem\w*)\s+)?" + r"(?:(?:je|su)\s+)?aj\s+(?:na|v|vo|z|zo)\s+(?:inych|ostatnych|dalsich)\s+(?:vysok\w+\s+)?(?:skol|univerzit|fakult)\w*" + r"(?:\s+podla\s+crzp)?" + r"|,?\s*a\s+kolko\s+podobn\w+\s+prac\s+(?:je\s+)?na\s+(?:inych|ostatnych|dalsich)\s+(?:skol|univerzit)\w*(?:\s+podla\s+crzp)?") + + +def home_only(question: str) -> str: + """The question for ZP Wiki without its other-schools clause ("Kto pracoval s GraphRAG na KEMT aj na iných + školách?" -> "Kto pracoval s GraphRAG na KEMT?"); the question itself when it has none or is only about them.""" + import unicodedata + low = "".join(next((c for c in unicodedata.normalize("NFKD", ch) if not unicodedata.combining(c)), ch) + for ch in question.lower()) # one character per character: the spans fit the question + match = OTHER_SCHOOLS_CLAUSE.search(low) + if not match or len(low) != len(question): + return question + rest = (question[:match.start()] + question[match.end():]).strip() + rest = re.sub(r"\s+([?.!,])", r"\1", re.sub(r"\s{2,}", " ", rest)) + return rest if len(re.findall(r"\w+", rest)) >= 3 else question def _crzp_future(pool, timed, question, person, complete, student): @@ -1575,7 +1790,9 @@ 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.asked_role(low) and re.search(r"\b(?:kto|ktor\w*|ako\s+sa\s+vola|meno)\b", low): + elif U.asked_role(low) and (re.search(r"\b(?:kto|ktor\w*|ako\s+sa\s+vola|meno)\b", low) + or re.search(r"\b(?:veduci|skolitel|oponent|konzultant)\w*\W*$", low)): + # (also "Čo robil Jánovi Ptákovi vedúci?": the role word closes the question) 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) @@ -1595,10 +1812,26 @@ def _unified(asked, question, engine, wiki, wiki_ok, part, person, wiki_context, return _with_token(result, wiki_context=wiki_context, options=options, question=pending_question(question, wiki, person)) out = U.methods(person, works, wiki_text, (part or {}).get("text") or "", low) + for kind, line in (out or {}).pop("missing", None) or []: + # the wiki answered one of the two named works only: its tools are asked for that work alone + alone = answer(f"Aké technológie využíva {person} vo svojej {U.TYPES[kind][2]}?", engine=engine) + found = re.search(r"(?m)^.+ vo svojej " + re.escape(U.TYPES[kind][2]) + r"\b.*využíva: .+$", + alone.get("answer") or "") if alone.get("status") == "ok" else None + if found: + out["text"] = out["text"].replace(line, found.group(0)) + out["urls"] = list(dict.fromkeys([*out.get("urls", []), *(alone.get("source_urls") or [])])) + if out and re.search(r"\bkto\b[^?]*\b(?:viedol|viedla|veduc\w*|oponoval\w*)\b", low): + # "… a kto ich viedol?": the roles of the same works below + led = U.roles(person, works, low, wiki_text, role="opponent" if re.search(r"\boponoval", low) else "supervisor") + if led and led.get("text") and not led.get("options"): + out = {**out, "text": out["text"] + "\n\n" + led["text"], + "urls": list(dict.fromkeys([*out.get("urls", []), *led.get("urls", [])]))} elif U.ABOUT_Q.search(low): out = U.about(person, works, low) elif U.WORKS_Q.search(low) or U.DID_Q.match(low) and not plan.get("period") and not plan.get("years"): out = U.works_list(person, works) + elif student and (U.WHO_Q.match(low) or bare_name(question, person)): + out = U.who(person, works) if out: return done(out) # Two people compared: one table. @@ -1624,14 +1857,16 @@ def _compose(asked: str, question: str, engine: str, wiki: dict, part: dict | No if part is not None and part["mode"] == "explicit" and wiki.get("status") == "ambiguous": wiki_ok = False if part is not None and part["mode"] == "explicit" and part.get("intent") in ("count", "methods") \ - and part.get("status") in ("ok", "ambiguous"): + and part.get("status") in ("ok", "ambiguous") and not part.get("addition") \ + or part is not None and part["mode"] == "explicit" and part.get("intent") == "relation" \ + and part.get("status") == "ok" and re.search(r"\bkto\s+oponoval\w*|\boponent\w*\s+prac", low): wiki_ok = False # a CRZP count (or the technologies of a CRZP work) is the answer; a wiki list is no count if wiki.get("accepted_for_delivery") is True and isinstance(wiki.get("answer"), str): wiki = {**wiki, "answer": finalize(wiki["answer"], wiki.get("source_urls"))} wiki_context = wiki.get("conversation_context") plan = wiki.pop("_plan", None) or {} if (part is not None and part["mode"] == "explicit" and part.get("status") == "ok" and part.get("text") - and NAMED_CRZP.search(low)): + and NAMED_CRZP.search(low) and not part.get("addition")): wiki_ok = False # "… v CRZP?", "hľadaj v registri": what CRZP itself records is asked else: special = _unified(asked, question, engine, wiki, wiki_ok, part, person, wiki_context, plan) @@ -1673,7 +1908,7 @@ def _compose(asked: str, question: str, engine: str, wiki: dict, part: dict | No return _with_token(result, question=question, crzp=part.get("crzp_token"), primary="crzp", options=part.get("options") or ()) if part.get("home_excluded"): - wiki_ok = False + wiki_ok = False # "na iných školách": the TUKE wiki part is not asked base = wiki if wiki_ok else {"index_version": wiki.get("index_version")} wiki_body, wiki_urls = split_sources(wiki["answer"]) if wiki_ok else ("", []) wiki_urls = wiki_urls or (wiki.get("source_urls") or [] if wiki_ok else []) @@ -1687,6 +1922,10 @@ def _compose(asked: str, question: str, engine: str, wiki: dict, part: dict | No head, items, tail, general = wiki_items(wiki_body, wiki_urls) if wiki_ok else ([], [], [], []) if wiki_ok and not items: # a wiki answer that is no list stays whole, the CRZP works follow it head, tail, general = [wiki_body], [], wiki_urls + from tools.answers.presentation.finalize import SIDE + if all(any(line.startswith(label + ":") for label in SIDE.values()) + for line in wiki_body.split("\n") if line.strip()): + head, tail = [], [wiki_body] # only "Téma je len v zadaní …: X." – a closing note after the works if not wiki_ok: head = ["V ZP Wiki k tomu nie je záznam. Práce na túto tému v CRZP (Centrálny register záverečných prác):"] shown, rest = first_page(items, part["items"]) diff --git a/tools/answers/planning/question_catalog.py b/tools/answers/planning/question_catalog.py index c867372..4992125 100644 --- a/tools/answers/planning/question_catalog.py +++ b/tools/answers/planning/question_catalog.py @@ -251,3 +251,13 @@ def route_for(decision: CatalogDecision | None, resolution: dict) -> Route | Non OUT_OF_SCOPE_MESSAGE = ("Odpovedám len na otázky o študentoch, ich prácach, vedúcich a témach v ZP Wiki. " "Pokyny na zmenu pravidiel nevykonávam a obsah databázy, prihlasovacie údaje ani " "systémové nastavenia nevypisujem.") +# A plain question about something else ("Aké bude zajtra počasie?") gets no warning about rules or passwords. +PLAIN_OUT_OF_SCOPE = ("Odpovedám len na otázky o študentoch, ich prácach, vedúcich a témach v ZP Wiki a v registri " + "záverečných prác. Opýtaj sa napríklad na študenta, tému, vedúceho alebo prácu.") +_RULES_WORDS = re.compile(r"\b(?:pokyn\w*|pravidl\w*|ignoruj\w*|prompt\w*|instrukc\w*|hesl\w*|prihlas\w*|token\w*|" + r"databaz\w*|nastaven\w*|systemov\w*|kluc\w*|api|vypis\w*\s+(?:vsetk|cel)\w*|admin\w*)\b") + + +def out_of_scope_message(question: str) -> str: + from tools.answers.verification.context_policy import normalized + return OUT_OF_SCOPE_MESSAGE if _RULES_WORDS.search(normalized(question)) else PLAIN_OUT_OF_SCOPE diff --git a/tools/answers/planning/question_plan.py b/tools/answers/planning/question_plan.py index 2e1f879..6d693c4 100644 --- a/tools/answers/planning/question_plan.py +++ b/tools/answers/planning/question_plan.py @@ -466,12 +466,12 @@ def build_question_plan(question, catalog, *, complete=None, verify_complete=Non if classify is not None and resolution.get('status')=='ok' and not {'request_out_of_scope','meeting_count_limit'}&set(spec.unsupported): # The catalog chooses the question type; the rules above remain the # fallback whenever the model is unavailable or its type is unclear. - from tools.answers.planning.question_catalog import route_for, OUT_OF_SCOPE_MESSAGE + from tools.answers.planning.question_catalog import route_for, out_of_scope_message decision=classify(resolution.get('resolved_query') or question) if (decision is not None and decision.type=='out_of_scope' and spec.intent=='metadata' and not spec.people and not WIKI_WORDS.search(normalized(question))): bound=PlannedQuestion(spec=spec,resolution=resolution,index_version=index_version) - return bound.model_copy(update={'reason':'request_out_of_scope','clarification':OUT_OF_SCOPE_MESSAGE}) + return bound.model_copy(update={'reason':'request_out_of_scope','clarification':out_of_scope_message(question)}) route=route_for(decision,resolution) if route is not None: spec=direct_spec(question,resolution,meeting=meeting,route=route,relative_year=relative_year) @@ -546,8 +546,10 @@ def build_question_plan(question, catalog, *, complete=None, verify_complete=Non if ambiguous_bindings: return bound.model_copy(update={'reason':'ambiguous_work_binding','clarification':'Ku každej osobe uveď prácu a príslušný rok; priradenie týchto podmienok nie je jednoznačne určené.'}) subject=' o osobe '+', '.join(p.name for p in spec.people) if spec.people else '' + # ("Akú Nobelovu cenu získal X?": such a fact is not in the records; say what they hold) + lead=('V podkladoch'+subject+' taký údaj nie je.' if spec.people else 'Otázke som úplne neporozumel.') return bound.model_copy(update={'reason':'unsupported_content_question','clarification': - 'Otázke'+subject+' som úplne neporozumel. Upresni, či ťa zaujíma zadanie, priebeh, problémy, výsledky, ' + lead+' Upresni, či ťa zaujíma zadanie, priebeh, problémy, výsledky, ' 'použité metódy, téma, vedúci alebo názov a rok práce'+('' if spec.people else ', prípadne uveď meno študenta')+'.'}) return bound diff --git a/tools/answers/presentation/finalize.py b/tools/answers/presentation/finalize.py index 0e1aa5f..7e57ae9 100644 --- a/tools/answers/presentation/finalize.py +++ b/tools/answers/presentation/finalize.py @@ -109,6 +109,22 @@ def _links(line: str) -> list[str]: return list(dict.fromkeys(urls)) +CATEGORY_LINE = re.compile(r"(?m)^(?P[^:\n*]{3,80}): uvedená kategória je \*\*(?P[^*\n]+)\*\*\.\s*$") + + +def same_category(text: str) -> str: + """"A: uvedená kategória je **dp2027**." for several people -> "Kategóriu **dp2027** majú: A, B, C.".""" + lines = list(CATEGORY_LINE.finditer(text)) + categories = {m.group("cat") for m in lines} + if len(lines) < 2 or len(categories) != 1: + return text + names = ", ".join(m.group("name").strip() for m in lines) + joined = f"Kategóriu **{categories.pop()}** majú: {names}." + first = lines[0] + rest = CATEGORY_LINE.sub("", text[first.end():]) + return re.sub(r"\n{3,}", "\n\n", text[:first.start()] + joined + rest).rstrip() + + def finalize(text: str, source_urls: list[str] | None = None) -> str: if not isinstance(text, str) or not text.strip(): return text @@ -133,6 +149,7 @@ def finalize(text: str, source_urls: list[str] | None = None) -> str: else m.group(1) + " " + LABEL_PREFIX.sub("", m.group(2)), out) out = re.sub(r"(?m)^(\s*-\s+)\[[ xX]\]\s+", r"\1", out) # a checkbox of the source ("[x] Doplňte…") + out = same_category(out) blocks = _collapse_side_people([b.strip() for b in re.split(r"\n\s*\n", out) if b.strip()]) substantive = [b for b in blocks if not MISSING.search(b) and not re.fullmatch(r"\*\*[^*]+\*\*", b) and not re.fullmatch(r"(?:\*\*[^*]+\*\*\s*)?(?:Posledný záznam[^\n]*|Zadanie a ciele:)", b)] diff --git a/tools/answers/presentation/unified.py b/tools/answers/presentation/unified.py index 3e4383e..8a8b446 100644 --- a/tools/answers/presentation/unified.py +++ b/tools/answers/presentation/unified.py @@ -55,6 +55,10 @@ ABOUT_Q = re.compile(r"\bo\s+com\s+(?:je|bola|bude)\b|\bco\s+(?:robil|robila|rie r"(?:svojej\s+)?(?:bakalar|diplom|dizerta|praci|projekt)") # "Čo robil Kristián Sopkovič?" without a time or meeting: an overview of the person's works DID_Q = re.compile(r"^\W*(?:a\s+)?(?:co|na\s+com)\s+(?:robil|robila|robi|pracoval|pracovala|pracuje)\b(?!.*\b(?:v|na|vo)\s)") +BOTH_TYPES = re.compile(r"\b(?:bakal\w*|diplom\w*|bp|dp)(?:\s+prac\w*)?\s+(?:a|aj|i|ako\s+aj)\s+(?:(?:v|vo|u|pri)\s+)?" + r"(?:jeho\s+|jej\s+|svojej\s+)?(?:bakal\w*|diplom\w*|bp|dp)\b") +# "Kto je Matej Ščišľak?", "Ján Holp" (only the name): who the person is, the works newest first +WHO_Q = re.compile(r"^\W*(?:a\s+)?(?:kto\s+(?:je|bol|bola|je\s+to)|povedz\s+mi\s+(?:nieco\s+)?o|predstav\s+mi)\s+\S") 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") @@ -321,6 +325,7 @@ def person_works(person: str, crzp_rows: list[dict] | None = None) -> list[dict] question's CRZP part and from the local cache of the register.""" from tools.crzp.answering import answer as crzp works = [dict(w) for w in catalog()["works"].get(person, [])] + wiki_known = bool(works or catalog()["people"].get(person)) rows, seen = [], set() for row in [*(crzp_rows or []), *registry_rows(person)]: key = (normalized(row.get("title") or ""), row.get("year")) @@ -346,7 +351,9 @@ def person_works(person: str, crzp_rows: list[dict] | None = None) -> list[dict] twin.setdefault("urls", []).append(row.get("url")) else: from tools.answers.combined import same_person_work - item["unconfirmed"] = not (same_person_work(person, row) or fits_studies(person, row, item, works)) + # (a person ZP Wiki does not know has no namesake there: the register's works are the person's) + item["unconfirmed"] = wiki_known and not ( + same_person_work(person, row) or fits_studies(person, row, item, works)) works.append(item) # A thesis without a title continues the project of its level ("Diplomový projekt 2026: # Inštrukčné dotrénovanie jazykového modelu" -> the diploma thesis 2027): that topic is shown. @@ -577,13 +584,32 @@ def supervisors(person: str, works: list[dict], low: str, wiki_text: str = "") - return roles(person, works, low, wiki_text, "supervisor") +def who(person: str, works: list[dict]) -> dict | None: + """"Kto je X?": one lead sentence (a student of ZP Wiki, the study start) and the works, newest first.""" + listed = works_list(person, works) + if listed is None: + return None + start = start_year(person) + year = re.search(r"(\d{4})", start["text"]).group(1) if start else None + lead = (f"{spelled(person)} je študent{'ka' if female(spelled(person)) else ''} v ZP Wiki" + + (f", štúdium začal{ending(person)} v roku {year}" if year else "") + ".") + body = re.sub(r"^.+?(?:má tieto práce|má túto prácu):", "Práce od najnovšej:" if len(works) > 1 else "Práca:", + listed["text"], count=1) + return {**listed, "text": lead + " " + body} + + def works_list(person: str, works: list[dict]) -> dict | None: if not works: return None lines = [f"{spelled(person)} má tieto práce:" if len(works) > 1 else f"{spelled(person)} má túto prácu:", ""] + from collections import Counter + twice = Counter((w["type"], w.get("year")) for w in works) for work in works: names = TYPES.get(work["type"]) or (work.get("heading") or "Práca",) - head = f"- **{names[0][:1].upper() + names[0][1:]}" + (f" ({work['year']})" if work.get("year") else "") + "**" + label = names[0][:1].upper() + names[0][1:] + if twice[(work["type"], work.get("year"))] > 1 and work.get("heading"): # "Diplomový projekt 1" and "… 2" + label = re.sub(r"\s*\b(?:19|20)\d{2}(?:/\d{2})?\b", "", work["heading"]).strip() or label + head = f"- **{label}" + (f" ({work['year']})" if work.get("year") else "") + "**" if work.get("title"): head += f": {work['title'].rstrip('.')}" details = results_of(person, work.get("heading")) if work["source"] == "wiki" else [] @@ -636,11 +662,13 @@ def about(person: str, works: list[dict], low: str, complete=None) -> dict | Non 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) + # "v bakalárskej a v diplomovej práci": both; a follow-up joined to the previous question ("… v nej … a v + # bakalárke?") names one type, the first one asked_type() finds + kinds = asked_types(low) if BOTH_TYPES.search(low) else [k for k in [asked_type(low)] if k] official = {} for source, text in (("wiki", wiki_text), ("crzp", crzp_text)): for sentence in re.finditer(r"vo svojej ([^„\n]+?)\s*„([^“]+)“[^:\n]*?využíva:\s*([^\n]+?)\.\s*$", text or "", re.M): - if kind and normalized(sentence.group(1)) != normalized(TYPES[kind][2]): + if kinds and normalized(sentence.group(1)) not in {normalized(TYPES[k][2]) for k in kinds if k in TYPES}: continue tools = [t.strip() for t in sentence.group(3).split(",") if t.strip()] found.setdefault(sentence.group(2), {"kind": sentence.group(1), "tools": []})["tools"] += tools @@ -677,7 +705,18 @@ def methods(person: str, works: list[dict], wiki_text: str, crzp_text: str, low: 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)} + missing = [] + if len(kinds) >= 2: # a named work without recorded tools is said so, not left out + said = {normalized(e["kind"]) for e in found.values()} + for k in kinds: + if k in TYPES and normalized(TYPES[k][2]) not in said: + work = next((w for w in works if w.get("type") == k), None) + if work: + title = f" „{work['title']}“" if work.get("title") else "" + year = f" ({work['year']})" if work.get("year") else "" + unique.append(f"Pri {TYPES[k][2]}{title}{year} technológie v podkladoch zapísané nie sú.") + missing.append((k, unique[-1])) + out = {"text": "\n\n".join(unique), "urls": work_urls(person, works), "missing": missing} if rest: out.update(rest=rest, rest_lead=rest_lead, offer=f"Ďalších technológií a metód je ešte {len(rest)}. Chceš vidieť aj zvyšné?") @@ -758,6 +797,10 @@ def meeting(person: str, text: str, low: str, follow_up: bool) -> str | 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}." + if re.search(r"\bzasobnik\w*", low) and not re.search(r"\b(?:ulohy|uloh)\b(?!\s*$)", low.replace("zasobnik uloh", "")): + backlog = backlog_of(person, when) # "a čo zásobník úloh?": the backlog only + return (f"Do zásobníka úloh zo stretnutia {when} patrí:\n\n" + "\n".join(f"- {p}" for p in backlog)) if backlog \ + else f"Pri stretnutí {when} nie je zapísaný zásobník úloh." tasks_only = bool(TASKS_Q.search(low)) and not re.search(r"\b(?:riesil\w*|robil\w*|urobil\w*|stihol\w*)\b", low) last = "poslednom " if re.search(r"\bposledn\w*", low) or follow_up else "" backlog = backlog_of(person, when) @@ -779,21 +822,33 @@ def meeting(person: str, text: str, low: str, follow_up: bool) -> str | None: return "\n".join(out) -def comparison(names: list[str], collaboration: bool = False) -> dict | None: - """A table of two students: their main work, focus, results and tools; shared points below.""" +def comparison(names: list[str], collaboration: bool = False, crzp_rows: list[dict] | None = None) -> dict | None: + """A table of two students: their main work, focus, results and tools; shared points below + (crzp_rows: the register's works of a person ZP Wiki does not know).""" 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")] + merged = [w for w in person_works(name, crzp_rows) if not w.get("unconfirmed")] works = [w for w in merged if w["type"] in THESES] or merged if not works: return None work = works[0] + newer = merged[0] # a newer project with recorded goals or results beats an older thesis without them + if newer is not work and (newer.get("year") or 0) > (work.get("year") or 0) and newer.get("heading") and ( + results_of(name, newer.get("heading"), 1) or goals_of(name, newer.get("heading"), 1)) and not ( + results_of(name, work.get("heading"), 1)): + work = newer data.append({"work": work, "goals": goals_of(name, work.get("heading"), 2), "results": results_of(name, work.get("heading"), 3)}) - block = comparison_block(names) or "" + known = all(catalog()["people"].get(n) for n in names) + block = (comparison_block(names) or "") if known else "" shared = re.search(r"- Spoločné: (.+)", block) only = [re.search(rf"- Len {re.escape(n)}: (.+)", block) for n in names] + if not known: # a person only the register knows: the keywords of each main work, the shared ones below + words = [list(dict.fromkeys((d["work"].get("row") or {}).get("keywords") or [])) for d in data] + common = [w for w in words[0] if fold_word(w) in {fold_word(v) for v in words[1]}] + only = [_Fixed(", ".join([w for w in ws if w not in common][:8])) if ws else None for ws in words] + shared = _Fixed(", ".join(common[:8]) + ".") if common else None def cell(values): return "
".join(v.replace("|", "/") for v in values) if values else "–" @@ -810,10 +865,23 @@ def comparison(names: list[str], collaboration: bool = False) -> dict | None: 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, []))) + urls = list(dict.fromkeys(u for n, d in zip(names, data) for u in work_urls(n, [d["work"]]))) return {"text": text, "urls": urls} +class _Fixed: + """A ready text where comparison() reads a regex match (group(1)).""" + def __init__(self, text: str): + self.text = text + + def group(self, _): + return self.text + + +def fold_word(text: str) -> str: + return normalized(text or "").strip() + + def roster_items(supervisor: str, wiki_items: list[dict], crzp_rows: list[dict]) -> list[dict]: """The students of a supervisor, newest work first, each once: name — work (year): title.""" from tools.crzp.answering import answer as crzp diff --git a/tools/crzp/answering/answer.py b/tools/crzp/answering/answer.py index b94cad1..ad75ed5 100644 --- a/tools/crzp/answering/answer.py +++ b/tools/crzp/answering/answer.py @@ -500,10 +500,15 @@ def work_line(row: dict) -> str: def describe(query: CrzpQuery) -> str: parts = [] for person in query.people: - parts.append(f"{ROLE_LABEL.get(person.role, 'osoba')} {person.name}" if person.role != "any" else person.name) + label = ROLE_LABEL.get(person.role, "osoba") + if label in ("vedúci", "autor", "oponent"): + from tools.answers.presentation.unified import female + if female(display_name(person.name)): + label = {"vedúci": "vedúca", "autor": "autorka", "oponent": "oponentka"}[label] + parts.append(f"{label} {person.name}" if person.role != "any" else person.name) if query.title: parts.append(f"názov „{query.title}“") - if query.topics and not query.people: + if query.topics: # also beside a person ("vedúci Juraj Sipko; téma „blockchain“") parts.append("téma „" + " ".join(query.topics[:2]) + "“") if query.work_types: parts.append(", ".join(WORK_TYPE_LABELS[t] for t in query.work_types)) @@ -570,8 +575,11 @@ def summary(detail: dict, complete=None) -> tuple[str, str]: if not abstract: return "Zhrnutie", _keyword_sentence(detail) if keywords else "CRZP pri tejto práci abstrakt neuvádza." payload = {"title": detail["title"], "abstract": abstract, "keywords": keywords} + prompt = SUMMARY_PROMPT + if _author_word(detail) == "autorka": # "Autorka navrhla …", not "Autor vyvinul …" for Iryna Kolisnichenko + prompt += " Práca je od autorky (žena): píš „autorka“ a slovesá v ženskom rode („navrhla“, „vytvorila“)." for attempt in range(2): - text = _ask(SUMMARY_PROMPT if attempt == 0 else SUMMARY_PROMPT + " Drž sa výlučne faktov z abstraktu.", + text = _ask(prompt if attempt == 0 else prompt + " Drž sa výlučne faktov z abstraktu.", payload, complete) if not text or len(text) > 1200: continue @@ -594,8 +602,10 @@ def _keyword_sentence(detail: dict) -> str: def _list(question, query, found, rows, complete=None) -> tuple[str, list[dict]]: rows = ranked(question, query, rows) hidden = 0 - if query.topics and not query.people and not query.title: # only works whose topic it is (relevance.py) - rows, hidden = topical(rows, query, complete) + if query.topics and not query.title and (not query.people or len(rows) <= PERSON_JUDGED): + # only works whose topic it is (relevance.py), also a person's ("Hládkovi študenti a rozpoznávanie reči": + # all of the person's works are judged, a supervisor's 64 works are no topic list) + rows, hidden = topical(rows, query, complete, limit=PERSON_JUDGED if query.people else TOPICAL_JUDGED) limit = query.show or LIST_LIMIT if query.show: # "vypíš prvých 8": the newest first rows = sorted(rows, key=lambda r: -(r.get("year") or 0)) @@ -618,16 +628,19 @@ def _list(question, query, found, rows, complete=None) -> tuple[str, list[dict]] TOPICAL_JUDGED = 60 # works of a topic list judged per question (the most relevant first) -def topical(rows: list[dict], query: CrzpQuery, complete=None) -> tuple[list[dict], int]: +PERSON_JUDGED = 160 # all works of one person (a supervisor's) judged for a topic (relevance.MAX_MODEL_ROWS) + + +def topical(rows: list[dict], query: CrzpQuery, complete=None, limit: int = TOPICAL_JUDGED) -> tuple[list[dict], int]: """The ranked works whose topic is the asked one (title, or judged so) first, the not yet judged after them; works that only mention the topic are left out: (rows, how many left out).""" from tools.crzp.answering import relevance - verdicts = relevance.judge(rows[:TOPICAL_JUDGED], query, complete=complete) - first = [r for r in rows[:TOPICAL_JUDGED] if verdicts.get(relevance.work_id(r)) == relevance.TOPIC] - unsure = [r for r in rows[:TOPICAL_JUDGED] + verdicts = relevance.judge(rows[:limit], query, complete=complete) + first = [r for r in rows[:limit] if verdicts.get(relevance.work_id(r)) == relevance.TOPIC] + unsure = [r for r in rows[:limit] if verdicts.get(relevance.work_id(r)) in (relevance.UNSURE, relevance.UNJUDGED, relevance.SKIPPED)] - hidden = len(rows[:TOPICAL_JUDGED]) - len(first) - len(unsure) - return first + unsure + rows[TOPICAL_JUDGED:], hidden + hidden = len(rows[:limit]) - len(first) - len(unsure) + return first + unsure + rows[limit:], hidden TYPE_FACET = {"bakalárska": "bakalárska práca", "diplomová": "diplomová práca", "dizertačná": "dizertačná práca", @@ -656,13 +669,26 @@ def _count(question, query, found, rows) -> tuple[str, list[dict]]: if values and len(found["texts"]) == 1 and not (query.school or query.unit or len(query.people) > 1): count, note = sum(values), " (súhrnný počet z CRZP)" else: - note = f" (aspoň; prehľadaných {len(found['rows'])} z {found['total']} výsledkov hľadania)" + note = (f" (najmenej toľko: hľadanie má {found['total']} výsledkov, prečítaných bolo {len(found['rows'])} " + "a ďalšie môžu tiež zodpovedať)") text = f"Počet prác ({describe(query)}): **{count}**{note}." + unpublished_note(found, query) + sentence = person_count(query, count, note) + if sentence: # "Daniel Hládek viedol v roku 2024 **5** bakalárskych prác." + text = sentence + unpublished_note(found, query) defended_place = query.published and not query.people and not query.topics and (query.unit or query.school) \ and len(query.work_types) <= 1 if defended_place: # "Koľko diplomových prác obhájili na KEMT v roku 2022?" -> one sentence when = f" v roku {query.years[0]}" if len(query.years) == 1 else (f" v rokoch {min(query.years)}–{max(query.years)}" if query.years else "") text = f"Na {_place(query)}{when} obhájili {works_phrase(count, query.work_types)}{note}." + unpublished_note(found, query) + if (query.published and not query.people and not query.topics and (query.unit or query.school) + and len(query.work_types) == 2 and not found.get("facet_only") and count and query.split != "year" + and len(set(query.years)) <= 1): + # "Koľko bakalárskych a koľko diplomových prác obhájili na KEMT v roku 2024?" -> both in one sentence + when = f" v roku {query.years[0]}" if len(query.years) == 1 else "" + parts = [works_phrase(sum(1 for r in rows if r.get("work_type") == t), [t]) for t in query.work_types] + text = (f"Na {_place(query)}{when} obhájili {parts[0]} a {parts[1]}, spolu {count}{note}." + + unpublished_note(found, query)) + return text, counted_sources(rows) asked_years = sorted(set(query.years)) compare = len(asked_years) == 2 and (query.split == "year" or COMPARE.search(fold(question))) if compare and count: # "o koľko viac v 2025 ako v 2024", "koľko v 2024 a koľko v 2025": each year and the change @@ -676,10 +702,16 @@ def _count(question, query, found, rows) -> tuple[str, list[dict]]: verbs = VERBS.get(person.role, VERBS["supervisor"]) text = (f"{display_name(person.name)} {verbs[1] if female(display_name(person.name)) else verbs[0]} v roku {first} " f"{works_phrase(a, query.work_types)} a v roku {second} {b}, {change}") + elif not query.people and not query.topics and len(query.work_types) <= 1 and (query.unit or query.school): + # "Bolo v roku 2023 na KEMT viac diplomových prác ako v roku 2022?" + text = f"Na {_place(query)} bolo v roku {first} {works_phrase(a, query.work_types)} a v roku {second} {b}, {change}" else: rest = describe(query.model_copy(update={"years": []})) text = f"Prác{' (' + rest + ')' if rest else ''} bolo v roku {first} {a} a v roku {second} {b}, {change}" text += f"{note}." + unpublished_note(found, query) + yes_no = _yes_no(question, first, second, a, b) + if yes_no: + text = yes_no + " " + text if query.topics and not query.people and not found.get("facet_only") and count: from tools.crzp.answering import relevance named = sum(relevance.names_topic(r, relevance.topic_terms(query)) for r in rows) @@ -691,6 +723,9 @@ def _count(question, query, found, rows) -> tuple[str, list[dict]]: lines = [f"- {y}: {n}" + (" (" + ", ".join(f"{k} {c}" for k, c in by_year[y].most_common()) + ")" if len(by_year.get(y) or {}) > 1 else "") for y, n in sorted(years.items(), reverse=True)] return text + "\n\nPodľa rokov (od najnovšieho):\n" + "\n".join(lines), counted_sources(rows) + if count and query.split == "type" and len(types) == 1: # one type only: no one-line list + kind = next(iter(types)) + return text + f"\n\nVšetky sú {'práce typu ' + kind if kind not in WORK_TYPE_PLURAL else WORK_TYPE_PLURAL[kind]}.", counted_sources(rows) if count and query.split == "type" and types: # "rozdeľ na bakalárske a diplomové" return text + "\n\nPodľa typu práce:\n" + "\n".join(f"- {k}: {v}" for k, v in types.most_common()), counted_sources(rows) if count and len(types) > 1: # one asked type or year needs no breakdown @@ -701,6 +736,10 @@ def _count(question, query, found, rows) -> tuple[str, list[dict]]: return text, counted_sources(rows) +WORK_TYPE_PLURAL = {"bakalárska práca": "bakalárske", "diplomová práca": "diplomové", "dizertačná práca": "dizertačné", + "habilitačná práca": "habilitačné", "rigorózna práca": "rigorózne"} + + def counted_sources(rows: list[dict]) -> list[dict]: """The sources of a count: its few works (at most 10, newest first); a larger count lists none at random ("aké napr." lists them).""" @@ -712,6 +751,21 @@ COMPARE = re.compile(r"\bo\s+kolko\b|\brozdiel\w*|\bviac\b|\bmenej\b|\bporovn\w* r"|\ba\s+(?:kolko\s+)?(?:bolo\s+)?v\s+(?:roku\s+)?(?:19|20)\d\d|\ba\s+kolko\b") +def _yes_no(question: str, first: int, second: int, a: int, b: int) -> str: + """"Bolo v roku 2023 viac prác ako v roku 2022?" -> "Áno." / "Nie." (a question, not "koľko").""" + low = fold(question) + if re.search(r"\bkolk\w*|\bpocet\b|\bo\s+kolko\b", low) or not re.search(r"\b(?:viac|menej)\b", low): + return "" + order = [int(y) for y in re.findall(r"\b(?:19|20)\d{2}\b", question)] + if len(order) < 2: + return "" + asked_year = order[0] # "v roku 2025 viac … ako v roku 2024": 2025 is compared + mine, other = (b, a) if asked_year == second else (a, b) + more = bool(re.search(r"\bviac\b", low)) + true = mine > other if more else mine < other + return "Áno." if true else "Nie." + + def _of(name: str) -> str: """"Technická univerzita v Košiciach" -> "Technickej univerzity v Košiciach" (genitive).""" head, _, town = name.partition(" v ") @@ -720,9 +774,40 @@ def _of(name: str) -> str: def _place(query: CrzpQuery) -> str: - """"KEMT FEI Technickej univerzity v Košiciach" (after "na").""" - school = _of(SCHOOLS[query.school][0]) if query.school else "" - return (UNITS[query.unit]["label"] + " " + school).strip() if query.unit else school + """"KEMT FEI Technickej univerzity v Košiciach", "Technickej univerzite v Košiciach" (after "na").""" + if query.unit: + school = _of(SCHOOLS[query.school][0]) if query.school else "" + return (UNITS[query.unit]["label"] + " " + school).strip() + return _at(SCHOOLS[query.school][0]) if query.school else "" + + +def _at(name: str) -> str: + """"Technická univerzita v Košiciach" -> "Technickej univerzite v Košiciach" (locative, after "na").""" + head, _, town = name.partition(" v ") + words = [w[:-1] + "ej" if w.endswith("á") else w[:-1] + "e" if w.endswith("a") else w for w in head.split()] + return " ".join(words) + (" v " + town if town else "") + + +def person_count(query: CrzpQuery, count: int, note: str) -> str: + """One person's count as a sentence: "Daniel Hládek viedol v roku 2024 **5** bakalárskych prác.", + "Juraj Sipko viedol **8** prác na tému „blockchain“."; "" for any other count.""" + if len(query.people) != 1 or query.title or query.sids or len(query.work_types) > 1: + return "" + person = query.people[0] + if person.role not in VERBS: + return "" + from tools.answers.presentation.unified import female + name = display_name(person.name) + verb = VERBS[person.role][1 if female(name) else 0] + years = sorted(set(query.years)) + when = (f" v roku {years[0]}" if len(years) == 1 else f" v rokoch {years[0]}–{years[-1]}" + if years == list(range(years[0], years[-1] + 1)) else " v rokoch " + ", ".join(map(str, years))) if years else "" + place = f" na {_place(query)}" if query.unit or query.school not in (None, "tuke") else "" + topic = f" na tému „{query.topic_key()}“" if query.topics else "" + if not count: + return f"{name} {'ne' + verb}{when}{place} žiadnu prácu{topic}{note}." + phrase = works_phrase(count, query.work_types) + return f"{name} {verb}{when}{place} **{count}**{phrase[len(str(count)):]}{topic}{note}." def works_phrase(count: int, work_types: list[str]) -> str: @@ -762,7 +847,7 @@ def _about(question, query, found, rows, complete=None) -> tuple[str, list[dict] blocks = [] for row, detail, done in zip(rows, details, summaries): head = (f"**{row['title']}** — {_kind(row)}, {row.get('year') or 'rok neuvedený'}, {university(row)}; " - f"autor {_names(row.get('authors', []))}") + f"{_author_word(row)} {_names(row.get('authors', []))}") if re.search(r"oponent|ved[uú]c|[sš]kolite", question.lower()): # "Kto bol oponentom … a o čom je?" head += f"; vedúci {_names(row.get('supervisors', []))}; oponent {_names(row.get('opponents', []))}" if detail is None: @@ -795,6 +880,15 @@ def _keywords(question, query, found, rows) -> tuple[str, list[dict]]: ROLE_INSTRUMENTAL = {"author": ("Autorom", "Autormi", "Autorkou"), "supervisor": ("Vedúcim", "Vedúcimi", "Vedúcou"), "opponent": ("Oponentom", "Oponentmi", "Oponentkou")} DOCTORAL = ("Školiteľom", "Školiteľmi", "Školiteľkou") # a dissertation has a "školiteľ", a thesis a "vedúci" +def _author_word(row: dict) -> str: + """"autorka" for one female author, "autori" for several, else "autor".""" + authors = row.get("authors") or [] + if len(authors) > 1: + return "autori" + from tools.answers.presentation.unified import female + return "autorka" if authors and female(display_name(authors[0])) else "autor" + + VERBS = {"supervisor": ("viedol", "viedla", "viedli"), "opponent": ("oponoval", "oponovala", "oponovali"), "author": ("napísal", "napísala", "napísali")} SHORT_SCHOOL = {"Technická univerzita v Košiciach": "TUKE", "Slovenská technická univerzita v Bratislave": "STU v Bratislave", @@ -1049,7 +1143,8 @@ def _schools(question, query, found, rows) -> tuple[str, list[dict]]: order = sorted(by_school.items(), key=lambda i: (-sum(i[1].values()), i[0])) lines = [] for name, units in order[:20]: - parts = [f"{u} {c}" for u, c in units.most_common() if u][:4] + # units written only as codes ("01000 01140" at other schools) name nothing: not shown + parts = [f"{u} {c}" for u, c in units.most_common() if u and not re.fullmatch(r"[\d\s,]+", u)][:4] lines.append(f"- {name} ({plural(sum(units.values()))}" + (": " + "; ".join(parts) if parts else "") + ")") more = f"\n- … a ďalšie ({len(order) - 20})" if len(order) > 20 else "" return (f"Školy prác v CRZP ({describe(query)}; {plural(len(rows))}):\n\n" @@ -1200,6 +1295,21 @@ def _answer_query(question: str, query: CrzpQuery, complete=None) -> dict: if found is None: return _result(question, "no_answer", "Otázke nezodpovedá žiadne vyhľadávanie v CRZP.", reason="missing_search_terms") + if not rows and query.intent == "count" and query.people and (query.school or query.unit): + # "Koľko prác viedol Hládek na Žilinskej univerzite?": 0, and where the person's works are + person = query.people[0] + elsewhere = Counter(university(r) for r in found["rows"] if people_in_role(r, person.name, person.role)) + from tools.answers.presentation.unified import female + name = display_name(person.name) + verb = {"supervisor": "neviedol", "opponent": "neoponoval"}.get(person.role, "nemá") + verb = verb + "a" if verb != "nemá" and female(name) else verb + text = f"Podľa registra záverečných prác {name} na {_place(query)} {verb} žiadnu prácu." + if elsewhere: + text += " Práce, pri ktorých je uvedený, sú z " + ", ".join( + f"{_of(school)} ({n})" for school, n in elsewhere.most_common(3)) + "." + result = _result(question, "ok", text, complete=found["complete"], count=0) + result["_shown"], result["_asked"], result["_matched"] = [], asked, 0 + return result if not rows: tried = "„" + "“, „".join(_without_suffix(query, query.searched)) + "“" result = _result(question, "no_answer", @@ -1217,6 +1327,9 @@ def _answer_query(question: str, query: CrzpQuery, complete=None) -> dict: return result # The exact number of works meeting the conditions (every row read, or CRZP's own total of a search # whose read rows all qualify); an "at least" reading has none and is never compared. + hidden = 0 + if query.intent == "count" and query.topics and query.people and not query.title and len(rows) <= PERSON_JUDGED: + rows, hidden = topical(ranked(question, query, rows), query, complete, limit=PERSON_JUDGED) exact = len(rows) if found["complete"] else (found["total"] if found.get("facet_only") else None) changed = (query.previous_count is not None and exact is not None and exact != query.previous_count) handler = {"list": _list, "count": _count, "keywords": _keywords, "relation": _relation, @@ -1233,6 +1346,9 @@ def _answer_query(question: str, query: CrzpQuery, complete=None) -> dict: except CrzpUnavailable: return _result(question, "error", "CRZP momentálne neodpovedá alebo obmedzil počet požiadaviek. Skús to o chvíľu.", reason="crzp_unavailable") + if hidden and query.intent == "count": + body += (f"\n\nĎalších {plural(hidden)} tento pojem len spomína (napr. v kľúčových slovách), nie je ich hlavnou " + "témou; nie sú započítané.") if getattr(query, "relaxed_author", False): body = (f"{query.people[0].name} nie je v CRZP autorom žiadnej z nájdených prác; uvedené sú práce, pri ktorých " "je školiteľom alebo oponentom.\n\n" + body) diff --git a/tools/crzp/answering/relevance.py b/tools/crzp/answering/relevance.py index 8722b20..0c1ac45 100644 --- a/tools/crzp/answering/relevance.py +++ b/tools/crzp/answering/relevance.py @@ -97,7 +97,17 @@ def mentions(text: str, term: str, case: bool = True) -> bool: def names_topic(row: dict, terms: list[str]) -> bool: - return any(mentions(row.get("title") or "", term) for term in terms) + """The title names the topic: a phrase's words next to each other ("rozpoznávanie nenávistnej reči" does not + name "rozpoznávanie reči"; such a title goes to the model).""" + title = row.get("title") or "" + return any(mentions(title, term) and (acronym(term) or len(_words(term)) < 2 or adjacent(title, term)) + for term in terms) + + +def adjacent(text: str, term: str) -> bool: + words, wanted = _words(text), _words(term) + return any(all(mentions(words[i + j], wanted[j], case=False) for j in range(len(wanted))) + for i in range(len(words) - len(wanted) + 1)) def _line(number: int, row: dict, abstract: str | None) -> str: diff --git a/tools/crzp/answering/understand.py b/tools/crzp/answering/understand.py index 2dfb05b..bb25cef 100644 --- a/tools/crzp/answering/understand.py +++ b/tools/crzp/answering/understand.py @@ -59,7 +59,9 @@ WORK_WORDS = {"bp", "dp", "praca", "prace", "prac", "bakalarska", "bakalarske", OUT_OF_SCOPE = re.compile( r"\b(?:ignoruj|zabudni|obid|prepis|zrus)\w*\b[^?.!]*\b(?:pravidl|pokyn|instrukci|obmedzen|prompt)\w*" r"|\b(?:vypis|exportuj|stiahni|ukaz|daj|dump)\w*\b[^?.!]*\b(?:vsetk|cel|kompletn)\w*\s+(?:\w+\s+)?" - r"(?:zaznam|databaz|register|crzp|prac)\w*" + r"(?:zaznam|databaz|register|crzp)\w*" + r"|\b(?:exportuj|stiahni|dump)\w*\b[^?.!]*\bprac\w*" + r"|\b(?:vypis|ukaz|daj)\w*\s+(?:mi\s+)?(?:vsetk|cel|kompletn)\w*\s+(?:\w+\s+)?prac\w*\W*$" # all works, nothing else r"|\bsystem\w* prompt|\bhesl\w*|\bapi kluc|\.env\b") ROLE_CUES = { "supervisor": r"\b(?:ved[uú]c|viedol|viedla|vedie|veden|pod veden|[sš]kolite[lľ])", @@ -154,7 +156,8 @@ def in_question(value: str, question: str) -> bool: return all(any(stem_match(v, w) for w in words) for v in _words(value)) and bool(_words(value)) -YEAR_RANGE = re.compile(r"\b(?:od\s+|medzi\s+)?((?:19|20)\d{2})\s*(?:až|az|-|–|do|a)\s*((?:19|20)\d{2})\b") +YEAR_RANGE = re.compile(r"\b(?:od\s+(?:roku\s+)?|medzi\s+(?:rokmi\s+|rokom\s+)?)?((?:19|20)\d{2})\s*" + r"(?:až|az|-|–|do|a)\s*(?:(?:roku|rokom)\s+)?((?:19|20)\d{2})\b") def years_in(question: str) -> list[int]: @@ -368,6 +371,11 @@ OTHER_SCHOOLS = re.compile( def understand(question: str, *, complete=None, use_model: bool = True) -> CrzpQuery: other = OTHER_SCHOOLS.search(question) + both = re.search(r"(?i)\b(?:na|v|vo|z|zo)\s+(\S+)\s+aj\s+(?:na|v|z|zo)?\s*(?:in|ostatn|ďalš|dalsi)", question) + if other and both and (fold(both.group(1)) in SCHOOLS or unit_in_question(both.group(1))): + # "na KEMT aj na iných školách": every school, not "the others only" + core = (question[:both.start()] + " " + question[other.end():]).strip() + return understand(core, complete=complete, use_model=use_model) if other: named = fold(other.group("school") or "") if not named or named in SCHOOLS or named in UNITS: diff --git a/tools/crzp/answering/units.py b/tools/crzp/answering/units.py index d3a56fc..757dbc2 100644 --- a/tools/crzp/answering/units.py +++ b/tools/crzp/answering/units.py @@ -89,5 +89,7 @@ def unit_label(row: dict) -> str: continue known = next((u["label"].split()[0] for u in VERIFIED.values() if u["code"] == part), None) entry = workplaces.name_of(workplaces.TUKE, part) if part.isdigit() and not known else None - names.append(known or (f"{entry['name']} ({part})" if entry else f"pracovisko {part}" if part.isdigit() else part)) - return ", ".join(names) + # a learned code is shown by its name only ("Katedra počítačov a informatiky", not "… (104009)"); + # a code without evidence stays a number (never a guessed name) + names.append(known or (entry["name"] if entry else f"pracovisko {part}" if part.isdigit() else part)) + return ", ".join(dict.fromkeys(names)) diff --git a/tools/crzp/tests/test_crzp.py b/tools/crzp/tests/test_crzp.py index 467adb9..dcf60eb 100644 --- a/tools/crzp/tests/test_crzp.py +++ b/tools/crzp/tests/test_crzp.py @@ -170,13 +170,13 @@ def test_count_of_supervised_works_from_complete_rows(crzp): def test_count_beyond_read_rows_uses_the_crzp_facet_and_marks_truncation(crzp): crzp["result"] = found([row("A"), row("B")], total=350, facet_count=120) result = A._answer("Koľko prác viedol Peter Novák?", complete=crzp["no_model"]) - assert "**120** (súhrnný počet z CRZP)" in result["answer"] + assert "Peter Novák viedol **120** záverečných prác (súhrnný počet z CRZP)" in result["answer"] assert result["truncated"] and result["complete"] is False and result["truncation_reasons"] == ["crzp_result_limit"] by_year = A._answer("Koľko prác viedol Peter Novák v roku 2025?", complete=crzp["no_model"]) - assert "**120** (súhrnný počet z CRZP)" in by_year["answer"] # CRZP filtered the year itself + assert "v roku 2025 **120** záverečných prác (súhrnný počet z CRZP)" in by_year["answer"] # CRZP filtered the year assert crzp["searches"][-1][1]["years"] == (2025, 2025) by_school = A._answer("Koľko prác viedol Peter Novák na TUKE?", complete=crzp["no_model"]) - assert "**2** (aspoň; prehľadaných 2 z 350" in by_school["answer"] + assert "**2** záverečné práce (najmenej toľko: hľadanie má 350 výsledkov, prečítaných bolo 2" in by_school["answer"] def test_name_with_diacritics_prefers_the_exact_spelling_and_warns_about_namesakes(crzp): @@ -358,7 +358,7 @@ def test_verified_workplace_filter_and_label(crzp): assert "KEMT práca" in result["answer"] and "Iná katedra" not in result["answer"] assert "Technická univerzita v Košiciach, FEI, KEMT" in result["answer"] assert units.unit_label({"school": "Technická univerzita v Košiciach", "school_unit": "1040 104009"}) == \ - "FEI, Katedra počítačov a informatiky (104009)" + "FEI, Katedra počítačov a informatiky" # the code once named is not repeated assert units.unit_in_question("práce z FEI") == "fei" and units.unit_in_question("práce z TUKE") is None @@ -497,7 +497,7 @@ def test_school_count_uses_the_crzp_total_only_when_every_read_row_is_from_that_ crzp["result"] = found([row("A", **dp), row("B", school="Iná škola", **dp)], total=1169) A._cache.clear() mixed = A._answer("Koľko diplomových prác bolo na TUKE v roku 2024?", complete=crzp["no_model"]) - assert "**1** (aspoň;" in mixed["answer"] + assert "**1** (najmenej toľko:" in mixed["answer"] def test_a_workplace_or_school_named_by_the_model_is_not_a_topic(): @@ -573,7 +573,7 @@ def test_follow_up_keeps_the_previous_conditions_and_replaces_the_new_ones(crzp, crzp["result"] = found([row("A", year=2024), row("C", year=2023), row("E", year=2024), row("D", year=2024, supervisor="Iný, Karol")]) count = A._answer("Koľko prác viedol Peter Novák?", complete=crzp["no_model"]) - assert "Počet prác" in follow(crzp, "a v roku 2024?", count)["answer"] # the count intent is kept + assert "Peter Novák viedol v roku 2024 **2**" in follow(crzp, "a v roku 2024?", count)["answer"] # the count is kept assert "**2**" in follow(crzp, "a v roku 2024?", count)["answer"] other = follow(crzp, "Ktoré práce viedol Karol Iný?", first) # own subject: answered on its own assert "**D**" in other["answer"] and "rok" not in other["answer"].split("\n")[0] @@ -967,3 +967,15 @@ def test_this_years_data_read_more_than_a_day_ago_carry_their_date(crzp): assert "Údaje sú k" not in A._answer(f"Koľko prác viedol Peter Novák v roku {this_year}?", complete=crzp["no_model"])["answer"] crzp["result"] = {**found([row("A", year=2020)]), "fetched_at": time.time() - 30 * 86400} assert "Údaje sú k" not in A._answer("Koľko prác viedol Peter Novák v roku 2020?", complete=crzp["no_model"])["answer"] + + +def test_suite_fixes_count_wording(): + """A yes/no year comparison leads with Áno/Nie; a title names a phrase only with its words together.""" + from tools.crzp.answering import relevance + assert A._yes_no("Viedol Daniel Hládek v roku 2025 viac bakalárskych prác ako v roku 2024?", 2024, 2025, 5, 7) == "Áno." + assert A._yes_no("Bolo v roku 2023 menej prác ako v roku 2022?", 2022, 2023, 37, 40) == "Nie." + assert A._yes_no("O koľko viac prác bolo v roku 2025 ako v 2024?", 2024, 2025, 5, 7) == "" + assert not relevance.names_topic({"title": "Rozpoznávanie nenávistnej reči pomocou LLM"}, ["rozpoznávanie reči"]) + assert relevance.names_topic({"title": "Automatické rozpoznávanie reči"}, ["rozpoznávanie reči"]) + assert A._at("Technická univerzita v Košiciach") == "Technickej univerzite v Košiciach" + assert A._author_word({"authors": ["Kolisnichenko, Iryna"]}) in ("autorka", "autor") diff --git a/tools/knowledge/roster.py b/tools/knowledge/roster.py index af75941..319e0ef 100644 --- a/tools/knowledge/roster.py +++ b/tools/knowledge/roster.py @@ -26,9 +26,25 @@ def roster_question(spec) -> bool: and years and re.search(r"\b(?:tem\w*|prac\w*|projekt\w*|na com sa|co sa|ries\w*)\b", n) and not re.search(r"\b(?:tag\w*|klucov\w*|kategor\w*|kolko|pocet|nazov\w*|autor\w*|vedu\w*|vedie)\b", n) + # a topic narrows the list ("diplomové práce o rozpoznávaní reči v roku 2024"): content search, no roster + and not getattr(spec, "topic", None) + and not re.search(r"\b(?:o|s|so|na\s+temu|v\s+oblasti|zameran\w*\s+na)\s+(?!com\b|com\s|tom\b|roku\b|rok\b)[a-z]{3,}", n) ) +def _no_topic(text: str) -> bool: + """A date ("18.2.2022") or a label without content ("Návrh na zadanie bakalárskej práce:") is no topic.""" + plain = re.sub(r"[\s*_#>\-]+", " ", text).strip() + return bool(re.fullmatch(r"[\d.\s/-]{4,}", plain) or plain.endswith(":") and len(plain) < 60 or len(plain) < 4) + + +def _shown(text: str) -> str: + """The source row without its list marker, checkbox and link syntax ("1. [ ] … [TUKE Cloud](https://…)").""" + text = re.sub(r"^\s*(?:[-*+]|\d+[.)])\s+", "", text.strip()) + text = re.sub(r"^\[[ xX]\]\s*", "", text) + return re.sub(r"\[([^\]]+)\]\([^)]*\)", r"\1", text).strip() + + def _year_label(spec): if spec.period and spec.period.field == "work_year": first, last = spec.period.start[:4], spec.period.end[:4] @@ -48,7 +64,7 @@ def answer_roster(spec, index, *, engine: str) -> dict: key = (row["person"], row["source_path"], row["work_label"]) # A bare heading ("## Diplomový projekt 2024") names the work, not its topic. heading = bool(re.fullmatch(r"\s*#+\s.*", row["text"])) or normalized(row["text"]) == normalized(row["work_label"]) - rank = 9 if heading else _RANK.get(row["kind"], 2) + rank = 9 if heading else 8 if _no_topic(row["text"]) else _RANK.get(row["kind"], 2) if key not in best or rank < best[key][0]: best[key] = (rank, row) works = sorted((row for _, row in best.values()), @@ -73,11 +89,12 @@ def answer_roster(spec, index, *, engine: str) -> dict: for person, rows in by_person.items(): lines.append(f"**{person}**") for row in rows: - if re.fullmatch(r"\s*#+\s.*", row["text"]) or normalized(row["text"]) == normalized(row["work_label"]): + if (re.fullmatch(r"\s*#+\s.*", row["text"]) or normalized(row["text"]) == normalized(row["work_label"]) + or _no_topic(row["text"])): lines.append(f"- {row['work_label']} (téma v profile neuvedená)") continue label = "téma alebo názov" if row["kind"] == "topic" else "zadanie" if row["kind"] == "assignment" else "podklad" - lines.append(f"- {row['work_label']}; {label}: {row['text'].strip()}") + lines.append(f"- {row['work_label']}; {label}: {_shown(row['text'])}") url = rows[0].get("source_url") if url: lines.append(f"Zdroj: {url}") diff --git a/tools/retrieval/person_names.py b/tools/retrieval/person_names.py index 59d1806..9ccb667 100644 --- a/tools/retrieval/person_names.py +++ b/tools/retrieval/person_names.py @@ -43,6 +43,10 @@ def name_token_variants(token: str) -> set[str]: variants.update(token[:-1] + s for s in ("a", "ovi", "om")) else: variants.update(token + s for s in ("a", "ovi", "om")) + if re.search(r"[^aeiouy](?:ek|ec|ok)$", token) and len(token) >= 5: + # a fleeting vowel: Hládek -> Hládka, Hládkovi, Hládkom; Kamenec -> Kamenca + stem = token[:-2] + token[-1] + variants.update(stem + s for s in ("a", "ovi", "om")) return variants @@ -203,7 +207,8 @@ def resolve_person_names(query: str, catalog: list[dict]) -> dict: author_lookup = bool( re.search( r"\b(?:autor\w*|dokument\w*|vedie|viedol|viedla|veduc\w*|veden\w*|skolitel\w*|skoli\w*|konzult\w*)\b" - r"|\bpod sebou\b", normalize(query) + # "študenti Daniela Hládka": the students of a supervisor (a supervisor has no profile of his own) + r"|\bstudent(?:i|ov|om|mi|ky|iek)\b|\bpod sebou\b", normalize(query) ) ) people = [ @@ -346,6 +351,8 @@ def resolve_person_names(query: str, catalog: list[dict]) -> dict: or _generic(words[i]) or inside_quote(token.start(), token.end()) or covered(token.start(), token.end()) + # an all-capital abbreviation ("študentov KEMT", "práce FEI") names a department or tool, no person + or (token[0].isupper() and 2 <= len(token[0]) <= 6 and words[i] not in surnames) ): continue # A capitalized surname with one typo ("Pervasov") names the single diff --git a/tools/retrieval/synonyms.py b/tools/retrieval/synonyms.py index 1005f8b..553b5d2 100644 --- a/tools/retrieval/synonyms.py +++ b/tools/retrieval/synonyms.py @@ -13,7 +13,8 @@ from functools import lru_cache from tools.answers.verification.context_policy import normalized GROUPS = [ - ["rozpoznávanie reči", "speech recognition", "ASR", "automatické rozpoznávanie reči", "prepis reči", "speech to text"], + ["rozpoznávanie reči", "speech recognition", "ASR", "automatické rozpoznávanie reči", "prepis reči", "speech to text", + "prepis reči na text", "prevod reči na text", "speech-to-text", "STT"], ["syntéza reči", "speech synthesis", "text to speech", "TTS"], ["chatbot", "dialógový systém", "konverzačný agent", "conversational agent"], ["veľký jazykový model", "LLM", "large language model", "jazykový model", "language model"],