"""Banco ALB v2: normalizzatore del SOLO formato e contratto di "interamente corretta". Regola (BRIEF-BENCH-ALB-V2 §1, pareri Sol/Argon): si avvolge in ... solo se l'INTERA risposta, tolti i blocchi ... chiusi e un recinto ``` che avvolge tutto, rispetta la grammatica del tipo di domanda. Niente estrazione dell'ultima riga, niente conversione da prosa, nessun valore cambiato o canonicalizzato. grammatica tipi ufficiali forma accettata (intera stringa) integer Count Frequency(Tool), Count Correctness(Env), -?\\d+ Count Frequency(Env), Find Round with Largest Value(Env), Weighted Summation(Env) yesno Find Duplicates(Tool) yes|no|true|false (maiuscole libere, al più un punto finale) pair Find Target Offsets(Tool) lista JSON valida di 2 id ["0728", "0137"] (stringhe di cifre) id Intersection (Concise-Response) un id: \\d+ idlist Intersection (Verbose-Response) lista JSON valida di id Non si avvolge MAI: risposta che contiene già un tag non chiuso (generazione tagliata), stringa vuota, rifiuti, prosa, più righe, alternative. Idempotenza: N(N(x)) = N(x) (l'uscita avvolta contiene e quindi non viene più toccata). Nota sulla forma "id1 and id2" (quella che il system ufficiale di Find Target Offsets chiede dentro ): NON è nella grammatica del normalizzatore (il brief ammette solo intero, sì/no, lista JSON). Una risposta "0728 and 0137" senza tag resta sbagliata anche dopo la normalizzazione; il conteggio di questi casi è riportato a parte. """ from __future__ import annotations import json import re INTEGER_TYPES = {"Count Frequency(Tool)", "Count Correctness(Env)", "Count Frequency(Env)", "Find Round with Largest Value(Env)", "Weighted Summation(Env)"} YESNO_TYPES = {"Find Duplicates(Tool)"} PAIR_TYPES = {"Find Target Offsets(Tool)"} INTERSECTION = "Intersection" _THINK_CLOSED = re.compile(r".*?", re.S | re.I) _FENCE = re.compile(r"\A```[A-Za-z0-9_+-]*[ \t]*\n(.*?)\n?```\Z", re.S) _INT = re.compile(r"\A-?\d+\Z") _ID = re.compile(r"\A\d+\Z") _YESNO = re.compile(r"\A(?:yes|no|true|false)\.?\Z", re.I) def grammar_of(question_type: str, history_label: str | None = None) -> str | None: if question_type in INTEGER_TYPES: return "integer" if question_type in YESNO_TYPES: return "yesno" if question_type in PAIR_TYPES: return "pair" if question_type == INTERSECTION: return "idlist" if history_label == "Verbose-Response" else "id" return None def _json_list(s: str): if not (s.startswith("[") and s.endswith("]")): return None try: v = json.loads(s) except ValueError: return None return v if isinstance(v, list) else None def matches(grammar: str, s: str) -> bool: if grammar == "integer": return bool(_INT.match(s)) if grammar == "yesno": return bool(_YESNO.match(s)) if grammar == "id": return bool(_ID.match(s)) if grammar in ("pair", "idlist"): v = _json_list(s) if v is None or not all(isinstance(x, str) and _ID.match(x) for x in v): return False return len(v) == 2 if grammar == "pair" else len(v) >= 1 return False def strip_wrappers(raw: str) -> str | None: """Toglie ... chiusi e un recinto ``` che avvolge TUTTO. None = mai avvolgibile (think aperto).""" t = _THINK_CLOSED.sub("", raw or "") if re.search(r" non chiuso o spaiato: generazione tagliata return None t = t.strip() m = _FENCE.match(t) if m: t = m.group(1).strip() return t def normalize_format(raw: str, question_type: str, history_label: str | None = None) -> str: """N(raw): raw invariata, oppure "" + intera risposta + "" se rispetta la grammatica.""" raw = raw or "" if re.search(r"%s" % t # --------------------------------------------------------------------------------------------------------------- # "Interamente corretta" (terza misura), contratto per tipo, verificato contro eval/evaluate.py ufficiale: # integer _to_number(pred) == _to_number(gold) (= ufficiale, già binario) # yesno _normalize_boolean(pred) == _normalize_boolean(gold) (= ufficiale, già binario) # pair due id, NELL'ORDINE del gold, dopo _normalize_name ufficiale (= ufficiale score 1.0; il credito # parziale 0,5 per il solo primo id NON è interamente corretto). Il vecchio confronto fra liste # ordinate di str() ignorava l'ordine: ["b","a"] contro gold ["a","b"] risultava corretto. # id _normalize_name(pred) == _normalize_name(gold) (= ufficiale) # idlist F1 ufficiale == 1.0 (insiemi uguali) # In più, STRUTTURA completa (Sol: "struttura e valori completi"): i parser ufficiali sono tolleranti (l'ultimo numero # di "3 or 4", la prima negazione di "yes, no"), quindi l'ufficiale = 1 non basta: # fully_correct = 1 sse punteggio ufficiale (sulla risposta normalizzata) == 1.0 # e tutti i tag hanno lo stesso contenuto (nessuna risposta multipla discordante) # e quel contenuto rispetta per intero la grammatica del tipo (per Find Target Offsets anche # la forma ufficiale "id1 and id2" chiesta dal system). _PAIR_AND = re.compile(r"\A(\d+)\s+and\s+(\d+)\Z", re.I) def strict_inner_ok(text: str, question_type: str, history_label: str | None = None) -> bool: inners = [x.strip() for x in re.findall(r"(.*?)", text or "", flags=re.S | re.I)] if not inners or len(set(inners)) != 1: return False s, g = inners[0], grammar_of(question_type, history_label) if g is None: return False return matches(g, s) or (g == "pair" and bool(_PAIR_AND.match(s))) def fully_correct(score, text: str, question_type: str, history_label: str | None = None) -> int: try: ok = abs(float(score) - 1.0) < 1e-9 except (TypeError, ValueError): return 0 return int(ok and strict_inner_ok(text, question_type, history_label))