File size: 5,823 Bytes
4bc63c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac3a340
 
 
 
 
4bc63c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74acaf8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bc63c7
ac3a340
 
 
 
 
 
4bc63c7
 
ac3a340
4bc63c7
 
 
 
 
 
 
 
 
 
ac3a340
 
 
 
 
 
74acaf8
 
 
 
 
 
 
ac3a340
 
 
 
 
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
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
"""Intent and intermediate representation.

The intent node is the only non deterministic node: it maps a surface request in one of
the six varieties onto a frame. Everything downstream is language free: no other node
reads the utterance, only the frame and the anchor.
"""

import re
from typing import Any, Dict, List, Optional, Tuple

from . import lexicon

IDENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]{2,}")
STOPWORDS = {"this", "that", "with", "into", "from", "before", "after", "please",
             "could", "would", "should", "not", "and", "for", "the", "are"}

#: Code tokens a developer types in any variety: they survive code switching, so a
#: frame may be named by them alone inside Arabic, Hindi or Chinese prose.
TECH_TOKENS = {"assert", "assertion", "comprehension", "default", "f", "guard",
               "import", "isinstance", "list", "loop", "nesting", "number", "string"}

IR_KEYS = ("frame", "anchor", "lang", "score", "candidates")


def make_ir(frame: str, anchor: Optional[str], lang: str, score: float,
            candidates: List[Tuple[str, float]]) -> Dict[str, Any]:
    return {"frame": frame, "anchor": anchor, "lang": lexicon.normalize(lang),
            "score": round(float(score), 4),
            "candidates": [(f, round(s, 4)) for f, s in candidates]}


def is_language_free(ir: Dict[str, Any]) -> bool:
    """True when the plan carries no trace of the surface form.

    Checked in tests/test_language_free_plan.py: no utterance text, no non ASCII token,
    no variety name anywhere in the structure that reaches executor and gates.
    """
    try:
        str(ir).encode("ascii")
    except UnicodeEncodeError:
        return False
    return set(ir.keys()) <= set(IR_KEYS)


def anchors_in(text: str) -> List[str]:
    out: List[str] = []
    for word in IDENT.findall(str(text or "")):
        if word.lower() in STOPWORDS:
            continue
        if word not in out:
            out.append(word)
    return out


def char_overlap(needle: str, folded: str) -> float:
    """Coverage of a phrase by overlapping two character runs, for unsegmented scripts.

    Chinese is written without spaces, so a phrase is a single token: it either appears
    whole or the word level signal says nothing at all. Two character runs are the honest
    counterpart of counting content words, and they let a request that names a shape with
    unusual wording still reach the right frame.
    """
    runs = [needle[i:i + 2] for i in range(len(needle) - 1)]
    if len(runs) < 2:
        return 0.0
    hits = sum(1 for run in runs if run in folded)
    return hits / float(len(runs))


def rank(text: str, lang: str, frames: Dict[str, List[str]]) -> List[Tuple[str, float]]:
    """Score every frame against the request, using the vocabulary of its variety.

    Two signals are combined. A phrase that appears whole is a direct hit. Otherwise the
    content words of the phrase are counted: coverage over them, with a boost when the
    matched words are code tokens, because those survive code switching.
    """
    data = lexicon.load(lang)
    folded = lexicon.fold(text, lang)
    words = set(folded.split())
    scored: List[Tuple[str, float]] = []
    for frame, phrases in frames.items():
        best = 0.0
        for phrase in phrases:
            needle = lexicon.fold(phrase, lang)
            if not needle:
                continue
            if needle in folded:
                weight = len(needle.split()) / max(1, len(folded.split()))
                best = max(best, 0.55 + 0.45 * min(1.0, weight * 2))
                continue
            tokens = [t for t in needle.split() if len(t) > 1 and t not in STOPWORDS]
            if not tokens:
                continue
            hits = [t for t in tokens if t in words or t in folded]
            if not hits:
                # In an unsegmented script the whole phrase is one token, so the word
                # level signal above is silent by construction. Fall back to the run of
                # characters it shares with the request.
                if len(needle) >= 4 and " " not in needle and not needle.isascii():
                    ratio = char_overlap(needle, folded)
                    if ratio >= 0.5:
                        best = max(best, min(0.58, 0.45 * ratio + 0.13))
                continue
            base = 0.45 * len(hits) / len(tokens)
            tech = sum(1 for t in hits if t in TECH_TOKENS)
            partial = min(0.60, base + 0.10 * tech + 0.05 * (len(hits) - 1))
            best = max(best, partial)
        if best > 0.0:
            scored.append((frame, best))
    scored.sort(key=lambda pair: (-pair[1], pair[0]))
    return scored


def route(text: str, lang: str, frames: Dict[str, List[str]],
          known_symbols: Optional[List[str]] = None,
          clarify_margin: float = 0.15, min_score: float = 0.45) -> Dict[str, Any]:
    """Return an IR, or an IR with frame None plus a reason."""
    lang = lexicon.normalize(lang)
    scored = rank(text, lang, frames)
    symbols = anchors_in(text)
    anchor = None
    if known_symbols:
        lowered = {s.lower(): s for s in known_symbols}
        for word in symbols:
            if word.lower() in lowered:
                anchor = lowered[word.lower()]
                break
    if anchor is None and symbols:
        anchor = symbols[0]
    if not scored or scored[0][1] < min_score:
        ir = make_ir("", anchor, lang, scored[0][1] if scored else 0.0, scored[:3])
        ir["reason"] = "NOT_UNDERSTOOD"
        return ir
    if len(scored) > 1 and (scored[0][1] - scored[1][1]) < clarify_margin:
        ir = make_ir(scored[0][0], anchor, lang, scored[0][1], scored[:3])
        ir["reason"] = "AMBIGUOUS_TARGET"
        return ir
    return make_ir(scored[0][0], anchor, lang, scored[0][1], scored[:3])