math-stratum / lgstratum /render.py
tailot's picture
publish math-stratum bundle
e9dac18 verified
Raw History Blame Contribute Delete
6.54 kB
"""The answer the user reads, in the language the user wrote in.
Nothing here decides anything: the text is built from the verdict ``decide`` produced and from the
words the lexicon of that language provides. Two kinds of text meet in one reply, and the boundary
between them is deliberate:
* every label, state name and reason is taken from ``lexicon/<lang>.json``, so the framing of the
answer belongs to the user's language;
* the mathematical content -- the canonical sentence the stratum understood and the answer the math
stratum returned -- is passed through byte for byte, because it is a value and not prose.
The sentence the stratum understood is always shown. A user who wrote in Italian and gets back
``integral 3*x^2 from 0 to 2 wrt x`` can see which reading was used, and that is the whole point of
a stratum: the interpretation is inspectable, not hidden inside a model.
When no answer can be shown, the reply says so in the user's language and lists the forms this
language variety does understand, from ``lexicon.examples``, so the failure is a correction and not
a dead end.
"""
import re
from typing import Any, Dict, List, Optional
from . import decide as decide_module
from . import lexicon
FIELDS = ("word", "kind", "detail", "left", "right", "slot")
_PLACEHOLDER = re.compile(r"\{[a-z_]+\}")
def _fill(text: str) -> str:
"""Drop a placeholder the template kept: an unfilled brace must never reach the user."""
return _PLACEHOLDER.sub("", text).replace(" ", " ").strip(" ;,:")
def note_fields(dossier: Dict[str, Any]) -> Dict[str, Dict[str, Any]]:
"""The fields each reason carries, collected from the notes the readers left behind."""
out: Dict[str, Dict[str, Any]] = {}
for reading in [dossier.get("reading_a") or {}, dossier.get("reading_b") or {},
dossier.get("reading_direct") or {}]:
for note in reading.get("notes") or []:
if isinstance(note, dict) and note.get("reason"):
fields = {key: note[key] for key in FIELDS if key in note}
out.setdefault(str(note["reason"]), fields)
for reason, fields in ((dossier.get("math") or {}).get("reason_fields") or {}).items():
out.setdefault(str(reason), dict(fields))
return out
def _kind_understood(dossier: Dict[str, Any]) -> str:
"""The kind of problem the stratum solved, as the identifier the math language uses."""
for key in ("reading_a", "reading_b", "reading_direct"):
reading = dossier.get(key) or {}
if reading.get("kind"):
return str(reading["kind"])
return ""
def _sentence(dossier: Dict[str, Any]) -> str:
"""The canonical sentence that was, or would have been, handed to the math stratum."""
compare = dossier.get("compare") or {}
math_verdict = dossier.get("math") or {}
for source in (dossier.get("sent"), compare.get("left"), math_verdict.get("problem_math")):
if source:
return str(source)
for key in ("reading_a", "reading_b", "reading_direct"):
reading = dossier.get(key) or {}
if reading.get("math"):
return str(reading["math"])
return ""
def _check_line(lang: str, records: Optional[List[Dict[str, Any]]]) -> str:
"""How many envelopes of the run the referee of the orchestrator confirmed."""
if not records:
return ""
good = sum(1 for record in records if record.get("claimed") == record.get("referee"))
return lexicon.labels(lang)["check"].format(a=good, b=len(records))
def reply(dossier: Dict[str, Any], final: Optional[Dict[str, Any]] = None,
records: Optional[List[Dict[str, Any]]] = None, lang: Optional[str] = None) -> Dict[str, Any]:
"""Build the user-facing answer: one text block plus the machine-readable parts."""
lang = lang or str(dossier.get("lang") or "en")
if lang not in lexicon.codes():
lang = "en"
verdict = final or decide_module.decide(dossier)
labels = lexicon.labels(lang)
states = lexicon.reading_labels(lang)
fields = note_fields(dossier)
lines: List[str] = []
state = str(verdict.get("state", "NONE"))
lines.append("%s: %s" % (labels["status"], states.get(state, state)))
sentence = _sentence(dossier)
kind = _kind_understood(dossier)
if sentence and state not in ("NOT COVERED", "NONE"):
lines.append("%s (%s): %s" % (labels["understood"], kind, sentence))
if verdict.get("answer"):
lines.append("%s: %s" % (labels["answer"], verdict["answer"]))
lines.append(labels["assurance"].replace("{n}", str(verdict.get("assurance", 0))))
math_verdict = dossier.get("math") or {}
if math_verdict.get("status"):
# Which solver family the math stratum used is its own bookkeeping and nothing the reader
# of an answer asked for; what belongs in the reply is the verdict and, when the math
# stratum abstained, the reason it abstained.
tail = str(math_verdict["status"])
why = math_verdict.get("reason") or math_verdict.get("note") or ""
if not why and math_verdict.get("reasons"):
why = str(math_verdict["reasons"][0])
if why:
tail += " (" + why + ")"
lines.append("%s: %s" % (labels["math_layer"], tail))
reasons = [str(reason) for reason in verdict.get("reasons") or []]
if reasons:
math_verdict = dossier.get("math") or {}
fields.setdefault("referee", {"detail": ", ".join(str(item) for item in verdict.get("detected") or [])})
fields.setdefault("math_unknown", {"detail": str(math_verdict.get("reason")
or math_verdict.get("note") or "")})
texts = [_fill(lexicon.translate_reason(lang, reason, **(fields.get(reason) or {}))) for reason in reasons]
lines.append("%s: %s" % (labels["notes"], "; ".join(texts)))
check = _check_line(lang, records)
if check:
lines.append(check)
if state in ("NOT COVERED", "AMBIGUOUS", "NONE") and not verdict.get("answer"):
samples = lexicon.examples(lang)
if samples:
lines.append("%s: %s" % (labels["question"], " | ".join(samples[:5])))
return {
"lang": lang,
"language": lexicon.language_name(lang),
"state": state,
"assurance": verdict.get("assurance", 0),
"answer": verdict.get("answer", ""),
"sentence": sentence,
"kind": kind,
"reasons": reasons,
"lines": lines,
"text": "\n".join(lines),
}