diff --git a/test/presentation/test_unified_answers.py b/test/presentation/test_unified_answers.py index 0595a6f..0902a83 100644 --- a/test/presentation/test_unified_answers.py +++ b/test/presentation/test_unified_answers.py @@ -206,3 +206,45 @@ def test_at_most_eight_tools_and_the_rest_on_request(data): out = U.methods("Ronald Zalacko", [], f"X vo svojej bakalárskej práci „Systém“ využíva: {tools}.", "") assert out["text"].endswith("Nástroj7 (uvedených 8 z 11).") and out["rest"] == ["Nástroj8", "Nástroj9", "Nástroj10"] assert out["offer"] == "Ďalších technológií a metód je ešte 3. Chceš vidieť aj zvyšné?" + + +def _crzp_thesis(kind, year, title, supervisor, opponent=None): + return {"source": "crzp", "type": kind, "year": year, "title": title, "urls": [f"https://opac.test/{kind}"], + "row": {"supervisors": [supervisor], "opponents": [opponent] if opponent else [], "url": f"https://opac.test/{kind}"}} + + +def test_a_question_naming_both_theses_gets_both_in_one_sentence(monkeypatch): + monkeypatch.setattr(U, "catalog", lambda: {"people": {}, "works": {}, "texts": {}}) + monkeypatch.setattr(U, "units", lambda person: []) + assert U.asked_types(normalized("kto bol vedúcim u bp a kto je teraz u dp")) == ["bachelor_thesis", "diploma_thesis"] + works = [_crzp_thesis("bachelor_thesis", 2025, "IoT dáta", "Galajda, Pavol", "Hládek, Daniel"), + _crzp_thesis("diploma_thesis", 2099, "Agent", "Hládek, Daniel")] + both = U.roles("Ján Pták", works, normalized("kto bol vedúcim práce Jána Ptáka u bp a kto je teraz u dp")) + assert both["text"] == ("Vedúcim bakalárskej práce Jána Ptáka „IoT dáta“ (2025) bol Pavol Galajda a vedúcim jeho " + "diplomovej práce „Agent“ (2099) je Daniel Hládek.") + opponents = U.roles("Ján Pták", works, normalized("Kto bol oponentom bakalárskej a diplomovej práce Jána Ptáka?")) + assert opponents["text"] == ("Oponentom bakalárskej práce Jána Ptáka „IoT dáta“ (2025) bol Daniel Hládek. Jeho diplomová " + "práca „Agent“ (2099) ešte nebola odovzdaná, oponent sa určuje až pri odovzdaní.") + assert "?" in U.roles("Ján Pták", works, normalized("Kto je vedúci Jána Ptáka?"))["text"] # none named: which one? + + +def test_a_tuke_thesis_whose_year_fits_the_studies_is_the_students(monkeypatch): + monkeypatch.setattr(U, "catalog", lambda: {"people": {"Ján Pták": {"start_year": 2022}}, "works": {}, "texts": {}}) + row = {"authors": ["Pták, Ján"], "school": "Technická univerzita v Košiciach 1040 104005"} + bachelor = {"type": "bachelor_thesis", "year": 2025} + assert U.fits_studies("Ján Pták", row, bachelor, []) + assert not U.fits_studies("Ján Pták", row, {"type": "bachelor_thesis", "year": 2019}, []) # before the studies + assert not U.fits_studies("Ján Pták", {**row, "school": "Žilinská univerzita v Žiline"}, bachelor, []) # elsewhere + assert not U.fits_studies("Ján Pták", row, bachelor, [{"source": "wiki", "type": "bachelor_thesis"}]) # wiki has one + + +def test_one_thesis_and_a_newer_running_project_both_answer_who_leads(monkeypatch): + monkeypatch.setattr(U, "catalog", lambda: {"people": {}, "works": {}, "texts": {}}) + monkeypatch.setattr(U, "units", lambda person: []) + monkeypatch.setattr(U, "_role_people", lambda person, work, role, text: ["Daniel Hládek"] if work["source"] == "wiki" + else ["Ľubomír Doboš"]) + works = [{"source": "wiki", "type": "diploma_project", "year": 2026, "title": "Grafové vyhľadávanie"}, + _crzp_thesis("bachelor_thesis", 2025, "5G", "Doboš, Ľubomír")] + 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š.") diff --git a/tools/answers/presentation/unified.py b/tools/answers/presentation/unified.py index 3bbad6f..3e4383e 100644 --- a/tools/answers/presentation/unified.py +++ b/tools/answers/presentation/unified.py @@ -143,6 +143,16 @@ def asked_type(low: str) -> str | None: return next((kind for pattern, kind in ASKED_TYPE if re.search(pattern, low)), None) +def asked_types(low: str) -> list[str]: + """Every work type the question names, in its order ("u bp … a u dp" -> bachelor, diploma).""" + found = [] + for pattern, kind in ASKED_TYPE: + match = re.search(pattern, low) + if match and kind not in (k for _, k in found): + found.append((match.start(), kind)) + return [kind for _, kind in sorted(found)] + + def clean_point(text: str) -> str: """One record as a point: no list marker, label, checkbox or trailing colon.""" text = re.sub(r"^\s*(?:[-*+]|\d+[.)])\s+", "", text.strip()) @@ -336,7 +346,7 @@ 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) + item["unconfirmed"] = 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. @@ -371,6 +381,28 @@ def work_urls(person: str, works: list[dict]) -> list[str]: # ------------------------------------------------------------------ answers by kind of question +STUDY_YEARS = {"bachelor_thesis": (2, 4), "diploma_thesis": (4, 6)} # years after the start of studies (3 and 5, ±1) + + +def fits_studies(person: str, row: dict, item: dict, works: list[dict]) -> bool: + """A TUKE thesis of the person's whole name whose year fits the studies recorded in ZP Wiki (bachelor ~3, + diploma ~5 years after the start) and of a type the wiki has no other work of: the same student, even + with another supervisor and topic (the wiki profile often starts with the diploma thesis).""" + from tools.crzp.answering import answer as crzp + from tools.crzp.source.parse import display_name + start = (catalog()["people"].get(person) or {}).get("start_year") + span = STUDY_YEARS.get(item.get("type")) + if not start or not span or not item.get("year") or crzp.university(row) != "Technická univerzita v Košiciach": + return False + try: + start = int(start) + except (TypeError, ValueError): + return False + whole = any(normalized(display_name(a)) == normalized(person) for a in row.get("authors", [])) + other = any(w["source"] == "wiki" and w["type"] == item["type"] for w in works) + return whole and not other and span[0] <= item["year"] - start <= span[1] + + def start_year(person: str) -> dict | None: year = (catalog()["people"].get(person) or {}).get("start_year") if not year: @@ -447,44 +479,98 @@ def _role_people(person: str, work: dict, role: str, wiki_text: str) -> list[str def roles(person: str, works: list[dict], low: str, wiki_text: str = "", role: str | None = None) -> dict | None: - """"Vedúcim bakalárskej práce Ronalda Zalacka „…“ (2026) je Matúš Pleva." for one work; for two or more - theses and no named one: {"options": …} (the answer asks which one); the same for opponents and - consultants.""" - import datetime + """"Vedúcim bakalárskej práce Ronalda Zalacka „…“ (2026) je Matúš Pleva." for one work; the question naming + two theses ("u bp … a u dp") gets one sentence for both; two or more theses and no named one: {"options": …} + (the answer asks which one); the same for opponents and consultants.""" role = role or asked_role(low) or "supervisor" - kind = asked_type(low) + named = [k for k in asked_types(low) if k in THESES] + 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]) options = work_options(person, works, low) if options: word = "školiteľa" if re.search(r"\bskolitel", low) else ROLES[role]["ask"] # the word the question used return {"options": options, "text": options_text(person, options, f"Pri ktorej práci chceš vedieť {word}?")} + kind = asked_type(low) + part = _role_part(person, works, kind, role, low, wiki_text) + if part and part.get("work") and not kind: + # the thesis answered and a newer running work of ZP Wiki (the diploma project after a bachelor thesis): + # "Kto je vedúci?" also asks who leads now, so both, the newest first + year = part["work"].get("year") or 0 + later = sorted((w for w in works if w["source"] == "wiki" and w["type"] not in THESES and (w.get("year") or 0) > year), + key=lambda w: -(w.get("year") or 0)) + if later: + now = {"work": later[0], "people": _role_people(person, later[0], role, wiki_text)} + if now["people"]: + return _role_sentence(person, role, low, [now, part]) + return _role_sentence(person, role, low, [part]) if part else None + + +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 = [w for w in works if (w["type"] == kind if kind else w["type"] in THESES)] chosen = [w for w in candidates if not w.get("unconfirmed")] if not chosen and not kind: chosen = [w for w in works if w["source"] == "wiki"][:1] chosen = (chosen or candidates)[:1] if not chosen: - return None + return {"missing": kind} if kind else None work = chosen[0] - people = _role_people(person, work, role, wiki_text) - names = TYPES.get(work["type"]) or ("práca", "práce", "práci") - title = f" „{work['title'].rstrip('.')}“" if work.get("title") else "" - year = f" ({work['year']})" if work.get("year") else "" - if not title and work.get("topic"): # the topic of the project the thesis continues - year = f" ({str(work['year']) + '; ' if work.get('year') else ''}téma: {work['topic'].rstrip('.')})" - if not people: - text = f"Pri {names[2]} {genitive(person)}{title}{year} {ROLES[role]['ask']} podklady neuvádzajú." - return {"text": text, "urls": work_urls(person, [work])} - plain = [p.split(" (")[0] for p in people] + return {"work": work, "people": _role_people(person, work, role, wiki_text)} + + +def _role_sentence(person: str, role: str, low: str, parts: list[dict]) -> dict | None: + """One sentence: "Vedúcim bakalárskej práce X „…“ (2025) bol A a vedúcim jeho diplomovej práce „…“ (2027) je B."; + a work the sources lack or whose role they do not record gets its own short sentence.""" + import datetime + if not parts: + return None + his = "jej" if female(person) else "jeho" words = ("Školiteľom", "Školiteľkou", "Školiteľmi") if role == "supervisor" and re.search(r"\bskolitel", low) \ else ROLES[role]["one"] - lead = words[2] if len(people) > 1 else words[1] if female(plain[0]) else words[0] - # an opponent reviews a submitted work (past); a supervisor or consultant of a running work "je" - current = role != "opponent" and (work.get("year") or 0) >= datetime.date.today().year - verb = ("sú" if current else "boli") if len(people) > 1 else "je" if current else ("bola" if female(plain[0]) else "bol") - text = f"{lead} {names[1]} {genitive(person)}{title}{year} {verb} {join(people)}." - if work.get("unconfirmed"): - text += " Nie je isté, že ide o tú istú osobu ako v profile študenta (iný vedúci a téma)." - return {"text": text, "urls": work_urls(person, [work])} + clauses, extra, urls, doubtful = [], [], [], [] + for part in parts: + if part.get("missing"): + names = TYPES.get(part["missing"]) or ("práca", "práce", "práci") + extra.append(f"{names[0][:1].upper() + names[0][1:]} {genitive(person)} v podkladoch nie je.") + continue + work, people = part["work"], part["people"] + names = TYPES.get(work["type"]) or ("práca", "práce", "práci") + title = f" „{work['title'].rstrip('.')}“" if work.get("title") else "" + year = f" ({work['year']})" if work.get("year") else "" + if not title and work.get("topic"): # the topic of the project the thesis continues + year = f" ({str(work['year']) + '; ' if work.get('year') else ''}téma: {work['topic'].rstrip('.')})" + urls += work_urls(person, [work]) + if work.get("unconfirmed"): + doubtful.append(names[2]) + again = bool(clauses or extra) # the person was named in an earlier part: "jeho/jej" + owner = his if again else genitive(person) + if not people: + later = (work.get("year") or 0) > datetime.date.today().year + work_name = f"{his[:1].upper() + his[1:]} {names[0]}" if again else \ + f"{names[0][:1].upper() + names[0][1:]} {genitive(person)}" + if role == "opponent" and later: # not submitted yet: the opponent is named at the submission + extra.append(f"{work_name}{title}{year} ešte nebola odovzdaná, oponent sa určuje až pri odovzdaní.") + else: + at = f"{his} {names[2]}" if again else f"{names[2]} {genitive(person)}" + extra.append(f"Pri {at}{title}{year} {ROLES[role]['ask']} podklady neuvádzajú.") + continue + plain = [p.split(" (")[0] for p in people] + lead = words[2] if len(people) > 1 else words[1] if female(plain[0]) else words[0] + # an opponent reviews a submitted work (past); a supervisor or consultant of a running work "je" + current = role != "opponent" and (work.get("year") or 0) >= datetime.date.today().year + verb = ("sú" if current else "boli") if len(people) > 1 else "je" if current else ("bola" if female(plain[0]) else "bol") + if clauses: # the second work: "a vedúcim jeho diplomovej práce …" + clauses.append(f"{lead[:1].lower() + lead[1:]} {owner} {names[1]}{title}{year} {verb} {join(people)}") + else: + clauses.append(f"{lead} {names[1]} {owner}{title}{year} {verb} {join(people)}") + text = (" a ".join(clauses) + ".") if clauses else "" + text = " ".join(t for t in [text, *extra] if t) + if doubtful: + text += (f" Pri {' a '.join(doubtful)} nie je isté, že ide o tú istú osobu ako v profile študenta " + "(iný vedúci a téma)." if len(parts) > 1 else + " Nie je isté, že ide o tú istú osobu ako v profile študenta (iný vedúci a téma).") + return {"text": text, "urls": list(dict.fromkeys(urls))} if text else None def supervisors(person: str, works: list[dict], low: str, wiki_text: str = "") -> dict | None: