julianvolodia's picture
Super-squash branch 'main' using huggingface_hub
90264a9
Raw History Blame Contribute Delete
13.8 kB
"""Parsing and assembling CKE-style task texts; static (code-only) validators for LLM outputs.
Everything that can be checked mechanically is checked here, not by the LLM: headings, option shuffles and
answer keys, source labels, verbatim Wikipedia excerpts, rubric formats, answer leaks in 'identify' tasks.
"""
import random
import re
from common import stable_int, stems
HEADER_RE = re.compile(r"^Zadanie (\d+)\. \(0[–-](\d+)\)\s*$")
SRC_LABEL_RE = re.compile(r"^Tekst (\d)\.\s*(.*)$")
OPT_RE = re.compile(r"^([A-F])\.\s+(.*)$")
STMT_RE = re.compile(r"^([1-6])\.\s+(.*)$")
ELEM_RE = re.compile(r"^([a-e])\)\s*(.*)$")
IDENTIFY_RE = re.compile(r"(podaj|wpisz|napisz|wymień)\s+(nazw|imię|imiona|nazwisk|dat|rok|termin|pojęci)|"
r"rozpozn|zidentyfikuj|ustal,?\s+(kto|jak)", re.I)
SYNTH = "opracowanie syntetyczne"
ANAPHORA = re.compile(r"^(?:Z tego|Dlatego|Ponadto|Również|Jednak|Wówczas|Następnie|Tam|Ten|Ta|To|Te|Tego|Ci|"
r"Jego|Jej|Ich|On|Ona|Oni|Natomiast|Zaś|Poza tym|W związku z tym|W tym)\b")
FAKE_LABEL = re.compile(r"Tekst \d|Wikipedi|fragment artykułu", re.I)
WIKI_LABEL = "Tekst {n}. Fragment artykułu „{title}” (pl.wikipedia.org, CC BY-SA 4.0)"
TF_INSTR = "Oceń prawdziwość zdań. Zaznacz P, jeśli zdanie jest prawdziwe, albo F – jeśli jest fałszywe."
TF_INSTR_SRC = ("Na podstawie tekstu i własnej wiedzy oceń prawdziwość zdań. Zaznacz P, jeśli zdanie jest "
"prawdziwe, albo F – jeśli jest fałszywe.")
MCQ_RUBRIC = "1 pkt – za poprawną odpowiedź.\n0 pkt – odpowiedź błędna albo brak odpowiedzi."
TF_RUBRIC = "1 pkt – za trzy poprawne oceny.\n0 pkt – odpowiedź niepełna lub błędna albo brak odpowiedzi."
ESSAY_TAIL = ("Wypracowanie powinno zawierać stanowisko wobec tezy zawartej w temacie, jego uzasadnienie "
"(argumentację popartą wiedzą historyczną) oraz wnioski. Wypowiedź powinna liczyć co najmniej 300 słów.")
# ---------------------------------------------------------------- parsing originals
def parse(r):
"""Split a task text into parts: header, sources [(n, label, text)], body lines, options, statements, essay parts."""
lines = r["question"].split("\n")
out = {"header": lines[0], "sources": [], "body": [], "options": [], "statements": [], "instr": None,
"thesis": None, "elements": [], "pre": [], "tail": []}
i = 1
while i < len(lines):
m = SRC_LABEL_RE.match(lines[i].strip())
if m and (SYNTH in lines[i] or "Fragment" in lines[i] or m.group(2).startswith("(")):
j, txt = i + 1, []
while j < len(lines) and lines[j].strip() and not SRC_LABEL_RE.match(lines[j].strip()):
txt.append(lines[j])
j += 1
if not any(not l.strip() for l in lines[j:j + 30]) and len(txt) >= 1:
break # no blank line after the source: it is a single line
out["sources"].append((int(m.group(1)), lines[i].strip(), "\n".join(txt).strip()))
i = j
continue
out["body"].append(lines[i])
i += 1
body = [l for l in out["body"]]
if r["task_type"] == "closed_choice":
out["options"] = [(m.group(1), m.group(2)) for m in (OPT_RE.match(l.strip()) for l in body) if m]
out["pre"] = [l for l in body if not OPT_RE.match(l.strip()) and l.strip()]
elif r["task_type"] == "true_false":
out["statements"] = [(int(m.group(1)), m.group(2)) for m in (STMT_RE.match(l.strip()) for l in body) if m]
rest = [l for l in body if not STMT_RE.match(l.strip()) and l.strip()]
out["instr"] = next((l for l in rest if "Zaznacz P" in l or "prawdziw" in l), None)
out["pre"] = [l for l in rest if l != out["instr"]]
elif r["task_type"] == "essay":
k = next((n for n, l in enumerate(body) if l.strip().startswith("W argumentacji")), None)
start = 1 if body and body[0].strip().startswith("Napisz wypracowanie") else 0
out["pre"] = body[:start]
out["thesis"] = " ".join(l.strip() for l in body[start:k] if l.strip()) if k is not None else None
out["arg_line"] = body[k].strip() if k is not None else None
rest = body[k + 1:] if k is not None else []
out["elements"] = [l.strip() for l in rest if ELEM_RE.match(l.strip())]
out["tail"] = [l for l in rest if l.strip() and not ELEM_RE.match(l.strip())]
m = re.search(r"(?<![\w(])a\)", out["arg_line"] or "")
if m and not out["elements"]: # elements inline: 'W argumentacji uwzględnij: a) …, b) …'
parts = re.split(r"\s*[,;]?\s*(?<![\w(])([a-e])\)\s*", out["arg_line"][m.start():])
out["elements"] = [f"{parts[i]}) {parts[i + 1].strip().rstrip(',;.')}" for i in range(1, len(parts) - 1, 2)]
out["arg_line"] = out["arg_line"][:m.start()].strip()
else:
out["pre"] = [l for l in body if l.strip()]
return out
def tf_truth(key):
return {int(n): v == "P" for n, v in re.findall(r"([1-6])\.\s*([PF])", key)}
def is_identify(r, text=None):
return r.get("task_type") == "open_identify" or bool(IDENTIFY_RE.search(text or r["question"]))
# ---------------------------------------------------------------- assembling
def source_block(srcs):
"""srcs: [{'title', 'fragment'}] -> 'Tekst 1. Fragment artykułu …\\n<fragment>\\n\\n'."""
out = []
for n, s in enumerate(srcs, 1):
out.append(WIKI_LABEL.format(n=n, title=s["title"]) + "\n" + s["fragment"].strip())
return ("\n\n".join(out) + "\n\n") if out else ""
def header(n, p):
return f"Zadanie {n}. (0–{p})"
def shuffled(seq, seed, move_from=None):
"""Deterministic permutation; if move_from is an index, it is guaranteed to move (when len > 1)."""
rng = random.Random(seed)
idx = list(range(len(seq)))
for _ in range(50):
rng.shuffle(idx)
if len(seq) < 2 or (idx != list(range(len(seq))) and (move_from is None or idx.index(move_from) != move_from)):
break
return idx
def assemble_mcq(n, polecenie, trzon, options, correct_text, seed, srcs=(), move=True):
"""options: list of option texts (any order); returns (question, key_letter).
move=True (variants): the correct option always changes its letter; move=False (new tasks): uniform shuffle."""
corr = options.index(correct_text)
perm = shuffled(options, seed, move_from=corr if move else None)
letters = "ABCDEF"
opts = [options[i] for i in perm]
key = letters[opts.index(correct_text)]
body = "\n".join(x for x in [polecenie.strip(), trzon.strip()] if x)
q = header(n, 1) + "\n" + source_block(srcs) + body + "\n" + "\n".join(f"{letters[i]}. {o}" for i, o in enumerate(opts))
return q, key
def assemble_tf(n, wstep, statements, seed, srcs=()):
"""statements: [(text, truth_bool)] -> (question, key)."""
perm = shuffled(statements, seed)
st = [statements[i] for i in perm]
q = header(n, 1) + "\n" + (wstep.strip() + "\n\n" if wstep and wstep.strip() else "")
q += source_block(srcs) + (TF_INSTR_SRC if srcs else TF_INSTR) + "\n"
q += "\n".join(f"{i + 1}. {t.strip()}" for i, (t, _) in enumerate(st))
key = ", ".join(f"{i + 1}. {'P' if v else 'F'}" for i, (_, v) in enumerate(st))
return q, key
def assemble_open(n, p, polecenie, srcs=()):
return header(n, p) + "\n" + source_block(srcs) + polecenie.strip()
def assemble_essay(n, temat, elements, tail=ESSAY_TAIL, arg_line="W argumentacji uwzględnij:"):
els = [e if ELEM_RE.match(e.strip()) else f"{'abc'[i]}) {e}" for i, e in enumerate(elements)]
return "\n".join([header(n, 15), "Napisz wypracowanie na temat:", temat.strip(), arg_line] + els + [tail])
# ---------------------------------------------------------------- static validators
def rubric_error(zasady, p):
z = zasady or ""
if not re.search(rf"(?m)^{p} pkt – ", z):
return f"zasady oceniania muszą zawierać linię zaczynającą się od „{p} pkt – ”"
if p == 2 and not re.search(r"(?m)^1 pkt – ", z):
return "zasady oceniania za 2 pkt muszą zawierać także linię „1 pkt – …”"
if not re.search(r"(?m)^0 pkt – ", z):
return "zasady oceniania muszą kończyć się linią „0 pkt – odpowiedź niepełna lub błędna albo brak odpowiedzi.”"
return None
def answer_core(answer):
"""The answer itself (not the explanation): text before the first sentence end / dash / parenthesis."""
a = re.sub(r"^(?:np\.|Przykładow\w+ odpowied\w+:?|Odpowiedź:?|Poprawna odpowiedź:?)\s*", "",
(answer or "").strip(), flags=re.I)
a = re.split(r"(?<=[^A-ZĄĆĘŁŃÓŚŹŻ])\.\s|;|\s[–—-]\s|\(|\n|:", a, maxsplit=1)[0]
return a[:90]
def leak_error(fragment, answer):
"""'podaj nazwę/rozpoznaj' tasks: most proper-noun words of the answer occur in the excerpt."""
names = re.findall(r"\b[A-ZĄĆĘŁŃÓŚŹŻ][\wąćęłńóśźż-]{3,}", answer_core(answer))
names = [n for n in names if n.lower() not in {"został", "została", "było", "była", "jest", "chodzi", "jego"}]
if not names:
return None
fst = set(stems(fragment, 5))
hits = [n for n in names if stems(n, 5) and stems(n, 5)[0] in fst]
if len(hits) / len(names) >= 0.6:
return (f"fragment zdradza odpowiedź ({', '.join(hits[:3])}) – zastąp te słowa w cytacie opuszczeniem „[…]” "
f"albo wybierz inny fragment")
return None
def option_leak(fragment, correct, distractors):
"""Closed task: the fragment contains (nearly) all content words of the correct option but not of distractors."""
def cw(s):
return {x for x in stems(s, 6) if len(x) >= 5 and not x.isdigit()}
fr = set(stems(fragment, 6))
c = cw(correct)
if not c or len(c & fr) / len(c) < 0.75:
return None
if any(cw(d) and len(cw(d) & fr) / len(cw(d)) >= 0.75 for d in distractors):
return None
return ("fragment źródłowy zawiera wprost poprawną odpowiedź – wybierz fragment, który jej nie podaje, albo "
"zastąp ją w cytacie opuszczeniem „[…]”")
def check_sources(w, obj, passages, keys=("zrodlo", "zrodlo2"), min_len=100, max_len=700, answer=None):
"""Validate LLM-chosen excerpts; returns (error|None, [{'title','url','snap','date_modified','fragment','pid'}])."""
out = []
for k in keys:
s = obj.get(k)
if not s:
continue
if not isinstance(s, dict) or "id" not in s or "fragment" not in s:
return f"pole „{k}” musi mieć postać {{\"id\": \"P1\", \"fragment\": \"…\"}} albo null", None
pid_idx = re.sub(r"\D", "", str(s["id"]))
if not pid_idx or not (1 <= int(pid_idx) <= len(passages)):
return f"„{k}.id” musi wskazywać fragment z MATERIAŁÓW (P1–P{len(passages)})", None
p = passages[int(pid_idx) - 1]
frag = (s["fragment"] or "").strip()
lim = max_len if k == "zrodlo" and not obj.get("zrodlo2") else min(max_len, 450)
if not (min_len <= len(frag) <= lim):
return f"„{k}.fragment” ma {len(frag)} znaków; wymagane {min_len}–{lim} znaków", None
if SYNTH in frag or frag.startswith("Tekst "):
return f"„{k}.fragment” ma zawierać wyłącznie cytat z artykułu, bez podpisu", None
if ANAPHORA.match(frag):
return (f"„{k}.fragment” zaczyna się od odwołania do wcześniejszego tekstu („{frag.split()[0]} …”) – "
f"zacznij cytat od zdania zrozumiałego bez kontekstu"), None
ok, msg, _ = w.check_excerpt(frag, [p["pid"]])
if not ok:
return (f"„{k}.fragment” musi być DOSŁOWNYM cytatem z [{s['id']}] ({msg}); skopiuj zdania bez zmian, "
f"opuszczenia oznacz „[…]”"), None
if answer:
e = leak_error(frag, answer)
if e:
return e, None
out.append({"title": p["title"], "url": p["url"], "snap": p["snap"], "date_modified": p["date_modified"],
"fragment": frag, "pid": p["pid"]})
return None, out
def verified_quotes(w, items, passages, max_len=260):
"""Keep only quotes that are verbatim in the referenced passage's article; returns list with refs."""
good = []
for it in items or []:
if not isinstance(it, dict):
continue
idx = re.sub(r"\D", "", str(it.get("id", "")))
q = (it.get("cytat") or "").strip()
if not idx or not q or not (1 <= int(idx) <= len(passages)) or len(q) > max_len:
continue
p = passages[int(idx) - 1]
ok, _, _ = w.check_excerpt(q, [p["pid"]])
if ok:
good.append({**{k: v for k, v in it.items() if k != "id"}, "cytat": q, "title": p["title"],
"url": p["url"], "snap": p["snap"]})
return good
def wiki_check_record(w, parent_id, wc, passages):
"""Normalise the LLM's fact-check of the original; conflicts keep only verbatim-verified evidence."""
wc = wc if isinstance(wc, dict) else {}
status = wc.get("status") if wc.get("status") in ("zgodne", "konflikt", "brak_danych") else "brak_danych"
ev = verified_quotes(w, wc.get("dowody"), passages)
rec = {"id": parent_id, "status": status, "note": (wc.get("uwagi") or "").strip()[:600], "evidence": ev,
"evidence_verified": bool(ev)}
return rec
def diff_ratio(a, b):
"""Share of word 3-grams of b not present in a (0 = identical wording)."""
def grams(s):
t = re.findall(r"\w+", s.lower())
return {" ".join(t[i:i + 3]) for i in range(max(1, len(t) - 2))}
ga, gb = grams(a), grams(b)
return 1 - len(ga & gb) / max(1, len(gb))