From 23c89773fa5ecc6df9c3608539e6de7dff5186ea Mon Sep 17 00:00:00 2001 From: jp170na Date: Fri, 20 Nov 2026 03:42:51 +0100 Subject: [PATCH] upravy --- README.md | 2 +- test/presentation/test_combined_answers.py | 49 ++++ test/presentation/test_unified_answers.py | 11 + tools/answers/combined.py | 233 +++++++++++++++- tools/answers/presentation/unified.py | 303 ++++++++++++++++++++- tools/crzp/answering/answer.py | 37 ++- tools/crzp/answering/understand.py | 4 +- tools/crzp/tests/test_crzp.py | 17 +- tools/knowledge/roster.py | 4 + 9 files changed, 629 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index e741fb4..63ea7df 100644 --- a/README.md +++ b/README.md @@ -88,7 +88,7 @@ a novým tokenom kontextu. Claude text zobrazí bez zmien. |---|---|---| | Backend | Python, FastAPI, Pydantic | HTTP API, typované plány a odpovede | | Textový index | SQLite + FTS5 | úseky, fulltext, vektory, cache | -| Vektory | bi-encoder `multilingual-e5-small` (Sentence Transformers) | sémantické vyhľadávanie | +| Vektory | bi-encoder `multilingual-e5-small` | sémantické vyhľadávanie | | Reranking | cross-encoder | presnejšie poradie podkladov | | Jazyk | Stanza, Tiktoken | lematizácia slovenčiny, delenie textu na úseky | | Graf | Neo4j, Cypher | osoby, práce, témy a vzťahy medzi nimi | diff --git a/test/presentation/test_combined_answers.py b/test/presentation/test_combined_answers.py index cd2d520..0397b1b 100644 --- a/test/presentation/test_combined_answers.py +++ b/test/presentation/test_combined_answers.py @@ -615,3 +615,52 @@ def test_the_wiki_is_asked_without_the_other_schools_clause(): 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?" + + +def test_a_pronoun_follow_up_names_the_conversation_person(monkeypatch): + monkeypatch.setattr(C, "_one_person", lambda q: {"name": "Samuel Vasiľ", "input": "Vasiľovi"} + if "Vasiľ" in q else None) + previous = {"question": "Kto je Samuel Vasiľ?", "person": "Samuel Vasiľ"} + assert C.with_subject("kto je jeho konzultant?", previous) == "kto je konzultant Samuela Vasiľa?" + assert C.with_subject("a kto ho viedol?", previous) == "a kto viedol Samuela Vasiľa?" + assert C.with_subject("kto robil niečo podobné?", previous) == "kto robil niečo podobné ako Samuel Vasiľ?" + assert C.with_subject("Kto robil RAG?", previous) is None # no pronoun: a new question + assert C.with_subject("kto je jeho konzultant?", {**previous, "options": [{}]}) is None # a choice is pending + assert C._back_to_person("vráť sa k Vasiľovi, kedy začal študovať?") == "kedy začal študovať Samuel Vasiľ?" + + +def test_the_newest_of_the_listed_people_is_chosen_from_the_list(): + previous = {"entities": [{"n": 1, "name": "Ján Holp", "year": 2021, "url": "https://w/holp"}, + {"n": 2, "name": "Michal Stromko", "year": 2024, "url": "https://w/stromko"}]} + result = C._newest_of("a ktorý z nich je najnovší?", C.normalized("a ktorý z nich je najnovší?"), previous, "rag") + assert result["answer"].startswith("Spomedzi uvedených má najnovšiu prácu Michal Stromko (2024).") + assert C.entity({"name": "X", "text": "Diplomová práca 2021 … Bakalárska práca 2019"}, 1)["year"] == 2021 + + +def test_contact_and_wiki_metadata_questions_are_recognized(): + assert C.CONTACT.search(C.normalized("Aký je e-mail Daniela Hládka?")) + from tools.answers.presentation import unified as U + assert U.TAG_Q.search(U.normalized("Ktorí študenti majú tag hatespeech?")).group(2) == "hatespeech" + assert U.TAG_Q.search(U.normalized("Koľko študentov má kategóriu dp2027?")).group(2) == "dp2027" + assert U.TOP_TOPICS_Q.search(U.normalized("Ktoré témy sú v ZP Wiki najčastejšie?")) + assert U.STARTED_Q.search(U.normalized("Ktorí študenti, čo začali študovať v roku 2022, robia diplomovku?")).group(1) == "2022" + assert C.STUDENTS_OF.search(C.normalized("Kto oponoval práce študentov, ktorých viedol Maroš Harahus?")) + assert C.SAME_SUPERVISOR.search(C.normalized("Ktorí študenti mali rovnakého vedúceho ako Dmytro Mural?")) + assert U.asked_types(U.normalized("Kto je školiteľom doktorandskej práce X?")) == ["doctoral_thesis"] + + +def test_a_verb_without_subject_continues_with_the_conversation_person(monkeypatch): + monkeypatch.setattr(C, "_one_person", lambda q: {"name": "Oleh Poiasnik", "input": "Oleh"} if "Oleh" in q else None) + previous = {"question": "Kto indexoval texty v Elasticsearch?", "person": "Oleh Poiasnik"} + assert C.with_subject("aké technológie ešte použil?", previous) == "aké technológie ešte použil Oleh Poiasnik?" + assert C.with_subject("kto robil s Neo4j?", previous) is None + assert C.with_subject("čo robili z nich v roku 2024?", previous) is None + + +def test_a_question_asking_who_is_meant_is_retried_with_the_conversations_person(monkeypatch): + monkeypatch.setattr(C, "_one_person", lambda question: None) + previous = {"person": "Valerii Kutsenko", "question": "a aké úlohy dostal Valerii Kutsenko?"} + asked = C._subject_retry("a čo zásobník úloh?", {"reason": "missing_subject"}, previous) + assert asked.startswith("a čo zásobník úloh ") and asked.endswith("?") and "Kutsenk" in asked + assert C._subject_retry("a čo zásobník úloh?", {"reason": None}, previous) is None + assert C._subject_retry("a čo zásobník úloh?", {"reason": "missing_subject"}, {"person": None}) is None diff --git a/test/presentation/test_unified_answers.py b/test/presentation/test_unified_answers.py index 02e5555..0afa654 100644 --- a/test/presentation/test_unified_answers.py +++ b/test/presentation/test_unified_answers.py @@ -250,6 +250,17 @@ def test_one_thesis_and_a_newer_running_project_both_answer_who_leads(monkeypatc "vedúcim jeho bakalárskej práce „5G“ (2025) bol Ľubomír Doboš.") +def test_the_title_of_an_untyped_work_lists_a_running_project_with_the_thesis(monkeypatch): + monkeypatch.setattr(U, "catalog", lambda: {"people": {}, "works": {}, "texts": {}}) + works = [{"source": "wiki", "type": "diploma_project", "year": 2026, "title": "Grafové vyhľadávanie"}, + _crzp_thesis("bachelor_thesis", 2025, "5G", "Doboš, Ľubomír")] + out = U.work_title("Ján Malinovský", works, normalized("Aký názov má práca Jána Malinovského?")) + assert out["text"].startswith("Ján Malinovský má tieto práce (od najnovšej):") + assert out["text"].index("Grafové vyhľadávanie") < out["text"].index("5G") + one = U.work_title("Ján Malinovský", works, normalized("Ako sa volá bakalárska práca Jána Malinovského?")) + assert one["text"] == "Názov bakalárskej práce Jána Malinovského (2025) je „5G“." + + 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 diff --git a/tools/answers/combined.py b/tools/answers/combined.py index db551d2..ad80e3f 100644 --- a/tools/answers/combined.py +++ b/tools/answers/combined.py @@ -52,12 +52,16 @@ PREFIX3 = "zc3." # the id of a step kept on the server (tools/answers/context_s # 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) +# The person the conversation is about (the last question naming exactly one person, or the one chosen from a list): +# stored with each step, so "kto je jeho konzultant?" or "a kto ho viedol?" knows whom it asks about. +_subject: contextvars.ContextVar[str | None] = contextvars.ContextVar("answer_subject", default=None) TUKE = "Technická univerzita v Košiciach" WIKI_SCHOOL = "Technická univerzita v Košiciach (KEMT FEI)" # What only the wiki records: CRZP is not asked. WIKI_ONLY = re.compile(r"\b(?:stretnut\w*|pokrok\w*|progres\w*|uloh\w*|zadan\w*|plan\w*|termin\w*|tyzd\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") + r"dokonc\w*|uspes\w*|statnic\w*|hodnot\w*|znamk\w*|problem\w*|vtedy|posledn\w*|" + r"zacal\w*|studoval\w*|studovat|cen[auy]|ocenen\w*|svoc|vyznamen\w*)\b") EXPLICIT = re.compile(r"\b(?:crzp|registr\w*|register|celoslovensk\w*|na slovensku|(?:inych|inej|inom|ostatnych|" r"vsetkych|dalsich|slovensk\w+)\s+(?:vysok\w+\s+)?(?:skol|univerzit|fakult)\w*|mimo tuke|" r"oponent\w*|oponoval\w*)\b") @@ -76,7 +80,8 @@ EXPLAIN = re.compile(r"^\W*(?:pre[čc]o|odkia[ľl]|ako|na\s+z[áa]klade\s+[čc]o 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,}") +TOPIC_CUE = re.compile(r"\b(?:na\s+temu|tem\w*|o(?!\s+kolk)|ohladom|s|so|v\s+oblasti|tykal\w*\s+sa|tyka\w*\s+sa|" + r"zameran\w*\s+na|venoval\w*\s+sa|zaoberal\w*\s+sa)\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")) @@ -276,6 +281,84 @@ def named_back(question: str, previous: dict | None) -> str | None: return question[:match.start()] + match.group(1) + " " + old["name"] + question[match.end():] +# "Koho vedie X?", "Komu robí vedúceho X?", "Akých študentov má X?", "študenti pod vedením X" +SUPERVISES = re.compile(r"\bkoho\s+(?:vedie|viedol|viedla|skoli\w*)|\bkomu\s+robi\s+veduc\w*|" + r"\b(?:akych|ktorych|kolkych|kolko)\s+studentov\b|\bstudent\w*\s+(?:pod\s+vedenim|ma|vedie)\b|" + r"\bpod\s+(?:sebou|vedenim)\b") +SAME_SUPERVISOR = re.compile(r"\b(?:rovnak\w*|toho\s+ist\w*|ten\s+ist\w*|spolocn\w*)\s+(?:veduc\w*|skolitel\w*)") +# "práce študentov, ktorých viedol X": X as the supervisor of others, not X's own theses +STUDENTS_OF = re.compile(r"\bstudent\w*\b[^?]*\bktor\w*\s+(?:viedol|viedla|vedie|vedu)\b") +CONTACT = re.compile(r"\b(?:e[\s-]?mail\w*|mailov\w*\s+adres\w*|telefon\w*|tel\.?\s+cisl\w*|kontaktn\w*|kontakt\s+na)\b") +# "jeho vedúci", "jej konzultant": the subject's; "kto ho viedol", "čo mu funguje": about the subject +POSSESSIVE = re.compile(r"(?i)\b(?:jeho|jej)\s+([^\W\d_]{3,})") +OBJECT = re.compile(r"(?i)\b(?:ho|mu|jemu|ju|neho|nemu)\b") +SIMILAR_TO = re.compile(r"\b(?:podobn\w*|rovnak\w*\s+tem\w*|spolupra\w*)\b") + + +def with_subject(question: str, previous: dict | None) -> str | None: + """A follow-up that points at the conversation's person by a pronoun gets the person's name: "kto je jeho + konzultant?" -> "kto je konzultant Samuela Vasiľa?", "a kto ho viedol?" -> "a kto viedol Samuela Vasiľa?", + "kto robil niečo podobné?" -> "… ako Samuel Vasiľ?". Questions naming a person or a work stay as they are.""" + person = (previous or {}).get("person") + if not person or previous.get("options") or _one_person(question): + return None + from tools.answers.presentation.unified import genitive + match = POSSESSIVE.search(question) + if match: + return question[:match.start()] + match.group(1) + " " + genitive(person) + question[match.end():] + match = OBJECT.search(question) + if match: + rest = re.sub(r"\s{2,}", " ", question[:match.start()] + question[match.end():]).strip() + return re.sub(r"\s*\?*\s*$", "", rest) + " " + genitive(person) + "?" + low = normalized(question) + if SIMILAR_TO.search(low) and len(question.split()) <= 6: + return re.sub(r"\s*\?*\s*$", "", question) + " ako " + person + "?" + if (len(low.split()) <= 7 and IMPLIED_SUBJECT.search(low) and not re.match(r"^\W*(?:a\s+)?kto\b", low) + and not re.search(r"\b(?:z\s+nich|tento|tito|ten|ta|tej|tom|nej|nom)\b", low)): + # "aké technológie ešte použil?", "a čo robil v roku 2024?": the verb's subject is the conversation's person + return re.sub(r"\s*\?*\s*$", "", question) + " " + person + "?" + return None + + +# a past-tense verb without its subject ("použil", "robila", "mal"), in a question that is not "kto …?" +IMPLIED_SUBJECT = re.compile(r"^\W*(?:a\s+)?(?:ake|aky|aka|co|kedy|kde|ako|kolko|s\s+cim|na\s+com|preco)\b.*\b\w+(?:il|al|ol|el|ul|yl)a?\b") + + +NEWEST_OF = re.compile(r"\bktor\w*\s+z\s+nich\b.*\b(najnov\w*|najstar\w*|posledn\w*)\b|" + r"\b(najnov\w*|najstar\w*)\s+z\s+nich\b") + + +def _newest_of(question: str, low: str, previous: dict | None, engine: str) -> dict | None: + """"a ktorý z nich je najnovší?": the listed person with the newest (or oldest) work, from the list itself.""" + match = NEWEST_OF.search(low) + entities = [e for e in (previous or {}).get("entities") or [] if e.get("year")] + if not match or not entities: + return None + oldest = (match.group(1) or match.group(2) or "").startswith("najstar") + chosen = (min if oldest else max)(entities, key=lambda e: e["year"]) + word = "najstaršiu" if oldest else "najnovšiu" + text = f"Spomedzi uvedených má {word} prácu {chosen['name']} ({chosen['year']})." + url = entity_url(chosen) + _subject.set(chosen["name"]) + result = _ok(question, engine, text + (f"\n\nZdroje: {url}" if url else ""), [url] if url else [], {}) + return _with_token(result, entities=previous["entities"], question=question, crzp=previous.get("crzp"), + primary=previous.get("primary", "wiki")) + + +BACK_TO = re.compile(r"(?i)^\W*vr[aá]ť(?:me)?\s+sa\s+(?:k|ku)\s+([^,:?]+?)\s*[,:]\s*(.+)$") + + +def _back_to_person(question: str) -> str | None: + """"vráť sa k Vasiľovi, kedy začal študovať?" -> "kedy začal študovať Samuel Vasiľ?" (a person, not a question).""" + match = BACK_TO.match(question) + if not match or _one_person(match.group(2)): + return None + found = _one_person(match.group(1)) + if not found: + return None + return re.sub(r"\s*\?*\s*$", "", match.group(2)) + " " + found["name"] + "?" + + AGAIN_FILLERS = {"a", "ale", "no", "tak", "teda", "este", "presne", "vlastne", "konkretne", "mi", "povedz", "napis", "prosim"} @@ -415,9 +498,13 @@ def crzp_plan(question: str, person: str | None, complete=None, student: bool = unit_in_question(question) or re.search(r"\b(?:univerzit\w*|fakult\w*|katedr\w*|skol\w*|tuke|stu|kemt|fei)\b", low))) if WIKI_ONLY.search(low) and not explicit and not defended_scope: return None + from tools.answers.presentation.unified import TAG_Q + if TAG_Q.search(low) and not RELATED.search(low): # a ZP Wiki tag or category, which CRZP does not have + return None # A person ZP Wiki knows needs no model reading of the question (the person and school are # fixed below; rules give the intent): one model call less, the wiki part has the slots. - query = understand(question, complete=complete, use_model=not person or explicit) + topical_person = bool(person and TOPIC_CUE.search(low)) # "Koľko prác o chatbotoch viedol Hládek?" + query = understand(question, complete=complete, use_model=not person or explicit or topical_person) if query.intent == "refused": return None other_school = query.school not in (None, "tuke") or explicit or bool(query.exclude_school) @@ -454,13 +541,17 @@ def crzp_plan(question: str, person: str | None, complete=None, student: bool = if SIMILAR.search(low) and student: return "similar", query role = query.people[0].role if query.people else "any" - if student: - role = "author" if role == "author" else "any" # "Kto vedie Jána Ptáka?": his own works + if student and SUPERVISES.search(low): + role = "supervisor" # "Akých študentov má Maroš Harahus?": a doctoral student as a supervisor + elif student: + role = "author" # a student's works are those he or she wrote ("Kto vedie Jána Ptáka?": his own works; + # a doctoral student who also reviews works keeps them out of "his works") elif role not in ("supervisor", "opponent"): role = "supervisor" # a supervisor's works are those he or she led query.people = [Person(name=person, role=role, typed=person, canonical=True)] query.school, query.unit, query.from_model, query.title = "tuke", None, True, None - query.topics, query.alternatives = [], [] + if not (not student and topical_person and query.topics): # a supervisor's works of a topic keep it + query.topics, query.alternatives = [], [] return "person", query if query.people and not person and query.search_text() and ( THESIS.search(low) or METHODS.search(low) or PERSON_Q.search(low) and HUMAN_NAME.fullmatch(query.people[0].name)): @@ -529,7 +620,9 @@ def supervisor_count(question: str) -> bool: low = normalized(question) years = years_in(question) 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())) + works = re.search(r"\bprac\w*\b", low) and not re.search(r"\bstudent\w*|\bludi\b|\bosob\w*", low) + return bool(counted and (years or any(re.search(cue, question.lower()) for cue in WORK_CUES.values()) + or works and TOPIC_CUE.search(low)) and all(y <= time.localtime().tm_year for y in years)) @@ -746,7 +839,12 @@ def _crzp_part(question: str, person: str | None, *, complete=None, student: boo rows = [r for r in rows if crzp.university(r) == TUKE] if not rows: return None - if not student: # a supervisor: the works he or she led, newest first + if not student or query.people and query.people[0].role == "supervisor": + # a supervisor (also a doctoral student asked about his students): the works he or she led, newest first + if query.topics: # "… a týkali sa generovania jazyka": only works whose topic it is + rows, _ = crzp.topical(rows, query, complete, limit=crzp.PERSON_JUDGED) + if not rows: + return None rows = sorted(rows, key=lambda r: -(r.get("year") or 0)) lines = [f"- {_names(r.get('authors', []))} — „{r['title']}“ ({_kind(r)}, {r.get('year')})" for r in rows[:8]] more = f"\n\nSpolu {len(rows)} prác v CRZP na TUKE; zobrazených je 8 najnovších." if len(rows) > 8 else "" @@ -1045,7 +1143,8 @@ def supervisor_header(person: str, query, rows: list[dict]) -> str: 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}:" + topic = f" na tému „{query.topic_key()}“" if query.topics else "" + return f"{lead}{topic}, ktoré {verb} {spelled}{when}:" def merge_people(wiki: list[dict], crzp_items: list[dict]) -> list[dict]: @@ -1107,9 +1206,12 @@ def compose_list(head: list[str], shown: list[dict], rest: list[dict], tail: lis def entity(item: dict, number: int) -> dict: + years = [int(y) for y in re.findall(r"\b(?:19|20)\d{2}\b", item.get("text") or "") + if int(y) <= time.localtime().tm_year + 3] # the newest work year the item shows return {k: v for k, v in {"n": number, "name": item["name"], "school": item.get("school"), "source": item.get("source"), "sid": item.get("sid"), "title": item.get("title"), - "url": (item.get("urls") or [None])[0] or item.get("url")}.items() + "url": (item.get("urls") or [None])[0] or item.get("url"), + "year": max(years) if years else None}.items() if v is not None} @@ -1140,7 +1242,7 @@ def _with_token(result: dict, *, wiki_context=None, entities=(), options=(), que wiki_context = wiki_context or {} token = seal({"wiki": wiki_context.get("token"), "entities": list(entities)[:40], "options": list(options)[:6], "question": question, "crzp": crzp, "primary": primary, "page": page, - "urls": list(result.get("source_urls") or [])[:30]}) + "urls": list(result.get("source_urls") or [])[:30], "person": _subject.get()}) if token: result["conversation_context"] = {**{k: v for k, v in wiki_context.items() if k != "token"}, "token": token, "work_options": wiki_context.get("work_options", []), @@ -1379,13 +1481,57 @@ def answer(question: str, *, engine: str, limit: int = 5, context_token: str | N _warmed.set() _pool().submit(tag_frequencies) parent = _parent.set(token_step(context_token)) # every step of this answer continues the sent one + previous = unseal(context_token) if context_token else None + subject = _subject.set((previous or {}).get("person") if isinstance(previous, dict) else None) try: - return _stamp(_answer(question, engine=engine, limit=limit, context_token=context_token, complete=complete, - deliver=deliver), question, engine) + result = _stamp(_answer(question, engine=engine, limit=limit, context_token=context_token, complete=complete, + deliver=deliver), question, engine) + full = _subject_retry(question, result, previous) + if full: # "a čo zásobník úloh?" -> "Uveď celé meno…" although the conversation is about one person + retried = _answer(full, engine=engine, limit=limit, context_token=context_token, complete=complete, + deliver=deliver) + retried["_asked_as"] = [full, *(retried.get("_asked_as") or [])] # bound to the sent question + retried = _stamp(retried, question, engine) + if retried.get("status") == "ok": + result = retried + return _carry_context(result, question, context_token, previous) finally: + _subject.reset(subject) _parent.reset(parent) +def _subject_retry(question: str, result: dict, previous: dict | None) -> str | None: + """The question once more with the conversation's person when the answer asks who is meant: a short follow-up + without a pronoun or a verb ("a čo zásobník úloh?") after an answer about one person.""" + person = previous.get("person") if isinstance(previous, dict) else None + if result.get("reason") != "missing_subject" or not person or previous.get("options") or _one_person(question): + return None + from tools.answers.presentation.unified import genitive + return re.sub(r"\s*\?*\s*$", "", question) + " " + genitive(person) + "?" + + +LOST = {"missing_subject", "answer_rejected", "backend_timeout", "backend_unavailable", "model_unavailable", + "crzp_unavailable", "no_content_evidence", "missing_evidence"} + + +def _carry_context(result: dict, question: str, context_token: str | None, previous: dict | None) -> dict: + """A step that answered nothing ("Uveď celé meno…", a rejected or failed answer) does not replace the context: + the next follow-up continues from the last step that did ("a kto ho viedol?" still knows the person). A plain + wiki token (a wiki clarification) is kept inside a step of ours, so the person stays with it.""" + context = result.get("conversation_context") or {} + token = context.get("token") + failed = result.get("status") in ("error", "no_answer") or result.get("reason") in LOST + if failed and previous and not previous.get("error") and isinstance(context_token, str) \ + and context_token.startswith(PREFIX3): + return {**result, "conversation_context": {**context, "token": context_token}} + if isinstance(token, str) and token and not token.startswith(PREFIX3) and result.get("status") in ("ok", "ambiguous"): + check = result.get("delivery_check") + wrapped = _with_token({k: v for k, v in result.items() if k != "conversation_context"}, + wiki_context=context, question=question) + return {**wrapped, "delivery_check": check} if check else wrapped + return result + + def _ask_choice(question: str, engine: str, previous: dict) -> dict: options = previous["options"] text = ("Odpovedz prosím číslom: " + ", ".join(f"{i} – {o['label']}" for i, o in enumerate(options, 1)) + ".") @@ -1475,6 +1621,37 @@ 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) + named = _one_person(question) if words else None + if named: + _subject.set(named["name"]) + newest = _newest_of(question, low, previous, engine) + if newest is not None: # "a ktorý z nich je najnovší?": chosen from the people just listed + return newest + from tools.answers.presentation import unified as U + supervisor = None if named else U.supervisor_in(question) + if supervisor and (U.WHO_Q.match(low) or bare_name(question, supervisor)): + # "Kto je Daniel Hládek?": a supervisor (no profile of his own), not a CRZP author or "unknown person" + _subject.set(supervisor) + out = U.supervisor_overview(supervisor) + text = out["text"] + ("\n\nZdroje: " + ", ".join(out["urls"]) if out["urls"] else "") + return _with_token(_ok(question, engine, text, out["urls"], {}), question=question) + if CONTACT.search(low) and (named or supervisor): # "Aký je e-mail Daniela Hládka?": not in the records + who = U.spelled((named or {}).get("name") or supervisor) + return _with_token(_ok(question, engine, f"Kontaktné údaje osoby {who} v podkladoch nie sú; ZP Wiki a " + "register záverečných prác uvádzajú len údaje o prácach.", [], {}), question=question) + if not named and not supervisor and not (previous or {}).get("options"): + # tags, categories, the most common topics and the start of studies come from the wiki's own metadata: + # complete, counted by code, and never sent to CRZP (CRZP has no ZP Wiki tags) + meta = (U.tag_answer(question) if U.TAG_Q.search(low) and not RELATED.search(low) else None) or ( + U.top_topics() if U.TOP_TOPICS_Q.search(low) else None) or ( + U.started_answer(question) if U.STARTED_Q.search(low) and not TOPIC_CUE.search(low) else None) + if meta: + text = meta["text"] + ("\n\nZdroje: " + ", ".join(meta["urls"]) if meta["urls"] else "") + return _with_token(_ok(question, engine, text, meta["urls"], {}), question=question) + back = _back_to_person(question) + if back: # "vráť sa k Vasiľovi, kedy začal študovať?" + return {**_answer(back, engine=engine, limit=limit, context_token=None, complete=complete, deliver=deliver), + "_asked_as": [back]} 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() @@ -1483,6 +1660,12 @@ def _answer(question: str, *, engine: str, limit: int, context_token: str | None result = _answer(asked, engine=engine, limit=limit, context_token=context_token, complete=complete, deliver=deliver) inner = result.pop("_asked_as", []) + student = _one_person(claim) + if (student and result.get("status") == "ok" + and not any("zp.kemt" in url for url in result.get("source_urls") or [])): + # a ZP Wiki student's claim whose wiki records were not confirmed: other records are no evidence for it + text = f"Tvrdenie „{claim.rstrip('.')}“ sa v záznamoch ZP Wiki nepodarilo overiť, preto ho nepotvrdzujem." + return {**_with_token(_ok(question, engine, text, [], result), question=question), "_asked_as": [asked, *inner]} 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"]} @@ -1540,6 +1723,10 @@ def _answer(question: str, *, engine: str, limit: int, context_token: str | None 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]} + full = with_subject(question, previous) + if full: # "kto je jeho konzultant?" -> "kto je konzultant Samuela Vasiľa?" (the wiki context stays) + return {**_answer(full, engine=engine, limit=limit, context_token=context_token, complete=complete, + deliver=deliver), "_asked_as": [full]} reference = _reference(question, entities) if entities else None if reference: match, chosen = reference @@ -1785,13 +1972,29 @@ def _unified(asked, question, engine, wiki, wiki_ok, part, person, wiki_context, if student: works = U.person_works(person, rows) out = None + if (students.get(person) or {}).get("person_kind") == "intern" and not works and ( + U.WHO_Q.match(low) or U.DID_Q.match(low) or bare_name(question, person)): + out = U.intern_overview(person) # "Na čom pracoval stážista Dries Huybens?": topic, goals, outputs + if out: + return done(out) + supervising = re.search(r"\b(?:viedol|viedla|vedie|oponoval\w*|skolil\w*)\b", low) if STUDY_START.search(low) and not re.search(r"\b(?:prac\w*|projekt\w*|nazov|tem\w*|veduc\w*)\b", low): out = U.start_year(person) # only the start of studies; a compound question stays with the wiki answer + if out is None: # "Kedy začal študovať Maroš Harahus?": not recorded, said so (no other data instead) + out = {"text": f"Rok začiatku štúdia osoby {U.spelled(person)} v podkladoch nie je uvedený.", + "urls": U.work_urls(person, [])} + elif U.COUNT_WORKS_Q.search(low) and not supervising and not U.asked_role(low): + out = U.work_count(person, works, low) # one entry per work, a namesake's work left out + elif U.TITLE_Q.search(low) and not supervising and not U.asked_role(low) and not METHODS.search(low): + out = U.work_title(person, works, low) 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) - or re.search(r"\b(?:veduci|skolitel|oponent|konzultant)\w*\W*$", low)): + elif SAME_SUPERVISOR.search(low): # "Ktorí študenti mali rovnakého vedúceho ako Dmytro Mural?" + out = U.same_supervisor(person) + elif U.asked_role(low) and not STUDENTS_OF.search(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? diff --git a/tools/answers/presentation/unified.py b/tools/answers/presentation/unified.py index 8a8b446..ec89869 100644 --- a/tools/answers/presentation/unified.py +++ b/tools/answers/presentation/unified.py @@ -40,7 +40,7 @@ THESES = {"bachelor_thesis", "diploma_thesis", "doctoral_thesis", "habilitation_ CRZP_TYPES = {"dissertation": "doctoral_thesis", "doctoral_thesis": "rigorous_thesis"} # CRZP names -> wiki names ASKED_TYPE = [(r"\bbakalar\w*\s+prac\w*|\bbakalark\w*|\bbakalarsk\w*\b(?!\s+projekt)|\bbp\b", "bachelor_thesis"), (r"\bdiplomov\w*\s+prac\w*|\bdiplomov\w*\b(?!\s+projekt)|\bdp\b", "diploma_thesis"), - (r"\bdizertac\w*|\bdisertac\w*", "doctoral_thesis"), + (r"\bdizertac\w*|\bdisertac\w*|\bdoktorand\w*|\bphd\b", "doctoral_thesis"), (r"\bbakalar\w*\s+projekt\w*", "bachelor_project"), (r"\bdiplomov\w*\s+projekt\w*", "diploma_project"), (r"\btimov\w*\s+projekt\w*", "team_project")] UPPER = "A-ZÁÄČĎÉÍĹĽŇÓÔŔŠŤÚÝŽ" @@ -59,6 +59,9 @@ BOTH_TYPES = re.compile(r"\b(?:bakal\w*|diplom\w*|bp|dp)(?:\s+prac\w*)?\s+(?:a|a r"(?:jeho\s+|jej\s+|svojej\s+)?(?:bakal\w*|diplom\w*|bp|dp)\b") # "Kto je Matej Ščišľak?", "Ján Holp" (only the name): who the person is, the works newest first WHO_Q = re.compile(r"^\W*(?:a\s+)?(?:kto\s+(?:je|bol|bola|je\s+to)|povedz\s+mi\s+(?:nieco\s+)?o|predstav\s+mi)\s+\S") +# "Koľko záverečných prác má X?", "Má X jednu alebo dve diplomové práce?" (not a supervisor's count) +COUNT_WORKS_Q = re.compile(r"\bkolk\w*\b[^?]*\bprac\w*|\bjednu\s+alebo\s+dve\b|\bkolko\s+(?:bakalar|diplom|zaverec)\w*") +TITLE_Q = re.compile(r"\b(?:nazov|nazvom|nazvu|ako\s+sa\s+vola|nazyva\w*)\b") METHODS_Q = re.compile(r"\b(?:technolog\w*|nastroj\w*|metod\w*|pouziv\w*|vyuziv\w*|framework\w*)\b") TASKS_Q = re.compile(r"\b(?:uloh\w*|dostal\w*|zadal\w*|ma\s+urobit|treba\s+urobit)\b") COUNT_STUDENTS_Q = re.compile(r"\bkolk\w*\s+(?:studentov|student\w*|ludi|osob)\b") @@ -584,6 +587,304 @@ def supervisors(person: str, works: list[dict], low: str, wiki_text: str = "") - return roles(person, works, low, wiki_text, "supervisor") +_chunks: dict = {} + + +def page_chunks(path: str) -> list[str]: + """The texts of one wiki page as the RAG index split it (chunks.json, reread when it changes).""" + from tools.rag.common import DB_FILE + file = Path(DB_FILE).parent / "chunks.json" + try: + stamp = file.stat().st_mtime_ns + except OSError: + return [] + with _lock: + if _chunks.get("stamp") != stamp: + by_path: dict = {} + for chunk in json.loads(file.read_text(encoding="utf-8")): + by_path.setdefault(chunk.get("document_path"), []).append(chunk) + _chunks.update(stamp=stamp, by_path=by_path) + rows = sorted(_chunks["by_path"].get(path, []), key=lambda c: c.get("chunk_index") or 0) + return [re.sub(r"^Dokument:[^\n]*\n+", "", c.get("text") or "") for c in rows] + + +def intern_overview(person: str) -> dict | None: + """An intern's page has no thesis headings: its topic, goals and outputs as written ("Topic:", "Goal:", "Outputs:").""" + info = catalog()["people"].get(person) or {} + text = "\n".join(page_chunks(info.get("source_document") or "")) + if not text.strip(): + return None + def section(*labels): + match = re.search(r"(?im)^\s*(?:" + "|".join(labels) + r")\s*:\s*\n+((?:\s*[-*].+\n?|[^\n#:]+\n?){1,6})", text) + if not match: + return [] + lines = [re.sub(r"^\s*[-*]\s*", "", l).strip() for l in match.group(1).splitlines()] + return list(dict.fromkeys(l for l in lines if l))[:4] + stay = re.search(r"(?i)\b(ERASMUS|IAESTE)[^\n]*", text) + topic = section("Topic", "Téma") + goals, outputs = section("Goal", "Goals", "Ciele", "Cieľ"), section("Outputs?", "Outupus", "Results", "Výsledky") + lead = f"{spelled(person)} je stážist{'ka' if female(spelled(person)) else 'a'} v ZP Wiki" + ( + f", pobyt {stay.group(0).strip()}" if stay else "") + "." + parts = [lead] + if topic: + parts.append("Téma: " + topic[0] + ".") + if goals: + parts.append("Ciele:\n" + "\n".join("- " + g for g in goals)) + if outputs: + parts.append("Výstupy:\n" + "\n".join("- " + o for o in outputs)) + if len(parts) == 1: + return None + return {"text": "\n\n".join(parts), "urls": [info["url"]] if info.get("url") else []} + + +_pages: dict = {} + + +def wiki_pages() -> list[dict]: + """Profiles of ZP Wiki (students and interns) with their tags and categories (documents.json).""" + import ast + from tools.rag.common import DB_FILE + file = Path(DB_FILE).parent / "documents.json" + try: + stamp = file.stat().st_mtime_ns + except OSError: + return [] + with _lock: + if _pages.get("stamp") == stamp: + return _pages["rows"] + by_path = {p.get("source_document"): (name, p) for name, p in catalog()["people"].items()} + rows = [] + for doc in json.loads(file.read_text(encoding="utf-8")): + if doc.get("path") not in by_path: + continue + name, person = by_path[doc["path"]] + taxonomy = doc.get("taxonomy") + if isinstance(taxonomy, str): + try: + taxonomy = ast.literal_eval(taxonomy) + except (ValueError, SyntaxError): + taxonomy = {} + taxonomy = taxonomy if isinstance(taxonomy, dict) else {} + rows.append({"name": name, "url": person.get("url"), "kind": person.get("person_kind"), + "start_year": person.get("start_year"), + "tags": [str(t).lower() for t in taxonomy.get("tag") or []], + "categories": [str(c).lower() for c in taxonomy.get("category") or []]}) + with _lock: + _pages.update(stamp=stamp, rows=rows) + return rows + + +def _people_sentence(names: list[str], limit: int = 40) -> str: + shown = [spelled(n) for n in names[:limit]] + return ", ".join(shown) + (f" a ďalší ({len(names) - limit})" if len(names) > limit else "") + + +TAG_Q = re.compile(r"\b(tag(?:om|u|y|mi|ov)?|kategori\w*)\s+([a-z0-9][a-z0-9\-]{1,30})\b") +TOP_TOPICS_Q = re.compile(r"\bnajcast\w*\b[^?]*\b(?:tem\w*|tag\w*|oblast\w*)|\b(?:tem\w*|tag\w*|oblast\w*)\b[^?]*\bnajcast\w*") + + +def tag_answer(question: str) -> dict | None: + """"Ktorí študenti majú tag hatespeech?", "Koľko študentov má kategóriu dp2027?": every profile with it.""" + low = normalized(question) + match = TAG_Q.search(low) + if not match: + return None + field = "categories" if match.group(1).startswith("kategori") else "tags" + value = match.group(2) + rows = [r for r in wiki_pages() if value in r[field]] + label = "Kategóriu" if field == "categories" else "Tag" + if not rows: + return {"text": f"{label} **{value}** v ZP Wiki nemá žiadny profil.", "urls": []} + rows.sort(key=lambda r: (-(r.get("start_year") or 0), normalized(r["name"]))) + names = [r["name"] for r in rows] + n = len(names) + who = "osoba" if n == 1 else "osoby" if n <= 4 else "osôb" + verb = "má" if n == 1 else "majú" + if re.search(r"\bkolk\w*|\bpocet\b", low): + text = f"{label} **{value}** {verb} v ZP Wiki {n} {who}: {_people_sentence(names)}." + else: + lines = [] + for r in rows[:40]: + theses = [w for w in catalog()["works"].get(r["name"], []) if w.get("type") in THESES and w.get("title")] + theses.sort(key=lambda w: -(w.get("year") or 0)) + lines.append(f"- {spelled(r['name'])}" + (f" — {describe(theses[0])}" if theses else "")) + text = f"{label} **{value}** {verb} v ZP Wiki {n} {who}:\n\n" + "\n".join(lines) + if n > 40: + text += f"\n\nZobrazených je 40 z {n}." + return {"text": text, "urls": [r["url"] for r in rows[:10] if r.get("url")]} + + +def top_topics() -> dict: + """"Ktoré témy sú v ZP Wiki najčastejšie?": the tags of the profiles by how many profiles have them.""" + from collections import Counter + counts = Counter(t for r in wiki_pages() for t in set(r["tags"])) + top = counts.most_common(12) + lines = [f"- {t}: {n} {'profil' if n == 1 else 'profily' if n <= 4 else 'profilov'}" for t, n in top] + return {"text": "Najčastejšie tagy profilov v ZP Wiki:\n\n" + "\n".join(lines), "urls": []} + + +STARTED_Q = re.compile(r"\bzac\w*\s+(?:studovat|studium|studia|studovali|studoval\w*)\s+(?:v\s+)?(?:roku\s+)?((?:19|20)\d{2})" + r"(?:\s+(?:alebo|a)\s+(neskor\w*|skor\w*|neskôr))?") + + +def started_answer(question: str) -> dict | None: + """"Ktorí študenti, čo začali študovať v roku 2022, robia diplomovú prácu?": the start of studies, not a work year.""" + low = normalized(question) + match = STARTED_Q.search(low) + if not match: + return None + year, more = int(match.group(1)), match.group(2) or "" + fits = (lambda y: y and y >= year) if more.startswith("nesk") else (lambda y: y and y <= year) if more else ( + lambda y: y == year) + rows = [r for r in wiki_pages() if r["kind"] == "student" and fits(r.get("start_year"))] + kinds = [k for k in asked_types(low) if k in TYPES] + lines = [] + for r in sorted(rows, key=lambda r: normalized(r["name"])): + works = [w for w in catalog()["works"].get(r["name"], []) if not kinds or w.get("type") in kinds] + if kinds and not works: + continue + works.sort(key=lambda w: -(w.get("year") or 0)) + lines.append(f"- {spelled(r['name'])}" + (f" — {describe(works[0])}" if works else "")) + when = f"v roku {year}" + (" alebo neskôr" if more.startswith("nesk") else " alebo skôr" if more else "") + accusative = " ".join(w[:-1] + "ú" if w.endswith("á") else w[:-1] + "u" if w.endswith("a") else w + for w in TYPES[kinds[0]][0].split()) if len(kinds) == 1 else "" + what = f" a majú {accusative}" if accusative else "" + if not lines: + return {"text": f"V podkladoch nie je študent, ktorý začal študovať {when}{what}.", "urls": []} + text = f"Študenti, ktorí začali študovať {when}{what} ({len(lines)}):\n\n" + "\n".join(lines) + return {"text": text, "urls": [r["url"] for r in rows[:10] if r.get("url")]} + + +def supervisor_students() -> dict[str, list[str]]: + """Supervisor (the profile author, KEMT convention) -> the students whose profiles they wrote.""" + from tools.knowledge.sources import profile_authors + by_path = {p.get("source_document"): name for name, p in catalog()["people"].items()} + result: dict = {} + for path, author in profile_authors().items(): + if author and by_path.get(path): + result.setdefault(author, []).append(by_path[path]) + return result + + +def supervisor_in(question: str) -> str | None: + """A supervisor named in the question in any form ("Daniela Hládka", "Hládek", "Harahusa"): every word of the + name, or the surname alone when no other supervisor has it.""" + from tools.retrieval.person_names import name_token_variants + words = set(re.findall(r"[a-z0-9]+", normalized(question))) + found = [] + for name in supervisor_students(): + parts = normalized(name).split() + hits = [any(v in words for v in name_token_variants(part)) for part in parts] + if all(hits): + return name + if hits and hits[-1]: + found.append(name) + return found[0] if len(found) == 1 else None + + +def same_supervisor(person: str) -> dict | None: + """"Ktorí študenti mali rovnakého vedúceho ako Dmytro Mural?": the person's supervisor and his other students.""" + supervisor = next((s for s, students in supervisor_students().items() if person in students), None) + if not supervisor: + return None + others = [s for s in supervisor_students()[supervisor] if s != person] + lead = f"Vedúcim {genitive(person)} je {spelled(supervisor)}." + if not others: + return {"text": lead + " Iných študentov s rovnakým vedúcim ZP Wiki neuvádza.", "urls": work_urls(person, [])} + text = lead + f" Rovnakého vedúceho majú aj: {_people_sentence(sorted(others, key=normalized))}." + urls = [catalog()["people"].get(s, {}).get("url") for s in others[:10]] + return {"text": text, "urls": [u for u in [*work_urls(person, []), *urls] if u]} + + +def supervisor_overview(name: str) -> dict: + """"Kto je Daniel Hládek?": a supervisor of ZP Wiki, how many students, the newest works of them.""" + students = supervisor_students().get(name, []) + works = [] + for student in students: + for work in catalog()["works"].get(student, []): + if work.get("type") in THESES and work.get("year"): + works.append((work["year"], student, work)) + works.sort(key=lambda w: (-w[0], w[1])) + shown = spelled(name) + lines = [f"{shown} je vedúci záverečných prác v ZP Wiki; vedie {len(students)} " + f"{'študenta' if len(students) == 1 else 'študentov' if len(students) >= 5 else 'študentov'}."] + if works: + lines.append("Najnovšie záverečné práce jeho študentov:") + lines += [f"- {spelled(s)} — {describe(w)}" for _, s, w in works[:6]] + urls = [catalog()["people"].get(s, {}).get("url") for _, s, _ in works[:6]] + return {"text": "\n".join(lines[:1]) + ("\n\n" + "\n".join(lines[1:]) if len(lines) > 1 else ""), + "urls": [u for u in dict.fromkeys(urls) if u]} + + +def _one_work(group: list[dict]) -> str: + work = group[0] + years = sorted({w.get("year") for w in group if w.get("year")}) + text = describe(work) + if len(years) > 1: + text += f", záznamy z rokov {', '.join(map(str, years))}" + return text + + +def work_count(person: str, works: list[dict], low: str) -> dict | None: + """"Koľko záverečných prác má Tomáš Kuchárik?": the person's works of the asked type, one entry per work (records + of the same work in two years are one work; a namesake's CRZP work is not counted).""" + kinds = asked_types(low) + pool = [w for w in works if not w.get("unconfirmed")] + if kinds: + pool = [w for w in pool if w["type"] in kinds] + elif re.search(r"\bzaverec\w*", low): + pool = [w for w in pool if w["type"] in THESES] + if not pool and not kinds: + return None + groups: dict = {} + for work in sorted(pool, key=lambda w: -(w.get("year") or 0)): + title = normalized(work.get("title") or "") + key = (work["type"], title if title else f"#{work.get('year')}") + groups.setdefault(key, []).append(work) + n = len(groups) + kind = TYPES[kinds[0]][0] if len(kinds) == 1 and kinds[0] in TYPES else ( + "záverečná práca" if re.search(r"\bzaverec\w*", low) else "práca") + words = kind.split() + form = (lambda w: w[:-1] + ("é" if w.endswith("á") else "e")) if 2 <= n <= 4 else ( + lambda w: w[:-1] + ("ých" if w.endswith("á") else "") if w.endswith("á") else w[:-1]) + if n == 1: + noun = " ".join([w[:-1] + "ú" if w.endswith("á") else w[:-1] + "u" if w.endswith("a") else w for w in words]) + elif 2 <= n <= 4: + noun = " ".join([form(w) for w in words[:-1]] + ["práce"]) + else: + noun = " ".join([w[:-1] + "ých" if w.endswith("á") else w for w in words[:-1]] + ["prác"]) + if not n: + return {"text": f"{spelled(person)} nemá v podkladoch žiadnu {kind}.", "urls": work_urls(person, [])} + text = f"{spelled(person)} má v podkladoch {n} {noun}:\n\n" + "\n".join(f"- {_one_work(g)}" for g in groups.values()) + same_kind = [k for k in {k for k, _ in groups} if k in THESES and sum(1 for t, _ in groups if t == k) > 1] + if same_kind: # two diploma theses of one student: say what it may be + text += ("\n\nDva záznamy toho istého typu záverečnej práce sú nezvyčajné; môže ísť o pokračovanie alebo " + "premenovanie tej istej práce v ďalšom roku.") + return {"text": text, "urls": work_urls(person, [w for g in groups.values() for w in g])} + + +def work_title(person: str, works: list[dict], low: str) -> dict | None: + """"Aký je názov bakalárskej práce X?": the title of the asked work, from ZP Wiki or the same work in CRZP.""" + kinds = [k for k in asked_types(low) if k in TYPES] + # no type asked: every recorded work counts (a current diploma project of ZP Wiki next to a defended BP) + pool = [w for w in works if not w.get("unconfirmed") and (w["type"] in kinds if kinds else w["type"] in TYPES)] + if not pool: + return None + if len(pool) > 1 and not kinds: + lines = [f"- {describe(w)}" for w in pool] + label = "záverečné práce" if all(w["type"] in THESES for w in pool) else "práce" + return {"text": f"{spelled(person)} má tieto {label} (od najnovšej):\n\n" + "\n".join(lines), + "urls": work_urls(person, pool)} + work = pool[0] + name = TYPES.get(work["type"], ("práca", "práce", "práci"))[1] + year = f" ({work['year']})" if work.get("year") else "" + if work.get("title"): + text = f"Názov {name} {genitive(person)}{year} je „{work['title'].rstrip('.')}“." + else: + text = f"Názov {name} {genitive(person)}{year} v podkladoch nie je uvedený." + return {"text": text, "urls": work_urls(person, [work])} + + def who(person: str, works: list[dict]) -> dict | None: """"Kto je X?": one lead sentence (a student of ZP Wiki, the study start) and the works, newest first.""" listed = works_list(person, works) diff --git a/tools/crzp/answering/answer.py b/tools/crzp/answering/answer.py index 6d4050a..de4793a 100644 --- a/tools/crzp/answering/answer.py +++ b/tools/crzp/answering/answer.py @@ -437,13 +437,15 @@ def find(query: CrzpQuery) -> tuple[dict | None, list[dict]]: # "práce X" may mean the works X supervised or reviewed: X is no author in the read rows. base, name = met or (last[0], query.people[0].name) relaxed = _asking(query, name).model_copy(deep=True) - relaxed.people[0].role = "any" - rows = prefer_exact([r for r in base["rows"] if keep(r, relaxed)], relaxed) - if rows: - query.people[0].role = "any" - query.people[0].name = name - query.relaxed_author = True - return base, rows + # "bakalárske práce Daniela Hládka": the works he supervised; reviewed ones only when he supervised none + for role in ("supervisor", "any"): + relaxed.people[0].role = role + rows = prefer_exact([r for r in base["rows"] if keep(r, relaxed)], relaxed) + if rows: + query.people[0].role = role + query.people[0].name = name + query.relaxed_author = True + return base, rows return last or (None, []) @@ -723,6 +725,13 @@ def _count(question, query, found, rows) -> tuple[str, list[dict]]: if named < count: # CRZP finds the word anywhere in a record: say how many name it in the title text += (f"\n\nTému „{query.topic_key()}“ má v názve {named} z nich; ostatné ju majú v kľúčových slovách " "alebo v abstrakte, nemusí to byť ich hlavná téma.") + if count and len(years) > 1 and re.search(r"\bv\s+ktor\w*\s+rok\w*", fold(question)) \ + and re.search(r"\bnaj(?:viac|menej)\b", fold(question)): + # "V ktorom roku obhájili na KEMT najviac diplomových prác?": the year first, the counts below + fewest = bool(re.search(r"\bnajmenej\b", fold(question))) + year, n = (min if fewest else max)(years.items(), key=lambda kv: (kv[1], kv[0])) + text = (f"{'Najmenej' if fewest else 'Najviac'} prác ({describe(query.model_copy(update={'years': []}))}) bolo " + f"v roku {year}: {n}.\n\n" + text) if count and query.split == "year" and len(years) > 1 and not compare: # "rozdeľ to podľa rokov" by_year = {y: Counter(_kind(r) for r in rows if r.get("year") == y) for y in years} if not found.get("facet_only") else {} lines = [f"- {y}: {n}" + (" (" + ", ".join(f"{k} {c}" for k, c in by_year[y].most_common()) + ")" @@ -885,6 +894,11 @@ 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 _female_name(name: str) -> bool: + from tools.answers.presentation.unified import female + return female(display_name(name)) + + def _author_word(row: dict) -> str: """"autorka" for one female author, "autori" for several, else "autor".""" authors = row.get("authors") or [] @@ -1354,9 +1368,12 @@ def _answer_query(question: str, query: CrzpQuery, complete=None) -> dict: 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) + if getattr(query, "relaxed_author", False) and not (query.people[0].role == "supervisor" and query.intent == "count"): + # (a count of supervised works says "X viedol …" itself) + led = query.people[0].role == "supervisor" + body = (f"{query.people[0].name} nie je v CRZP autorom žiadnej z nájdených prác; uvedené sú práce, " + + ("ktoré viedol" + ("a" if _female_name(query.people[0].name) else "") if led + else "pri ktorých je školiteľom alebo oponentom") + ".\n\n" + body) if query.intent in ("about", "keywords", "list"): body += namesakes(used, query) if query.unverified_only: diff --git a/tools/crzp/answering/understand.py b/tools/crzp/answering/understand.py index 0ba4d66..13939e5 100644 --- a/tools/crzp/answering/understand.py +++ b/tools/crzp/answering/understand.py @@ -400,8 +400,8 @@ def understand(question: str, *, complete=None, use_model: bool = True) -> CrzpQ name = " ".join(person["name"].split()) title = proposed.get("title") if isinstance(proposed.get("title"), str) else query.title or "" if (not 2 <= len(name) <= 80 or len(name.split()) > 4 or not in_question(name, question) - or (title and fold(name) in fold(title))): - continue # a work title or an invented name is not a person + or (title and fold(name) in fold(title)) or names_a_school(name)): + continue # a work title, an invented name or a school/unit ("na kemte") is not a person role = person.get("role") if person.get("role") in ("author", "supervisor", "opponent", "any") else "any" query.people.append(Person(name=name, role=role, typed=typed_form(name, question))) query.people = query.people[:2] diff --git a/tools/crzp/tests/test_crzp.py b/tools/crzp/tests/test_crzp.py index 50a5cc8..0bb0cce 100644 --- a/tools/crzp/tests/test_crzp.py +++ b/tools/crzp/tests/test_crzp.py @@ -408,8 +408,14 @@ def test_works_of_a_person_who_is_no_author_show_the_other_roles_with_a_notice(c reply = {"people": [{"name": "Pavol Galajda", "role": "author"}], "topics": [], "title": None, "target_role": None} model = lambda messages, **kw: {"choices": [{"message": {"content": json.dumps(reply)}}]} result = A._answer("Aké kľúčové slová majú práce Pavla Galajdu?", complete=model) - assert result["status"] == "ok" and "Vedená" in result["answer"] and "Oponovaná" in result["answer"] - assert result["answer"].startswith("Pavol Galajda nie je v CRZP autorom žiadnej z nájdených prác") + # the works he supervised; the reviewed ones are not mixed in (19. 11. 2026) + assert result["status"] == "ok" and "Vedená" in result["answer"] and "Oponovaná" not in result["answer"] + assert result["answer"].startswith("Pavol Galajda nie je v CRZP autorom žiadnej z nájdených prác; uvedené sú " + "práce, ktoré viedol") + crzp["result"] = found([row("Oponovaná", opponents=("Galajda, Pavol",))]) + A._cache.clear() + reviewed = A._answer("Aké kľúčové slová majú práce Pavla Galajdu?", complete=model) + assert "Oponovaná" in reviewed["answer"] and "školiteľom alebo oponentom" in reviewed["answer"] explicit = A._answer("Koľko prác oponoval Peter Malý?", complete=crzp["no_model"]) assert explicit["status"] == "no_answer" @@ -989,3 +995,10 @@ def test_an_excluded_tool_leaves_out_works_that_name_it(): query = CrzpQuery(exclude_terms=["pythonu"]) assert not A.keep({"title": "Využitie GPT v jazyku Python", "keywords": []}, query) assert A.keep({"title": "Hodnotenie odpovedí pomocou LLM", "keywords": ["NLP"]}, query) + + +def test_a_unit_in_a_case_form_proposed_as_a_person_is_dropped(): + from tools.crzp.answering import understand as und + model = lambda *a, **k: '{"intent": "count", "people": [{"name": "KEMTE", "role": "any"}], "topics": []}' + query = und.understand("pocet obhajenych dp na kemte za rok 2021", complete=model) + assert query.people == [] and query.unit == "kemt" diff --git a/tools/knowledge/roster.py b/tools/knowledge/roster.py index 319e0ef..208d992 100644 --- a/tools/knowledge/roster.py +++ b/tools/knowledge/roster.py @@ -35,6 +35,10 @@ def roster_question(spec) -> bool: 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() + if re.fullmatch(r"\s*(?:[-*]\s*)?\[[^\]]+\]\([^)]*\)\s*", text): # only a link ("[Bakalárska práca na CRZP](…)") + return True + if re.match(r"(?i)stretnut\w*\b", plain) and len(plain) < 40: # "Stretnutie 12.3." is a heading of notes + return True return bool(re.fullmatch(r"[\d.\s/-]{4,}", plain) or plain.endswith(":") and len(plain) < 60 or len(plain) < 4)