File size: 7,122 Bytes
3a0a69b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
"""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 physical content -- the canonical sentence the stratum understood and the answer the physics
  layer 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
``pi period from mass, stiffness`` 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("physics") 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 physics 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 physics layer."""
    compare = dossier.get("compare") or {}
    physics_verdict = dossier.get("physics") or {}
    for source in (dossier.get("sent"), compare.get("left"), physics_verdict.get("problem_physics")):
        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 _physics_why(physics_verdict: Dict[str, Any]) -> str:
    """What to say about the physics layer next to its status, in one short phrase.

    An error of this stratum comes first -- the layer was not started, was started and died, was
    turned off -- because that is the part this layer knows and the user can act on. When the layer
    itself refused or abstained, its own one-line sentence about the refusal is shown. The reason
    codes the layer carries are bookkeeping of its internal nodes and are not repeated here.
    """
    why = str(physics_verdict.get("error") or physics_verdict.get("reason") or "")
    if why:
        return why
    if str(physics_verdict.get("status") or "") in decide_module.ANSWERING:
        return ""
    return str(physics_verdict.get("answer_text") or "")


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))))
    physics_verdict = dossier.get("physics") or {}
    if physics_verdict.get("status"):
        # Which road of the physics layer carried the answer is its own bookkeeping and nothing the
        # reader of an answer asked for; what belongs in the reply is the verdict and, when the layer
        # abstained, the reason it abstained.
        tail = str(physics_verdict["status"])
        why = _physics_why(physics_verdict)
        if why:
            tail += " (" + why + ")"
        lines.append("%s: %s" % (labels["physics_layer"], tail))
    reasons = [str(reason) for reason in verdict.get("reasons") or []]
    if reasons:
        fields.setdefault("referee", {"detail": ", ".join(str(item) for item in verdict.get("detected") or [])})
        fields.setdefault("physics_unknown", {"detail": _physics_why(physics_verdict)})
        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),
    }