File size: 2,125 Bytes
4bc63c7
 
 
 
 
 
 
 
 
 
 
 
 
35d4b41
 
 
 
 
 
4bc63c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35d4b41
 
 
 
 
 
 
 
 
 
 
 
4bc63c7
 
 
35d4b41
 
4bc63c7
 
 
 
 
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
"""Node: intent. The only non deterministic node in the topology.

Reads a task envelope on stdin, writes an envelope on stdout. It never touches the
workspace: it only turns a request into a frame and an anchor.
"""

import json
import os
import sys

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)

from lingologos_thinkingpython import (  # noqa: E402
    catalog,
    intent,
    lexicon,
    ngram,
)


def main() -> int:
    task = json.load(sys.stdin)
    request = task.get("request", "")
    lang = lexicon.normalize(task.get("lang", "en"))
    known = list(task.get("symbols") or [])
    try:
        entries = catalog.load_entries()
        known_frames = {entry["id"]: entry["frames"] for entry in entries}
        frames = dict(lexicon.load(lang)["frames"])
        for frame, phrases in known_frames.items():
            frames.setdefault(frame, list(phrases))
    except (catalog.CatalogError, lexicon.LexiconError) as exc:
        print(json.dumps({"node": "intent", "status": "error", "reason": str(exc)}))
        return 2
    ir = intent.route(request, lang, frames, known_symbols=known)
    second = False
    if not ir["frame"] and ir.get("reason") == "NOT_UNDERSTOOD" and ngram.exists():
        # The lexicon ranking gave up: ask the classifier trained from the corpus. Its
        # margin was fixed on the eval split, and it abstains as well when unsure.
        try:
            model = ngram.load()
            voted, _gap = ngram.classify(model, lang, request)
        except ngram.ModelError:
            voted = ""
        if voted:
            ir = intent.make_ir(voted, ir["anchor"], lang, 0.5, [(voted, 0.5)])
            second = True
    status = "clarify" if ir.get("reason") == "AMBIGUOUS_TARGET" else (
        "refused" if not ir["frame"] else "ok")
    print(json.dumps({"node": "intent", "status": status, "ir": ir,
                      "reason": ir.get("reason", ""), "second_opinion": second},
                     ensure_ascii=False))
    return 0 if status != "refused" else 1


if __name__ == "__main__":
    raise SystemExit(main())