témy a nadväznosti
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
db671f15ba
commit
8351c3e33c
@ -70,7 +70,13 @@ s osobami a témami ZP Wiki (`PROBABLY_SAME`, `SAME_TOPIC`).
|
|||||||
dostane výsledok z toho istého hľadania.
|
dostane výsledok z toho istého hľadania.
|
||||||
- Meno osoby z otázky sa v CRZP hľadá v základnom tvare od modelu, potom v pravidlovom tvare
|
- Meno osoby z otázky sa v CRZP hľadá v základnom tvare od modelu, potom v pravidlovom tvare
|
||||||
(„Samuela Furdy“ → „Samuel Furda“), s celým menom prezývky („Samo“ → „Samuel“) a nakoniec
|
(„Samuela Furdy“ → „Samuel Furda“), s celým menom prezývky („Samo“ → „Samuel“) a nakoniec
|
||||||
len podľa priezviska s kontrolou krstného mena.
|
len podľa priezviska s kontrolou krstného mena. Keď wiki celé meno nepozná a CRZP ho má, odpovedá CRZP.
|
||||||
|
- Otázky na tému (napr. „Kto viedol najviac prác o blockchaine?“) počítajú len práce, ktorých témou to je
|
||||||
|
(názov, inak posúdenie modelom podľa názvu, kľúčových slov, fakulty a abstraktu); odpoveď začína priamou vetou,
|
||||||
|
pri každom človeku je škola a jeden zdroj, zvyšok sa ponúkne.
|
||||||
|
- Nadväzujúce správy: „aké napr.“, „vypíš všetky 4“, „rozdeľ to podľa rokov“, „hľadaj v CRZP“, „málo zdrojov“;
|
||||||
|
poznámka („to nie je ono“, „nie“, „ďakujem“) nič nehľadá. Počet za dva roky uvedie oba a rozdiel
|
||||||
|
(„o koľko viac BP na Kemte v 2025 ako v 2024“); pracoviská aj v páde (Kemte, KEMTu) a skratky bp/dp.
|
||||||
- Súvisiace témy: téma, kto ju robil v ZP Wiki a koľko prác je v CRZP (vážené podľa toho,
|
- Súvisiace témy: téma, kto ju robil v ZP Wiki a koľko prác je v CRZP (vážené podľa toho,
|
||||||
ako špecifický je pojem); podobné práce: najšpecifickejšie spoločné pojmy v základnom tvare.
|
ako špecifický je pojem); podobné práce: najšpecifickejšie spoločné pojmy v základnom tvare.
|
||||||
- Čas každej odpovede (kroky, počet a typ volaní modelu, bez textu otázky) sa zapisuje do
|
- Čas každej odpovede (kroky, počet a typ volaní modelu, bez textu otázky) sa zapisuje do
|
||||||
|
|||||||
@ -17,6 +17,8 @@ os.environ.setdefault("NAME_FORMS_MODEL", "0") # names declined by rules; tests
|
|||||||
# Conversation steps and paged lists of tests go to a temporary file, not to data/.
|
# Conversation steps and paged lists of tests go to a temporary file, not to data/.
|
||||||
import tempfile
|
import tempfile
|
||||||
os.environ.setdefault("ANSWER_CONTEXT_FILE", os.path.join(tempfile.mkdtemp(prefix="zp-context-"), "conversation_pages.sqlite"))
|
os.environ.setdefault("ANSWER_CONTEXT_FILE", os.path.join(tempfile.mkdtemp(prefix="zp-context-"), "conversation_pages.sqlite"))
|
||||||
|
# CRZP searches, records and topic verdicts of tests: a temporary cache, never data/crzp.
|
||||||
|
os.environ.setdefault("CRZP_DB_FILE", os.path.join(tempfile.mkdtemp(prefix="zp-crzp-"), "crzp.sqlite"))
|
||||||
|
|
||||||
# Evaluation code lives outside Git (see local/OBSAH.md). Without it, tests that
|
# Evaluation code lives outside Git (see local/OBSAH.md). Without it, tests that
|
||||||
# import it at module level are skipped at collection instead of failing.
|
# import it at module level are skipped at collection instead of failing.
|
||||||
|
|||||||
@ -432,3 +432,127 @@ def test_an_unavailable_crzp_is_never_reported_as_searched(combo, monkeypatch):
|
|||||||
combo["match"], combo["deliver"] = None, lambda q, **kw: dict(NO_WIKI)
|
combo["match"], combo["deliver"] = None, lambda q, **kw: dict(NO_WIKI)
|
||||||
result = ask(combo, "Kto bol vedúci práce Samuela Furdy?")
|
result = ask(combo, "Kto bol vedúci práce Samuela Furdy?")
|
||||||
assert result["status"] == "no_answer" and "registri" not in result["answer"]
|
assert result["status"] == "no_answer" and "registri" not in result["answer"]
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ follow-ups, counts, names (19. 11. 2026)
|
||||||
|
|
||||||
|
def test_a_remark_or_no_starts_no_search(combo):
|
||||||
|
first = ask(combo, "Kto vedie Jána Ptáka?")
|
||||||
|
asked = []
|
||||||
|
combo["deliver"] = lambda q, **kw: (asked.append(q), dict(WIKI))[1]
|
||||||
|
remark = ask(combo, "to nie je ono", first["conversation_context"]["token"])
|
||||||
|
assert remark["status"] == "ambiguous" and "Upresni prosím" in remark["answer"] and asked == []
|
||||||
|
assert ask(combo, "nie, netreba" if False else "nie", first["conversation_context"]["token"])["answer"] == "Dobre."
|
||||||
|
assert ask(combo, "ďakujem", first["conversation_context"]["token"])["answer"] == "Rado sa stalo." and asked == []
|
||||||
|
assert remark["conversation_context"]["token"] # the conversation goes on
|
||||||
|
|
||||||
|
|
||||||
|
def test_search_in_crzp_answers_the_previous_question_from_crzp(combo):
|
||||||
|
first = ask(combo, "Kto vedie Jána Ptáka?")
|
||||||
|
asked = []
|
||||||
|
combo["deliver"] = lambda q, **kw: (asked.append(q), dict(WIKI))[1]
|
||||||
|
ask(combo, "hľadaj to na CRZP", first["conversation_context"]["token"])
|
||||||
|
assert asked == ["Kto vedie Jána Ptáka v CRZP?"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_sources_of_a_wiki_answer_are_its_own_links(combo):
|
||||||
|
first = ask(combo, "Kto vedie Jána Ptáka?")
|
||||||
|
result = ask(combo, "nejak málo zdrojov", first["conversation_context"]["token"])
|
||||||
|
assert result["answer"].startswith("Predchádzajúca odpoveď vychádza z týchto zdrojov:") and "https://zp.test/jan" in result["answer"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_crzp_count_is_the_answer_not_a_wiki_list(combo):
|
||||||
|
combo["match"] = None
|
||||||
|
combo["deliver"] = lambda q, **kw: dict(LIST)
|
||||||
|
combo["part"] = {"mode": "explicit", "status": "ok", "intent": "count", "rows": [], "urls": [], "crzp_token": None,
|
||||||
|
"entities": [], "text": "Na KEMT FEI Technickej univerzity v Košiciach obhájili v roku 2024 3 bakalárske "
|
||||||
|
"práce a v roku 2025 5, teda o 2 viac."}
|
||||||
|
result = ask(combo, "koľko bolo obhájených bp na KEMT v roku 2024 a koľko v roku 2025")
|
||||||
|
assert result["answer"].startswith("Na KEMT FEI") and "Maksym Zatirka" not in result["answer"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_whole_name_crzp_knows_beats_the_wiki_question_which_samuel(combo):
|
||||||
|
combo["match"] = None
|
||||||
|
combo["deliver"] = lambda q, **kw: {**WIKI, "status": "ambiguous", "reason": "incomplete_person_name",
|
||||||
|
"answer": "Meno „samuel“ nie je jednoznačné. Ktorú osobu máš na mysli?"}
|
||||||
|
combo["part"] = {"mode": "explicit", "status": "ok", "intent": "about", "person": "Samuel Furda", "rows": [],
|
||||||
|
"urls": ["https://opac.test/f"], "crzp_token": None, "entities": [],
|
||||||
|
"text": "**Detekcia vnútorných sieťových hrozieb** — bakalárska práca, 2025; autor Samuel Furda"}
|
||||||
|
result = ask(combo, "samuel furda, o com je jeho praca")
|
||||||
|
assert result["status"] == "ok" and "Detekcia vnútorných sieťových hrozieb" in result["answer"]
|
||||||
|
combo["part"] = {**combo["part"], "person": "Samuel Bagín"} # another Samuel: the wiki question stays
|
||||||
|
assert ask(combo, "samuel furda, o com je jeho praca")["status"] == "ambiguous"
|
||||||
|
|
||||||
|
|
||||||
|
def test_schools_of_listed_people_name_their_sources(combo):
|
||||||
|
combo["match"] = None
|
||||||
|
combo["deliver"] = lambda q, **kw: dict(LIST)
|
||||||
|
combo["part"] = {"mode": "similar", "items": crzp_items(1), "rows": [], "urls": [], "text": ""}
|
||||||
|
first = ask(combo, "Kto pracoval na podobnej téme ako Ján Pták?")
|
||||||
|
schools = ask(combo, "a z akých škôl sú?", first["conversation_context"]["token"])
|
||||||
|
assert "Zdroje: https://zp.test/students/2022/jan_ptak" in schools["answer"] and "https://opac.test/0" in schools["answer"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_rest_of_a_ranking_is_shown_on_yes(combo):
|
||||||
|
combo["match"] = None
|
||||||
|
rest = [{"name": f"Osoba {i} (TUKE) – 2", "source": "crzp", "text": "", "urls": [f"https://opac.test/r{i}"]} for i in range(3)]
|
||||||
|
combo["part"] = {"mode": "explicit", "status": "ok", "intent": "relation", "rows": [], "urls": ["https://opac.test/1"],
|
||||||
|
"crzp_token": None, "entities": [], "rest": rest, "offer": "Chceš vidieť ďalších (3)?",
|
||||||
|
"text": "Najviac prác na tému „blockchain“ viedol Kristián Košťál (STU v Bratislave) – 36."}
|
||||||
|
combo["deliver"] = lambda q, **kw: {**WIKI, "status": "no_answer", "reason": "evidence_not_found", "answer": "Nič."}
|
||||||
|
first = ask(combo, "Kto viedol najviac prác o blockchaine?")
|
||||||
|
assert first["answer"].rstrip().endswith("Chceš vidieť ďalších (3)?")
|
||||||
|
more = ask(combo, "áno", first["conversation_context"]["token"])
|
||||||
|
assert more["answer"].startswith("- Osoba 0 (TUKE) – 2\n- Osoba 1 (TUKE) – 2") and "https://opac.test/r2" in more["answer"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_count_of_a_supervisors_works_by_year_goes_to_crzp():
|
||||||
|
assert C.supervisor_count("koľko robilo bakalárku u Hládka v roku 2025 a v roku 2024")
|
||||||
|
assert C.supervisor_count("Koľko diplomových prác viedol Daniel Hládek?")
|
||||||
|
assert not C.supervisor_count("Koľko študentov vedie Daniel Hládek?")
|
||||||
|
assert not C.supervisor_count(f"Koľko bakalárok bude viesť Hládek v roku {time.localtime().tm_year + 1}?")
|
||||||
|
mode, query = C.crzp_plan("koľko robilo bakalárku u Hládka v roku 2025 a v roku 2024", "Daniel Hládek", student=False)
|
||||||
|
assert mode == "explicit" and query.intent == "count" and query.years == [2024, 2025]
|
||||||
|
assert query.people[0].name == "Daniel Hládek" and query.people[0].role == "supervisor" and query.people[0].canonical
|
||||||
|
|
||||||
|
|
||||||
|
def test_technologies_of_a_person_only_crzp_knows(monkeypatch):
|
||||||
|
from tools.crzp.answering import answer as A
|
||||||
|
from tools.crzp.answering.understand import Person, understand
|
||||||
|
rows = [{"title": "Simulačné prostredie pre RL", "year": 2025, "work_type": "bachelor_thesis", "sid": "S1",
|
||||||
|
"url": "https://opac.test/s1", "authors": ["Kuchinka, Bohdan"], "keywords": ["reinforcement learning", "Python"],
|
||||||
|
"school": "Univerzita Pavla Jozefa Šafárika v Košiciach"},
|
||||||
|
{"title": "Edge IoT siete", "year": 2027, "work_type": "diploma_thesis", "sid": "S2", "url": "https://opac.test/s2",
|
||||||
|
"authors": ["Kuchinka, Bohdan"], "keywords": ["IoT"], "school": "Univerzita Pavla Jozefa Šafárika v Košiciach"}]
|
||||||
|
monkeypatch.setattr(A, "find", lambda query: ({"rows": rows}, [r for r in rows if not query.work_types
|
||||||
|
or r["work_type"] in query.work_types]))
|
||||||
|
monkeypatch.setattr(A.fetch, "detail", lambda sid: {"abstract": "Prostredie v Pythone pre reinforcement learning.",
|
||||||
|
"keywords": next(r["keywords"] for r in rows if r["sid"] == sid)})
|
||||||
|
query = understand("Aké technológie využíva Bohdan Kuchinka?", use_model=False)
|
||||||
|
query.people = [Person(name="Bohdan Kuchinka", role="author", typed="Bohdan Kuchinka")]
|
||||||
|
asked = C.crzp_person_methods("Aké technológie využíva Bohdan Kuchinka?", query)
|
||||||
|
assert asked["status"] == "ambiguous" and [o["type"] for o in asked["options"]] == ["diploma_thesis", "bachelor_thesis"]
|
||||||
|
assert "Z ktorej chceš vedieť, aké technológie využíva?" in asked["text"]
|
||||||
|
query.work_types = ["bachelor_thesis"]
|
||||||
|
one = C.crzp_person_methods("Aké technológie využíva Bohdan Kuchinka v bakalárskej práci?", query)
|
||||||
|
assert one["status"] == "ok" and one["text"].startswith(
|
||||||
|
"Bohdan Kuchinka vo svojej bakalárskej práci „Simulačné prostredie pre RL“ (2025) využíva: reinforcement learning, Python")
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_wiki_that_cannot_count_yields_to_the_crzp_count(combo):
|
||||||
|
combo["match"] = None
|
||||||
|
combo["deliver"] = lambda q, **kw: {**WIKI, "status": "ambiguous", "reason": "content_count_not_established",
|
||||||
|
"answer": "Obsahové vyhľadávanie poskytuje doložené prípady, nie overený úplný počet."}
|
||||||
|
combo["part"] = {"mode": "explicit", "status": "ok", "intent": "count", "rows": [], "urls": [], "crzp_token": None,
|
||||||
|
"entities": [], "text": "Na KEMT FEI Technickej univerzity v Košiciach obhájili v roku 2024 55 "
|
||||||
|
"bakalárskych prác a v roku 2025 101, teda o 46 viac."}
|
||||||
|
result = ask(combo, "o kolko bolo obhajenych bp na KEMT v roku 2024 než v roku 2025")
|
||||||
|
assert result["status"] == "ok" and result["answer"].startswith("Na KEMT FEI")
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_question_naming_crzp_gets_what_crzp_records(combo):
|
||||||
|
combo["part"] = {"mode": "explicit", "status": "ok", "intent": "relation", "rows": [], "urls": ["https://opac.test/bp"],
|
||||||
|
"crzp_token": None, "entities": [], "person": "Ján Pták",
|
||||||
|
"text": "Vedúcim bakalárskej práce Jána Ptáka „Databázová implementácia IoT dát“ (2025) bol Pavol Galajda."}
|
||||||
|
result = ask(combo, "Kto vedie Jána Ptáka v CRZP?")
|
||||||
|
assert result["answer"].startswith("Vedúcim bakalárskej práce Jána Ptáka") and "Daniel Hladek" not in result["answer"]
|
||||||
|
|||||||
@ -180,6 +180,27 @@ def test_the_backlog_of_the_meeting_is_listed_with_its_tasks(monkeypatch):
|
|||||||
assert "Iná staršia úloha" not in text # the backlog of another meeting
|
assert "Iná staršia úloha" not in text # the backlog of another meeting
|
||||||
|
|
||||||
|
|
||||||
|
def test_tasks_come_from_the_records_task_section_never_from_its_progress(monkeypatch):
|
||||||
|
# the index joins overlapping chunks: the task section is cut in the first one and whole in the next
|
||||||
|
profile = ("Stretnutie 22.10.2026\n\nStav:\n\n- Databáza ADC spracovaná do grafu.\n\nÚlohy:\n\n- Pridajte dávkovanie."
|
||||||
|
"\n\nDokument: Oleh Poiasnik\nSekcia: Diplomová práca 2027\n\nÚlohy:\n\n- Pridajte dávkovanie.\n\n"
|
||||||
|
"- Dajte dáta na školský server.\n\nZásobník úloh:\n\n- Zverejnite dataset.\n")
|
||||||
|
path = "pages/students/2022/oleh/README.md"
|
||||||
|
monkeypatch.setattr(U, "catalog", lambda: {"people": {}, "works": {}, "texts": {path: profile}})
|
||||||
|
monkeypatch.setattr(U, "units", lambda person: [{"kind": "meeting", "record_date": "2026-10-22", "line": 1,
|
||||||
|
"text": "Stretnutie 22.10.2026", "source_path": path}])
|
||||||
|
assert U.tasks_of("Oleh Poiasnik", "22.10.2026") == ["Pridajte dávkovanie.", "Dajte dáta na školský server."]
|
||||||
|
wiki = "Podľa zápisu zo stretnutia 22.10.2026:\n\nStav:\n- Databáza ADC spracovaná do grafu." # the model wrote no tasks
|
||||||
|
text = U.meeting("Oleh Poiasnik", wiki, normalized("a aké úlohy dostal?"), True)
|
||||||
|
assert "- Pridajte dávkovanie.\n- Dajte dáta na školský server." in text and "ADC" not in text.split("Do zásobníka")[0]
|
||||||
|
assert text.endswith("- Zverejnite dataset.")
|
||||||
|
undated = "**Oleh Poiasnik — Diplomová práca 2027**\n\nPlánované úlohy:\n- Databáza ADC spracovaná do grafu."
|
||||||
|
text = U.meeting("Oleh Poiasnik", undated, normalized("a aké úlohy dostal?"), True) # the newest meeting of the record
|
||||||
|
assert text.startswith("Na stretnutí 22.10.2026 dostal tieto úlohy:") and "ADC spracovaná" not in text.split("Do zásobníka")[0]
|
||||||
|
monkeypatch.setattr(U, "catalog", lambda: {"people": {}, "works": {}, "texts": {path: "Stretnutie 22.10.2026\n\nStav:\n- X.\n"}})
|
||||||
|
assert U.meeting("Oleh Poiasnik", wiki, normalized("a aké úlohy dostal?"), True) == "Pri stretnutí 22.10.2026 nie sú zapísané úlohy."
|
||||||
|
|
||||||
|
|
||||||
def test_at_most_eight_tools_and_the_rest_on_request(data):
|
def test_at_most_eight_tools_and_the_rest_on_request(data):
|
||||||
tools = ", ".join(f"Nástroj{i}" for i in range(11))
|
tools = ", ".join(f"Nástroj{i}" for i in range(11))
|
||||||
out = U.methods("Ronald Zalacko", [], f"X vo svojej bakalárskej práci „Systém“ využíva: {tools}.", "")
|
out = U.methods("Ronald Zalacko", [], f"X vo svojej bakalárskej práci „Systém“ využíva: {tools}.", "")
|
||||||
|
|||||||
@ -58,17 +58,20 @@ WIKI_ONLY = re.compile(r"\b(?:stretnut\w*|pokrok\w*|progres\w*|uloh\w*|zadan\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*)\b")
|
||||||
EXPLICIT = re.compile(r"\b(?:crzp|registr\w*|register|celoslovensk\w*|na slovensku|(?:inych|inej|inom|ostatnych|"
|
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)\s+(?:vysok\w+\s+)?(?:skol|univerzit|fakult)\w*|mimo tuke|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")
|
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
|
ABOUT = re.compile(r"\b(?:o com|zhrn\w*|abstrakt\w*|ciel\w*)\b") # not "čomu sa venuje": the current work
|
||||||
# A question about a thesis (not "na čom pracuje", which CRZP's submitted works cannot answer).
|
# A question about a thesis (not "na čom pracuje", which CRZP's submitted works cannot answer).
|
||||||
THESIS = re.compile(r"\b(?:prac(?:a|e|u|i|ou|ach|ami)?|bakalar\w*|diplom\w*|dizerta\w*|habilita\w*|tem(?:a|u|y|ou)|"
|
THESIS = re.compile(r"\b(?:prac(?:a|e|u|i|ou|ach|ami)?|bakalar\w*|diplom\w*|dizerta\w*|habilita\w*|bp|dp|tem(?:a|u|y|ou)|"
|
||||||
r"oponent\w*|vedu\w*|skolitel\w*|abstrakt\w*|klucov\w*|tagy?)\b")
|
r"oponent\w*|vedu\w*|skolitel\w*|abstrakt\w*|klucov\w*|tagy?)\b")
|
||||||
WIKI_CLARIFICATION_YIELDS = {"missing_subject", "unsupported_content_question", "unsupported_constraint"}
|
WIKI_CLARIFICATION_YIELDS = {"missing_subject", "unsupported_content_question", "unsupported_constraint",
|
||||||
|
"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
|
# "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.
|
# published works, not a wiki question about one student's defence.
|
||||||
DEFENDED = re.compile(r"\b(?:obhaj\w*|obhajen\w*|obhajil\w*|uspesn\w*)\b")
|
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"))
|
TOPIC_MIN_SCORE = float(os.getenv("CRZP_TOPIC_MIN_SCORE", "0"))
|
||||||
PAGE = int(os.getenv("ANSWER_PAGE_SIZE", "6"))
|
PAGE = int(os.getenv("ANSWER_PAGE_SIZE", "6"))
|
||||||
|
MAX_SOURCES = 40 # CRZP links in one "Zdroje:" line (every work an answer lists or counts per person)
|
||||||
WIKI_FIRST = 4 # a mixed list shows at most this many ZP Wiki people before the CRZP works
|
WIKI_FIRST = 4 # a mixed list shows at most this many ZP Wiki people before the CRZP works
|
||||||
REFUSED = {"request_out_of_scope", "irrelevant", "unsupported_request", "out_of_scope"}
|
REFUSED = {"request_out_of_scope", "irrelevant", "unsupported_request", "out_of_scope"}
|
||||||
RELATED = re.compile(r"\b(?:suvis\w*|pribuzn\w*)\b")
|
RELATED = re.compile(r"\b(?:suvis\w*|pribuzn\w*)\b")
|
||||||
@ -395,6 +398,14 @@ 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)
|
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:
|
if person and other_school and not query.from_model:
|
||||||
query = understand(question, complete=complete)
|
query = understand(question, complete=complete)
|
||||||
|
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 = [], []
|
||||||
|
return "explicit", query
|
||||||
if person and not other_school:
|
if person and not other_school:
|
||||||
if SIMILAR.search(low) and student:
|
if SIMILAR.search(low) and student:
|
||||||
return "similar", query
|
return "similar", query
|
||||||
@ -408,7 +419,7 @@ def crzp_plan(question: str, person: str | None, complete=None, student: bool =
|
|||||||
query.topics, query.alternatives = [], []
|
query.topics, query.alternatives = [], []
|
||||||
return "person", query
|
return "person", query
|
||||||
if query.people and not person and query.search_text() and (
|
if query.people and not person and query.search_text() and (
|
||||||
THESIS.search(low) or PERSON_Q.search(low) and HUMAN_NAME.fullmatch(query.people[0].name)):
|
THESIS.search(low) or METHODS.search(low) or PERSON_Q.search(low) and HUMAN_NAME.fullmatch(query.people[0].name)):
|
||||||
return "explicit", query # a person ZP Wiki does not know: CRZP knows the theses of all schools
|
return "explicit", query # a person ZP Wiki does not know: CRZP knows the theses of all schools
|
||||||
if query.topics and not query.people and RELATED.search(low) and not re.search(r"\b(?:tag\w*|klucov\w*)\b", low):
|
if query.topics and not query.people and RELATED.search(low) and not re.search(r"\b(?:tag\w*|klucov\w*)\b", low):
|
||||||
query.intent = "keywords" # "Ktoré témy súvisia s X?": topics of works about X, and who did them
|
query.intent = "keywords" # "Ktoré témy súvisia s X?": topics of works about X, and who did them
|
||||||
@ -425,6 +436,46 @@ def crzp_plan(question: str, person: str | None, complete=None, student: bool =
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
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()))
|
||||||
|
and all(y <= time.localtime().tm_year for y in years))
|
||||||
|
|
||||||
|
|
||||||
|
def crzp_person_methods(question: str, query, complete=None) -> dict | None:
|
||||||
|
""""Aké technológie využíva Bohdan Kuchinka v bakalárskej práci?" about a person only CRZP knows:
|
||||||
|
the work's keywords and the tools its abstract names (crzp_methods). Two or more theses and the
|
||||||
|
question names no type: which one? None when CRZP has no work (the general answer says so)."""
|
||||||
|
from tools.crzp.answering import answer as crzp
|
||||||
|
from tools.crzp.source.parse import display_name
|
||||||
|
found, rows = crzp.find(query)
|
||||||
|
rows = [r for r in crzp.resubmissions(rows) if crzp.people_in_role(r, query.people[0].name, "author")]
|
||||||
|
if not rows:
|
||||||
|
return None
|
||||||
|
rows = sorted(rows, key=lambda r: -(r.get("year") or 0))
|
||||||
|
name = display_name(rows[0]["authors"][0]) if rows[0].get("authors") else query.people[0].name
|
||||||
|
if len(rows) > 1 and not query.work_types:
|
||||||
|
options = [{"source": "crzp", "label": f"{_kind(r)} ({r.get('year') or '?'}) „{r['title']}“",
|
||||||
|
"type": r.get("work_type"), "key": crzp.work_key(r)} for r in rows[:4]]
|
||||||
|
text = (f"{name} má {len(options)} {'záverečné práce' if len(options) < 5 else 'záverečných prác'}:\n\n"
|
||||||
|
+ "\n".join(f"{i}. {o['label']}" for i, o in enumerate(options, 1))
|
||||||
|
+ "\n\nZ ktorej chceš vedieť, aké technológie využíva?")
|
||||||
|
return {"mode": "explicit", "status": "ambiguous", "text": text, "rows": [], "urls": [], "crzp_token": None,
|
||||||
|
"entities": [], "options": options, "intent": "methods", "person": name}
|
||||||
|
lines, used = [], []
|
||||||
|
for row in rows[:3]:
|
||||||
|
detail = crzp.fetch.detail(row["sid"]) if row.get("sid") else None
|
||||||
|
lines.append(crzp_methods(name, row, detail))
|
||||||
|
used.append(row)
|
||||||
|
return {"mode": "explicit", "status": "ok", "text": "\n\n".join(lines), "rows": used,
|
||||||
|
"urls": [r["url"] for r in used if r.get("url")], "crzp_token": None, "entities": [],
|
||||||
|
"intent": "methods", "person": name}
|
||||||
|
|
||||||
|
|
||||||
def clean_crzp(text: str) -> str:
|
def clean_crzp(text: str) -> str:
|
||||||
"""CRZP answer text inside a combined answer: its own source lines go to the common "Zdroje CRZP" line."""
|
"""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)]
|
lines = [l for l in text.split("\n") if not re.match(r"^\s*(?:-\s*)?Zdroj:\s", l)]
|
||||||
@ -445,7 +496,9 @@ def explicit_part(question: str, result: dict) -> dict | None:
|
|||||||
token = issued["token"] if issued else None
|
token = issued["token"] if issued else None
|
||||||
entities = result.pop("_entities", None) or []
|
entities = result.pop("_entities", None) or []
|
||||||
return {"mode": "explicit", "status": result["status"], "text": clean_crzp(result["answer"]), "rows": rows,
|
return {"mode": "explicit", "status": result["status"], "text": clean_crzp(result["answer"]), "rows": rows,
|
||||||
"urls": result.get("source_urls", []), "crzp_token": token, "entities": entities}
|
"urls": result.get("source_urls", []), "crzp_token": token, "entities": entities,
|
||||||
|
"rest": result.pop("_rest", None), "offer": result.pop("_offer", None),
|
||||||
|
"intent": getattr(asked, "intent", None), "person": (asked.people[0].name if getattr(asked, "people", None) else None)}
|
||||||
|
|
||||||
|
|
||||||
def _kind(row) -> str:
|
def _kind(row) -> str:
|
||||||
@ -526,8 +579,14 @@ def _crzp_part(question: str, person: str | None, *, complete=None, student: boo
|
|||||||
if mode == "related":
|
if mode == "related":
|
||||||
return related_part(query)
|
return related_part(query)
|
||||||
if mode == "explicit":
|
if mode == "explicit":
|
||||||
|
if METHODS.search(low) and query.people: # technologies of a person known only to CRZP ("technológie" is no topic)
|
||||||
|
methods = crzp_person_methods(question, query, complete)
|
||||||
|
if methods is not None:
|
||||||
|
return methods
|
||||||
result = crzp._answer_query(question, query, complete)
|
result = crzp._answer_query(question, query, complete)
|
||||||
part = explicit_part(question, result)
|
part = explicit_part(question, result)
|
||||||
|
if part is not None and query.people:
|
||||||
|
part["person"] = query.people[0].name # as CRZP writes it (find() set it)
|
||||||
if query.exclude_school == "tuke": # "na iných školách": the ZP Wiki (TUKE) part is not asked
|
if query.exclude_school == "tuke": # "na iných školách": the ZP Wiki (TUKE) part is not asked
|
||||||
if part is None: # nothing found: CRZP's own "not found" answer, not the wiki's
|
if part is None: # nothing found: CRZP's own "not found" answer, not the wiki's
|
||||||
part = {"mode": "explicit", "status": "ok", "rows": [], "urls": [], "crzp_token": None,
|
part = {"mode": "explicit", "status": "ok", "rows": [], "urls": [], "crzp_token": None,
|
||||||
@ -538,7 +597,8 @@ def _crzp_part(question: str, person: str | None, *, complete=None, student: boo
|
|||||||
if not rows:
|
if not rows:
|
||||||
return None
|
return None
|
||||||
if mode == "topic":
|
if mode == "topic":
|
||||||
rows = relevant(question, query, rows)[:12]
|
rows, _ = crzp.topical(relevant(question, query, rows)[:24], query, complete)
|
||||||
|
rows = rows[:12]
|
||||||
if not rows:
|
if not rows:
|
||||||
return None # nothing in CRZP is really about the topic: no filler works
|
return None # nothing in CRZP is really about the topic: no filler works
|
||||||
return {"mode": mode, "items": [crzp_item(r) for r in rows], "rows": rows, "text": "",
|
return {"mode": mode, "items": [crzp_item(r) for r in rows], "rows": rows, "text": "",
|
||||||
@ -748,9 +808,12 @@ def relevant(question: str, query, rows: list[dict]) -> list[dict]:
|
|||||||
scores = rerank.scores(asked, texts)
|
scores = rerank.scores(asked, texts)
|
||||||
if scores is not None: # the cross-encoder scores at most MAX_PAIRS texts; the rest only by name
|
if scores is not None: # the cross-encoder scores at most MAX_PAIRS texts; the rest only by name
|
||||||
scores = list(scores) + [float("-inf")] * (len(texts) - len(scores))
|
scores = list(scores) + [float("-inf")] * (len(texts) - len(scores))
|
||||||
|
from tools.crzp.answering.relevance import acronym, mentions
|
||||||
kept = []
|
kept = []
|
||||||
for i, (row, text) in enumerate(zip(rows, texts)):
|
for i, (row, text) in enumerate(zip(rows, texts)):
|
||||||
named = any(p.search(normalized(text)) for p in patterns)
|
keywords = ", ".join(row.get("keywords", [])) # authors' tags: any letter case ("rag")
|
||||||
|
named = any(mentions(row["title"], t) or p.search(normalized(keywords)) if acronym(t) else p.search(normalized(text))
|
||||||
|
for t, p in zip(terms, patterns))
|
||||||
score = scores[i] if scores is not None else (1.0 if named else -1.0)
|
score = scores[i] if scores is not None else (1.0 if named else -1.0)
|
||||||
if named or score >= TOPIC_MIN_SCORE:
|
if named or score >= TOPIC_MIN_SCORE:
|
||||||
kept.append((score + (1.0 if named else 0.0), i, row))
|
kept.append((score + (1.0 if named else 0.0), i, row))
|
||||||
@ -881,10 +944,21 @@ def compose_list(head: list[str], shown: list[dict], rest: list[dict], tail: lis
|
|||||||
|
|
||||||
def entity(item: dict, number: int) -> dict:
|
def entity(item: dict, number: int) -> dict:
|
||||||
return {k: v for k, v in {"n": number, "name": item["name"], "school": item.get("school"),
|
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")}.items()
|
"source": item.get("source"), "sid": item.get("sid"), "title": item.get("title"),
|
||||||
|
"url": (item.get("urls") or [None])[0] or item.get("url")}.items()
|
||||||
if v is not None}
|
if v is not None}
|
||||||
|
|
||||||
|
|
||||||
|
def entity_url(entity: dict) -> str | None:
|
||||||
|
"""The source of a listed person: the wiki profile or the CRZP work it was listed with."""
|
||||||
|
if entity.get("url"):
|
||||||
|
return entity["url"]
|
||||||
|
if entity.get("sid"):
|
||||||
|
from tools.crzp.source.client import PERMALINK
|
||||||
|
return PERMALINK.format(sid=entity["sid"])
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------ composition
|
# ------------------------------------------------------------------ composition
|
||||||
|
|
||||||
def _ok(question, engine, text, urls, base) -> dict:
|
def _ok(question, engine, text, urls, base) -> dict:
|
||||||
@ -901,7 +975,8 @@ def _with_token(result: dict, *, wiki_context=None, entities=(), options=(), que
|
|||||||
primary="wiki", page=None) -> dict:
|
primary="wiki", page=None) -> dict:
|
||||||
wiki_context = wiki_context or {}
|
wiki_context = wiki_context or {}
|
||||||
token = seal({"wiki": wiki_context.get("token"), "entities": list(entities)[:40], "options": list(options)[:6],
|
token = seal({"wiki": wiki_context.get("token"), "entities": list(entities)[:40], "options": list(options)[:6],
|
||||||
"question": question, "crzp": crzp, "primary": primary, "page": page})
|
"question": question, "crzp": crzp, "primary": primary, "page": page,
|
||||||
|
"urls": list(result.get("source_urls") or [])[:30]})
|
||||||
if token:
|
if token:
|
||||||
result["conversation_context"] = {**{k: v for k, v in wiki_context.items() if k != "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", []),
|
"token": token, "work_options": wiki_context.get("work_options", []),
|
||||||
@ -1048,6 +1123,58 @@ def _return_to(message: str, step: str, *, engine: str, limit: int, complete, de
|
|||||||
return {**result, "_asked_as": [asked, *result.pop("_asked_as", [])]}
|
return {**result, "_asked_as": [asked, *result.pop("_asked_as", [])]}
|
||||||
|
|
||||||
|
|
||||||
|
# A remark about the previous answer starts no search ("to nie je ono", "málo zdrojov" of a wiki answer).
|
||||||
|
REMARK = re.compile(r"^\W*(?:no\s+|ale\s+)?(?:to\s+)?(?:nie\s+je\s+(?:to\s+)?(?:ono|pravda|spravne|dobre)|nesedi|je\s+to\s+zle|"
|
||||||
|
r"to\s+je\s+zle|zle|nespravne|nie\s+to|hm+|nerozumiem|divne|blbost|nezmysel|to\s+nedava\s+zmysel|"
|
||||||
|
r"nieco\s+je\s+zle|chyba)\W*$")
|
||||||
|
NEGATIVE = re.compile(r"^\W*(?:nie|netreba|nechcem|nie\s+dakujem|nie\s+treba|staci|to\s+staci|ok\s+staci|dobre\s+staci)\W*$")
|
||||||
|
THANKS = re.compile(r"^\W*(?:dakujem|dakujeme|vdaka|diky)(?:\s+(?:velmi|pekne|moc|krasne))?\W*$")
|
||||||
|
NOTED = re.compile(r"^\W*(?:super|ok|okej|dobre|jasne|perfektne|vyborne|rozumiem|aha)\W*$") # no question, no search
|
||||||
|
CRZP_AGAIN = re.compile(r"\b(?:hladaj|pohladaj|vyhladaj|pozri|skus|skontroluj|over|najdi)\w*\s+(?:to\s+|aj\s+|este\s+|mi\s+)*"
|
||||||
|
r"(?:v|na|do|cez|z)\s+(?:crzp|registr\w*|centraln\w*)|^\W*(?:a\s+)?(?:v|na|z)\s+crzp\W*$")
|
||||||
|
|
||||||
|
|
||||||
|
def _note(question: str, engine: str, text: str, previous: dict | None, clarify: bool = False) -> dict:
|
||||||
|
result = _ok(question, engine, text, [], {})
|
||||||
|
if clarify:
|
||||||
|
result.update(status="ambiguous", reason="clarification_required",
|
||||||
|
delivery_check={"layer": "planning", "code": "clarification_required",
|
||||||
|
"request_fingerprint": fingerprint(question, engine)})
|
||||||
|
return _keep_context(result, previous) if previous else result
|
||||||
|
|
||||||
|
|
||||||
|
def _remark(question: str, low: str, words: list[str], previous: dict | None, *, engine, limit, complete, deliver):
|
||||||
|
"""A message about the previous answer, not a new question: a remark or "nie" (no search), "hľadaj
|
||||||
|
v CRZP" (the previous question answered from CRZP), "málo zdrojov" after a wiki answer (its sources)."""
|
||||||
|
from tools.crzp.answering.context import SOURCES
|
||||||
|
if NEGATIVE.match(low) or THANKS.match(low) or NOTED.match(low):
|
||||||
|
return _note(question, engine, "Rado sa stalo." if THANKS.match(low) else "Dobre.", previous)
|
||||||
|
if REMARK.match(low):
|
||||||
|
return _note(question, engine, "Upresni prosím, čo mám hľadať alebo čo v odpovedi nesedí: osobu, tému, rok, "
|
||||||
|
"školu alebo typ práce.", previous, clarify=True)
|
||||||
|
if CRZP_AGAIN.search(low) and len(words) <= 8:
|
||||||
|
asked = (previous or {}).get("question")
|
||||||
|
if not asked:
|
||||||
|
return _note(question, engine, "Napíš, čo mám hľadať v CRZP: osobu, tému alebo názov práce.", previous,
|
||||||
|
clarify=True)
|
||||||
|
if not EXPLICIT.search(normalized(asked)):
|
||||||
|
asked = asked.rstrip(" ?.!") + " v CRZP?"
|
||||||
|
from tools.answers import context_store
|
||||||
|
steps = context_store.chain(previous.get("_step"), limit=2) if previous.get("_step") else []
|
||||||
|
parent = step_token(steps[1]["id"]) if len(steps) > 1 else None # the context that question was asked in
|
||||||
|
result = _answer(asked, engine=engine, limit=limit, context_token=parent, complete=complete, deliver=deliver)
|
||||||
|
return {**result, "_asked_as": [asked, *result.pop("_asked_as", [])]}
|
||||||
|
if SOURCES.search(low) and not (previous and previous.get("primary") == "crzp" and previous.get("crzp")):
|
||||||
|
urls = (previous or {}).get("urls") or []
|
||||||
|
if not urls:
|
||||||
|
return _note(question, engine, "Predchádzajúca odpoveď nemá ďalšie zdroje. Polož otázku na konkrétnu osobu, "
|
||||||
|
"tému alebo prácu.", previous)
|
||||||
|
result = _ok(question, engine, "Predchádzajúca odpoveď vychádza z týchto zdrojov:\n\n"
|
||||||
|
+ "\n".join(f"- {u}" for u in urls), urls, {})
|
||||||
|
return _keep_context(result, previous)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _with_people(question: str, low: str, previous: dict) -> dict:
|
def _with_people(question: str, low: str, previous: dict) -> dict:
|
||||||
"""The latest step, unless the message points at listed people ("druhý z nich", "a z akých škôl
|
"""The latest step, unless the message points at listed people ("druhý z nich", "a z akých škôl
|
||||||
sú?") the latest answer has not listed: then the newest of the last MAX_BACK steps that has them."""
|
sú?") the latest answer has not listed: then the newest of the last MAX_BACK steps that has them."""
|
||||||
@ -1113,6 +1240,18 @@ def _next_page(question: str, engine: str, previous: dict) -> dict:
|
|||||||
return _ok(question, engine, "Ďalšie položky predchádzajúcej odpovede už nie sú k dispozícii; zopakuj otázku.",
|
return _ok(question, engine, "Ďalšie položky predchádzajúcej odpovede už nie sú k dispozícii; zopakuj otázku.",
|
||||||
[], {})
|
[], {})
|
||||||
items, mixed = stored["items"], stored["meta"].get("mixed", False)
|
items, mixed = stored["items"], stored["meta"].get("mixed", False)
|
||||||
|
if stored["meta"].get("kind") == "lines": # the rest of a ranking ("- Gabriel Bugár (TUKE) – 6"), page by page
|
||||||
|
shown, rest = items[:PAGE * 2], items[PAGE * 2:]
|
||||||
|
urls = list(dict.fromkeys(u for item in shown for u in item.get("urls") or []))
|
||||||
|
text = "\n".join(f"- {item['name']}" for item in shown) + ("\n\nZdroje: " + ", ".join(urls) if urls else "")
|
||||||
|
page_id = None
|
||||||
|
if rest:
|
||||||
|
from tools.answers import pages
|
||||||
|
page_id = pages.put(rest, {"kind": "lines"})
|
||||||
|
if page_id:
|
||||||
|
text += f"\n\nChceš vidieť ďalších ({len(rest)})?"
|
||||||
|
return _with_token(_ok(question, engine, text, urls, {}), entities=entities, question=question, page=page_id,
|
||||||
|
crzp=previous.get("crzp"), primary=previous.get("primary", "wiki"))
|
||||||
if stored["meta"].get("kind") == "tools": # the rest of a list of technologies: all of it, once
|
if stored["meta"].get("kind") == "tools": # the rest of a list of technologies: all of it, once
|
||||||
text = stored["meta"]["lead"] + ", ".join(i["name"] for i in items) + "."
|
text = stored["meta"]["lead"] + ", ".join(i["name"] for i in items) + "."
|
||||||
return _with_token(_ok(question, engine, text, [], {}), entities=entities, question=question,
|
return _with_token(_ok(question, engine, text, [], {}), entities=entities, question=question,
|
||||||
@ -1128,8 +1267,9 @@ def _schools_answer(question: str, engine: str, previous: dict) -> dict:
|
|||||||
entities = previous["entities"]
|
entities = previous["entities"]
|
||||||
lines = [f"{e.get('n', i)}. {e['name']} — {e.get('school') or 'škola neuvedená'}"
|
lines = [f"{e.get('n', i)}. {e['name']} — {e.get('school') or 'škola neuvedená'}"
|
||||||
for i, e in enumerate(entities, 1)]
|
for i, e in enumerate(entities, 1)]
|
||||||
text = "Školy ľudí z predchádzajúcej odpovede:\n\n" + "\n".join(lines)
|
urls = list(dict.fromkeys(u for u in (entity_url(e) for e in entities) if u))
|
||||||
return _with_token(_ok(question, engine, text, [], {}), entities=entities, question=question,
|
text = "Školy ľudí z predchádzajúcej odpovede:\n\n" + "\n".join(lines) + ("\n\nZdroje: " + ", ".join(urls) if urls else "")
|
||||||
|
return _with_token(_ok(question, engine, text, urls, {}), entities=entities, question=question,
|
||||||
page=previous.get("page"), crzp=previous.get("crzp"), primary=previous.get("primary", "wiki"))
|
page=previous.get("page"), crzp=previous.get("crzp"), primary=previous.get("primary", "wiki"))
|
||||||
|
|
||||||
|
|
||||||
@ -1201,6 +1341,9 @@ def _answer(question: str, *, engine: str, limit: int, context_token: str | None
|
|||||||
return _with_token(_ok(question, engine, "Všetko nájdené už je v predchádzajúcej odpovedi.", [], {}),
|
return _with_token(_ok(question, engine, "Všetko nájdené už je v predchádzajúcej odpovedi.", [], {}),
|
||||||
entities=previous["entities"], question=question, crzp=previous.get("crzp"),
|
entities=previous["entities"], question=question, crzp=previous.get("crzp"),
|
||||||
primary=previous.get("primary", "wiki"))
|
primary=previous.get("primary", "wiki"))
|
||||||
|
handled = _remark(question, low, words, previous, engine=engine, limit=limit, complete=complete, deliver=deliver)
|
||||||
|
if handled is not None:
|
||||||
|
return handled
|
||||||
if previous and previous.get("_step") and BACK.search(low): # "vráť sa k otázke o blockchaine, …"
|
if previous and previous.get("_step") and BACK.search(low): # "vráť sa k otázke o blockchaine, …"
|
||||||
returned = _back_reference(question, previous, engine=engine, limit=limit, complete=complete, deliver=deliver)
|
returned = _back_reference(question, previous, engine=engine, limit=limit, complete=complete, deliver=deliver)
|
||||||
if returned is not None:
|
if returned is not None:
|
||||||
@ -1226,26 +1369,34 @@ def _answer(question: str, *, engine: str, limit: int, context_token: str | None
|
|||||||
return {**_answer(question, engine=engine, limit=limit, context_token=None, complete=complete,
|
return {**_answer(question, engine=engine, limit=limit, context_token=None, complete=complete,
|
||||||
deliver=deliver), "_asked_as": [question]}
|
deliver=deliver), "_asked_as": [question]}
|
||||||
match = wiki_match(question)
|
match = wiki_match(question)
|
||||||
from tools.crzp.answering.context import CONTINUES
|
from tools.crzp.answering.context import CONTINUES, FOLLOW
|
||||||
from tools.crzp.source.parse import fold
|
from tools.crzp.source.parse import fold
|
||||||
continues = bool(CONTINUES.search(fold(question))) or len(words) <= 4
|
continues = bool(CONTINUES.search(fold(question)) or FOLLOW.search(fold(question))) or len(words) <= 4
|
||||||
if previous and previous.get("primary") == "crzp" and previous.get("crzp") and not match and continues:
|
if previous and previous.get("primary") == "crzp" and previous.get("crzp") and not match and continues:
|
||||||
# The last answer came from CRZP ("O čom je práca Jána Nováka?" -> "2", "a kto bol oponent?").
|
# 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
|
from tools.crzp.answering import answer as crzp
|
||||||
followed = crzp._answer(question, complete, context_token=previous["crzp"])
|
followed = crzp._answer(question, complete, context_token=previous["crzp"])
|
||||||
followed.pop("_shown", None), followed.pop("_asked", None), followed.pop("_options", None)
|
followed.pop("_shown", None), followed.pop("_asked", None), followed.pop("_options", None)
|
||||||
shown = followed.pop("_entities", None) or []
|
shown = followed.pop("_entities", None) or []
|
||||||
|
rest, offer = followed.pop("_rest", None), followed.pop("_offer", None)
|
||||||
if followed.get("accepted_for_delivery") is True:
|
if followed.get("accepted_for_delivery") is True:
|
||||||
from tools.answers.presentation.unified import strip_sources
|
from tools.answers.presentation.unified import strip_sources
|
||||||
body, urls = split_sources(strip_sources(clean_crzp(followed["answer"])))
|
body, urls = split_sources(strip_sources(clean_crzp(followed["answer"])))
|
||||||
urls = list(dict.fromkeys([*urls, *(followed.get("source_urls") or [])]))[:12]
|
urls = list(dict.fromkeys([*urls, *(followed.get("source_urls") or [])]))[:MAX_SOURCES]
|
||||||
result = {**followed, "answer": body + ("\n\nZdroje: " + ", ".join(urls) if urls else ""),
|
text = body + ("\n\nZdroje: " + ", ".join(urls) if urls else "")
|
||||||
|
page = None
|
||||||
|
if rest:
|
||||||
|
from tools.answers import pages
|
||||||
|
page = pages.put(rest, {"kind": "lines"})
|
||||||
|
text += "\n\n" + (offer or "Chceš vidieť ďalšie?") if page else ""
|
||||||
|
result = {**followed, "answer": text, "source_urls": urls,
|
||||||
"delivery_check": {**followed["delivery_check"], "request_fingerprint": fingerprint(question, engine)}}
|
"delivery_check": {**followed["delivery_check"], "request_fingerprint": fingerprint(question, engine)}}
|
||||||
token = (followed.get("conversation_context") or {}).get("token")
|
token = (followed.get("conversation_context") or {}).get("token")
|
||||||
result.pop("conversation_context", None)
|
result.pop("conversation_context", None)
|
||||||
entities = [{**e, "n": i} for i, e in enumerate(shown, 1)] or previous.get("entities", [])
|
entities = [{**e, "n": i} for i, e in enumerate(shown, 1)] or previous.get("entities", [])
|
||||||
return _with_token(result, entities=entities, question=question, crzp=token or previous["crzp"],
|
return _with_token(result, entities=entities, question=question, crzp=token or previous["crzp"],
|
||||||
primary="crzp")
|
primary="crzp", page=page)
|
||||||
person, student = (match["name"], match["student"]) if match else (None, True)
|
person, student = (match["name"], match["student"]) if match else (None, True)
|
||||||
started = time.monotonic()
|
started = time.monotonic()
|
||||||
pool = _pool()
|
pool = _pool()
|
||||||
@ -1320,7 +1471,8 @@ def needs_crzp(wiki: dict, probe: dict, person: str | None) -> bool:
|
|||||||
if mode is None or wiki.get("reason") in REFUSED:
|
if mode is None or wiki.get("reason") in REFUSED:
|
||||||
return False # CRZP adds nothing to this question, or it is out of scope
|
return False # CRZP adds nothing to this question, or it is out of scope
|
||||||
if wiki.get("status") == "ambiguous": # the wiki asks first, unless CRZP answers the question as a whole
|
if wiki.get("status") == "ambiguous": # the wiki asks first, unless CRZP answers the question as a whole
|
||||||
return person is None and wiki.get("reason") in WIKI_CLARIFICATION_YIELDS and mode in ("explicit", "unplanned")
|
return person is None and mode in ("explicit", "unplanned") and wiki.get("reason") in (
|
||||||
|
*WIKI_CLARIFICATION_YIELDS, "incomplete_person_name") # "samuel furda": CRZP may know the whole name
|
||||||
wiki_ok = wiki.get("accepted_for_delivery") is True and wiki.get("status") == "ok"
|
wiki_ok = wiki.get("accepted_for_delivery") is True and wiki.get("status") == "ok"
|
||||||
return mode == "explicit" or not wiki_ok
|
return mode == "explicit" or not wiki_ok
|
||||||
|
|
||||||
@ -1462,19 +1614,27 @@ def _compose(asked: str, question: str, engine: str, wiki: dict, part: dict | No
|
|||||||
"""One answer from the ZP Wiki result and the CRZP part."""
|
"""One answer from the ZP Wiki result and the CRZP part."""
|
||||||
from tools.answers.presentation.finalize import finalize
|
from tools.answers.presentation.finalize import finalize
|
||||||
low = normalized(question)
|
low = normalized(question)
|
||||||
if wiki.get("reason") in REFUSED or wiki.get("status") == "ambiguous" and (
|
named_in_crzp = crzp_names_the_person(question, wiki, part)
|
||||||
|
if wiki.get("reason") in REFUSED or wiki.get("status") == "ambiguous" and not named_in_crzp and (
|
||||||
person or wiki.get("reason") not in WIKI_CLARIFICATION_YIELDS):
|
person or wiki.get("reason") not in WIKI_CLARIFICATION_YIELDS):
|
||||||
part = None # refused/out of scope, or the wiki asks first (which person, which work): no CRZP
|
part = None # refused/out of scope, or the wiki asks first (which person, which work): no CRZP
|
||||||
wiki_ok = wiki.get("accepted_for_delivery") is True and wiki.get("status") == "ok"
|
wiki_ok = wiki.get("accepted_for_delivery") is True and wiki.get("status") == "ok"
|
||||||
if part is not None and part["mode"] == "explicit" and wiki.get("status") == "ambiguous":
|
if part is not None and part["mode"] == "explicit" and wiki.get("status") == "ambiguous":
|
||||||
wiki_ok = False
|
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"):
|
||||||
|
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):
|
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 = {**wiki, "answer": finalize(wiki["answer"], wiki.get("source_urls"))}
|
||||||
wiki_context = wiki.get("conversation_context")
|
wiki_context = wiki.get("conversation_context")
|
||||||
plan = wiki.pop("_plan", None) or {}
|
plan = wiki.pop("_plan", None) or {}
|
||||||
special = _unified(asked, question, engine, wiki, wiki_ok, part, person, wiki_context, plan)
|
if (part is not None and part["mode"] == "explicit" and part.get("status") == "ok" and part.get("text")
|
||||||
if special is not None:
|
and NAMED_CRZP.search(low)):
|
||||||
return special
|
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)
|
||||||
|
if special is not None:
|
||||||
|
return special
|
||||||
if part is None or wiki.get("status") == "ambiguous" and part["mode"] != "explicit":
|
if part is None or wiki.get("status") == "ambiguous" and part["mode"] != "explicit":
|
||||||
# (a wiki clarification such as "Uveď meno študenta" yields to a question CRZP answers as a whole)
|
# (a wiki clarification such as "Uveď meno študenta" yields to a question CRZP answers as a whole)
|
||||||
if wiki.get("accepted_for_delivery") is not True:
|
if wiki.get("accepted_for_delivery") is not True:
|
||||||
@ -1502,12 +1662,13 @@ def _compose(asked: str, question: str, engine: str, wiki: dict, part: dict | No
|
|||||||
delivery_check={"layer": "planning", "code": "clarification_required",
|
delivery_check={"layer": "planning", "code": "clarification_required",
|
||||||
"request_fingerprint": fingerprint(question, engine)})
|
"request_fingerprint": fingerprint(question, engine)})
|
||||||
return _with_token(result, wiki_context=wiki_context, options=options, question=question)
|
return _with_token(result, wiki_context=wiki_context, options=options, question=question)
|
||||||
if part["mode"] == "explicit" and part.get("status") == "ambiguous": # CRZP asks which namesake
|
if part["mode"] == "explicit" and part.get("status") == "ambiguous": # CRZP asks which namesake or which work
|
||||||
result = _ok(question, engine, part["text"], [], wiki if wiki_ok else {"index_version": wiki.get("index_version")})
|
result = _ok(question, engine, part["text"], [], wiki if wiki_ok else {"index_version": wiki.get("index_version")})
|
||||||
result.update(status="ambiguous", reason="clarification_required",
|
result.update(status="ambiguous", reason="clarification_required",
|
||||||
delivery_check={"layer": "planning", "code": "clarification_required",
|
delivery_check={"layer": "planning", "code": "clarification_required",
|
||||||
"request_fingerprint": fingerprint(question, engine)})
|
"request_fingerprint": fingerprint(question, engine)})
|
||||||
return _with_token(result, question=question, crzp=part.get("crzp_token"), primary="crzp")
|
return _with_token(result, question=question, crzp=part.get("crzp_token"), primary="crzp",
|
||||||
|
options=part.get("options") or ())
|
||||||
if part.get("home_excluded"):
|
if part.get("home_excluded"):
|
||||||
wiki_ok = False
|
wiki_ok = False
|
||||||
base = wiki if wiki_ok else {"index_version": wiki.get("index_version")}
|
base = wiki if wiki_ok else {"index_version": wiki.get("index_version")}
|
||||||
@ -1530,7 +1691,7 @@ def _compose(asked: str, question: str, engine: str, wiki: dict, part: dict | No
|
|||||||
return _with_token(_ok(question, engine, text, urls, base), wiki_context=wiki_context, question=question,
|
return _with_token(_ok(question, engine, text, urls, base), wiki_context=wiki_context, question=question,
|
||||||
entities=[entity(item, i) for i, item in enumerate(shown, 1)], page=page_id)
|
entities=[entity(item, i) for i, item in enumerate(shown, 1)], page=page_id)
|
||||||
crzp_body, crzp_urls = split_sources(part["text"])
|
crzp_body, crzp_urls = split_sources(part["text"])
|
||||||
crzp_urls = list(dict.fromkeys([*crzp_urls, *part.get("urls", [])]))[:12]
|
crzp_urls = list(dict.fromkeys([*crzp_urls, *part.get("urls", [])]))[:MAX_SOURCES]
|
||||||
entities = [{**e, "n": i} for i, e in enumerate(part.get("entities") or [], 1)]
|
entities = [{**e, "n": i} for i, e in enumerate(part.get("entities") or [], 1)]
|
||||||
if wiki_ok: # a list of wiki people ("Koho vedie X?") is paged; the CRZP part follows the first page
|
if wiki_ok: # a list of wiki people ("Koho vedie X?") is paged; the CRZP part follows the first page
|
||||||
head, items, tail, general = wiki_items(wiki_body, wiki_urls)
|
head, items, tail, general = wiki_items(wiki_body, wiki_urls)
|
||||||
@ -1558,11 +1719,29 @@ def _compose(asked: str, question: str, engine: str, wiki: dict, part: dict | No
|
|||||||
urls = list(dict.fromkeys([*wiki_urls, *crzp_urls]))
|
urls = list(dict.fromkeys([*wiki_urls, *crzp_urls]))
|
||||||
if urls:
|
if urls:
|
||||||
text += "\n\nZdroje: " + ", ".join(urls)
|
text += "\n\nZdroje: " + ", ".join(urls)
|
||||||
|
page = None
|
||||||
|
if part.get("rest"): # "Chceš vidieť ďalších?": the rest of a ranking, shown on "áno"
|
||||||
|
from tools.answers import pages
|
||||||
|
page = pages.put(part["rest"], {"kind": "lines"})
|
||||||
|
if page:
|
||||||
|
text += "\n\n" + (part.get("offer") or "Chceš vidieť ďalšie?")
|
||||||
result = _ok(question, engine, text, urls, base)
|
result = _ok(question, engine, text, urls, base)
|
||||||
return _with_token(result, wiki_context=wiki_context, entities=entities, question=question,
|
return _with_token(result, wiki_context=wiki_context, entities=entities, question=question, page=page,
|
||||||
crzp=part.get("crzp_token"), primary="crzp" if part["mode"] == "explicit" and not wiki_ok else "wiki")
|
crzp=part.get("crzp_token"), primary="crzp" if part["mode"] == "explicit" and not wiki_ok else "wiki")
|
||||||
|
|
||||||
|
|
||||||
|
def crzp_names_the_person(question: str, wiki: dict, part: dict | None) -> bool:
|
||||||
|
"""The wiki asks which person ("Meno „samuel“ nie je jednoznačné") or does not know the name, while
|
||||||
|
CRZP found a person whose whole name (first name and surname) is in the question: CRZP answers."""
|
||||||
|
from tools.crzp.answering.understand import in_question
|
||||||
|
if not part or part.get("mode") != "explicit" or part.get("status") not in ("ok", "ambiguous") or not part.get("person"):
|
||||||
|
return False
|
||||||
|
if wiki.get("reason") not in ("incomplete_person_name", "unknown_person"):
|
||||||
|
return False
|
||||||
|
name = part["person"]
|
||||||
|
return len(name.split()) >= 2 and in_question(name, question)
|
||||||
|
|
||||||
|
|
||||||
def _work_options(person: str, part: dict, low: str) -> list[dict]:
|
def _work_options(person: str, part: dict, low: str) -> list[dict]:
|
||||||
"""The person's works when the two sources hold works of different types and the question names none."""
|
"""The person's works when the two sources hold works of different types and the question names none."""
|
||||||
if re.search(r"\b(?:bakalar\w*|diplom\w*|dizerta\w*|projekt\w*)\b", low):
|
if re.search(r"\b(?:bakalar\w*|diplom\w*|dizerta\w*|projekt\w*)\b", low):
|
||||||
|
|||||||
@ -599,8 +599,19 @@ def methods(person: str, works: list[dict], wiki_text: str, crzp_text: str, low:
|
|||||||
|
|
||||||
|
|
||||||
def backlog_of(person: str, when: str) -> list[str]:
|
def backlog_of(person: str, when: str) -> list[str]:
|
||||||
"""The points under "Zásobník úloh:" in the record of the meeting of that date: the profile text from
|
"""The points under "Zásobník úloh:" of the meeting of that date (meeting_section)."""
|
||||||
"Stretnutie 27.10.2026" to the next meeting or heading; [] when that meeting has none."""
|
return meeting_section(person, when, r"Zásobník úloh[^:\n]*")
|
||||||
|
|
||||||
|
|
||||||
|
def tasks_of(person: str, when: str) -> list[str]:
|
||||||
|
"""The points under "Úlohy:" of the meeting of that date, as the profile writes them (never the "Stav:"
|
||||||
|
points, which are the progress, and never the backlog)."""
|
||||||
|
return meeting_section(person, when, r"Úlohy(?:\s*\([^)\n]*\))?")
|
||||||
|
|
||||||
|
|
||||||
|
def meeting_section(person: str, when: str, label: str) -> list[str]:
|
||||||
|
"""The points under a section label in the record of the meeting of that date: the profile text from
|
||||||
|
"Stretnutie 27.10.2026" to the next meeting or heading; [] when that meeting has no such section."""
|
||||||
match = re.fullmatch(r"(\d{1,2})\.(\d{1,2})\.(\d{4})", when)
|
match = re.fullmatch(r"(\d{1,2})\.(\d{1,2})\.(\d{4})", when)
|
||||||
if not match:
|
if not match:
|
||||||
return []
|
return []
|
||||||
@ -614,15 +625,13 @@ def backlog_of(person: str, when: str) -> list[str]:
|
|||||||
rest = text[start + len(marker["text"].strip()):]
|
rest = text[start + len(marker["text"].strip()):]
|
||||||
stop = re.search(r"\n\s*(?:(?:Virtuálne\s+)?[Ss]tretnutie\b|#)", rest)
|
stop = re.search(r"\n\s*(?:(?:Virtuálne\s+)?[Ss]tretnutie\b|#)", rest)
|
||||||
block = rest[:stop.start()] if stop else rest
|
block = rest[:stop.start()] if stop else rest
|
||||||
section = re.search(r"Zásobník úloh[^:\n]*:\s*\n((?:\s*[-*+].*(?:\n|$)|\s*\n)+)", block)
|
points = [] # the index text joins overlapping chunks: a section may be cut in one and whole in the next
|
||||||
if not section:
|
for section in re.finditer(r"(?m)^\s*" + label + r":\s*\n((?:\s*[-*+].*(?:\n|$)|\s*\n)+)", block):
|
||||||
return []
|
for line in section.group(1).splitlines():
|
||||||
points = []
|
if line.strip().startswith(("-", "*", "+")):
|
||||||
for line in section.group(1).splitlines():
|
point = clean_point(line)
|
||||||
if line.strip().startswith(("-", "*", "+")):
|
if point and point not in points:
|
||||||
point = clean_point(line)
|
points.append(point)
|
||||||
if point and point not in points:
|
|
||||||
points.append(point)
|
|
||||||
return points
|
return points
|
||||||
|
|
||||||
|
|
||||||
@ -630,9 +639,18 @@ def meeting(person: str, text: str, low: str, follow_up: bool) -> str | None:
|
|||||||
"""A meeting record: "X na poslednom stretnutí 16. 10. 2026 riešil:" and its points."""
|
"""A meeting record: "X na poslednom stretnutí 16. 10. 2026 riešil:" and its points."""
|
||||||
date = re.search(r"(?:Posledný záznam s úplným dátumom|Podľa zápisu zo stretnutia|Úlohy zo stretnutia|"
|
date = re.search(r"(?:Posledný záznam s úplným dátumom|Podľa zápisu zo stretnutia|Úlohy zo stretnutia|"
|
||||||
r"stretnutia|stretnutie)\s*:?\s*(\d{4}-\d{2}-\d{2}|\d{1,2}\.\s*\d{1,2}\.\s*(?:\d{4})?)", text)
|
r"stretnutia|stretnutie)\s*:?\s*(\d{4}-\d{2}-\d{2}|\d{1,2}\.\s*\d{1,2}\.\s*(?:\d{4})?)", text)
|
||||||
if not date:
|
if date:
|
||||||
|
when = day(date.group(1).strip())
|
||||||
|
elif TASKS_Q.search(low) or re.search(r"\bposledn\w*", low): # the wiki text names no date: the newest meeting
|
||||||
|
dates = sorted((u.get("record_date") or u.get("date") or "") for u in units(person) if u.get("kind") == "meeting")
|
||||||
|
dates = [d for d in dates if re.fullmatch(r"\d{4}-\d{2}-\d{2}", d)]
|
||||||
|
if not dates:
|
||||||
|
return None
|
||||||
|
when = day(dates[-1])
|
||||||
|
if TASKS_Q.search(low) and (tasks_of(person, when) or backlog_of(person, when)):
|
||||||
|
text = "" # the record's own sections answer it (below)
|
||||||
|
else:
|
||||||
return None
|
return None
|
||||||
when = day(date.group(1).strip())
|
|
||||||
done, todo = [], []
|
done, todo = [], []
|
||||||
section = None
|
section = None
|
||||||
for raw in text.splitlines():
|
for raw in text.splitlines():
|
||||||
@ -649,7 +667,7 @@ def meeting(person: str, text: str, low: str, follow_up: bool) -> str | None:
|
|||||||
point = clean_point(line)
|
point = clean_point(line)
|
||||||
if point:
|
if point:
|
||||||
(todo if is_task else done).append(point)
|
(todo if is_task else done).append(point)
|
||||||
if not done and not todo:
|
if not done and not todo and not (TASKS_Q.search(low) and (tasks_of(person, when) or backlog_of(person, when))):
|
||||||
return None
|
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):
|
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) \
|
return f"Posledné stretnutie {genitive(person)} bolo {when}." if re.search(r"\bposledn", low) \
|
||||||
@ -658,11 +676,14 @@ def meeting(person: str, text: str, low: str, follow_up: bool) -> str | None:
|
|||||||
last = "poslednom " if re.search(r"\bposledn\w*", low) or follow_up else ""
|
last = "poslednom " if re.search(r"\bposledn\w*", low) or follow_up else ""
|
||||||
backlog = backlog_of(person, when)
|
backlog = backlog_of(person, when)
|
||||||
stack = ("\n\n" + f"Do zásobníka úloh zo stretnutia {when} patrí:\n\n" + "\n".join(f"- {p}" for p in backlog)) if backlog else ""
|
stack = ("\n\n" + f"Do zásobníka úloh zo stretnutia {when} patrí:\n\n" + "\n".join(f"- {p}" for p in backlog)) if backlog else ""
|
||||||
|
todo = tasks_of(person, when) or todo # the record's own "Úlohy:" points first
|
||||||
if tasks_only:
|
if tasks_only:
|
||||||
|
if not todo: # the progress ("Stav:") is never given out as tasks
|
||||||
|
none = f"Pri stretnutí {when} nie sú zapísané úlohy."
|
||||||
|
return none + stack if stack else none
|
||||||
head = (f"Na stretnutí {when} dostal{ending(person)} tieto úlohy:" if follow_up
|
head = (f"Na stretnutí {when} dostal{ending(person)} tieto úlohy:" if follow_up
|
||||||
else f"{spelled(person)} dostal{ending(person)} na {last}stretnutí {when} tieto úlohy:")
|
else f"{spelled(person)} dostal{ending(person)} na {last}stretnutí {when} tieto úlohy:")
|
||||||
points = todo or done
|
return head + "\n\n" + "\n".join(f"- {p}" for p in todo) + stack
|
||||||
return head + "\n\n" + "\n".join(f"- {p}" for p in points) + stack
|
|
||||||
out = [f"{spelled(person)} na {last}stretnutí {when} riešil{ending(person)}:", "", *[f"- {p}" for p in done]]
|
out = [f"{spelled(person)} na {last}stretnutí {when} riešil{ending(person)}:", "", *[f"- {p}" for p in done]]
|
||||||
if todo and not done:
|
if todo and not done:
|
||||||
out = [f"Na {last}stretnutí {when} dostal{ending(person)} {spelled(person)} tieto úlohy:", "", *[f"- {p}" for p in todo]]
|
out = [f"Na {last}stretnutí {when} dostal{ending(person)} {spelled(person)} tieto úlohy:", "", *[f"- {p}" for p in todo]]
|
||||||
|
|||||||
@ -32,8 +32,11 @@ from tools.crzp.storage import graph
|
|||||||
ENGINE = "crzp"
|
ENGINE = "crzp"
|
||||||
LIST_LIMIT = 30
|
LIST_LIMIT = 30
|
||||||
ROLE_FIELD = {"author": "authors", "supervisor": "supervisors", "opponent": "opponents"}
|
ROLE_FIELD = {"author": "authors", "supervisor": "supervisors", "opponent": "opponents"}
|
||||||
ROLE_LABEL = {"author": "autor", "supervisor": "školiteľ", "opponent": "oponent"}
|
ROLE_LABEL = {"author": "autor", "supervisor": "vedúci", "opponent": "oponent"}
|
||||||
ROLE_PLURAL = {"author": "Autori", "supervisor": "Školitelia", "opponent": "Oponenti"}
|
ROLE_PLURAL = {"author": "Autori", "supervisor": "Vedúci", "opponent": "Oponenti"}
|
||||||
|
# Extra results of one answer (the not shown rest of a ranking, the people it shows), set by the handlers.
|
||||||
|
import contextvars as _contextvars
|
||||||
|
_extras: _contextvars.ContextVar[dict | None] = _contextvars.ContextVar("crzp_answer_extras", default=None)
|
||||||
FACET = {"author": "Autor", "supervisor": "Školiteľ"}
|
FACET = {"author": "Autor", "supervisor": "Školiteľ"}
|
||||||
_cache: OrderedDict = OrderedDict()
|
_cache: OrderedDict = OrderedDict()
|
||||||
_cache_lock = threading.Lock()
|
_cache_lock = threading.Lock()
|
||||||
@ -216,9 +219,10 @@ def identities(rows: list[dict], person) -> list[dict]:
|
|||||||
groups: dict = {}
|
groups: dict = {}
|
||||||
seen = set()
|
seen = set()
|
||||||
for row in rows:
|
for row in rows:
|
||||||
if work_key(row) in seen:
|
held = (work_key(row), tuple(sorted(fold(a) for a in row.get("authors", []))))
|
||||||
continue # the same work held twice in CRZP
|
if held in seen:
|
||||||
seen.add(work_key(row))
|
continue # the same work held twice in CRZP (two students of one title and year are two works)
|
||||||
|
seen.add(held)
|
||||||
for name in people_in_role(row, person.name, person.role):
|
for name in people_in_role(row, person.name, person.role):
|
||||||
key = (display_name(name), university(row))
|
key = (display_name(name), university(row))
|
||||||
group = groups.setdefault(key, {"name": key[0], "school": key[1], "count": 0, "years": set(),
|
group = groups.setdefault(key, {"name": key[0], "school": key[1], "count": 0, "years": set(),
|
||||||
@ -247,12 +251,22 @@ def identities(rows: list[dict], person) -> list[dict]:
|
|||||||
|
|
||||||
|
|
||||||
def _identity_line(group: dict) -> str:
|
def _identity_line(group: dict) -> str:
|
||||||
|
""""Lukáš Juhás — Technická univerzita v Košiciach, FEI, KEMT (autor; 2012; 1 práca: „Návrh a …“)": the
|
||||||
|
faculty or department and the newest work tell two namesakes of one school apart."""
|
||||||
years = sorted(y for y in group["years"] if y)
|
years = sorted(y for y in group["years"] if y)
|
||||||
span = (f"{years[0]}–{years[-1]}" if len(years) > 1 else str(years[0])) if years else "rok neuvedený"
|
span = (f"{years[0]}–{years[-1]}" if len(years) > 1 else str(years[0])) if years else "rok neuvedený"
|
||||||
roles = ", ".join(ROLE_LABEL[r] for r, _ in group["roles"].most_common())
|
roles = ", ".join(ROLE_LABEL[r] for r, _ in group["roles"].most_common())
|
||||||
works = f"{group['count']} {'práca' if group['count'] == 1 else 'práce' if group['count'] < 5 else 'prác'}"
|
works = f"{group['count']} {'práca' if group['count'] == 1 else 'práce' if group['count'] < 5 else 'prác'}"
|
||||||
hint = f"; {group['hint']}" if group.get("hint") else ""
|
hint = f"; {group['hint']}" if group.get("hint") else ""
|
||||||
return f"{group['name']} — {group['school']} ({roles}; {span}; {works}{hint})"
|
newest = max(group["rows"], key=lambda r: r.get("year") or 0) if group.get("rows") else None
|
||||||
|
place = group["school"]
|
||||||
|
if newest:
|
||||||
|
unit = unit_label(newest) if group["school"] == "Technická univerzita v Košiciach" else \
|
||||||
|
_faculty(newest.get("school") or "", group["school"]).strip(" ,")
|
||||||
|
place += f", {unit}" if unit else ""
|
||||||
|
title = newest["title"] if len(newest["title"]) <= 60 else newest["title"][:57].rstrip() + "…"
|
||||||
|
works += f": „{title}“"
|
||||||
|
return f"{group['name']} — {place} ({roles}; {span}; {works}{hint})"
|
||||||
|
|
||||||
|
|
||||||
def namesakes(rows: list[dict], query: CrzpQuery) -> str:
|
def namesakes(rows: list[dict], query: CrzpQuery) -> str:
|
||||||
@ -338,7 +352,7 @@ def reader(query: CrzpQuery):
|
|||||||
return lambda text: fetch.search(text, links=False, depth=20, **window)
|
return lambda text: fetch.search(text, links=False, depth=20, **window)
|
||||||
if query.intent in ("keywords", "schools", "count"):
|
if query.intent in ("keywords", "schools", "count"):
|
||||||
return lambda text: fetch.search_deep(text, links=False, **window)
|
return lambda text: fetch.search_deep(text, links=False, **window)
|
||||||
if query.intent == "relation" or query.people:
|
if query.intent in ("relation", "sources") or query.people: # a ranking and its works read every row
|
||||||
return lambda text: fetch.search_deep(text, links=True, **window)
|
return lambda text: fetch.search_deep(text, links=True, **window)
|
||||||
if query.intent == "list" and (query.school or query.unit) and not query.topics and not query.title:
|
if query.intent == "list" and (query.school or query.unit) and not query.topics and not query.title:
|
||||||
return lambda text: fetch.search_deep(text, links=True, limit=fetch.LINKED_ROWS, **window)
|
return lambda text: fetch.search_deep(text, links=True, limit=fetch.LINKED_ROWS, **window)
|
||||||
@ -459,7 +473,8 @@ def school(row: dict) -> str:
|
|||||||
def work_block(row: dict, detail: dict | None = None) -> str:
|
def work_block(row: dict, detail: dict | None = None) -> str:
|
||||||
record = detail or row
|
record = detail or row
|
||||||
head = f"**{record['title']}** — {_kind(record)}, {record.get('year') or 'rok neuvedený'}, {school(record)}"
|
head = f"**{record['title']}** — {_kind(record)}, {record.get('year') or 'rok neuvedený'}, {school(record)}"
|
||||||
lines = [head, f"- Autor: {_names(record.get('authors', []))}; školiteľ: {_names(record.get('supervisors', []))}; "
|
lead = "školiteľ" if record.get("work_type") in ("dissertation", "doctoral_thesis") else "vedúci"
|
||||||
|
lines = [head, f"- Autor: {_names(record.get('authors', []))}; {lead}: {_names(record.get('supervisors', []))}; "
|
||||||
f"oponent: {_names(record.get('opponents', []))}"]
|
f"oponent: {_names(record.get('opponents', []))}"]
|
||||||
if detail and detail.get("consultants"):
|
if detail and detail.get("consultants"):
|
||||||
lines.append(f"- Konzultant: {_names(detail['consultants'])}")
|
lines.append(f"- Konzultant: {_names(detail['consultants'])}")
|
||||||
@ -574,8 +589,11 @@ def _keyword_sentence(detail: dict) -> str:
|
|||||||
|
|
||||||
# ------------------------------------------------------------------ answers by intent
|
# ------------------------------------------------------------------ answers by intent
|
||||||
|
|
||||||
def _list(question, query, found, rows) -> tuple[str, list[dict]]:
|
def _list(question, query, found, rows, complete=None) -> tuple[str, list[dict]]:
|
||||||
rows = ranked(question, query, rows)
|
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)
|
||||||
limit = query.show or LIST_LIMIT
|
limit = query.show or LIST_LIMIT
|
||||||
if query.show: # "vypíš prvých 8": the newest first
|
if query.show: # "vypíš prvých 8": the newest first
|
||||||
rows = sorted(rows, key=lambda r: -(r.get("year") or 0))
|
rows = sorted(rows, key=lambda r: -(r.get("year") or 0))
|
||||||
@ -585,13 +603,29 @@ def _list(question, query, found, rows) -> tuple[str, list[dict]]:
|
|||||||
newest = not query.topics and not query.title and not query.people
|
newest = not query.topics and not query.title and not query.people
|
||||||
header = (f"Hľadaniu zodpovedá {found['total']} výsledkov ({describe(query)}); prehľadaných bolo "
|
header = (f"Hľadaniu zodpovedá {found['total']} výsledkov ({describe(query)}); prehľadaných bolo "
|
||||||
f"{len(found['rows'])} {'najnovších' if newest else 'najrelevantnejších'}, z nich zodpovedá {len(rows)}:")
|
f"{len(found['rows'])} {'najnovších' if newest else 'najrelevantnejších'}, z nich zodpovedá {len(rows)}:")
|
||||||
|
note = f"\n\nĎalších {plural(hidden)} tento pojem len spomína, nie sú uvedené." if hidden else ""
|
||||||
if len(rows) <= 5 and not query.show:
|
if len(rows) <= 5 and not query.show:
|
||||||
return header + "\n\n" + "\n\n".join(work_block(r) for r in rows), rows
|
return header + "\n\n" + "\n\n".join(work_block(r) for r in rows) + note, rows
|
||||||
shown = rows[:limit]
|
shown = rows[:limit]
|
||||||
text = header + "\n\n" + "\n".join(work_line(r) for r in shown)
|
text = header + "\n\n" + "\n".join(work_line(r) for r in shown)
|
||||||
if len(rows) > limit and not query.show:
|
if len(rows) > limit and not query.show:
|
||||||
text += f"\n\nZobrazených je {limit} z {len(rows)}; spresni rok, typ práce alebo tému."
|
text += f"\n\nZobrazených je {limit} z {len(rows)}; spresni rok, typ práce alebo tému."
|
||||||
return text, shown
|
return text + note, shown
|
||||||
|
|
||||||
|
|
||||||
|
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]:
|
||||||
|
"""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]
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
TYPE_FACET = {"bakalárska": "bakalárska práca", "diplomová": "diplomová práca", "dizertačná": "dizertačná práca",
|
TYPE_FACET = {"bakalárska": "bakalárska práca", "diplomová": "diplomová práca", "dizertačná": "dizertačná práca",
|
||||||
@ -622,44 +656,106 @@ def _count(question, query, found, rows) -> tuple[str, list[dict]]:
|
|||||||
else:
|
else:
|
||||||
note = f" (aspoň; prehľadaných {len(found['rows'])} z {found['total']} výsledkov hľadania)"
|
note = f" (aspoň; prehľadaných {len(found['rows'])} z {found['total']} výsledkov hľadania)"
|
||||||
text = f"Počet prác ({describe(query)}): **{count}**{note}." + unpublished_note(found, query)
|
text = f"Počet prác ({describe(query)}): **{count}**{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) <= 1:
|
defended_place = query.published and not query.people and not query.topics and (query.unit or query.school) \
|
||||||
# "Koľko diplomových prác obhájili na KEMT v roku 2022?" -> one sentence
|
and len(query.work_types) <= 1
|
||||||
def of(name): # "Technická univerzita v Košiciach" -> "Technickej univerzity v Košiciach"
|
if defended_place: # "Koľko diplomových prác obhájili na KEMT v roku 2022?" -> one sentence
|
||||||
head, _, town = name.partition(" v ")
|
|
||||||
words = [w[:-1] + "ej" if w.endswith("á") else w[:-1] + "y" if w.endswith("a") else w for w in head.split()]
|
|
||||||
return " ".join(words) + (" v " + town if town else "")
|
|
||||||
place = (UNITS[query.unit]["label"] + " " + of(SCHOOLS[query.school][0])) if query.unit else of(SCHOOLS[query.school][0])
|
|
||||||
kind = WORK_TYPE_LABELS[query.work_types[0]] if query.work_types else "záverečná práca"
|
|
||||||
words = kind.split()
|
|
||||||
def form(word, long, short): # rhythmic law: "diplomových", but "bakalárskych" after a long syllable
|
|
||||||
stem = word[:-1]
|
|
||||||
return stem + (short if re.search(r"[áéíóúýô]", stem[-4:]) else long)
|
|
||||||
many = " ".join([form(w, "ých", "ych") if w.endswith(("á", "a")) else w for w in words[:-1]] + ["prác"])
|
|
||||||
few = " ".join([form(w, "é", "e") if w.endswith(("á", "a")) else w for w in words[:-1]] + ["práce"])
|
|
||||||
what = kind if count == 1 else few if 2 <= count <= 4 else many
|
|
||||||
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 "")
|
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}{when} obhájili {count} {what}{note}." + unpublished_note(found, query)
|
text = f"Na {_place(query)}{when} obhájili {works_phrase(count, query.work_types)}{note}." + unpublished_note(found, query)
|
||||||
|
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
|
||||||
|
first, second = asked_years
|
||||||
|
a, b = years.get(first, 0), years.get(second, 0)
|
||||||
|
change = "teda rovnako" if a == b else f"teda o {abs(b - a)} {'viac' if b > a else 'menej'}"
|
||||||
|
if defended_place:
|
||||||
|
text = f"Na {_place(query)} obhájili v roku {first} {works_phrase(a, query.work_types)} a v roku {second} {b}, {change}"
|
||||||
|
elif person and len(query.people) == 1:
|
||||||
|
from tools.answers.presentation.unified import female
|
||||||
|
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}")
|
||||||
|
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)
|
||||||
|
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)
|
||||||
|
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 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()) + ")"
|
||||||
|
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 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
|
if count and len(types) > 1: # one asked type or year needs no breakdown
|
||||||
text += "\n\n- Podľa typu: " + ", ".join(f"{k} {v}" for k, v in types.most_common())
|
text += "\n\n- Podľa typu: " + ", ".join(f"{k} {v}" for k, v in types.most_common())
|
||||||
if count and len(years) > 1:
|
if count and len(years) > 1 and not compare:
|
||||||
text += ("\n" if len(types) > 1 else "\n\n") + "- Podľa roku: " + ", ".join(
|
text += ("\n" if len(types) > 1 else "\n\n") + "- Podľa roku: " + ", ".join(
|
||||||
f"{y}: {n}" for y, n in sorted(years.items(), reverse=True))
|
f"{y}: {n}" for y, n in sorted(years.items(), reverse=True))
|
||||||
return text, rows
|
return text, counted_sources(rows)
|
||||||
|
|
||||||
|
|
||||||
|
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)."""
|
||||||
|
return sorted(rows, key=lambda r: -(r.get("year") or 0))[:10] if len(rows) <= 10 else []
|
||||||
|
|
||||||
|
|
||||||
|
# "o koľko viac", "rozdiel", "koľko v 2024 a koľko v 2025", "a v roku 2024": each of two years and the change
|
||||||
|
COMPARE = re.compile(r"\bo\s+kolko\b|\brozdiel\w*|\bviac\b|\bmenej\b|\bporovn\w*|\boproti\b|\bnez\b|\bako\s+v\b"
|
||||||
|
r"|\ba\s+(?:kolko\s+)?(?:bolo\s+)?v\s+(?:roku\s+)?(?:19|20)\d\d|\ba\s+kolko\b")
|
||||||
|
|
||||||
|
|
||||||
|
def _of(name: str) -> str:
|
||||||
|
""""Technická univerzita v Košiciach" -> "Technickej univerzity v Košiciach" (genitive)."""
|
||||||
|
head, _, town = name.partition(" v ")
|
||||||
|
words = [w[:-1] + "ej" if w.endswith("á") else w[:-1] + "y" if w.endswith("a") else w for w in head.split()]
|
||||||
|
return " ".join(words) + (" v " + town if town else "")
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
def works_phrase(count: int, work_types: list[str]) -> str:
|
||||||
|
""""1 diplomovú prácu", "3 bakalárske práce", "34 diplomových prác" (the object of "obhájili", "viedol")."""
|
||||||
|
kind = WORK_TYPE_LABELS[work_types[0]] if len(work_types) == 1 else "záverečná práca"
|
||||||
|
words = kind.split()
|
||||||
|
|
||||||
|
def form(word, long, short): # rhythmic law: "diplomových", but "bakalárskych" after a long syllable
|
||||||
|
stem = word[:-1]
|
||||||
|
return stem + (short if re.search(r"[áéíóúýô]", stem[-4:]) else long)
|
||||||
|
adjectives = words[:-1]
|
||||||
|
if count == 1:
|
||||||
|
return "1 " + " ".join([w[:-1] + "ú" if w.endswith("á") else w[:-1] + "u" if w.endswith("a") else w
|
||||||
|
for w in adjectives] + ["prácu"])
|
||||||
|
if 2 <= count <= 4:
|
||||||
|
return f"{count} " + " ".join([form(w, "é", "e") if w.endswith(("á", "a")) else w for w in adjectives] + ["práce"])
|
||||||
|
return f"{count} " + " ".join([form(w, "ých", "ych") if w.endswith(("á", "a")) else w for w in adjectives] + ["prác"])
|
||||||
|
|
||||||
|
|
||||||
def _about(question, query, found, rows, complete=None) -> tuple[str, list[dict]]:
|
def _about(question, query, found, rows, complete=None) -> tuple[str, list[dict]]:
|
||||||
candidates = rows
|
|
||||||
unique, seen = [], set()
|
unique, seen = [], set()
|
||||||
for row in ranked(question, query, rows): # CRZP sometimes holds one work twice (two records)
|
for row in ranked(question, query, rows): # CRZP sometimes holds one work twice (two records)
|
||||||
key = (fold(row["title"]).rstrip(" ."), row.get("year"), tuple(row.get("authors", [])))
|
key = (fold(row["title"]).rstrip(" ."), row.get("year"), tuple(row.get("authors", [])))
|
||||||
if key not in seen:
|
if key not in seen:
|
||||||
seen.add(key)
|
seen.add(key)
|
||||||
unique.append(row)
|
unique.append(row)
|
||||||
rows = unique[:2]
|
unique = resubmissions(unique) if len(unique) > 1 else unique
|
||||||
details = [fetch.detail(row["sid"]) if row.get("sid") else None for row in rows]
|
if len(unique) <= ABOUT_ALL: # "o čom boli?" about the 4 works of a count: all of them, newest first
|
||||||
# The model summaries (and their checks) of the two works run at the same time.
|
rows = sorted(unique, key=lambda r: -(r.get("year") or 0))
|
||||||
|
else: # many works: the most relevant ones, newest first
|
||||||
|
rows = sorted(unique[:ABOUT_ALL], key=lambda r: -(r.get("year") or 0))
|
||||||
|
# The records and the model summaries (and their checks) run two at a time (the model has two slots).
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||||
|
details = list(pool.map(lambda r: fetch.detail(r["sid"]) if r.get("sid") else None, rows))
|
||||||
summaries = list(pool.map(lambda d: summary(d, complete) if d else None, details))
|
summaries = list(pool.map(lambda d: summary(d, complete) if d else None, details))
|
||||||
blocks = []
|
blocks = []
|
||||||
for row, detail, done in zip(rows, details, summaries):
|
for row, detail, done in zip(rows, details, summaries):
|
||||||
@ -672,11 +768,15 @@ def _about(question, query, found, rows, complete=None) -> tuple[str, list[dict]
|
|||||||
continue
|
continue
|
||||||
_, text = done
|
_, text = done
|
||||||
blocks.append(head + f"\n\n{text}\n\nZdroj: {_link(row)}")
|
blocks.append(head + f"\n\n{text}\n\nZdroj: {_link(row)}")
|
||||||
more = len(candidates) > len(rows)
|
more = len(unique) > len(rows)
|
||||||
tail = "\n\nZodpovedá viac prác; zobrazené sú najrelevantnejšie. Spresni typ práce alebo rok." if more else ""
|
tail = (f"\n\nZodpovedá {plural(len(unique))}; zhrnutých je {len(rows)} najrelevantnejších. Spresni typ práce, "
|
||||||
|
"rok alebo tému." if more else "")
|
||||||
return "\n\n".join(blocks) + tail, rows
|
return "\n\n".join(blocks) + tail, rows
|
||||||
|
|
||||||
|
|
||||||
|
ABOUT_ALL = 8 # "o čom boli?": up to this many works are all summarized
|
||||||
|
|
||||||
|
|
||||||
def _keywords(question, query, found, rows) -> tuple[str, list[dict]]:
|
def _keywords(question, query, found, rows) -> tuple[str, list[dict]]:
|
||||||
rows = ranked(question, query, rows)
|
rows = ranked(question, query, rows)
|
||||||
if len(rows) <= 3:
|
if len(rows) <= 3:
|
||||||
@ -690,8 +790,24 @@ def _keywords(question, query, found, rows) -> tuple[str, list[dict]]:
|
|||||||
rows)
|
rows)
|
||||||
|
|
||||||
|
|
||||||
ROLE_INSTRUMENTAL = {"author": ("Autorom", "Autormi", "Autorkou"), "supervisor": ("Školiteľom", "Školiteľmi", "Školiteľkou"),
|
ROLE_INSTRUMENTAL = {"author": ("Autorom", "Autormi", "Autorkou"), "supervisor": ("Vedúcim", "Vedúcimi", "Vedúcou"),
|
||||||
"opponent": ("Oponentom", "Oponentmi", "Oponentkou")}
|
"opponent": ("Oponentom", "Oponentmi", "Oponentkou")}
|
||||||
|
DOCTORAL = ("Školiteľom", "Školiteľmi", "Školiteľkou") # a dissertation has a "školiteľ", a thesis a "vedúci"
|
||||||
|
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",
|
||||||
|
"Univerzita Komenského v Bratislave": "UK v Bratislave",
|
||||||
|
"Univerzita Pavla Jozefa Šafárika v Košiciach": "UPJŠ v Košiciach", "Žilinská univerzita v Žiline": "UNIZA",
|
||||||
|
"Univerzita Mateja Bela v Banskej Bystrici": "UMB v Banskej Bystrici",
|
||||||
|
"Ekonomická univerzita v Bratislave": "EU v Bratislave", "Prešovská univerzita v Prešove": "PU v Prešove",
|
||||||
|
"Univerzita Konštantína Filozofa v Nitre": "UKF v Nitre",
|
||||||
|
"Slovenská poľnohospodárska univerzita v Nitre": "SPU v Nitre",
|
||||||
|
"Trenčianska univerzita Alexandra Dubčeka v Trenčíne": "TnUAD"}
|
||||||
|
OTHERS_MAX = 7 # "Ďalší s viacerými prácami": at most this many (and everyone tied with the last one)
|
||||||
|
|
||||||
|
|
||||||
|
def short_school(name: str) -> str:
|
||||||
|
return SHORT_SCHOOL.get(name, name)
|
||||||
|
|
||||||
|
|
||||||
def _relation_sentences(query: CrzpQuery, target: str, rows: list[dict]) -> str:
|
def _relation_sentences(query: CrzpQuery, target: str, rows: list[dict]) -> str:
|
||||||
@ -710,9 +826,11 @@ def _relation_sentences(query: CrzpQuery, target: str, rows: list[dict]) -> str:
|
|||||||
if len(rows) == 1:
|
if len(rows) == 1:
|
||||||
row, who = rows[0], names(rows[0])
|
row, who = rows[0], names(rows[0])
|
||||||
if not who:
|
if not who:
|
||||||
return f"Pri {kind(row, 2)}{owner} „{row['title']}“ ({row.get('year') or '?'}) CRZP {ROLE_LABEL[target]}a neuvádza."
|
return f"Pri {kind(row, 2)}{owner} „{row['title']}“ ({row.get('year') or '?'}) CRZP {ROLE_LABEL[target]}ho neuvádza."
|
||||||
woman = len(who) == 1 and female(who[0])
|
woman = len(who) == 1 and female(who[0])
|
||||||
role = ROLE_INSTRUMENTAL[target][2 if woman else int(len(who) > 1)]
|
forms = DOCTORAL if target == "supervisor" and row.get("work_type") in ("dissertation", "doctoral_thesis") \
|
||||||
|
else ROLE_INSTRUMENTAL[target]
|
||||||
|
role = forms[2 if woman else int(len(who) > 1)]
|
||||||
verb = "boli" if len(who) > 1 else "bola" if woman else "bol"
|
verb = "boli" if len(who) > 1 else "bola" if woman else "bol"
|
||||||
return f"{role} {kind(row, 1)}{owner} „{row['title']}“ ({row.get('year') or '?'}) {verb} {join(who)}."
|
return f"{role} {kind(row, 1)}{owner} „{row['title']}“ ({row.get('year') or '?'}) {verb} {join(who)}."
|
||||||
head = f"{ROLE_PLURAL[target]} prác{owner}:" if owner else f"{ROLE_PLURAL[target]} prác ({describe(query)}):"
|
head = f"{ROLE_PLURAL[target]} prác{owner}:" if owner else f"{ROLE_PLURAL[target]} prác ({describe(query)}):"
|
||||||
@ -721,7 +839,141 @@ def _relation_sentences(query: CrzpQuery, target: str, rows: list[dict]) -> str:
|
|||||||
return head + "\n\n" + "\n".join(lines)
|
return head + "\n\n" + "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
def _relation(question, query, found, rows) -> tuple[str, list[dict]]:
|
def resubmissions(rows: list[dict]) -> list[dict]:
|
||||||
|
"""One work per author, title and type: a work submitted again within two years (CRZP keeps both
|
||||||
|
records of a repeated defence) counts once, its newest record kept. Different authors of one
|
||||||
|
title (the same topic given to two students) stay two works."""
|
||||||
|
kept, seen = [], {}
|
||||||
|
for row in sorted(rows, key=lambda r: -(r.get("year") or 0)):
|
||||||
|
authors = tuple(sorted(fold(a) for a in row.get("authors") or []))
|
||||||
|
key = (" ".join(fold(row.get("title") or "").rstrip(" .").split()), row.get("work_type"), authors)
|
||||||
|
years = seen.setdefault(key, [])
|
||||||
|
if authors and any(abs((row.get("year") or 0) - year) <= 2 for year in years):
|
||||||
|
continue
|
||||||
|
years.append(row.get("year") or 0)
|
||||||
|
kept.append(row)
|
||||||
|
return kept
|
||||||
|
|
||||||
|
|
||||||
|
def topic_ranking(query: CrzpQuery, rows: list[dict], target: str, complete=None) -> dict:
|
||||||
|
"""People of the target role by the works whose topic is the asked one (relevance.judge: the title,
|
||||||
|
else the model over title, keywords, faculty and abstract), each person once per school, newest
|
||||||
|
work first. The works of the people with the most works are judged first."""
|
||||||
|
from tools.crzp.answering import relevance
|
||||||
|
rows = resubmissions(rows)
|
||||||
|
field = ROLE_FIELD[target]
|
||||||
|
people: dict = {}
|
||||||
|
for row in rows:
|
||||||
|
for name in row.get(field, []):
|
||||||
|
people.setdefault((display_name(name), university(row)), []).append(row)
|
||||||
|
ordered, seen = [], set()
|
||||||
|
for _, works in sorted(people.items(), key=lambda item: (-len(item[1]), item[0])):
|
||||||
|
for work in works:
|
||||||
|
if relevance.work_id(work) not in seen:
|
||||||
|
seen.add(relevance.work_id(work))
|
||||||
|
ordered.append(work)
|
||||||
|
ordered += [r for r in rows if relevance.work_id(r) not in seen]
|
||||||
|
verdicts = relevance.judge(ordered, query, complete=complete)
|
||||||
|
ranking = []
|
||||||
|
for (name, school), works in people.items():
|
||||||
|
topical = [w for w in works if verdicts.get(relevance.work_id(w)) == relevance.TOPIC]
|
||||||
|
if topical:
|
||||||
|
ranking.append({"name": name, "school": school, "works": topical, "count": len(topical)})
|
||||||
|
ranking.sort(key=lambda p: (-p["count"], fold(p["name"])))
|
||||||
|
values = [verdicts.get(relevance.work_id(r)) for r in rows]
|
||||||
|
return {"ranking": ranking, "rows": rows, "topic": values.count(relevance.TOPIC),
|
||||||
|
"failed": values.count(relevance.UNJUDGED), "skipped": values.count(relevance.SKIPPED)}
|
||||||
|
|
||||||
|
|
||||||
|
def ranking_parts(ranking: list[dict]) -> tuple[list[dict], list[dict], list[dict]]:
|
||||||
|
"""(the leaders, the others shown: at least a third of the leader's count and two works, at most
|
||||||
|
OTHERS_MAX plus ties, the rest offered)."""
|
||||||
|
if not ranking:
|
||||||
|
return [], [], []
|
||||||
|
top = ranking[0]["count"]
|
||||||
|
leaders = [p for p in ranking if p["count"] == top]
|
||||||
|
pool = ranking[len(leaders):]
|
||||||
|
floor = max(2, -(-top // 3))
|
||||||
|
others = [p for p in pool if p["count"] >= floor]
|
||||||
|
if len(others) > OTHERS_MAX:
|
||||||
|
last = others[OTHERS_MAX - 1]["count"]
|
||||||
|
others = [p for p in others if p["count"] >= last] if sum(p["count"] >= last for p in others) <= OTHERS_MAX + 3 \
|
||||||
|
else others[:OTHERS_MAX]
|
||||||
|
return leaders, others, pool[len(others):]
|
||||||
|
|
||||||
|
|
||||||
|
def _who(person: dict) -> str:
|
||||||
|
return f"{person['name']} ({short_school(person['school'])})"
|
||||||
|
|
||||||
|
|
||||||
|
def _newest_link(person: dict) -> dict | None:
|
||||||
|
return next((w for w in sorted(person["works"], key=lambda w: -(w.get("year") or 0)) if w.get("url")), None)
|
||||||
|
|
||||||
|
|
||||||
|
def _topic_relation(question, query, rows, target, complete=None) -> tuple[str, list[dict]]:
|
||||||
|
""""Najviac prác na tému „blockchain“ viedol Kristián Košťál (STU v Bratislave) – 36." The others with
|
||||||
|
several works follow, the rest is offered; one source per person shown (the newest work)."""
|
||||||
|
from tools.answers.presentation.unified import female, join
|
||||||
|
data = topic_ranking(query, rows, target, complete)
|
||||||
|
ranking, topic = data["ranking"], query.topic_key()
|
||||||
|
conditions = describe(query.model_copy(update={"topics": [], "alternatives": [], "phrases": []}))
|
||||||
|
where = f" ({conditions})" if conditions else ""
|
||||||
|
if not ranking:
|
||||||
|
return (f"V CRZP som nenašiel prácu, ktorej témou je „{topic}“{where}; nájdené práce tento pojem len "
|
||||||
|
"spomínajú." if not data["failed"] else
|
||||||
|
"Posúdenie, ktoré práce sú naozaj o tejto téme, momentálne nie je dostupné. Skús otázku o chvíľu."), []
|
||||||
|
leaders, others, rest = ranking_parts(ranking)
|
||||||
|
verbs = VERBS[target]
|
||||||
|
count = leaders[0]["count"]
|
||||||
|
if len(leaders) == 1:
|
||||||
|
verb = verbs[1] if female(leaders[0]["name"]) else verbs[0]
|
||||||
|
text = f"Najviac prác na tému „{topic}“{where} {verb} {_who(leaders[0])} – {count}."
|
||||||
|
else:
|
||||||
|
text = f"Najviac prác na tému „{topic}“{where} {verbs[2]} {join([_who(p) for p in leaders])} – po {count}."
|
||||||
|
if others:
|
||||||
|
text += "\n\nĎalší s viacerými prácami na túto tému:\n" + "\n".join(f"- {_who(p)} – {p['count']}" for p in others)
|
||||||
|
text += (f"\n\nZapočítané sú práce, ktorých témou je „{topic}“ ({data['topic']} z {plural(len(data['rows']))}); "
|
||||||
|
+ ("ostatné tento pojem len spomínajú." if not data["skipped"] else
|
||||||
|
"ostatné ho len spomínajú alebo patria ľuďom s menej prácami, pri ktorých sa téma neposudzovala "
|
||||||
|
f"({data['skipped']})."))
|
||||||
|
if data["failed"]:
|
||||||
|
text += " Časť prác sa nepodarilo posúdiť; započítané sú len posúdené."
|
||||||
|
shown = [*leaders, *others]
|
||||||
|
extras = _extras.get()
|
||||||
|
if extras is not None:
|
||||||
|
extras["entities"] = [{"name": p["name"], "school": p["school"], "source": "crzp", "role": target,
|
||||||
|
**({"url": _newest_link(p)["url"]} if _newest_link(p) else {})} for p in shown]
|
||||||
|
if rest:
|
||||||
|
extras["rest"] = [{"name": f"{_who(p)} – {p['count']}", "source": "crzp", "text": "",
|
||||||
|
"urls": [w["url"] for w in [_newest_link(p)] if w]} for p in rest]
|
||||||
|
extras["offer"] = (f"Chceš vidieť ďalších (" + str(len(rest)) + ")?")
|
||||||
|
return text, [w for w in (_newest_link(p) for p in shown) if w]
|
||||||
|
|
||||||
|
|
||||||
|
def _sources(question, query, found, rows, complete=None) -> tuple[str, list[dict]]:
|
||||||
|
""""málo zdrojov" after "Kto viedol najviac prác o X?": the works of every person shown."""
|
||||||
|
target = query.target_role if query.target_role in ROLE_FIELD else "supervisor"
|
||||||
|
if not query.topics or query.people:
|
||||||
|
return _list(question, query, found, rows, complete)
|
||||||
|
data = topic_ranking(query, rows, target, complete)
|
||||||
|
leaders, others, _ = ranking_parts(data["ranking"])
|
||||||
|
blocks, used = [], []
|
||||||
|
for person in [*leaders, *others]:
|
||||||
|
works = sorted(person["works"], key=lambda w: -(w.get("year") or 0))[:5]
|
||||||
|
more = f" (zobrazených 5 najnovších z {person['count']})" if person["count"] > 5 else ""
|
||||||
|
blocks.append(f"**{_who(person)}**{more}\n" + "\n".join(f"- „{w['title']}“ ({_kind(w)}, {w.get('year') or '?'})"
|
||||||
|
for w in works))
|
||||||
|
used += [w for w in works if w.get("url")]
|
||||||
|
if not blocks:
|
||||||
|
return f"K téme „{query.topic_key()}“ nemám ďalšie práce.", []
|
||||||
|
extras = _extras.get()
|
||||||
|
if extras is not None: # "a z akých škôl sú?" asks about these people, not about the authors listed
|
||||||
|
extras["entities"] = [{"name": p["name"], "school": p["school"], "source": "crzp", "role": target,
|
||||||
|
**({"url": _newest_link(p)["url"]} if _newest_link(p) else {})} for p in [*leaders, *others]]
|
||||||
|
return f"Práce na tému „{query.topic_key()}“ ľudí z predchádzajúcej odpovede:\n\n" + "\n\n".join(blocks), used
|
||||||
|
|
||||||
|
|
||||||
|
def _relation(question, query, found, rows, complete=None) -> tuple[str, list[dict]]:
|
||||||
target = query.target_role
|
target = query.target_role
|
||||||
if query.title: # the asked work itself, if CRZP has that exact title
|
if query.title: # the asked work itself, if CRZP has that exact title
|
||||||
exact = [r for r in rows if fold(r["title"]).rstrip(" .") == fold(query.title).rstrip(" .")]
|
exact = [r for r in rows if fold(r["title"]).rstrip(" .") == fold(query.title).rstrip(" .")]
|
||||||
@ -731,19 +983,23 @@ def _relation(question, query, found, rows) -> tuple[str, list[dict]]:
|
|||||||
rows = sorted(rows, key=lambda r: -(r.get("year") or 0))
|
rows = sorted(rows, key=lambda r: -(r.get("year") or 0))
|
||||||
return _relation_sentences(query, target, rows), rows
|
return _relation_sentences(query, target, rows), rows
|
||||||
if not query.people: # "Kto viedol práce o X?": the target role over the found works
|
if not query.people: # "Kto viedol práce o X?": the target role over the found works
|
||||||
counts = Counter(n for r in rows for n in r.get(ROLE_FIELD[target], []))
|
|
||||||
if (found.get("facet_only") and target == "supervisor" and not found["complete"]
|
if (found.get("facet_only") and target == "supervisor" and not found["complete"]
|
||||||
and all(part["facets"].get("Školiteľ") for part in found["parts"])): # CRZP's full supervisor facet
|
and all(part["facets"].get("Školiteľ") for part in found["parts"])): # only CRZP's supervisor facet
|
||||||
counts = Counter()
|
counts = Counter()
|
||||||
for part in found["parts"]:
|
for part in found["parts"]:
|
||||||
counts.update({f["label"]: f["count"] for f in part["facets"].get("Školiteľ", [])})
|
counts.update({f["label"]: f["count"] for f in part["facets"].get("Školiteľ", [])})
|
||||||
total = found["total"]
|
lines = [f"- {display_name(n)} – {c}" for n, c in sorted(counts.items(), key=lambda i: (-i[1], i[0]))[:15]]
|
||||||
lines = [f"- {display_name(n)} ({plural(c)})" for n, c in sorted(counts.items(), key=lambda i: (-i[1], i[0]))[:15]]
|
return (f"{ROLE_PLURAL[target]} prác ({describe(query)}) podľa súhrnu CRZP z {plural(found['total'])} "
|
||||||
return (f"{ROLE_PLURAL[target]} prác ({describe(query)}; súhrn CRZP z {plural(total)}):\n\n" +
|
"(počty zahŕňajú aj práce, ktoré tému len spomínajú):\n\n" + ("\n".join(lines) or "- CRZP ich neuvádza")), \
|
||||||
("\n".join(lines) or "- CRZP ich neuvádza")), ranked(question, query, rows)[:10]
|
ranked(question, query, rows)[:len(lines)]
|
||||||
lines = [f"- {display_name(n)} ({plural(c)})" for n, c in sorted(counts.items(), key=lambda i: (-i[1], i[0]))[:15]]
|
if query.topics:
|
||||||
return (f"{ROLE_PLURAL[target]} prác ({describe(query)}; spočítané z {plural(len(rows))} v CRZP):\n\n" +
|
return _topic_relation(question, query, rows, target, complete)
|
||||||
("\n".join(lines) or "- CRZP ich neuvádza")), ranked(question, query, rows)[:10]
|
counts = Counter((display_name(n), university(r)) for r in resubmissions(rows) for n in r.get(ROLE_FIELD[target], []))
|
||||||
|
ranking = [{"name": n, "school": sch, "count": c, "works": [r for r in rows if any(display_name(x) == n for x in r.get(ROLE_FIELD[target], []))]}
|
||||||
|
for (n, sch), c in sorted(counts.items(), key=lambda i: (-i[1], i[0]))]
|
||||||
|
lines = [f"- {_who(p)} – {p['count']}" for p in ranking[:15]]
|
||||||
|
return (f"{ROLE_PLURAL[target]} prác ({describe(query)}; spočítané z {plural(len(rows))}):\n\n" +
|
||||||
|
("\n".join(lines) or "- CRZP ich neuvádza")), [w for w in (_newest_link(p) for p in ranking[:15]) if w]
|
||||||
person = query.people[0]
|
person = query.people[0]
|
||||||
source = person.role if person.role in ROLE_FIELD else max(
|
source = person.role if person.role in ROLE_FIELD else max(
|
||||||
ROLE_FIELD, key=lambda role: sum(bool(people_in_role(r, person.name, role)) for r in rows))
|
ROLE_FIELD, key=lambda role: sum(bool(people_in_role(r, person.name, role)) for r in rows))
|
||||||
@ -752,8 +1008,14 @@ def _relation(question, query, found, rows) -> tuple[str, list[dict]]:
|
|||||||
lines = [f"- {display_name(n)} ({plural(c)})" for n, c in pairs[:15]]
|
lines = [f"- {display_name(n)} ({plural(c)})" for n, c in pairs[:15]]
|
||||||
conditions = describe(query.model_copy(update={"people": []}))
|
conditions = describe(query.model_copy(update={"people": []}))
|
||||||
text = (f"{ROLE_PLURAL[target]} prác, pri ktorých je {display_name(names[0]) if names else person.name} "
|
text = (f"{ROLE_PLURAL[target]} prác, pri ktorých je {display_name(names[0]) if names else person.name} "
|
||||||
f"{ROLE_LABEL[source]} ({conditions + '; ' if conditions else ''}{plural(len(rows))} v CRZP):\n\n" + ("\n".join(lines) or "- CRZP ich neuvádza"))
|
f"{ROLE_LABEL[source]} ({conditions + '; ' if conditions else ''}{plural(len(rows))}):\n\n" + ("\n".join(lines) or "- CRZP ich neuvádza"))
|
||||||
return text, rows
|
field = ROLE_FIELD[target]
|
||||||
|
newest = [] # one source per person shown: the newest work where he or she had the role
|
||||||
|
for name, _ in pairs[:15]:
|
||||||
|
work = next((r for r in sorted(rows, key=lambda r: -(r.get("year") or 0)) if name in r.get(field, []) and r.get("url")), None)
|
||||||
|
if work and work not in newest:
|
||||||
|
newest.append(work)
|
||||||
|
return text, newest or rows
|
||||||
|
|
||||||
|
|
||||||
def university(row: dict) -> str:
|
def university(row: dict) -> str:
|
||||||
@ -952,11 +1214,16 @@ def _answer_query(question: str, query: CrzpQuery, complete=None) -> dict:
|
|||||||
result["_shown"], result["_asked"], result["_options"] = [], asked, asked_who[1]
|
result["_shown"], result["_asked"], result["_options"] = [], asked, asked_who[1]
|
||||||
return result
|
return result
|
||||||
handler = {"list": _list, "count": _count, "keywords": _keywords, "relation": _relation,
|
handler = {"list": _list, "count": _count, "keywords": _keywords, "relation": _relation,
|
||||||
"similar": _similar, "schools": _schools}.get(query.intent)
|
"similar": _similar, "schools": _schools, "sources": _sources}.get(query.intent)
|
||||||
if query.intent == "about":
|
extras = {}
|
||||||
body, used = _about(question, query, found, rows, complete)
|
marker = _extras.set(extras)
|
||||||
else:
|
try:
|
||||||
body, used = handler(question, query, found, rows)
|
if query.intent in ("about", "relation", "sources", "list"): # these may ask the model
|
||||||
|
body, used = (_about if query.intent == "about" else handler)(question, query, found, rows, complete)
|
||||||
|
else:
|
||||||
|
body, used = handler(question, query, found, rows)
|
||||||
|
finally:
|
||||||
|
_extras.reset(marker)
|
||||||
except CrzpUnavailable:
|
except CrzpUnavailable:
|
||||||
return _result(question, "error", "CRZP momentálne neodpovedá alebo obmedzil počet požiadaviek. Skús to o chvíľu.",
|
return _result(question, "error", "CRZP momentálne neodpovedá alebo obmedzil počet požiadaviek. Skús to o chvíľu.",
|
||||||
reason="crzp_unavailable")
|
reason="crzp_unavailable")
|
||||||
@ -974,7 +1241,9 @@ def _answer_query(question: str, query: CrzpQuery, complete=None) -> dict:
|
|||||||
result = _result(question, "ok", body, rows=used, complete=not truncated, truncated=truncated, reasons=reasons,
|
result = _result(question, "ok", body, rows=used, complete=not truncated, truncated=truncated, reasons=reasons,
|
||||||
count=len(rows) if query.intent == "count" else None)
|
count=len(rows) if query.intent == "count" else None)
|
||||||
result["_shown"], result["_asked"] = used, asked
|
result["_shown"], result["_asked"] = used, asked
|
||||||
result["_entities"] = displayed_entities(query, body, used, rows)
|
result["_entities"] = extras.get("entities") or displayed_entities(query, body, used, rows)
|
||||||
|
if extras.get("rest"): # "Chceš vidieť ďalších?": the rest of a ranking, kept by the combined answer
|
||||||
|
result["_rest"], result["_offer"] = extras["rest"], extras["offer"]
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
@ -992,9 +1261,11 @@ def displayed_entities(query: CrzpQuery, body: str, used: list[dict], rows: list
|
|||||||
if names:
|
if names:
|
||||||
return [{"name": n, "school": _school_of(n, rows, field), "source": "crzp", "role": query.target_role}
|
return [{"name": n, "school": _school_of(n, rows, field), "source": "crzp", "role": query.target_role}
|
||||||
for n in names]
|
for n in names]
|
||||||
entities = []
|
entities, text = [], fold(body)
|
||||||
for row in used:
|
for row in used:
|
||||||
for author in row.get("authors", [])[:1]:
|
for author in row.get("authors", [])[:1]:
|
||||||
entities.append({"name": display_name(author), "school": university(row), "source": "crzp",
|
# only what the text shows: a count names no work, its sources are links ("tretí z nich" is not one of them)
|
||||||
"role": "author", "sid": row.get("sid"), "title": row["title"]})
|
if fold(display_name(author)) in text or fold(row["title"][:40]) in text:
|
||||||
|
entities.append({"name": display_name(author), "school": university(row), "source": "crzp",
|
||||||
|
"role": "author", "sid": row.get("sid"), "title": row["title"]})
|
||||||
return entities
|
return entities
|
||||||
|
|||||||
@ -34,6 +34,19 @@ LIST_CUE = re.compile(r"\b(?:ktor\w*|vypis\w*|zoznam\w*|ukaz\w*|ake prace|ake su
|
|||||||
ORDINALS = [(re.compile(r"\b(?:prv\w*|first)\b"), 0), (re.compile(r"\b(?:druh\w*|second)\b"), 1),
|
ORDINALS = [(re.compile(r"\b(?:prv\w*|first)\b"), 0), (re.compile(r"\b(?:druh\w*|second)\b"), 1),
|
||||||
(re.compile(r"\b(?:tret\w*|third)\b"), 2), (re.compile(r"\b(?:stvrt\w*|fourth)\b"), 3),
|
(re.compile(r"\b(?:tret\w*|third)\b"), 2), (re.compile(r"\b(?:stvrt\w*|fourth)\b"), 3),
|
||||||
(re.compile(r"\b(?:piat\w*|fifth)\b"), 4), (re.compile(r"\b(?:posledn\w*|last)\b"), -1)]
|
(re.compile(r"\b(?:piat\w*|fifth)\b"), 4), (re.compile(r"\b(?:posledn\w*|last)\b"), -1)]
|
||||||
|
# Follow-ups about the previous search itself (checked before "a message with its own subject": the model
|
||||||
|
# may read "napr." or "zdrojov" as a topic).
|
||||||
|
EXAMPLES = re.compile(r"^\W*(?:a\s+)?(?:(?:ake|ktore|aky|ktory|aka|ktora)\s+(?:napr\w*|napriklad|to\s+(?:su|boli|je|bola|bol)|"
|
||||||
|
r"su\s+to|boli\s+to)|napr\w*|napriklad|(?:vypis|ukaz|daj|zobraz|vymenuj)\w*\s+(?:mi\s+)?"
|
||||||
|
r"(?:ich|tie|ty|vsetk\w*|tych|zoznam|ake|ktore))\b")
|
||||||
|
SPLIT = re.compile(r"\b(?:rozdel|rozdelit|rozpis|rozpisat|rozloz|rozclen)\w*|\bpo\s+(?:jednotlivych\s+)?rokoch\b|"
|
||||||
|
r"\bpodla\s+(?:rok|typ|druh)\w*|\bza\s+kazdy\s+rok\b")
|
||||||
|
SOURCES = re.compile(r"^\W*(?:a\s+)?(?:nejak\w*\s+|trochu\s+|dost\s+|prilis\s+)?(?:malo|viac|dalsie|dalsich|ukaz\w*|"
|
||||||
|
r"vypis\w*|ake|aky|kde\s+su|daj\s+mi)\s+(?:su\s+|mi\s+|tie\s+)?zdroj\w*(?:\s+(?:prosim|pls|daj))?\W*$"
|
||||||
|
r"|^\W*(?:a\s+)?zdroje?\W*$|^\W*(?:a\s+)?odkial\s+(?:to\s+)?(?:to|su|je|mas)\b")
|
||||||
|
NOISE = {"napr", "napriklad", "priklad", "zdroj", "zdroje", "zdrojov", "vsetky", "vsetko", "vsetkych", "zoznam", "rok", "roky",
|
||||||
|
"rokoch", "typ", "typy", "typov", "ich", "tie", "ake", "ktore", "dalsie"} # words a model may take for a topic
|
||||||
|
FOLLOW = re.compile("|".join(f"(?:{r.pattern})" for r in (EXAMPLES, SPLIT, SOURCES)))
|
||||||
SINGLE = re.compile(r"\b(?:ta|tu|tej|tou|tato|tuto|tejto) (?:praca|pracu|prace|praci|pracou|bakalark\w*|diplomov\w*)\b"
|
SINGLE = re.compile(r"\b(?:ta|tu|tej|tou|tato|tuto|tejto) (?:praca|pracu|prace|praci|pracou|bakalark\w*|diplomov\w*)\b"
|
||||||
r"|\bo com (?:je|bola|bolo)\b|\bjej (?:abstrakt|klucov|oponent|skolitel|vedu)")
|
r"|\bo com (?:je|bola|bolo)\b|\bjej (?:abstrakt|klucov|oponent|skolitel|vedu)")
|
||||||
|
|
||||||
@ -122,10 +135,13 @@ def follow_up(question: str, new: CrzpQuery, previous: dict) -> tuple[CrzpQuery,
|
|||||||
reference to the previous answer is answered on its own; otherwise the previous
|
reference to the previous answer is answered on its own; otherwise the previous
|
||||||
conditions are kept and the new ones (person, topic, year, type, school, intent) replace them."""
|
conditions are kept and the new ones (person, topic, year, type, school, intent) replace them."""
|
||||||
low = fold(question)
|
low = fold(question)
|
||||||
|
old: CrzpQuery = previous["query"]
|
||||||
|
about_previous = _about_previous(low, question, new, old)
|
||||||
|
if about_previous is not None:
|
||||||
|
return about_previous, None
|
||||||
own_subject = bool(new.people or new.title or new.topics)
|
own_subject = bool(new.people or new.title or new.topics)
|
||||||
if own_subject and not CONTINUES.search(low):
|
if own_subject and not CONTINUES.search(low):
|
||||||
return new, None # "Koľko prác viedol Staš?" stands on its own even with a token
|
return new, None # "Koľko prác viedol Staš?" stands on its own even with a token
|
||||||
old: CrzpQuery = previous["query"]
|
|
||||||
pending = re.fullmatch(r"\s*(?:(?:tak|ta|tu|tú|cislo|prace?|pracu)\s+)*(\d{1,2})\s*[.)]?\s*", low)
|
pending = re.fullmatch(r"\s*(?:(?:tak|ta|tu|tú|cislo|prace?|pracu)\s+)*(\d{1,2})\s*[.)]?\s*", low)
|
||||||
if previous.get("pending") and pending: # the answer to "Ktorú prácu myslíš?": the pending question
|
if previous.get("pending") and pending: # the answer to "Ktorú prácu myslíš?": the pending question
|
||||||
sids = previous.get("sids") or []
|
sids = previous.get("sids") or []
|
||||||
@ -194,3 +210,38 @@ def follow_up(question: str, new: CrzpQuery, previous: dict) -> tuple[CrzpQuery,
|
|||||||
return merged, _which(sids, previous.get("titles") or [])
|
return merged, _which(sids, previous.get("titles") or [])
|
||||||
merged.sids = list(sids)
|
merged.sids = list(sids)
|
||||||
return merged, None
|
return merged, None
|
||||||
|
|
||||||
|
|
||||||
|
def _about_previous(low: str, question: str, new: CrzpQuery, old: CrzpQuery) -> CrzpQuery | None:
|
||||||
|
""""aké napr.", "vypíš všetky 4", "rozdeľ to na 2024 a 2025", "málo zdrojov": the previous
|
||||||
|
search again, listed, split or with the works behind its numbers (a short message only)."""
|
||||||
|
words = re.findall(r"[a-z0-9]+", low)
|
||||||
|
# words of the follow-up phrase itself ("rozdeľ … podľa rokov", "napr.", "zdrojov") are no topic of their own
|
||||||
|
phrase = {w for match in FOLLOW.finditer(low) for w in re.findall(r"[a-z0-9]+", match.group(0))}
|
||||||
|
same = lambda a, b: a.startswith(b[:4]) or b.startswith(a[:4])
|
||||||
|
topic_words = [w for t in new.topics for w in re.findall(r"[a-z0-9]+", fold(t))]
|
||||||
|
own = bool(new.people or new.title or any(w not in NOISE and not w.isdigit() and not any(same(w, p) for p in phrase)
|
||||||
|
for w in topic_words))
|
||||||
|
if len(words) > 9 or own and not CONTINUES.search(low):
|
||||||
|
return None # "Vypíš všetky práce o RAG" is a question of its own
|
||||||
|
merged = old.model_copy(deep=True)
|
||||||
|
merged.sids, merged.searched, merged.relaxed_author, merged.unverified_only = [], [], False, []
|
||||||
|
merged.years = new.years or old.years
|
||||||
|
merged.work_types = new.work_types or old.work_types
|
||||||
|
if SOURCES.search(low): # the works behind a ranking, or the works of a count
|
||||||
|
merged.intent = "sources" if old.intent == "relation" else "list"
|
||||||
|
merged.show = None if old.intent == "relation" else 8
|
||||||
|
return merged
|
||||||
|
if SPLIT.search(low):
|
||||||
|
merged.intent = "count" if old.intent in ("count", "list", "about") else old.intent
|
||||||
|
merged.split = "type" if re.search(r"\b(?:typ|druh|bakalar|diplom|dizert)\w*", low) and not new.years else "year"
|
||||||
|
return merged
|
||||||
|
if EXAMPLES.search(low):
|
||||||
|
number = re.search(r"\b(\d{1,3})\b", low)
|
||||||
|
if old.intent == "relation":
|
||||||
|
merged.intent, merged.show = "sources", None
|
||||||
|
else:
|
||||||
|
merged.intent, merged.target_role = "list", None
|
||||||
|
merged.show = min(int(number.group(1)), 100) if number else 8 if old.intent == "count" else None
|
||||||
|
return merged
|
||||||
|
return None
|
||||||
|
|||||||
@ -42,7 +42,8 @@ def _build() -> dict:
|
|||||||
|
|
||||||
def vocabulary() -> dict:
|
def vocabulary() -> dict:
|
||||||
with _lock:
|
with _lock:
|
||||||
if time.monotonic() - _state["built"] > REFRESH_SECONDS:
|
# 0.0 = never built (the monotonic clock starts at boot, so "now - 0.0" may be under an hour)
|
||||||
|
if not _state["built"] or time.monotonic() - _state["built"] > REFRESH_SECONDS:
|
||||||
_state["phrases"] = _build()
|
_state["phrases"] = _build()
|
||||||
_state["built"] = time.monotonic()
|
_state["built"] = time.monotonic()
|
||||||
return _state["phrases"]
|
return _state["phrases"]
|
||||||
|
|||||||
@ -55,6 +55,8 @@ NICKNAMES = {
|
|||||||
"dano": ["Daniel"], "danko": ["Daniel"], "rado": ["Radoslav", "Radovan"], "stano": ["Stanislav"],
|
"dano": ["Daniel"], "danko": ["Daniel"], "rado": ["Radoslav", "Radovan"], "stano": ["Stanislav"],
|
||||||
"vlado": ["Vladimír"], "laco": ["Ladislav"], "riso": ["Richard"], "robo": ["Róbert"], "kubo": ["Jakub"],
|
"vlado": ["Vladimír"], "laco": ["Ladislav"], "riso": ["Richard"], "robo": ["Róbert"], "kubo": ["Jakub"],
|
||||||
"filo": ["Filip"], "ondro": ["Ondrej"], "adko": ["Adam"], "lubo": ["Ľubomír", "Ľuboš"], "maros": ["Maroš"],
|
"filo": ["Filip"], "ondro": ["Ondrej"], "adko": ["Adam"], "lubo": ["Ľubomír", "Ľuboš"], "maros": ["Maroš"],
|
||||||
|
"samko": ["Samuel"], "petko": ["Peter"], "matko": ["Matej", "Martin"], "misko": ["Michal"], "jurko": ["Juraj"],
|
||||||
|
"ferko": ["František"], "palko": ["Pavol"], "tomasko": ["Tomáš"], "lukasko": ["Lukáš"],
|
||||||
"zuzka": ["Zuzana"], "katka": ["Katarína"], "janka": ["Jana"], "evka": ["Eva"], "majka": ["Mária"],
|
"zuzka": ["Zuzana"], "katka": ["Katarína"], "janka": ["Jana"], "evka": ["Eva"], "majka": ["Mária"],
|
||||||
"danka": ["Daniela"], "lucka": ["Lucia"], "miska": ["Michaela"], "baska": ["Barbora"], "tana": ["Tatiana"],
|
"danka": ["Daniela"], "lucka": ["Lucia"], "miska": ["Michaela"], "baska": ["Barbora"], "tana": ["Tatiana"],
|
||||||
"sasa": ["Alexandra", "Alexander"], "nika": ["Nikola", "Veronika"], "peta": ["Petra"],
|
"sasa": ["Alexandra", "Alexander"], "nika": ["Nikola", "Veronika"], "peta": ["Petra"],
|
||||||
@ -100,8 +102,13 @@ def name_candidates(model_name: str | None, typed: str) -> tuple[list[str], list
|
|||||||
middle = _capital(" ".join(words[1:-1]))
|
middle = _capital(" ".join(words[1:-1]))
|
||||||
join = lambda first, last: " ".join(p for p in (first, middle, last) if p)
|
join = lambda first, last: " ".join(p for p in (first, middle, last) if p)
|
||||||
surname = _capital(model_words[-1]) if model_words else rule_surname
|
surname = _capital(model_words[-1]) if model_words else rule_surname
|
||||||
# A nickname: the model writes the nominative ("Samo"); without the model the typed form may be inflected ("Sama").
|
# A nickname: the model writes the nominative ("Samo"); the typed form may be inflected ("Sama", which
|
||||||
nicknames = NICKNAMES.get(fold(model_words[0]), []) if model_words else nickname_names(words[0])
|
# the model may wrongly shorten to "Sam") and is read too when the model changed it.
|
||||||
|
nicknames = nickname_names(model_words[0]) if model_words else []
|
||||||
|
if not model_words or fold(model_words[0]) != fold(words[0]):
|
||||||
|
nicknames = list(dict.fromkeys([*nicknames, *nickname_names(words[0])]))
|
||||||
|
if surname.lower().endswith("á") or fold(surname).endswith("ova"): # a woman: "Jana Nováková" is no "Jano"
|
||||||
|
nicknames = [n for n in nicknames if fold(n).endswith("a")]
|
||||||
surnames = [surname, *([rule_surname] if inflected else [])]
|
surnames = [surname, *([rule_surname] if inflected else [])]
|
||||||
candidates = [*full, *([join(rule_first, rule_surname)] if inflected else []),
|
candidates = [*full, *([join(rule_first, rule_surname)] if inflected else []),
|
||||||
*[join(n, s) for n in nicknames for s in _unique(surnames)]]
|
*[join(n, s) for n in nicknames for s in _unique(surnames)]]
|
||||||
|
|||||||
190
tools/crzp/answering/relevance.py
Normal file
190
tools/crzp/answering/relevance.py
Normal file
@ -0,0 +1,190 @@
|
|||||||
|
"""Is the asked topic a work's own topic, or only mentioned in it?
|
||||||
|
|
||||||
|
CRZP finds a word anywhere in a record (title, keywords, abstract), so a work found
|
||||||
|
for "blockchain" may be about the history of accounting and only list "blockchain"
|
||||||
|
among its keywords. Questions over the works of a topic ("Kto viedol najviac prác o
|
||||||
|
blockchaine?", the works listed for a topic) count a work only when the topic is
|
||||||
|
its topic:
|
||||||
|
1. its title names the topic (or a term that is the topic itself, RELATED:
|
||||||
|
"smart kontrakt", "DeFi" for blockchain) -> topic, no model;
|
||||||
|
2. otherwise the model judges the title, the author's keywords and the school and
|
||||||
|
faculty (a law or economics faculty vs. informatics) -> "tema" / "zmienka" /
|
||||||
|
"nesuvisi" / "neiste"; a keyword alone, or its position, decides nothing;
|
||||||
|
3. "neiste" works are judged again with their abstract (the CRZP record detail),
|
||||||
|
at most MAX_DETAILS per question; a work still unsure counts as a mention.
|
||||||
|
The code accepts "tema" only when a topic term really is in the judged text. A
|
||||||
|
verdict is stored once per topic and work (crzp.sqlite, table relevance) and never
|
||||||
|
asked again; a failed model call stores nothing (the work stays unjudged).
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
|
||||||
|
from tools.crzp.source.parse import fold
|
||||||
|
|
||||||
|
TOPIC, MENTION, UNRELATED, UNSURE = "topic", "mention", "unrelated", "unsure"
|
||||||
|
UNJUDGED, SKIPPED = "unjudged", "skipped" # the model failed / over the per-question budget
|
||||||
|
BATCH = 40 # works judged in one model call
|
||||||
|
MAX_MODEL_ROWS = int(os.getenv("CRZP_RELEVANCE_ROWS", "160")) # works judged by the model per question
|
||||||
|
MAX_DETAILS = int(os.getenv("CRZP_RELEVANCE_DETAILS", "20")) # abstracts read per question
|
||||||
|
# Terms that are the topic itself when a title names them (reviewed by hand; never searched).
|
||||||
|
RELATED = {
|
||||||
|
"blockchain": ["smart kontrakt", "smart contract", "inteligentné zmluvy", "ethereum", "hyperledger", "defi",
|
||||||
|
"decentralizovaná aplikácia", "decentralized application", "dapp", "web3", "nft", "dao",
|
||||||
|
"distributed ledger", "distribuovaná databáza transakcií", "kryptografický reťazec", "solana"],
|
||||||
|
"chatbot": ["dialógový systém", "konverzačný agent", "četbot", "chatbot"],
|
||||||
|
"rag": ["retrieval augmented generation", "retrieval-augmented"],
|
||||||
|
"llm": ["jazykový model", "language model", "gpt"],
|
||||||
|
}
|
||||||
|
PROMPT_VERSION = "v2" # part of the stored verdict key: a changed prompt never reuses older verdicts
|
||||||
|
PROMPT = ("Posudzuješ záverečné práce. Pre každú očíslovanú prácu rozhodni, či je „{topic}“ jej predmetom.\n"
|
||||||
|
"- \"tema\": predmetom práce (podľa názvu) je „{topic}“ alebo jeho priama technická súčasť či využitie "
|
||||||
|
"(navrhuje, implementuje, skúma alebo hodnotí ho, alebo systém postavený na ňom);\n"
|
||||||
|
"- \"zmienka\": predmetom práce je iný jav (napr. ekonomický, finančný, právny, spoločenský alebo iný "
|
||||||
|
"produkt či trh) a „{topic}“ je len súvisiaci pojem, napr. v kľúčových slovách;\n"
|
||||||
|
"- \"nesuvisi\": s témou nesúvisí;\n"
|
||||||
|
"- \"neiste\": z uvedených údajov sa to nedá rozhodnúť.\n"
|
||||||
|
"Rozhoduj podľa názvu, kľúčových slov, fakulty a abstraktu, ak je uvedený. Samotný výskyt pojmu v "
|
||||||
|
"kľúčových slovách nestačí: ak názov hovorí o inom predmete, je to zmienka, pokiaľ abstrakt nepotvrdí opak. "
|
||||||
|
"Odpovedz iba JSON objektom, napr. {{\"1\": \"tema\", \"2\": \"zmienka\"}}.")
|
||||||
|
VERDICTS = {"tema": TOPIC, "zmienka": MENTION, "nesuvisi": UNRELATED, "nesúvisí": UNRELATED, "neiste": UNSURE,
|
||||||
|
"neisté": UNSURE}
|
||||||
|
|
||||||
|
|
||||||
|
def work_id(row: dict) -> str:
|
||||||
|
"""The work's CRZP id, else its title, year and first author."""
|
||||||
|
if row.get("sid"):
|
||||||
|
return row["sid"]
|
||||||
|
authors = row.get("authors") or [""]
|
||||||
|
return f"{' '.join(fold(row.get('title') or '').split())}|{row.get('year')}|{fold(authors[0])}"
|
||||||
|
|
||||||
|
|
||||||
|
def topic_terms(query) -> list[str]:
|
||||||
|
"""The asked topic, its searched alternatives and the related terms that are the topic itself."""
|
||||||
|
topic = query.topic_key()
|
||||||
|
terms = [topic, *(query.topics[:1]), *query.alternatives, *RELATED.get(" ".join(fold(topic).split()), [])]
|
||||||
|
return list(dict.fromkeys(t for t in terms if t and t.strip()))
|
||||||
|
|
||||||
|
|
||||||
|
def _words(text: str) -> list[str]:
|
||||||
|
return re.findall(r"[a-z0-9]+", fold(text))
|
||||||
|
|
||||||
|
|
||||||
|
def acronym(term: str) -> bool:
|
||||||
|
""""WER", "RAG", "NFT": an upper-case abbreviation, matched in its own letter case (never "Wer", "rag")."""
|
||||||
|
term = term.strip()
|
||||||
|
return 2 <= len(term) <= 6 and term.isupper() and term.isalnum()
|
||||||
|
|
||||||
|
|
||||||
|
def mentions(text: str, term: str, case: bool = True) -> bool:
|
||||||
|
"""Every word of the term in the text, up to inflection ("blockchainu", "smart kontraktov"); in a
|
||||||
|
title (case=True) an abbreviation in upper case only ("WER" is not the German "Wer"); keywords are
|
||||||
|
often written in lower case ("rag"), so they are compared with case=False."""
|
||||||
|
if acronym(term) and case:
|
||||||
|
return bool(re.search(r"(?<![\w])" + re.escape(term.strip()) + r"(?:-?[a-zá-ž]{1,3})?(?![\w])", text))
|
||||||
|
words = _words(text)
|
||||||
|
wanted = _words(term)
|
||||||
|
|
||||||
|
def same(word: str, asked: str) -> bool:
|
||||||
|
if len(asked) <= 4: # "defi", "nft", "rag": the word itself or a short ending, never "definícia"
|
||||||
|
return word.startswith(asked) and len(word) - len(asked) <= 2
|
||||||
|
stem = asked[:len(asked) - 1] if len(asked) <= 6 else asked[:len(asked) - 2]
|
||||||
|
return word.startswith(stem)
|
||||||
|
return bool(wanted) and all(any(same(w, t) for w in words) for t in wanted)
|
||||||
|
|
||||||
|
|
||||||
|
def names_topic(row: dict, terms: list[str]) -> bool:
|
||||||
|
return any(mentions(row.get("title") or "", term) for term in terms)
|
||||||
|
|
||||||
|
|
||||||
|
def _line(number: int, row: dict, abstract: str | None) -> str:
|
||||||
|
keywords = ", ".join((row.get("keywords") or [])[:12]) or "neuvedené"
|
||||||
|
line = f"{number}. Názov: {row.get('title')} | Kľúčové slová: {keywords} | Škola: {row.get('school') or 'neuvedená'}"
|
||||||
|
return line + (f" | Abstrakt: {' '.join(abstract.split())[:900]}" if abstract else "")
|
||||||
|
|
||||||
|
|
||||||
|
def _ask(topic: str, batch: list[tuple[dict, str | None]], complete) -> dict[int, str]:
|
||||||
|
"""{position: verdict} of one model call; {} when the model fails."""
|
||||||
|
from tools.answers.generation.model_client import complete_with_configured_model
|
||||||
|
lines = "\n".join(_line(i, row, abstract) for i, (row, abstract) in enumerate(batch, 1))
|
||||||
|
try:
|
||||||
|
response = (complete or complete_with_configured_model)(
|
||||||
|
[{"role": "system", "content": PROMPT.format(topic=topic)}, {"role": "user", "content": lines}],
|
||||||
|
max_tokens=12 * len(batch) + 60)
|
||||||
|
text = response["choices"][0]["message"]["content"]
|
||||||
|
found = json.loads(re.search(r"\{[\s\S]*\}", text).group(0))
|
||||||
|
except Exception:
|
||||||
|
return {}
|
||||||
|
return {int(k): VERDICTS[str(v).strip().lower()] for k, v in found.items()
|
||||||
|
if str(k).strip().isdigit() and str(v).strip().lower() in VERDICTS and 1 <= int(k) <= len(batch)}
|
||||||
|
|
||||||
|
|
||||||
|
def _judge(topic: str, items: list[tuple[dict, str | None]], complete) -> dict[str, str]:
|
||||||
|
batches = [items[i:i + BATCH] for i in range(0, len(items), BATCH)]
|
||||||
|
verdicts: dict[str, str] = {}
|
||||||
|
with ThreadPoolExecutor(max_workers=2) as pool: # the school model has two slots
|
||||||
|
for batch, answer in zip(batches, pool.map(lambda b: _ask(topic, b, complete), batches)):
|
||||||
|
for position, (row, _) in enumerate(batch, 1):
|
||||||
|
if position in answer:
|
||||||
|
verdicts[work_id(row)] = answer[position]
|
||||||
|
return verdicts
|
||||||
|
|
||||||
|
|
||||||
|
def judge(rows: list[dict], query, *, complete=None, store=None, detail=None) -> dict[str, str]:
|
||||||
|
"""{work_id: TOPIC | MENTION | UNRELATED | UNSURE | UNJUDGED | SKIPPED} for the given works (the most
|
||||||
|
important first: the model budget goes to the first ones, the rest is SKIPPED)."""
|
||||||
|
from tools.crzp import fetch
|
||||||
|
store = store or fetch.store()
|
||||||
|
detail = detail or fetch.detail
|
||||||
|
topic = query.topic_key()
|
||||||
|
key = PROMPT_VERSION + "|" + " ".join(fold(topic).split())
|
||||||
|
terms = topic_terms(query)
|
||||||
|
verdicts, rest = {}, []
|
||||||
|
for row in rows:
|
||||||
|
if names_topic(row, terms):
|
||||||
|
verdicts[work_id(row)] = TOPIC
|
||||||
|
else:
|
||||||
|
rest.append(row)
|
||||||
|
try:
|
||||||
|
stored = store.get_verdicts(key, [work_id(r) for r in rest])
|
||||||
|
except Exception:
|
||||||
|
stored = {}
|
||||||
|
verdicts.update({w: v for w, v in stored.items()})
|
||||||
|
open_rows = [r for r in rest if work_id(r) not in stored]
|
||||||
|
asked, over = open_rows[:MAX_MODEL_ROWS], open_rows[MAX_MODEL_ROWS:]
|
||||||
|
first = _judge(topic, [(r, None) for r in asked], complete) if asked else {}
|
||||||
|
unsure = [r for r in asked if first.get(work_id(r)) == UNSURE and r.get("sid")][:MAX_DETAILS]
|
||||||
|
abstracts = {}
|
||||||
|
for row in unsure:
|
||||||
|
try:
|
||||||
|
abstracts[work_id(row)] = (detail(row["sid"]) or {}).get("abstract") or ""
|
||||||
|
except Exception:
|
||||||
|
abstracts[work_id(row)] = ""
|
||||||
|
second = _judge(topic, [(r, abstracts[work_id(r)]) for r in unsure if abstracts.get(work_id(r))],
|
||||||
|
complete) if unsure else {}
|
||||||
|
new = {}
|
||||||
|
for row in asked:
|
||||||
|
wid = work_id(row)
|
||||||
|
verdict = second.get(wid) or first.get(wid)
|
||||||
|
if verdict is None:
|
||||||
|
verdicts[wid] = UNJUDGED # the model failed: nothing stored, asked again next time
|
||||||
|
continue
|
||||||
|
judged_text = " ".join([row.get("title") or "", *(row.get("keywords") or []), abstracts.get(wid, "")])
|
||||||
|
if verdict == TOPIC and not any(mentions(judged_text, t, case=False) for t in terms):
|
||||||
|
verdict = UNSURE # the model may not promote a work whose judged text lacks the topic
|
||||||
|
if verdict == UNSURE and wid in second:
|
||||||
|
verdict = MENTION # judged with the abstract and still unsure: not the topic
|
||||||
|
verdicts[wid] = verdict
|
||||||
|
if verdict != UNSURE or not row.get("sid"): # unsure without an abstract to read stays so
|
||||||
|
new[wid] = verdict
|
||||||
|
for row in over:
|
||||||
|
verdicts[work_id(row)] = SKIPPED
|
||||||
|
if new:
|
||||||
|
try:
|
||||||
|
store.put_verdicts(key, new)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return verdicts
|
||||||
@ -1,7 +1,9 @@
|
|||||||
"""Alternative search terms of a topic (synonyms, expanded abbreviations, English).
|
"""Alternative search terms of a topic (synonyms, expanded abbreviations, English).
|
||||||
|
|
||||||
CRZP matches exact words, so "LLM" does not find a thesis that only writes
|
CRZP matches exact words, so "LLM" does not find a thesis that only writes
|
||||||
"jazykový model". A small reviewed table comes first; the model may add
|
"jazykový model". Inflected forms add nothing (measured: all 39 works with
|
||||||
|
"blockchainu" are among the 581 found by "blockchain"; "blockchain*" is not
|
||||||
|
truncated), so only real synonyms and spelled-out abbreviations are searched. A small reviewed table comes first; the model may add
|
||||||
proposals up to two alternatives in total. A model proposal is unverified: it
|
proposals up to two alternatives in total. A model proposal is unverified: it
|
||||||
is searched only when CRZP itself uses it next to the topic (a work found for
|
is searched only when CRZP itself uses it next to the topic (a work found for
|
||||||
the topic has it in its title or keywords) or when the topic alone finds
|
the topic has it in its title or keywords) or when the topic alone finds
|
||||||
@ -36,7 +38,7 @@ TABLE = {
|
|||||||
"rozpoznavanie reci": ["speech recognition", "prepis reči"],
|
"rozpoznavanie reci": ["speech recognition", "prepis reči"],
|
||||||
"pocitacove videnie": ["computer vision"],
|
"pocitacove videnie": ["computer vision"],
|
||||||
"kyberneticka bezpecnost": ["cybersecurity"],
|
"kyberneticka bezpecnost": ["cybersecurity"],
|
||||||
"blockchain": ["distribuovaná účtovná kniha"],
|
"blockchain": ["distributed ledger"], # measured 19. 11. 2026: "distribuovaná účtovná kniha" finds nothing
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -20,7 +20,7 @@ from tools.crzp.answering.units import UNITS, unit_in_question
|
|||||||
from tools.crzp.source.parse import fold
|
from tools.crzp.source.parse import fold
|
||||||
|
|
||||||
Role = Literal["author", "supervisor", "opponent", "any"]
|
Role = Literal["author", "supervisor", "opponent", "any"]
|
||||||
Intent = Literal["list", "count", "about", "keywords", "relation", "similar", "schools", "refused"]
|
Intent = Literal["list", "count", "about", "keywords", "relation", "similar", "schools", "sources", "refused"]
|
||||||
|
|
||||||
SCHOOLS = {
|
SCHOOLS = {
|
||||||
# abbreviation -> (name sent to search, distinctive part of the CRZP school name)
|
# abbreviation -> (name sent to search, distinctive part of the CRZP school name)
|
||||||
@ -44,13 +44,14 @@ SCHOOLS = {
|
|||||||
"uvlf": ("Univerzita veterinárneho lekárstva a farmácie v Košiciach", "univerzita veterinarneho lekarstva"),
|
"uvlf": ("Univerzita veterinárneho lekárstva a farmácie v Košiciach", "univerzita veterinarneho lekarstva"),
|
||||||
"vsmu": ("Vysoká škola múzických umení v Bratislave", "vysoka skola muzickych umeni"),
|
"vsmu": ("Vysoká škola múzických umení v Bratislave", "vysoka skola muzickych umeni"),
|
||||||
}
|
}
|
||||||
WORK_CUES = {
|
WORK_CUES = { # "bp", "dp": the usual abbreviations ("bakalárka", "diplomovka" are covered by the stems)
|
||||||
"bachelor_thesis": r"bakal[aá]r|\bbachelor", "diploma_thesis": r"diplom|\bmaster",
|
"bachelor_thesis": r"bakal[aá]r|\bbachelor|\bbp\b", "diploma_thesis": r"diplom|\bmaster|\bdp\b",
|
||||||
"dissertation": r"dizerta|doktorandsk|\bphd\b|dissertation", "habilitation_thesis": r"habilita",
|
"dissertation": r"dizerta|doktorandsk|\bphd\b|dissertation", "habilitation_thesis": r"habilita",
|
||||||
"doctoral_thesis": r"rigor[oó]z",
|
"doctoral_thesis": r"rigor[oó]z",
|
||||||
}
|
}
|
||||||
|
SCHOOL_FORMS = {"tuke": r"\btuke(?:cke|cka|cku|ckou|cky)\b", "stu": r"\bstu(?:cke|cka|cku|ckou|cky)\b"}
|
||||||
# Words that name the kind of work, never a topic ("dizertačné práce", "bachelor thesis").
|
# Words that name the kind of work, never a topic ("dizertačné práce", "bachelor thesis").
|
||||||
WORK_WORDS = {"praca", "prace", "prac", "bakalarska", "bakalarske", "bakalarsku", "bakalarskej", "bakalarka", "bakalarke",
|
WORK_WORDS = {"bp", "dp", "praca", "prace", "prac", "bakalarska", "bakalarske", "bakalarsku", "bakalarskej", "bakalarka", "bakalarke",
|
||||||
"diplomova", "diplomove", "diplomovu", "diplomovej", "diplomovka", "dizertacna", "dizertacne",
|
"diplomova", "diplomove", "diplomovu", "diplomovej", "diplomovka", "dizertacna", "dizertacne",
|
||||||
"habilitacna", "rigorozna", "zaverecna", "zaverecne", "thesis", "theses", "bachelor", "master",
|
"habilitacna", "rigorozna", "zaverecna", "zaverecne", "thesis", "theses", "bachelor", "master",
|
||||||
"dissertation", "work", "projekt"}
|
"dissertation", "work", "projekt"}
|
||||||
@ -115,6 +116,7 @@ class CrzpQuery(BaseModel):
|
|||||||
published: bool = False # "obhájili": only published works (CRZP publishes a work after its defence)
|
published: bool = False # "obhájili": only published works (CRZP publishes a work after its defence)
|
||||||
exclude_school: str | None = None # "na iných školách", "mimo TUKE": works of every school but this one
|
exclude_school: str | None = None # "na iných školách", "mimo TUKE": works of every school but this one
|
||||||
show: int | None = None # follow-up "vypíš prvých 8": how many works to list
|
show: int | None = None # follow-up "vypíš prvých 8": how many works to list
|
||||||
|
split: str | None = None # follow-up "rozdeľ podľa rokov / typov": "year" or "type"
|
||||||
|
|
||||||
def topic_key(self) -> str:
|
def topic_key(self) -> str:
|
||||||
"""The topic the alternative terms belong to (the rule phrase without the model)."""
|
"""The topic the alternative terms belong to (the rule phrase without the model)."""
|
||||||
@ -205,6 +207,8 @@ def _rules(question: str) -> CrzpQuery:
|
|||||||
years = years_in(question)
|
years = years_in(question)
|
||||||
work_types = [t for t, cue in WORK_CUES.items() if re.search(cue, low)]
|
work_types = [t for t, cue in WORK_CUES.items() if re.search(cue, low)]
|
||||||
school = next((key for key in SCHOOLS if re.search(r"\b" + key + r"\b", fold(question))), None)
|
school = next((key for key in SCHOOLS if re.search(r"\b" + key + r"\b", fold(question))), None)
|
||||||
|
if school is None: # "na TUKEčke", "na STUčke"
|
||||||
|
school = next((key for key, form in SCHOOL_FORMS.items() if re.search(form, fold(question))), None)
|
||||||
if school is None:
|
if school is None:
|
||||||
school = next((key for key, (_, part) in SCHOOLS.items() if part in fold(question)), None)
|
school = next((key for key, (_, part) in SCHOOLS.items() if part in fold(question)), None)
|
||||||
intent = _intent(low)
|
intent = _intent(low)
|
||||||
|
|||||||
@ -33,9 +33,9 @@ VERIFIED = {
|
|||||||
"fei": {"school": "tuke", "code": "1040", "label": "FEI", "text": "fakulta elektrotechniky a informatiky",
|
"fei": {"school": "tuke", "code": "1040", "label": "FEI", "text": "fakulta elektrotechniky a informatiky",
|
||||||
"search": ["1040"]}, # old FEI records also start with 1040
|
"search": ["1040"]}, # old FEI records also start with 1040
|
||||||
}
|
}
|
||||||
CUES = {
|
CUES = { # also inflected: "na Kemte", "z KEMTu", "s KEMTom", "na KEMT-e"
|
||||||
"kemt": r"\bkemt\b|katedr\w* elektroniky a multimedi",
|
"kemt": r"\bkemt(?:e|u|a|om|ke|ku|ka)?\b|katedr\w* elektroniky a multimedi",
|
||||||
"fei": r"\bfei\b|fakult\w* elektrotechniky a informatiky",
|
"fei": r"\bfei(?:ke|ka|ku|kou)?\b|fakult\w* elektrotechniky a informatiky",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -44,6 +44,9 @@ class CrzpStore:
|
|||||||
query TEXT PRIMARY KEY, fetched_at REAL NOT NULL, payload TEXT NOT NULL);
|
query TEXT PRIMARY KEY, fetched_at REAL NOT NULL, payload TEXT NOT NULL);
|
||||||
CREATE TABLE IF NOT EXISTS details (
|
CREATE TABLE IF NOT EXISTS details (
|
||||||
sid TEXT PRIMARY KEY, fetched_at REAL NOT NULL, payload TEXT NOT NULL);
|
sid TEXT PRIMARY KEY, fetched_at REAL NOT NULL, payload TEXT NOT NULL);
|
||||||
|
CREATE TABLE IF NOT EXISTS relevance (
|
||||||
|
topic TEXT NOT NULL, work TEXT NOT NULL, verdict TEXT NOT NULL, judged_at REAL NOT NULL,
|
||||||
|
PRIMARY KEY (topic, work));
|
||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
self._ready = True
|
self._ready = True
|
||||||
@ -94,3 +97,22 @@ class CrzpStore:
|
|||||||
return {"searches": 0, "details": 0}
|
return {"searches": 0, "details": 0}
|
||||||
with self._connect() as connection:
|
with self._connect() as connection:
|
||||||
return {t: connection.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0] for t in ("searches", "details")}
|
return {t: connection.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0] for t in ("searches", "details")}
|
||||||
|
|
||||||
|
def get_verdicts(self, topic: str, works: list[str]) -> dict[str, str]:
|
||||||
|
"""Stored "is the topic this work's topic" verdicts (tools/crzp/answering/relevance.py)."""
|
||||||
|
if not works:
|
||||||
|
return {}
|
||||||
|
found = {}
|
||||||
|
with self._connect() as connection:
|
||||||
|
for start in range(0, len(works), 500):
|
||||||
|
part = works[start:start + 500]
|
||||||
|
found.update(connection.execute(
|
||||||
|
f"SELECT work, verdict FROM relevance WHERE topic = ? AND work IN ({','.join('?' * len(part))})",
|
||||||
|
(topic, *part)).fetchall())
|
||||||
|
return found
|
||||||
|
|
||||||
|
def put_verdicts(self, topic: str, verdicts: dict[str, str]) -> None:
|
||||||
|
now = time.time()
|
||||||
|
with self._connect() as connection:
|
||||||
|
connection.executemany("INSERT OR REPLACE INTO relevance VALUES (?, ?, ?, ?)",
|
||||||
|
[(topic, work, verdict, now) for work, verdict in verdicts.items()])
|
||||||
|
|||||||
@ -185,7 +185,7 @@ def test_name_with_diacritics_prefers_the_exact_spelling_and_warns_about_namesak
|
|||||||
assert "Moja práca" in exact["answer"] and "Cudzia práca" not in exact["answer"]
|
assert "Moja práca" in exact["answer"] and "Cudzia práca" not in exact["answer"]
|
||||||
plain = A._answer("Ake su prace Jan Ptak?", complete=crzp["no_model"])
|
plain = A._answer("Ake su prace Jan Ptak?", complete=crzp["no_model"])
|
||||||
assert "Cudzia práca" in plain["answer"] and "Upozornenie: menu zodpovedá v CRZP viac pravdepodobných osôb" in plain["answer"]
|
assert "Cudzia práca" in plain["answer"] and "Upozornenie: menu zodpovedá v CRZP viac pravdepodobných osôb" in plain["answer"]
|
||||||
assert "- Ján Pták — Technická univerzita v Košiciach (autor; 2025; 1 práca)" in plain["answer"]
|
assert "- Ján Pták — Technická univerzita v Košiciach, FEI, KEMT (autor; 2025; 1 práca: „Moja práca“)" in plain["answer"]
|
||||||
|
|
||||||
|
|
||||||
def test_about_shows_a_summary_only_after_the_check(crzp):
|
def test_about_shows_a_summary_only_after_the_check(crzp):
|
||||||
@ -478,13 +478,14 @@ def test_opponent_of_a_titled_work_and_supervisors_of_a_topic(crzp):
|
|||||||
result = A._answer("Kto bol oponentom práce „Trénovanie modelov reči“?", complete=crzp["no_model"])
|
result = A._answer("Kto bol oponentom práce „Trénovanie modelov reči“?", complete=crzp["no_model"])
|
||||||
assert "Oponentom bakalárskej práce „Trénovanie modelov reči“ (2025) bol Jozef Juhár." in result["answer"]
|
assert "Oponentom bakalárskej práce „Trénovanie modelov reči“ (2025) bol Jozef Juhár." in result["answer"]
|
||||||
assert "II" not in result["answer"]
|
assert "II" not in result["answer"]
|
||||||
crzp["result"] = found([row(f"Emócie {i}", supervisor=s) for i, s in
|
crzp["result"] = found([row(f"Rozpoznávanie emócií {i}", supervisor=s) for i, s in
|
||||||
enumerate(["Ondáš, Stanislav"] * 3 + ["Pleva, Matúš"] * 2)])
|
enumerate(["Ondáš, Stanislav"] * 3 + ["Pleva, Matúš"] * 2)])
|
||||||
reply = {"intent": "relation", "people": [], "topics": ["rozpoznávanie emócií"], "title": None,
|
reply = {"intent": "relation", "people": [], "topics": ["rozpoznávanie emócií"], "title": None,
|
||||||
"target_role": "supervisor"}
|
"target_role": "supervisor"}
|
||||||
model = lambda messages, **kw: {"choices": [{"message": {"content": json.dumps(reply)}}]}
|
model = lambda messages, **kw: {"choices": [{"message": {"content": json.dumps(reply)}}]}
|
||||||
topic = A._answer("Kto viedol práce o rozpoznávaní emócií?", complete=model)
|
topic = A._answer("Kto viedol práce o rozpoznávaní emócií?", complete=model)
|
||||||
assert "- Stanislav Ondáš (3 práce)\n- Matúš Pleva (2 práce)" in topic["answer"]
|
assert topic["answer"].startswith("Najviac prác na tému „rozpoznávanie emócií“ viedol Stanislav Ondáš (TUKE) – 3.")
|
||||||
|
assert "Ďalší s viacerými prácami na túto tému:\n- Matúš Pleva (TUKE) – 2" in topic["answer"]
|
||||||
|
|
||||||
|
|
||||||
def test_school_count_uses_the_crzp_total_only_when_every_read_row_is_from_that_school(crzp):
|
def test_school_count_uses_the_crzp_total_only_when_every_read_row_is_from_that_school(crzp):
|
||||||
@ -522,16 +523,16 @@ def test_a_proposed_term_is_searched_only_when_crzp_uses_it_next_to_the_topic(cr
|
|||||||
reply = {"people": [], "topics": ["blockchain"], "alternatives": ["rozložená kniha"], "title": None,
|
reply = {"people": [], "topics": ["blockchain"], "alternatives": ["rozložená kniha"], "title": None,
|
||||||
"target_role": None, "intent": "list"}
|
"target_role": None, "intent": "list"}
|
||||||
query = understand("Ktoré práce sú o blockchain?", complete=model_reply(reply))
|
query = understand("Ktoré práce sú o blockchain?", complete=model_reply(reply))
|
||||||
assert query.alternatives == ["distribuovaná účtovná kniha", "rozložená kniha"] # reviewed table first
|
assert query.alternatives == ["distributed ledger", "rozložená kniha"] # reviewed table first
|
||||||
crzp["result"] = found([])
|
crzp["result"] = found([])
|
||||||
crzp["by_text"] = {"blockchain": found([row("Blockchain v logistike", keywords=("blockchain", "smart kontrakt"))]),
|
crzp["by_text"] = {"blockchain": found([row("Blockchain v logistike", keywords=("blockchain", "smart kontrakt"))]),
|
||||||
"distribuovaná účtovná kniha": found([row("Distribuovaná účtovná kniha v praxi")])}
|
"distributed ledger": found([row("Distributed ledger v praxi")])}
|
||||||
for key, value in crzp["by_text"].items():
|
for key, value in crzp["by_text"].items():
|
||||||
value["query"] = key
|
value["query"] = key
|
||||||
for r in value["rows"]:
|
for r in value["rows"]:
|
||||||
r["sid"] = key[:4]
|
r["sid"] = key[:4]
|
||||||
A._answer("Ktoré práce sú o blockchain?", complete=model_reply(reply))
|
A._answer("Ktoré práce sú o blockchain?", complete=model_reply(reply))
|
||||||
assert [t for t, _ in crzp["searches"]] == ["blockchain", "distribuovaná účtovná kniha"] # no "rozložená kniha"
|
assert [t for t, _ in crzp["searches"]] == ["blockchain", "distributed ledger"] # no "rozložená kniha"
|
||||||
crzp["searches"].clear()
|
crzp["searches"].clear()
|
||||||
reply["alternatives"] = ["smart kontrakt"] # CRZP writes it in a work found for the topic: searched
|
reply["alternatives"] = ["smart kontrakt"] # CRZP writes it in a work found for the topic: searched
|
||||||
A._answer("Ktoré práce sú o blockchain?", complete=model_reply(reply))
|
A._answer("Ktoré práce sú o blockchain?", complete=model_reply(reply))
|
||||||
@ -565,7 +566,7 @@ def test_follow_up_keeps_the_previous_conditions_and_replaces_the_new_ones(crzp,
|
|||||||
schools = follow(crzp, "a z akých škôl boli tí študenti?", first)
|
schools = follow(crzp, "a z akých škôl boli tí študenti?", first)
|
||||||
assert schools["status"] == "ok" and "Žilinská univerzita v Žiline (1 práca)" in schools["answer"]
|
assert schools["status"] == "ok" and "Žilinská univerzita v Žiline (1 práca)" in schools["answer"]
|
||||||
assert "Technická univerzita v Košiciach (1 práca: FEI, KEMT 1)" in schools["answer"] and "2 práce)" in schools["answer"]
|
assert "Technická univerzita v Košiciach (1 práca: FEI, KEMT 1)" in schools["answer"] and "2 práce)" in schools["answer"]
|
||||||
assert "školiteľ Peter Novák; rok 2024" in schools["answer"]
|
assert "vedúci Peter Novák; rok 2024" in schools["answer"]
|
||||||
year = follow(crzp, "a v roku 2023?", first)
|
year = follow(crzp, "a v roku 2023?", first)
|
||||||
assert "**C**" in year["answer"] and "**A**" not in year["answer"] and "rok 2023" in year["answer"]
|
assert "**C**" in year["answer"] and "**A**" not in year["answer"] and "rok 2023" in year["answer"]
|
||||||
crzp["result"] = found([row("A", year=2024), row("C", year=2023), row("E", year=2024),
|
crzp["result"] = found([row("A", year=2024), row("C", year=2023), row("E", year=2024),
|
||||||
@ -612,7 +613,7 @@ def test_schools_group_faculties_and_a_follow_up_name_keeps_the_role(crzp, signe
|
|||||||
assert "- Slovenská technická univerzita v Bratislave (2 práce: FEI ÚMIKT (FEI) 1; FIIT UISI (FIIT) 1)" in schools["answer"]
|
assert "- Slovenská technická univerzita v Bratislave (2 práce: FEI ÚMIKT (FEI) 1; FIIT UISI (FIIT) 1)" in schools["answer"]
|
||||||
reply = {"people": [{"name": "Ján Staš", "role": "author"}], "topics": [], "title": None, "target_role": None}
|
reply = {"people": [{"name": "Ján Staš", "role": "author"}], "topics": [], "title": None, "target_role": None}
|
||||||
other = A._answer("a čo Ján Staš?", complete=model_reply(reply), context_token=first["conversation_context"]["token"])
|
other = A._answer("a čo Ján Staš?", complete=model_reply(reply), context_token=first["conversation_context"]["token"])
|
||||||
assert "školiteľ Ján Staš" in other["answer"] and "**C**" in other["answer"] # role kept, not the model's guess
|
assert "vedúci Ján Staš" in other["answer"] and "**C**" in other["answer"] # role kept, not the model's guess
|
||||||
none = A._answer("Ktoré práce viedol Peter Novák v roku 2023?", complete=crzp["no_model"])
|
none = A._answer("Ktoré práce viedol Peter Novák v roku 2023?", complete=crzp["no_model"])
|
||||||
assert none["status"] == "no_answer" and "v inej role: oponent pri 1 práci" in none["answer"]
|
assert none["status"] == "no_answer" and "v inej role: oponent pri 1 práci" in none["answer"]
|
||||||
empty = follow(crzp, "o čom je tá druhá?", none)
|
empty = follow(crzp, "o čom je tá druhá?", none)
|
||||||
@ -624,8 +625,8 @@ def test_namesakes_are_asked_for_before_a_summary_and_the_choice_is_a_follow_up(
|
|||||||
school="Iná univerzita v Trnave FF KSJ", year=2019)])
|
school="Iná univerzita v Trnave FF KSJ", year=2019)])
|
||||||
asked = A._answer("Ake klucove slova ma praca Jan Ptak?", complete=crzp["no_model"])
|
asked = A._answer("Ake klucove slova ma praca Jan Ptak?", complete=crzp["no_model"])
|
||||||
assert asked["status"] == "ambiguous" and asked["accepted_for_delivery"] is True
|
assert asked["status"] == "ambiguous" and asked["accepted_for_delivery"] is True
|
||||||
assert "1. Ján Pták — Technická univerzita v Košiciach (autor; 2025; 1 práca)" in asked["answer"]
|
assert "1. Ján Pták — Technická univerzita v Košiciach, FEI, KEMT (autor; 2025; 1 práca: „" in asked["answer"]
|
||||||
assert "2. Jan Pták — Iná univerzita v Trnave (autor; 2019; 1 práca)" in asked["answer"]
|
assert "2. Jan Pták — Iná univerzita v Trnave, FF KSJ (autor; 2019; 1 práca: „Cudzia práca“)" in asked["answer"]
|
||||||
assert_client_accepts(asked, "Ake klucove slova ma praca Jan Ptak?")
|
assert_client_accepts(asked, "Ake klucove slova ma praca Jan Ptak?")
|
||||||
second = follow(crzp, "2", asked)
|
second = follow(crzp, "2", asked)
|
||||||
assert second["status"] == "ok" and "Cudzia práca" in second["answer"] and "Moja práca" not in second["answer"]
|
assert second["status"] == "ok" and "Cudzia práca" in second["answer"] and "Moja práca" not in second["answer"]
|
||||||
@ -792,3 +793,150 @@ def test_the_surname_alone_is_the_last_resort_and_the_first_name_is_checked(crzp
|
|||||||
result = A._answer("Aké kľúčové slová má práca Samka Furdu?", complete=_person_model("Samko Furda"))
|
result = A._answer("Aké kľúčové slová má práca Samka Furdu?", complete=_person_model("Samko Furda"))
|
||||||
searched = [t for t, _ in crzp["searches"]]
|
searched = [t for t, _ in crzp["searches"]]
|
||||||
assert searched[-1] == "Furda" and "Detekcia hrozieb" in result["answer"] and "Cudzia práca" not in result["answer"]
|
assert searched[-1] == "Furda" and "Detekcia hrozieb" in result["answer"] and "Cudzia práca" not in result["answer"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_nickname_is_read_from_the_typed_form_when_the_model_shortened_it():
|
||||||
|
from tools.crzp.answering.names import name_candidates
|
||||||
|
assert "Samuel Furda" in name_candidates("Sam Furda", "Sama Furdu")[0] # the model wrote "Sam"
|
||||||
|
assert "Samuel Furda" in name_candidates("Samka Furda", "Samka Furdu")[0]
|
||||||
|
assert name_candidates("Jana Nováková", "Jana Nováková")[0] == ["Jana Nováková"] # a first name, not "Jano"
|
||||||
|
|
||||||
|
|
||||||
|
def test_only_people_or_works_the_text_shows_can_be_referred_to(crzp):
|
||||||
|
crzp["result"] = found([row("Prvá práca", author="Furda, Samuel", year=2024), row("Druhá práca", year=2025)])
|
||||||
|
count = A._answer("Koľko prác viedol Peter Novák?", complete=crzp["no_model"])
|
||||||
|
assert count["count"] == 2 and count["_entities"] == [] # a count shows no work; its sources are only links
|
||||||
|
listed = A._answer("Aké kľúčové slová majú práce, ktoré viedol Peter Novák?", complete=crzp["no_model"])
|
||||||
|
assert {e["title"] for e in listed["_entities"]} == {"Prvá práca", "Druhá práca"}
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ topic vs. mention, rankings, follow-ups (19. 11. 2026)
|
||||||
|
|
||||||
|
def judging_model(verdicts, calls=None, understood=None):
|
||||||
|
"""A model that understands the question (understood) and judges works (verdicts: title -> "tema"/"zmienka")."""
|
||||||
|
def complete(messages, **kw):
|
||||||
|
system, user = messages[0]["content"], messages[-1]["content"]
|
||||||
|
if system.startswith("Posudzuješ"):
|
||||||
|
if calls is not None:
|
||||||
|
calls.append(user)
|
||||||
|
lines = re.findall(r"^(\d+)\. Názov: (.+?) \|", user, re.M)
|
||||||
|
return {"choices": [{"message": {"content": json.dumps({n: verdicts.get(t, "neiste") for n, t in lines})}}]}
|
||||||
|
return {"choices": [{"message": {"content": json.dumps(understood or {})}}]}
|
||||||
|
return complete
|
||||||
|
|
||||||
|
|
||||||
|
TOPIC_QUESTION = {"intent": "relation", "people": [], "topics": ["blockchain"], "title": None, "target_role": "supervisor",
|
||||||
|
"alternatives": []}
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_keyword_alone_is_no_topic_the_model_judges_it_once(crzp, tmp_path, monkeypatch):
|
||||||
|
from tools.crzp.answering import relevance
|
||||||
|
from tools.crzp.storage.cache import CrzpStore
|
||||||
|
store = CrzpStore(tmp_path / "c.sqlite")
|
||||||
|
monkeypatch.setattr(fetch, "store", lambda: store)
|
||||||
|
rows = [row("Blockchain v sieťach", supervisor="Papaj, Ján", keywords=("blockchain",)),
|
||||||
|
row("Regulácia kryptomien", supervisor="Sipko, Juraj", keywords=("blockchain", "kryptomeny"),
|
||||||
|
school="Paneurópska vysoká škola v Bratislave FE"),
|
||||||
|
row("Decentralizovaná aplikácia pre správu identity", supervisor="Hurtuk, Ján", keywords=("blockchain",))]
|
||||||
|
crzp["result"] = found(rows)
|
||||||
|
calls = []
|
||||||
|
model = judging_model({"Regulácia kryptomien": "zmienka", "Decentralizovaná aplikácia pre správu identity": "tema"},
|
||||||
|
calls, TOPIC_QUESTION)
|
||||||
|
query = understand("Kto viedol najviac prác o blockchaine?", complete=model)
|
||||||
|
found_, kept = A.find(query)
|
||||||
|
verdicts = relevance.judge(kept, query, complete=model)
|
||||||
|
by_title = {r["title"]: verdicts[relevance.work_id(r)] for r in kept}
|
||||||
|
assert by_title == {"Blockchain v sieťach": "topic", "Regulácia kryptomien": "mention",
|
||||||
|
"Decentralizovaná aplikácia pre správu identity": "topic"} # "decentralizovaná aplikácia" is the topic itself
|
||||||
|
assert len(calls) == 1 and "Blockchain v sieťach" not in calls[0] # the title decides without the model
|
||||||
|
relevance.judge(kept, query, complete=model)
|
||||||
|
assert len(calls) == 1 # stored verdicts are not asked again
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_model_cannot_make_a_work_without_the_term_a_topic(crzp, tmp_path, monkeypatch):
|
||||||
|
from tools.crzp.answering import relevance
|
||||||
|
from tools.crzp.storage.cache import CrzpStore
|
||||||
|
monkeypatch.setattr(fetch, "store", lambda: CrzpStore(tmp_path / "c.sqlite"))
|
||||||
|
query = understand("Kto viedol najviac prác o blockchaine?", complete=judging_model({}, None, TOPIC_QUESTION))
|
||||||
|
work = {"title": "Účtovníctvo malých podnikov", "keywords": ["účtovníctvo"], "school": "X", "year": 2024, "authors": ["A, B"]}
|
||||||
|
verdicts = relevance.judge([work], query, complete=judging_model({"Účtovníctvo malých podnikov": "tema"}))
|
||||||
|
assert verdicts[relevance.work_id(work)] != "topic"
|
||||||
|
assert relevance.mentions("DeFi herná platforma", "defi") and not relevance.mentions("Definícia pojmov", "defi")
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_topic_ranking_reads_as_a_sentence_with_one_source_per_person(crzp, tmp_path, monkeypatch):
|
||||||
|
from tools.crzp.storage.cache import CrzpStore
|
||||||
|
monkeypatch.setattr(fetch, "store", lambda: CrzpStore(tmp_path / "c.sqlite"))
|
||||||
|
works = ([row(f"Blockchain A{i}", supervisor="Košťál, Kristián", year=2020 + i % 6) for i in range(9)]
|
||||||
|
+ [row(f"Blockchain B{i}", supervisor="Hurtuk, Ján") for i in range(4)]
|
||||||
|
+ [row(f"Blockchain C{i}", supervisor="Papaj, Ján") for i in range(3)]
|
||||||
|
+ [row(f"Blockchain D{i}", supervisor="Majer, Tomáš") for i in range(2)]
|
||||||
|
+ [row("Blockchain E", supervisor="Malý, Igor")]
|
||||||
|
+ [row(f"Kryptomeny {i}", supervisor="Sipko, Juraj", keywords=("blockchain",)) for i in range(12)])
|
||||||
|
crzp["result"] = found(works)
|
||||||
|
model = judging_model({f"Kryptomeny {i}": "zmienka" for i in range(12)}, None, TOPIC_QUESTION)
|
||||||
|
result = A._answer("Kto viedol najviac prác o blockchaine?", complete=model)
|
||||||
|
text = result["answer"]
|
||||||
|
assert text.startswith("Najviac prác na tému „blockchain“ viedol Kristián Košťál (TUKE) – 9.")
|
||||||
|
assert "Ďalší s viacerými prácami na túto tému:\n- Ján Hurtuk (TUKE) – 4\n- Ján Papaj (TUKE) – 3" in text
|
||||||
|
assert "Majer" not in text and "Sipko" not in text # under a third of the leader / only mentions
|
||||||
|
assert "(19 z 31 prác)" in text and result["_offer"] == "Chceš vidieť ďalších (2)?"
|
||||||
|
assert [r["name"] for r in result["_rest"]] == ["Tomáš Majer (TUKE) – 2", "Igor Malý (TUKE) – 1"]
|
||||||
|
assert len(result["source_urls"]) == 3 # the newest work of each person shown
|
||||||
|
assert [e["name"] for e in result["_entities"]] == ["Kristián Košťál", "Ján Hurtuk", "Ján Papaj"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_repeated_submission_is_one_work_two_students_of_one_title_are_two():
|
||||||
|
rows = [{"title": "Regulácia krypto mien", "year": 2024, "work_type": "diploma_thesis", "authors": ["Halfon, Nikolas"]},
|
||||||
|
{"title": "Regulácia krypto mien", "year": 2023, "work_type": "diploma_thesis", "authors": ["Halfon, Nikolas"]},
|
||||||
|
{"title": "Regulácia krypto mien", "year": 2024, "work_type": "diploma_thesis", "authors": ["Halienková, Ľubica"]},
|
||||||
|
{"title": "Regulácia krypto mien", "year": 2018, "work_type": "diploma_thesis", "authors": ["Halfon, Nikolas"]}]
|
||||||
|
kept = A.resubmissions(rows)
|
||||||
|
assert [(r["authors"][0], r["year"]) for r in kept] == [("Halfon, Nikolas", 2024), ("Halienková, Ľubica", 2024),
|
||||||
|
("Halfon, Nikolas", 2018)]
|
||||||
|
from tools.crzp.answering.understand import Person
|
||||||
|
groups = A.identities(found([row("Cross-blockchain sharing", author="Morháč, Dušan", year=2022),
|
||||||
|
row("Cross-blockchain sharing", author="Páleník, Roman", year=2022)])["rows"],
|
||||||
|
Person(name="Roman Páleník", role="author"))
|
||||||
|
assert len(groups) == 1 and groups[0]["count"] == 1 # the second student keeps his work
|
||||||
|
|
||||||
|
|
||||||
|
def test_follow_ups_about_the_previous_search(crzp, signed):
|
||||||
|
crzp["result"] = found([row(f"Práca {i}", year=2024 + i % 2, kind="Zverejnená bakalárska práca") for i in range(10)])
|
||||||
|
count = A._answer("Koľko bakalárskych prác viedol Peter Novák?", complete=crzp["no_model"])
|
||||||
|
examples = follow(crzp, "aké napr.?", count)
|
||||||
|
assert examples["answer"].startswith("Našlo sa 10 prác") and "8 najnovších" in examples["answer"]
|
||||||
|
four = follow(crzp, "vypíš všetky 4", count)
|
||||||
|
assert "4 najnovších" in four["answer"]
|
||||||
|
split = follow(crzp, "rozdeľ to podľa rokov", count)
|
||||||
|
assert "Podľa rokov (od najnovšieho):\n- 2025: 5\n- 2024: 5" in split["answer"]
|
||||||
|
years = follow(crzp, "rozdeľ to na 2024 a 2025", count)
|
||||||
|
assert "v roku 2024 5 bakalárskych prác a v roku 2025 5, teda rovnako" in years["answer"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_two_years_are_compared_with_the_difference(crzp):
|
||||||
|
crzp["result"] = found([row(f"P{i}", year=2024, kind="Zverejnená bakalárska práca") for i in range(3)]
|
||||||
|
+ [row(f"Q{i}", year=2025, kind="Zverejnená bakalárska práca") for i in range(5)])
|
||||||
|
result = A._answer("koľko bolo obhájených bp na KEMT v roku 2024 a koľko v roku 2025", complete=crzp["no_model"])
|
||||||
|
assert result["answer"].startswith("Na KEMT FEI Technickej univerzity v Košiciach obhájili v roku 2024 3 bakalárske "
|
||||||
|
"práce a v roku 2025 5, teda o 2 viac.")
|
||||||
|
person = A._answer("O koľko viac bakalárskych prác viedol Peter Novák v roku 2025 ako v roku 2024?", complete=crzp["no_model"])
|
||||||
|
assert person["answer"].startswith("Peter Novák viedol v roku 2024 3 bakalárske práce a v roku 2025 5, teda o 2 viac.")
|
||||||
|
one = A._answer("Koľko bakalárskych prác obhájili na KEMT v roku 2024?",
|
||||||
|
complete=crzp["no_model"]) if False else None
|
||||||
|
assert A.works_phrase(1, ["bachelor_thesis"]) == "1 bakalársku prácu"
|
||||||
|
|
||||||
|
|
||||||
|
def test_about_summarizes_every_work_up_to_eight(crzp, monkeypatch):
|
||||||
|
rows = [row(f"Práca {i}", year=2020 + i) for i in range(4)]
|
||||||
|
crzp["result"] = found(rows)
|
||||||
|
monkeypatch.setattr(fetch, "detail", lambda sid: {"sid": sid, "title": "t", "abstract": "abstrakt", "keywords": []})
|
||||||
|
monkeypatch.setattr(A, "summary", lambda detail, complete=None: ("", "Zhrnutie."))
|
||||||
|
result = A._answer("O čom sú práce, ktoré viedol Peter Novák?", complete=crzp["no_model"])
|
||||||
|
assert result["answer"].count("Zhrnutie.") == 4 and result["answer"].index("Práca 3") < result["answer"].index("Práca 0")
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_abbreviation_is_matched_in_upper_case_only():
|
||||||
|
from tools.crzp.answering.relevance import mentions
|
||||||
|
assert mentions("Vyhodnotenie WER pre rozpoznávanie reči", "WER") and mentions("Systém RAG-u", "RAG")
|
||||||
|
assert not mentions("Kommentierte Übersetzung: Wer sind die Gewinner?", "WER")
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user