File size: 2,813 Bytes
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
"""The words of the bundle: one file per variety, validated before use.

Section 6.5 of SPECIFICATION.md. The six varieties are the ones the genesis gateway
carries. A variety is declared, never inferred, and a declared variety without a file
answers instead of crashing.
"""

import json
import os
import re
from typing import Any, Dict, Optional

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
LEXICON_DIR = os.path.join(ROOT, "lexicon")

#: The six varieties this bundle carries (SPECIFICATION.md 6.5).
LANGS = ("ar", "en", "es", "hi", "it", "zh")

REQUIRED_KEYS = ("lang", "name", "noise", "units", "frames", "labels", "examples")

LABEL_KEYS = ("state", "level", "domain", "not_understood", "out_of_domain", "refused",
              "clarify", "verified", "unknown", "single_prover", "progress")

_CACHE: Dict[str, Dict[str, Any]] = {}


class LexiconError(Exception):
    """Raised when a variety file is missing, incomplete or inconsistent."""


def normalize(text: str) -> str:
    raw = str(text or "").strip().replace("_", "-")
    if not raw:
        return "en"
    return raw.split("-")[0].lower()


def has(code: str) -> bool:
    return normalize(code) in LANGS and os.path.isfile(os.path.join(LEXICON_DIR, normalize(code) + ".json"))


def load(code: str) -> Dict[str, Any]:
    code = normalize(code)
    if code in _CACHE:
        return _CACHE[code]
    path = os.path.join(LEXICON_DIR, code + ".json")
    if not os.path.isfile(path):
        raise LexiconError("variety %r has no lexicon file in this bundle" % code)
    with open(path, "r", encoding="utf-8") as handle:
        raw = json.load(handle)
    missing = [key for key in REQUIRED_KEYS if key not in raw]
    if missing:
        raise LexiconError("lexicon %s misses keys: %s" % (code, ", ".join(missing)))
    if raw["lang"] != code:
        raise LexiconError("lexicon %s declares lang %r" % (code, raw["lang"]))
    labels = raw["labels"] or {}
    missing_labels = [key for key in LABEL_KEYS if key not in labels]
    if missing_labels:
        raise LexiconError("lexicon %s misses labels: %s" % (code, ", ".join(missing_labels)))
    if not raw["frames"]:
        raise LexiconError("lexicon %s carries no frames" % code)
    _CACHE[code] = raw
    return raw


def label(code: str, key: str, fallback: Optional[str] = None) -> str:
    try:
        return str(load(code)["labels"].get(key, fallback or key))
    except LexiconError:
        return fallback or key


_FOLD = re.compile(r"\s+")


def fold(text: str, code: str) -> str:
    """Lowercase, drop the punctuation native to the variety, squeeze whitespace."""
    data = load(code)
    out = str(text or "").lower().replace("-", " ")
    for ch in data.get("noise", []):
        out = out.replace(ch, " ")
    return _FOLD.sub(" ", out).strip()