diff --git a/test/presentation/test_record_answers.py b/test/presentation/test_record_answers.py index 5749bd6..0b4e968 100644 --- a/test/presentation/test_record_answers.py +++ b/test/presentation/test_record_answers.py @@ -99,3 +99,83 @@ def test_a_work_read_twice_keeps_the_copy_with_the_register_link(): assert U._better_copy(old, new) == {"title": "A", "year": 2024, "url": "https://opac.test/a", "opponents": ["Malý, Igor"]} assert U._better_copy(new, old)["url"] == "https://opac.test/a" assert U._better_copy(None, old) is old + + +ROW = lambda sup, opp: {"supervisors": [sup], "opponents": [opp], "url": "https://opac.test/x"} + + +@pytest.fixture +def theses(monkeypatch, data): + works = {"Ana Nová": [ + {"type": "diploma_thesis", "year": 2027, "title": "Grafy", "source": "wiki", "heading": "Diplomová práca 2027", + "row": ROW("Hládek, Daniel", "Staš, Ján")}, + {"type": "bachelor_thesis", "year": 2025, "title": "Vyhľadávanie", "source": "wiki", "heading": "Bakalárska práca 2025", + "row": ROW("Hládek, Daniel", "Pleva, Matúš")}]} + monkeypatch.setattr(U, "person_works", lambda person, rows=None: [dict(w) for w in works.get(person, [])]) + monkeypatch.setattr(U, "units", lambda person: []) + return works + + +def test_a_claimed_supervisor_is_checked_not_confirmed(theses): + no = answer("Viem, že vedúcim Ana Nová je Peter Novák, len mi to potvrď.")["text"] + assert no.startswith("Nie, Peter Novák v záznamoch nie je uvedený ako vedúci.") and "Daniel Hládek" in no + yes = answer("Viem, že vedúcim Ana Nová je Daniel Hládek, len mi to potvrď.")["text"] + assert yes.startswith("Áno, podľa záznamov to sedí.") + assert answer("Kto je vedúci diplomovej práce Ana Nová?") is None # no claim: the usual answer + + +def test_the_same_supervisor_at_both_theses_is_said_without_asking(theses): + works = U.person_works("Ana Nová") + assert U.same_role_people("Ana Nová", works, "supervisor") + assert U.same_role_people("Ana Nová", works, "opponent") is None # Staš and Pleva: the answer asks which thesis + works[1]["row"] = {} # a thesis without its own record: ask + assert U.same_role_people("Ana Nová", works, "supervisor") is None + + +def test_a_work_year_in_a_title_question_is_kept(theses): + none = answer("Aký názov práce má osoba Ana Nová v roku 2018?")["text"] + assert "z roku 2018 v zázname nie je uvedená" in none and "Grafy" in none + one = answer("Uveď názov práce osoby Ana Nová a rok práce pre rok 2025.")["text"] + assert "Vyhľadávanie" in one and "Grafy" not in one + assert answer("Ako sa volá bakalárska práca Ana Nová z roku 2025?") is None # the year leaves nothing out + + +def test_an_interns_stay_year_topic_and_missing_thesis(data): + TEXTS["eva.md"] = "Eva Biela\n\nIAESTE Intern Summer 2023, two months\n\nTopic: Hate speech detection\n" + assert "v roku 2023" in answer("V ktorom roku prebiehala stáž osoby Eva Biela?")["text"] + assert "Hate speech detection" in answer("Aká bola téma stáže Eva Biela?")["text"] + assert "dizertačná práca osoby v podkladoch nie je uvedená" in answer("Kto bol oponentom dizertačnej práce Eva Biela?")["text"] + assert answer("V ktorom roku prebiehala stáž osoby Ana Nová?") is None or "stáž" not in answer("V ktorom roku prebiehala stáž osoby Ana Nová?")["text"] + + +def test_a_topic_page_is_found_by_its_title(monkeypatch, data): + monkeypatch.setattr(U, "topic_pages", lambda: [{"title": "Anotácia textových dát", "url": "https://zp.test/topics/prodigy"}]) + out = C.record_answer("Nájdi projektovú alebo informačnú stránku „Anotácia textových dát“.", None) + assert out["urls"] == ["https://zp.test/topics/prodigy"] and "„Anotácia textových dát“" in out["text"] + assert C.record_answer("Nájdi projektovú alebo informačnú stránku „Úplne iná téma“.", None) is None + assert C.record_answer("Kto robil anotáciu textových dát?", None) is None + + +def test_a_tag_with_a_hyphen_is_read_as_written(data): + PAGES[0]["tags"].append("mind-maps") + try: + out = U.tag_answer("Kto v ZP Wiki rieši tému s tagom mind-maps?") + assert "**mind-maps**" in out["text"] and "Ana Nová" in out["text"] + assert "**nlp**" in U.tag_answer("Ktorí študenti majú tag nlp?")["text"] + finally: + PAGES[0]["tags"].remove("mind-maps") + + +def test_the_work_a_student_is_doing_is_the_newest_wiki_thesis(theses): + works = U.person_works("Ana Nová") + works[1]["row"] = {"supervisors": ["Pleva, Matúš"], "opponents": ["Staš, Ján"]} # the theses differ + monkeypatch_works = lambda person, rows=None: works + U.person_works, old = monkeypatch_works, U.person_works + try: + low = U.normalized("Kto je vedúci práce, ktorú robí Ana Nová?") + out = U.roles("Ana Nová", works, low) + assert "options" not in out and "Daniel Hládek" in out["text"] and "Pleva" not in out["text"] + asked = U.roles("Ana Nová", works, U.normalized("Kto bol vedúci práce Ana Nová?")) + assert asked.get("options") # no present tense: which thesis? + finally: + U.person_works = old diff --git a/tools/answers/combined.py b/tools/answers/combined.py index 4c94dec..559bd3c 100644 --- a/tools/answers/combined.py +++ b/tools/answers/combined.py @@ -265,21 +265,33 @@ def record_answer(question: str, named: dict | None) -> dict | None: """Questions a ZP Wiki profile answers alone, by code (tools/answers/presentation/unified.py): where the person's record is, which lines of it name a topic, a keyword (tag) condition of a work title, and two people's keywords or study starts.""" + from tools.answers.planning.noise import fold_chars from tools.answers.presentation import unified as U low = normalized(question) if named: person = named["name"] if not (U.catalog()["people"].get(person) or {}).get("url"): return None - if U.PERSON_TOPIC_Q.search(low): + if U.CLAIM_Q.search(fold_chars(question)): # "Viem, že vedúcim X je Peter Novák, len mi to potvrď." + claim = U.claimed_role(person, question) + if claim: + return claim + if U.PERSON_TOPIC_Q.search(low): # also "Ktorá stáž osoby X súvisela s témou Y?" return U.person_topic(person, question) + intern = U.intern_answer(person, question) # "V ktorom roku prebiehala stáž osoby X?" + if intern: + return intern if U.PROFILE_Q.search(low): return U.profile(person) if U.KEYWORD_Q.search(low) and U.TITLE_Q.search(low): return U.keyword_title(person, question) + if U.TITLE_Q.search(low) and U.YEAR_IN_Q.search(low): # "Aký názov práce má X v roku 2018?" + return U.year_title(person, question) return None if U.SHARED_KEYWORD_Q.search(low) or U.WHICH_OF_Q.search(low) or U.SHARED_START_Q.search(low): return U.pair_answer(question, _people(question)) + if U.TOPIC_PAGE_Q.search(low): # "Nájdi projektovú alebo informačnú stránku „Anotácia textových dát“." + return U.topic_page(question) return None diff --git a/tools/answers/presentation/unified.py b/tools/answers/presentation/unified.py index e6392c3..8a1513c 100644 --- a/tools/answers/presentation/unified.py +++ b/tools/answers/presentation/unified.py @@ -557,8 +557,18 @@ def roles(person: str, works: list[dict], low: str, wiki_text: str = "", role: s if len(named) >= 2: # "Kto bol vedúcim jeho bakalárky a kto je teraz pri diplomovke?" parts = [_role_part(person, works, k, role, low, wiki_text) for k in named] return _role_sentence(person, role, low, [p for p in parts if p]) + if not asked_type(low) and CURRENT_WORK_Q.search(low): + # "Kto je vedúci práce, ktorú robí X?": the work X is doing now, the newest thesis X has in ZP Wiki + current = sorted((w for w in works if w["source"] == "wiki" and w["type"] in THESES and not w.get("unconfirmed")), + key=lambda w: -(w.get("year") or 0)) + people = _role_people(person, current[0], role, wiki_text) if current else [] + if people: + return _role_sentence(person, role, low, [{"work": current[0], "people": people}]) options = work_options(person, works, low) if options: + same = same_role_people(person, works, role) + if same: # "Kto je vedúci práce, ktorú robí X?" and every thesis had the same supervisor: no "which one?" + return _role_sentence(person, role, low, same) word = "školiteľa" if re.search(r"\bskolitel", low) else ROLES[role]["ask"] # the word the question used return {"options": options, "text": options_text(person, options, f"Pri ktorej práci chceš vedieť {word}?")} kind = asked_type(low) @@ -576,6 +586,42 @@ def roles(person: str, works: list[dict], low: str, wiki_text: str = "", role: s return _role_sentence(person, role, low, [part]) if part else None +# "práce, ktorú robí X", "práca, na ktorej pracuje X": the work in progress, in the present tense +CURRENT_WORK_Q = re.compile(r"\b(?:prac\w*|projekt\w*)\s*,?\s*(?:ktoru|ktory|na\s+ktorej|na\s+ktorom)\s+" + r"(?:teraz\s+|prave\s+|aktualne\s+)?(?:robi|pise|pracuje|riesi|vypracuva)\b") + + +def _stated_role(person: str, work: dict, role: str) -> list[str]: + """The role at this work only from a record of the work itself: the register's row, or (supervisor) the work's + own "Vedúci:" line in the wiki; never the profile's author or another work's line.""" + from tools.crzp.source.parse import display_name + row = work.get("row") or {} + if row.get(ROLES[role]["field"]): + return [display_name(s) for s in row[ROLES[role]["field"]]] + if role == "supervisor" and work["source"] == "wiki": + for unit in units(person): + if (unit.get("kind") == "supervisor" and not unit.get("meeting_id") and unit.get("work_label") == work.get("heading") + and re.match(r"^[-*\s]*(?:Ved[uú]c\w*|Školite\w*|Skolite\w*)[^:.\n]{0,30}:", unit["text"])): + match = re.search(rf"(?:(?:Ing|Mgr|doc|prof|Bc|RNDr|PhD)\.?\s*)*([{UPPER}][\w\-]+\s+[{UPPER}][\w\-]+)", + unit["text"].split(":", 1)[-1]) + if match: + return [match.group(1)] + return [] + + +def same_role_people(person: str, works: list[dict], role: str) -> list[dict] | None: + """[{"work", "people"}] of every thesis when each has the role recorded at the work itself and it is the same + person(s) at all of them; None otherwise (the answer asks which thesis).""" + theses = [w for w in works if w["type"] in THESES and not w.get("unconfirmed")] + if len(theses) < 2: + return None + parts = [{"work": w, "people": _stated_role(person, w, role)} for w in theses] + keys = [frozenset(normalized(n) for n in p["people"]) for p in parts] + if not all(keys) or len(set(keys)) != 1: + return None + return [{"work": p["work"], "people": [spelled(n) for n in p["people"]]} for p in parts] + + def _role_part(person: str, works: list[dict], kind: str | None, role: str, low: str, wiki_text: str) -> dict | None: """The one work of that type (or the person's thesis) and who had the role in it.""" candidates = of_kind(works, kind) if kind else [w for w in works if w["type"] in THESES] @@ -850,6 +896,15 @@ def _people_sentence(names: list[str], limit: int = 40) -> str: TAG_Q = re.compile(r"\b(tag(?:om|u|y|mi|ov)?|kategori\w*)\s+([a-z0-9][a-z0-9\-]{1,30})\b") +# The tag as written ("mind-maps", "c++"): normalized() drops the hyphen and the plus, the question's own text keeps them +TAG_RAW = re.compile(r"\b(tag(?:om|u|y|mi|ov)?|kategori\w*)\s+([a-z0-9][a-z0-9\-+#.]{0,30}[a-z0-9+#])") + + +def asked_tag(question: str) -> str | None: + """The tag or category value of a tag question, with its hyphens and pluses.""" + from tools.answers.planning.noise import fold_chars + match = TAG_RAW.search(fold_chars(question)) + return match.group(2) if match else None 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*") @@ -861,6 +916,9 @@ def tag_answer(question: str) -> dict | None: return None field = "categories" if match.group(1).startswith("kategori") else "tags" value = match.group(2) + raw = asked_tag(question) + if raw and raw != value and normalized(raw).replace(" ", "").startswith(value): + value = raw # "mind-maps" (normalized: "mind maps", read as the tag "mind") rows = [r for r in wiki_pages() if value in r[field]] label = "Kategóriu" if field == "categories" else "Tag" if not rows: @@ -974,8 +1032,10 @@ def set_join(question: str, person: str | None = None) -> dict | None: pages, label = wiki_pages(), [] if tag: field = "categories" if tag.group(1).startswith("kategori") else "tags" - pages = [r for r in pages if tag.group(2) in r[field]] - label.append(f"{'kategóriou' if field == 'categories' else 'tagom'} {tag.group(2)}") + raw = asked_tag(question) + value = raw if raw and normalized(raw).replace(" ", "").startswith(tag.group(2)) else tag.group(2) + pages = [r for r in pages if value in r[field]] + label.append(f"{'kategóriou' if field == 'categories' else 'tagom'} {value}") rest = low if started: first, more = int(started.group(1)), started.group(2) or "" @@ -1571,6 +1631,10 @@ def meeting(person: str, text: str, low: str, follow_up: bool) -> str | None: text = "" # the record's own sections answer it (below) else: return None + if re.match(r"^\W*(?:a\s+)?kedy\b", low) and not re.search(r"\b(?:co|riesil\w*|robil\w*|uloh\w*)\b", low): + # "Kedy sa naposledy stretol X s vedúcim?": the date is the answer, also of a meeting without recorded points + return f"Posledné stretnutie {genitive(person)} bolo {when}." if re.search(r"\b(?:posledn|naposledy)", low) \ + else f"Stretnutie {genitive(person)} bolo {when}." done, todo = [], [] section = None for raw in text.splitlines(): @@ -1984,3 +2048,142 @@ def pair_answer(question: str, names: list[str]) -> dict | None: return {"text": f"Nie, spoločný rok začiatku štúdia nemajú: {spelled(a)} začal{ending(a)} študovať v roku " f"{years[a]}, {spelled(b)} v roku {years[b]}.", "urls": urls} return None + + +# ------------------------------------------------------------------ a claimed role, a work year, interns, topic pages +# "Viem, že vedúcim X je Peter Novák, len mi to potvrď.", "Potvrď, že oponentom práce X bol Ján Staš." +CLAIM_Q = re.compile(r"\b(?:viem|myslim|tusim|pocul\w*|vraj|som\s+si\s+ist\w*|je\s+pravda|potvrd\w*|over\w*)\b[^?]*?\bze\s+" + r"(?Pveduc\w*|skolitel\w*|oponent\w*|konzultant\w*)\b[^?]*?\b(?:je|bol|bola|bude)\s+" + r"(?P[^\W\d_]+(?:\s+[^\W\d_]+){1,2})(?=\s*[,.?!]|\s+(?:a|len|tak|ci|alebo)\b|\s*$)") +CLAIM_CUE = re.compile(r"\b(?:potvrd\w*|over\w*|je\s+to\s+tak|mam\s+pravdu|pravda)\b") + + +def claimed_role(person: str, question: str) -> dict | None: + """"Viem, že vedúcim X je Peter Novák, len mi to potvrď.": the claim is checked against the records of X's theses, + never confirmed only because the question says so.""" + from tools.answers.planning.noise import fold_chars + folded = fold_chars(question) + match = CLAIM_Q.search(folded) + if not match or not CLAIM_CUE.search(folded): + return None + claimed = question[match.start("claimed"):match.end("claimed")].strip() + if _is(person, claimed) or normalized(claimed).split()[0] in normalized(person).split(): + return None # the claimed name is the student's own name: not a claim about the role + word = match.group("role") + role = "opponent" if word.startswith("opon") else "consultant" if word.startswith("konz") else "supervisor" + works = person_works(person) + theses = [w for w in works if w["type"] in THESES and not w.get("unconfirmed")] or \ + [w for w in works if w["source"] == "wiki"][:1] + parts = [{"work": w, "people": _role_people(person, w, role, "")} for w in theses] + parts = [p for p in parts if p["people"]] + if not parts: + return None + label = {"supervisor": "vedúci", "opponent": "oponent", "consultant": "konzultant"}[role] + told = _role_sentence(person, role, normalized(question), parts) + if not told: + return None + named = any(_is(claimed, n) or set(normalized(claimed).split()) <= set(normalized(n).split()) + for p in parts for n in p["people"]) + lead = (f"Áno, podľa záznamov to sedí." if named + else f"Nie, {spelled(claimed)} v záznamoch nie je uvedený ako {label}.") + return {"text": lead + " " + told["text"], "urls": told.get("urls") or work_urls(person, works)} + + +YEAR_IN_Q = re.compile(r"\b(?:v|z|pre|zo)\s+roku\s+((?:18|19|20)\d{2})\b|\b((?:18|19|20)\d{2})\b") + + +def year_title(person: str, question: str) -> dict | None: + """"Aký názov práce má X v roku 2018?", "Uveď názov práce X a rok práce pre rok 2019.": only works of that year + (and of the named type); none -> said so, with the person's works.""" + low = normalized(question) + years = sorted({int(a or b) for a, b in YEAR_IN_Q.findall(low)}) + info = catalog()["people"].get(person) or {} + if not years or not info.get("url"): + return None + kinds = asked_types(low) + works = [w for w in person_works(person) if not w.get("unconfirmed")] + candidates = [w for w in works if not kinds or w["type"] in kinds] + chosen = [w for w in candidates if w.get("year") in years or (w.get("row") or {}).get("year") in years] + if chosen and len(chosen) == len(candidates): + return None # the year leaves out nothing: the usual title answer (with the register's title) + when = join([str(y) for y in years]) + if not chosen and any((w.get("year") in years or (w.get("row") or {}).get("year") in years) + and (not kinds or w["type"] in kinds) for w in person_works(person) if w.get("unconfirmed")): + return None # a register's work of that year, perhaps a namesake's: the usual answer says so + if not chosen: + listed = "; ".join(_title_line(w) for w in works) or "žiadne" + what = TYPES[kinds[0]][0] if len(kinds) == 1 and kinds[0] in TYPES else "práca" + return {"text": f"{what[:1].upper() + what[1:]} osoby {spelled(person)} z roku {when} v zázname nie je uvedená. " + f"Práce osoby: {listed}.", "urls": work_urls(person, works)} + lines = "\n".join(f"- {_title_line(w)}" for w in chosen) + return {"text": f"Práca osoby {spelled(person)} z roku {when}:\n\n{lines}" if len(chosen) == 1 + else f"Práce osoby {spelled(person)} z roku {when}:\n\n{lines}", "urls": work_urls(person, chosen)} + + +INTERN_YEAR_Q = re.compile(r"\b(?:v\s+ktorom\s+roku|kedy|ktory\s+rok)\b[^?]*\bstaz\w*|\bstaz\w*[^?]*\b(?:v\s+ktorom\s+roku|kedy)\b") +INTERN_TOPIC_Q = re.compile(r"\btem\w*\s+(?:jeho\s+|jej\s+)?staz\w*|\bstaz\w*[^?]*\b(?:tem\w*|zameran\w*)\b") + + +def intern_answer(person: str, question: str) -> dict | None: + """An intern: the year and topic of the stay as the page writes them; a thesis an intern does not have.""" + info = catalog()["people"].get(person) or {} + if info.get("person_kind") != "intern" or not info.get("url"): + return None + low = normalized(question) + text = page_text(person) + urls = [info["url"]] + stay = re.search(r"(?i)\b(?:ERASMUS|IAESTE)[^\n]*", text) or re.search(r"(?im)^\s*Intern\b[^\n]*", text) + if INTERN_YEAR_Q.search(low): + years = sorted(set(re.findall(r"\b(20\d{2})\b", stay.group(0)))) if stay else [] + if not years: + return {"text": f"Rok stáže osoby {spelled(person)} v zázname nie je uvedený.", "urls": urls} + return {"text": f"Stáž osoby {spelled(person)} prebiehala v roku {join(years)} ({stay.group(0).strip().rstrip('.')}).", + "urls": urls} + if INTERN_TOPIC_Q.search(low): + topic = re.search(r"(?im)^\s*(?:Topic|Téma)\s*:\s*(\S[^\n]*)$", text) or re.search(r"(?im)^\s*(?:Goals?|Ciele?|Cieľ)\s*:\s*(\S[^\n]*)$", text) + if topic: + shown = re.sub(r"\[([^\]]+)\]\([^)]*\)", r"\1", topic.group(1)).strip() + return {"text": f"Téma stáže osoby {spelled(person)}: {shown}", "urls": urls} + return None + kinds = [k for k in asked_types(low) if k in THESES] + if kinds: # "Kto bol oponentom dizertačnej práce stážistu X?" + what = TYPES[kinds[0]][0] + return {"text": f"{spelled(person)} je v ZP Wiki stážist{'ka' if female(spelled(person)) else 'a'}; " + f"{what} osoby v podkladoch nie je uvedená.", "urls": urls} + return None + + +# "Nájdi projektovú alebo informačnú stránku „Anotácia textových dát“.", "Ktorý dokument v ZP Wiki sa priamo venuje téme „X“?" +TOPIC_PAGE_Q = re.compile(r"\b(?:projektov\w*|informacn\w*|navodov\w*|temov\w*)\s+(?:alebo\s+\w+\s+)?strank\w*" + r"|\b(?:najdi|ukaz|kde\s+je)\s+(?:mi\s+)?strank\w*|\bktory\s+dokument\b[^?]*\bvenuje\s+tem\w*") +_topic_pages: dict = {} + + +def topic_pages() -> list[dict]: + """The wiki's topic and guide pages (documents.json): their titles and links.""" + from tools.rag.common import DB_FILE + from tools.rag.search_utils import make_source_url + file = Path(DB_FILE).parent / "documents.json" + try: + stamp = file.stat().st_mtime_ns + except OSError: + return [] + if _topic_pages.get("stamp") != stamp: + rows = [{"title": d.get("title") or "", "path": d["path"], "url": make_source_url(d["path"])} + for d in json.loads(file.read_text(encoding="utf-8")) + if "/topics/" in (d.get("path") or "") and d.get("title")] + _topic_pages.update(stamp=stamp, rows=rows) + return _topic_pages["rows"] + + +def topic_page(question: str) -> dict | None: + """The topic page whose title the question names (quoted, as written); None when no title matches.""" + quoted = re.search(r"[„\"“]([^„“\"]{3,120})[“\"”]", question) + if not quoted: + return None + asked = normalized(quoted.group(1)).split() + for page in topic_pages(): + words = normalized(page["title"]).split() + if len(words) == len(asked) and all(_word_fits(a, w) for a, w in zip(asked, words)): + return {"text": f"Stránka „{page['title']}“ je v ZP Wiki na adrese {page['url']}.", "urls": [page["url"]]} + return None