From 747a4ad937992b2607014c675b77a65903a9c31f Mon Sep 17 00:00:00 2001 From: jp170na Date: Thu, 19 Nov 2026 14:09:51 +0100 Subject: [PATCH] =?UTF-8?q?kontrola=20a=20s=C3=BAlad?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- README.md | 5 ++ test/presentation/test_combined_answers.py | 8 +++ test/verification/test_delivery_contract.py | 51 +++++++++++++++++++ tools/answers/answer_delivery.py | 5 ++ tools/answers/combined.py | 25 +++++++-- tools/answers/presentation/finalize.py | 16 ++++++ .../answers/verification/delivery_contract.py | 34 ++++++++++++- tools/crzp/answering/answer.py | 29 +++++++++-- tools/crzp/answering/context.py | 14 +++-- tools/crzp/answering/understand.py | 1 + tools/crzp/fetch.py | 3 ++ tools/crzp/storage/cache.py | 5 +- tools/crzp/tests/test_crzp.py | 27 ++++++++++ 13 files changed, 210 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 13a7d3f..862f347 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,11 @@ s osobami a témami ZP Wiki (`PROBABLY_SAME`, `SAME_TOPIC`). - 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. +- Záverečná kontrola odpovede ZP Wiki dostane presne text, ktorý uvidí používateľ (študenti len s plánom sú + už zbalení do jednej poznámky); odpoveď zložená len zo zdrojových riadkov, ktorú kontrola zamietne pre fakty, + dostane ešte jednu nezávislú kontrolu a zobrazí sa, len keď ju potvrdí. +- Nadväzujúca otázka na to isté hľadanie povie, keď sa medzitým zmenil počet prác v registri („z 34 na 35“); + odpoveď o aktuálnom roku z údajov starších ako 1 deň uvedie ich dátum („Údaje sú k 14. 11. 2026.“). - 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. diff --git a/test/presentation/test_combined_answers.py b/test/presentation/test_combined_answers.py index ba2b4f9..5fa3f48 100644 --- a/test/presentation/test_combined_answers.py +++ b/test/presentation/test_combined_answers.py @@ -556,3 +556,11 @@ def test_a_question_naming_crzp_gets_what_crzp_records(combo): "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"] + + +def test_a_thesis_choice_is_asked_again_with_the_person_named(): + assert C.pending_question("A kto je jeho vedúci?", {}, "Ján Holp") == "A kto je vedúci Jána Holpa?" + assert C.pending_question("Aké technológie použil?", {}, "Ján Holp") == "Aké technológie použil Ján Holp?" + assert C.pending_question("A kto je jeho vedúci?", {"resolved_query": "Kto je vedúci Jána Holpa?"}, + "Ján Holp") == "Kto je vedúci Jána Holpa?" + assert C.pending_question("Kto je vedúci Jána Ptáka?", {}, "Ján Pták") == "Kto je vedúci Jána Ptáka?" diff --git a/test/verification/test_delivery_contract.py b/test/verification/test_delivery_contract.py index 4751b26..0c5dd5f 100644 --- a/test/verification/test_delivery_contract.py +++ b/test/verification/test_delivery_contract.py @@ -310,3 +310,54 @@ def test_doubt_disclosed_by_the_backend_notice_is_delivered_as_partial(): # The same doubt without the backend's own notice is still rejected. out=c.enforce(plan.question,'rag',plan,result,index=index,complete=doubt(lambda t:note not in t)) assert not out['accepted_for_delivery'] + + +def _verbatim_fixture(): + """An answer made only of a heading, the source line of the evidence and the source links.""" + plan,result,index=fixture() + row=result['evidence'][0] + result['answer']='**Eva Nová**\n\n- Diplomová práca 2027; zaznamenaný výsledok: '+row['text'].lstrip('- ')+'\n\nZdroje: '+row['source_url'] + return plan,result,index + + +def test_a_verbatim_answer_doubted_once_gets_one_more_independent_audit(): + plan,result,index=_verbatim_fixture();calls=[] + def model(messages): + calls.append(1) + return audit(facts_supported=len(calls)>1)(messages) # the first audit doubts, the second confirms + assert c.verbatim_answer(result) + out=c.enforce(plan.question,'rag',plan,result,index=index,complete=model) + assert len(calls)==2 and out['accepted_for_delivery'] and out['delivery_check']['code']=='complete' + + +def test_two_rejections_of_a_verbatim_answer_stand(): + plan,result,index=_verbatim_fixture();calls=[] + def model(messages): + calls.append(1) + return audit(facts_supported=False)(messages) + out=c.enforce(plan.question,'rag',plan,result,index=index,complete=model) + assert len(calls)==2 and not out['accepted_for_delivery'] and out['reason']=='answer_rejected' + + +def test_model_wording_never_gets_a_second_audit(): + plan,result,index=fixture();calls=[] # "Eva Nová: funguje model BERT." is not the source line + def model(messages): + calls.append(1) + return audit(facts_supported=False)(messages) + assert not c.verbatim_answer(result) + out=c.enforce(plan.question,'rag',plan,result,index=index,complete=model) + assert len(calls)==1 and not out['accepted_for_delivery'] + + +def test_the_audit_sees_plan_only_students_as_the_closing_notice_the_user_sees(): + from tools.answers.presentation.finalize import collapse_side_people + result = {"answer": "**Andrii Pervashov**\n\n- Diplomová práca 2027; zaznamenaný výsledok: Je urobené vyhodnotenie WER.\n\n" + "**Nikita Bodnar**\n\nNikita Bodnar — téma je v zadaní, téme alebo pláne práce; zaznamenaný výsledok " + "k nej sa nenašiel.\n\n- Bakalárska práca 2025; plán: Vyhodnoťte pomocou metriky WER.\n\n" + "Zdroje: https://zp.test/a, https://zp.test/b", "presentation_notes": []} + out = collapse_side_people(result) + assert out["answer"] == ("**Andrii Pervashov**\n\n- Diplomová práca 2027; zaznamenaný výsledok: Je urobené vyhodnotenie WER." + "\n\nTéma je len v zadaní alebo pláne, bez zaznamenaného výsledku: Nikita Bodnar." + "\n\nZdroje: https://zp.test/a, https://zp.test/b") + assert "Téma je len v zadaní alebo pláne, bez zaznamenaného výsledku: Nikita Bodnar." in out["presentation_notes"] + assert collapse_side_people({"answer": "**X**\n\n- iné"}) == {"answer": "**X**\n\n- iné"} # nothing to collapse diff --git a/tools/answers/answer_delivery.py b/tools/answers/answer_delivery.py index 876c828..e70fa9c 100644 --- a/tools/answers/answer_delivery.py +++ b/tools/answers/answer_delivery.py @@ -189,6 +189,11 @@ def _deliver_checked( result=checked_repository_links(result) from tools.answers.presentation.notices import clean_answer_notices result=clean_answer_notices(result) + if plan_data and plan_data.get('intent')=='discovery': + # "Kto robil X?": the audit checks the list the user will see (students with only a plan are one closing + # notice); a comparison or overview of named people keeps every asked person + from tools.answers.presentation.finalize import collapse_side_people + result=collapse_side_people(result) if plan_data: from tools.answers.verification.delivery_contract import enforce result=enforce(question,engine,QuestionPlan.model_validate(plan_data),result,index=index,facts=facts, diff --git a/tools/answers/combined.py b/tools/answers/combined.py index 32bf520..01f7bb4 100644 --- a/tools/answers/combined.py +++ b/tools/answers/combined.py @@ -1582,7 +1582,8 @@ def _unified(asked, question, engine, wiki, wiki_ok, part, person, wiki_context, result.update(status="ambiguous", reason="clarification_required", delivery_check={"layer": "planning", "code": "clarification_required", "request_fingerprint": fingerprint(question, engine)}) - return _with_token(result, wiki_context=wiki_context, options=out["options"], question=question) + return _with_token(result, wiki_context=wiki_context, options=out["options"], + question=pending_question(question, wiki, person)) elif U.METHODS_Q.search(low): options = U.work_options(person, works, low) if options: @@ -1591,7 +1592,8 @@ def _unified(asked, question, engine, wiki, wiki_ok, part, person, wiki_context, result.update(status="ambiguous", reason="clarification_required", delivery_check={"layer": "planning", "code": "clarification_required", "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=pending_question(question, wiki, person)) out = U.methods(person, works, wiki_text, (part or {}).get("text") or "", low) elif U.ABOUT_Q.search(low): out = U.about(person, works, low) @@ -1661,7 +1663,8 @@ def _compose(asked: str, question: str, engine: str, wiki: dict, part: dict | No result.update(status="ambiguous", reason="clarification_required", delivery_check={"layer": "planning", "code": "clarification_required", "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=pending_question(question, wiki, person)) 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.update(status="ambiguous", reason="clarification_required", @@ -1742,6 +1745,22 @@ def crzp_names_the_person(question: str, wiki: dict, part: dict | None) -> bool: return len(name.split()) >= 2 and in_question(name, question) +def pending_question(question: str, wiki: dict, person: str | None) -> str: + """The question a thesis choice ("diplomovku", "1") answers, with the person in it: the reply is asked + again without the conversation, so "A kto je jeho vedúci?" becomes "A kto je vedúci Jána Holpa?".""" + if not person: + return question + surname = normalized(person.split()[-1])[:4] + resolved = wiki.get("resolved_query") + if isinstance(resolved, str) and surname in normalized(resolved): + return resolved # the wiki's own resolution of the follow-up + if surname in normalized(question): + return question + from tools.answers.presentation.unified import genitive + named = re.sub(r"(?i)\b(?:jeho|jej)\s+([^\W\d_]+)", lambda m: f"{m.group(1)} {genitive(person)}", question, count=1) + return named if named != question else question.rstrip(" ?.!") + f" {person}?" + + 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.""" if re.search(r"\b(?:bakalar\w*|diplom\w*|dizerta\w*|projekt\w*)\b", low): diff --git a/tools/answers/presentation/finalize.py b/tools/answers/presentation/finalize.py index 89f0eb3..0e1aa5f 100644 --- a/tools/answers/presentation/finalize.py +++ b/tools/answers/presentation/finalize.py @@ -76,6 +76,22 @@ def _collapse_side_people(blocks: list[str]) -> list[str]: else: kept += group return kept + [f"{label}: {', '.join(names)}." for label, names in side.items()] +def collapse_side_people(result: dict) -> dict: + """The answer as the user will see it before the final audit checks it: a student whose only match is an + assignment/plan or reading becomes one closing line ("Téma je len v zadaní alebo pláne, bez zaznamenaného + výsledku: Nikita Bodnar."), a code-made notice, instead of a block listing that student among those who did + it. Without this the audit judged a block the user never sees ("vyhodnoťte pomocou WER" as if done).""" + text = result.get("answer") + if not isinstance(text, str) or not any(key in text for key in SIDE): + return result + blocks = [b.strip() for b in re.split(r"\n\s*\n", text) if b.strip()] + sources = [b for b in blocks if b.startswith(("Zdroje:", "Zdroj:"))] + collapsed = _collapse_side_people([b for b in blocks if b not in sources]) + notes = [b for b in collapsed if any(b.startswith(label + ":") for label in SIDE.values())] + return {**result, "answer": "\n\n".join([*collapsed, *sources]), + "presentation_notes": list(dict.fromkeys([*(result.get("presentation_notes") or []), *notes]))} + + MISSING = re.compile(r"(?:požadovaný údaj nie je v tomto zápise doložený|v podkladoch chýbajú doložené údaje|" r"Požadované údaje k tomuto stretnutiu nie sú v dostupnom výbere doložené)", re.I) RENAME = [ diff --git a/tools/answers/verification/delivery_contract.py b/tools/answers/verification/delivery_contract.py index 30f02bb..d4cc891 100644 --- a/tools/answers/verification/delivery_contract.py +++ b/tools/answers/verification/delivery_contract.py @@ -55,7 +55,12 @@ event date are different. A record date cannot become an event date. Do not infer supervision, graduation, collaboration or successful implementation. A record dated before the work year is normal: a thesis of year 2027 is worked on during 2026; it is no inconsistency. For "who did X" a student's own record -of doing X supports listing that student; sole authorship is not required. +of doing X supports listing that student; sole authorship is not required. The +record need not repeat the question's own words for X ("modely", "systém"): a +record of the activity with the asked method, metric or tool (an evaluation with +WER, a model fine-tuned with LoRA) supports it; a plan or assignment does not. +A supplied deterministic notice naming students whose topic is only in a plan or +assignment is a disclosure that they did NOT do X, never a claim that they did. answered requires evidence and an answer that addresses that requirement. missing_disclosed is allowed only when a supplied deterministic missing-data notice is explicitly present in the answer and the supplied sources do not @@ -329,6 +334,26 @@ def _with_notice(result,notice): return result if notice in answer else {**result,'answer':answer.rstrip()+'\n\n'+notice} +def verbatim_answer(result): + """Every paragraph of the answer is code-made: a heading, a deterministic notice, the source line, or a + paragraph holding a supplied evidence unit's complete text byte for byte (a list item may hold several). + Such an answer contains no model wording, so a rejection of its facts is the audit's doubt, not a fact + the model wrote.""" + quotes=[re.sub(r'^\s*(?:[-*+]|\d+[.)])\s+','',r.get('text') or '').strip() for r in result.get('evidence',[])] + quotes=[q for q in quotes if len(q)>=12] + notes=[n for n in result.get('presentation_notes',[]) if n] + paragraphs=[p.strip() for p in (result.get('answer') or '').split('\n\n') if p.strip()] + if not paragraphs or not quotes: + return False + for paragraph in paragraphs: + if re.fullmatch(r'\*\*[^*\n]+\*\*',paragraph) or paragraph.startswith(('Zdroje:','Zdroj:')): + continue + if any(n in paragraph for n in notes) or any(q in paragraph for q in quotes): + continue + return False + return True + + def verbatim(result,swaps): """Restore the verbatim source lines replaced by not-yet-audited wording.""" answer=result.get('answer','') @@ -375,6 +400,13 @@ def enforce(query,engine,plan,result,*,index=None,facts=(),complete=None,prose_s # verbatim lines get their own audit when time allows. result=verbatim(result,prose_swaps) state=semantic_check(query,plan,result,complete=complete) if has_budget(audit_seconds) else 'unverified' + elif (getattr(error,'unsupported_facts',False) and verbatim_answer(result) + and has_budget(audit_seconds)): + # Only source lines (checked above by code) and the audit still doubts a fact: one more + # independent audit. Delivered only when it confirms; a second rejection stands. + from tools.answers import timing + timing.note('second_audit',True) + state=semantic_check(query,plan,result,complete=complete) elif deadline or (error.code=='verification_unavailable' and str(error.__cause__)=='input_budget'): # Out of time, or too many sources for one audit diff --git a/tools/crzp/answering/answer.py b/tools/crzp/answering/answer.py index 9d6f630..b94cad1 100644 --- a/tools/crzp/answering/answer.py +++ b/tools/crzp/answering/answer.py @@ -307,7 +307,9 @@ def _merge(results: list[dict]) -> dict: rows.append(row) elif row.get("sid") and not seen[key].get("sid"): # the same work read with its permalink seen[key].update(sid=row["sid"], url=row.get("url")) + read = [r["fetched_at"] for r in results if r.get("fetched_at")] return {"texts": [r["query"] for r in results], "totals": [r["total"] for r in results], + "fetched_at": min(read) if read else None, # the oldest data of the answer "total": results[0]["total"] if len(results) == 1 else sum(r["total"] for r in results), "facets": results[0]["facets"], "rows": rows, "complete": all(r["complete"] for r in results), "incomplete": [(r["query"], r["total"], len(r["rows"])) for r in results if not r["complete"]], @@ -1181,10 +1183,10 @@ def _answer(question: str, complete=None, context_token: str | None = None) -> d result = _answer_query(question, query, complete) if result["status"] in ("ok", "no_answer", "ambiguous") and result.get("reason") != "request_out_of_scope": conversation = context.issue(question, result.pop("_asked", query), result.pop("_shown", []), - result.pop("_options", None)) + result.pop("_options", None), matched=result.pop("_matched", None)) if conversation: result["conversation_context"] = conversation - result.pop("_shown", None), result.pop("_asked", None), result.pop("_options", None) + result.pop("_shown", None), result.pop("_asked", None), result.pop("_options", None), result.pop("_matched", None) return result @@ -1213,6 +1215,10 @@ def _answer_query(question: str, query: CrzpQuery, complete=None) -> dict: result = _result(question, "ambiguous", asked_who[0], reason="clarification_required") result["_shown"], result["_asked"], result["_options"] = [], asked, asked_who[1] return result + # The exact number of works meeting the conditions (every row read, or CRZP's own total of a search + # whose read rows all qualify); an "at least" reading has none and is never compared. + exact = len(rows) if found["complete"] else (found["total"] if found.get("facet_only") else None) + changed = (query.previous_count is not None and exact is not None and exact != query.previous_count) handler = {"list": _list, "count": _count, "keywords": _keywords, "relation": _relation, "similar": _similar, "schools": _schools, "sources": _sources}.get(query.intent) extras = {} @@ -1235,18 +1241,35 @@ def _answer_query(question: str, query: CrzpQuery, complete=None) -> dict: if query.unverified_only: body = (f"Výraz „{query.topic_key()}“ sa v CRZP nenašiel; uvedené práce sú nájdené pod navrhnutým " f"príbuzným výrazom „{'“, „'.join(query.unverified_only)}“ (návrh, nie overené synonymum).\n\n" + body) + if changed: # the count and the list behind it never contradict each other unexplained + body += f"\n\nOd predchádzajúcej odpovede sa počet nájdených prác zmenil z {query.previous_count} na {exact}." + body += data_date(query, found) truncated = not found["complete"] and not found.get("facet_only") # a CRZP total needs no read rows reasons = ["crzp_result_limit"] if truncated else [] body += "\n\nZdroj: Centrálny register záverečných prác (CRZP), metadáta záznamov." result = _result(question, "ok", body, rows=used, complete=not truncated, truncated=truncated, reasons=reasons, count=len(rows) if query.intent == "count" else None) - result["_shown"], result["_asked"] = used, asked + result["_shown"], result["_asked"], result["_matched"] = used, asked, exact 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 +DATA_AGE = 86400 # data of the current year older than this get their date in the answer + + +def data_date(query: CrzpQuery, found: dict) -> str: + """"Údaje sú k 14. 11. 2026." for a count, list or ranking of the current year whose data were read more than + a day ago (works of this year are still being added); nothing otherwise.""" + fetched = found.get("fetched_at") + if (query.intent not in ("count", "list", "relation", "sources") or not fetched + or time.localtime().tm_year not in query.years or time.time() - fetched <= DATA_AGE): + return "" + day = time.localtime(fetched) + return f"\n\nÚdaje sú k {day.tm_mday}. {day.tm_mon}. {day.tm_year}." + + def _school_of(name: str, rows: list[dict], field: str) -> str: schools = Counter(university(r) for r in rows if any(display_name(n) == name for n in r.get(field, []))) return schools.most_common(1)[0][0] if schools else "škola neuvedená" diff --git a/tools/crzp/answering/context.py b/tools/crzp/answering/context.py index 73b0ac2..1165ac8 100644 --- a/tools/crzp/answering/context.py +++ b/tools/crzp/answering/context.py @@ -68,16 +68,18 @@ def _unb64(value: str) -> bytes: return base64.b64decode(value + "=" * (-len(value) % 4), altchars=b"-_", validate=True) -def issue(question: str, query: CrzpQuery, shown: list[dict], options: list[dict] | None = None) -> dict | None: +def issue(question: str, query: CrzpQuery, shown: list[dict], options: list[dict] | None = None, + matched: int | None = None) -> dict | None: """conversation_context for the result, or None (no key configured, nothing to continue). - options: the namesakes offered in a clarification ({"name", "school"}).""" + options: the namesakes offered in a clarification ({"name", "school"}); matched: the exact number + of works meeting the conditions (None for an "at least" reading).""" key = _key() if key is None or not (query.people or query.title or query.topics or query.school): return None rows = [r for r in shown if r.get("sid")][:MAX_SIDS] payload = {"schema": SCHEMA, "expires": int(time.time()) + LIFETIME, "question": question, "query": query.model_dump(mode="json", include=CARRIED - {"sids"}), - "sids": [r["sid"] for r in rows], "options": (options or [])[:8], + "sids": [r["sid"] for r in rows], "options": (options or [])[:8], "matched": matched, "titles": [f"{r['title'][:120]} ({r.get('year') or '?'})" for r in rows]} body = _b64(json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode()) token = body + "." + _b64(hmac.digest(key, body.encode(), "sha256")) @@ -136,7 +138,7 @@ def follow_up(question: str, new: CrzpQuery, previous: dict) -> tuple[CrzpQuery, conditions are kept and the new ones (person, topic, year, type, school, intent) replace them.""" low = fold(question) old: CrzpQuery = previous["query"] - about_previous = _about_previous(low, question, new, old) + about_previous = _about_previous(low, question, new, old, previous.get("matched")) if about_previous is not None: return about_previous, None own_subject = bool(new.people or new.title or new.topics) @@ -212,7 +214,7 @@ def follow_up(question: str, new: CrzpQuery, previous: dict) -> tuple[CrzpQuery, return merged, None -def _about_previous(low: str, question: str, new: CrzpQuery, old: CrzpQuery) -> CrzpQuery | None: +def _about_previous(low: str, question: str, new: CrzpQuery, old: CrzpQuery, matched: int | None = None) -> 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) @@ -228,6 +230,8 @@ def _about_previous(low: str, question: str, new: CrzpQuery, old: CrzpQuery) -> 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 merged.years == old.years and merged.work_types == old.work_types: # the same search: its count is compared + merged.previous_count = matched 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 diff --git a/tools/crzp/answering/understand.py b/tools/crzp/answering/understand.py index 7fcef94..2dfb05b 100644 --- a/tools/crzp/answering/understand.py +++ b/tools/crzp/answering/understand.py @@ -117,6 +117,7 @@ class CrzpQuery(BaseModel): 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 split: str | None = None # follow-up "rozdeľ podľa rokov / typov": "year" or "type" + previous_count: int | None = None # follow-up of the same search: the exact count the previous answer had def topic_key(self) -> str: """The topic the alternative terms belong to (the rule phrase without the model).""" diff --git a/tools/crzp/fetch.py b/tools/crzp/fetch.py index fabfedb..8abbfde 100644 --- a/tools/crzp/fetch.py +++ b/tools/crzp/fetch.py @@ -137,6 +137,7 @@ def search(text: str, *, years: tuple[int, int] | None = None, work_types: list[ record_outcome(error) raise record_outcome(None) + result["fetched_at"] = time.time() cache.put_search(key, result) return {**result, "cached": False} @@ -250,6 +251,8 @@ def search_deep(text: str, *, years: tuple[int, int] | None = None, work_types: depth=LINKED_ROWS if links else limit, cache=cache), chunks)) rows = [r for part in parts for r in part["rows"]][:limit] read_total = sum(part["total"] for part in parts) + read = [t for t in (part.get("fetched_at") for part in [head, *parts]) if t] return {**head, "rows": rows, "complete": len(rows) >= head["total"], "chunks": chunks, + "fetched_at": min(read) if read else None, "links": links, "cached": all(part.get("cached") for part in parts), "chunks_complete": all(part["complete"] for part in parts) and read_total >= head["total"]} diff --git a/tools/crzp/storage/cache.py b/tools/crzp/storage/cache.py index c4f34ef..146f5fa 100644 --- a/tools/crzp/storage/cache.py +++ b/tools/crzp/storage/cache.py @@ -59,7 +59,10 @@ class CrzpStore: if row is None or time.time() - row[0] > ttl: return None payload = json.loads(row[1]) - return payload if payload.get("schema") == SCHEMA else None + if payload.get("schema") != SCHEMA: + return None + payload["fetched_at"] = row[0] # when CRZP was read (an answer about this year says the date of its data) + return payload def _put(self, table: str, key: str, payload: dict) -> None: with self._connect() as connection: diff --git a/tools/crzp/tests/test_crzp.py b/tools/crzp/tests/test_crzp.py index de27ad2..467adb9 100644 --- a/tools/crzp/tests/test_crzp.py +++ b/tools/crzp/tests/test_crzp.py @@ -3,6 +3,7 @@ Fixtures copy the structure of real opac.crzp.sk pages with invented people. """ import json +import time import httpx import pytest @@ -940,3 +941,29 @@ 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") + + +def test_a_follow_up_of_the_same_search_says_when_the_count_changed(crzp, signed): + works = [row(f"Práca {i}", year=2024, kind="Zverejnená bakalárska práca") for i in range(10)] + crzp["result"] = found(works) + count = A._answer("Koľko bakalárskych prác viedol Peter Novák v roku 2024?", complete=crzp["no_model"]) + assert "**10**" in count["answer"] + same = follow(crzp, "aké napr.?", count) + assert "zmenil" not in same["answer"] # the same data: nothing to explain + crzp["result"] = found(works + [row("Nová práca", year=2024, kind="Zverejnená bakalárska práca")]) + more = follow(crzp, "aké napr.?", count) + assert "Od predchádzajúcej odpovede sa počet nájdených prác zmenil z 10 na 11." in more["answer"] + other = follow(crzp, "a v roku 2023?", count) # other conditions: another number is no change + assert "zmenil" not in other["answer"] + + +def test_this_years_data_read_more_than_a_day_ago_carry_their_date(crzp): + this_year = time.localtime().tm_year + crzp["result"] = {**found([row("A", year=this_year), row("B", year=this_year)]), "fetched_at": time.time() - 3 * 86400} + old = A._answer(f"Koľko prác viedol Peter Novák v roku {this_year}?", complete=crzp["no_model"]) + day = time.localtime(time.time() - 3 * 86400) + assert f"Údaje sú k {day.tm_mday}. {day.tm_mon}. {day.tm_year}." in old["answer"] + crzp["result"]["fetched_at"] = time.time() - 3600 + assert "Údaje sú k" not in A._answer(f"Koľko prác viedol Peter Novák v roku {this_year}?", complete=crzp["no_model"])["answer"] + crzp["result"] = {**found([row("A", year=2020)]), "fetched_at": time.time() - 30 * 86400} + assert "Údaje sú k" not in A._answer("Koľko prác viedol Peter Novák v roku 2020?", complete=crzp["no_model"])["answer"]