yellowmist 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
yellowmist/__init__.py ADDED
@@ -0,0 +1,48 @@
1
+ """YellowMIST: tiny on-device text models for every language your users type.
2
+
3
+ import yellowmist as ym
4
+ ym.punct("e kaaro bawo ni", "yor_Latn") # punctuation + capitals, in the language's marks
5
+ ym.switch("Yaar aaj office mein meetings thi", langs=["hin_Latn", "eng_Latn"]) # language of every word
6
+ ym.segment("ภาษาไทยไม่มีช่องว่างระหว่างคำ", "tha_Thai") # word boundaries
7
+ ym.suggest("Nitakupigia simu bada", "swh_Latn") # next-word / phrase suggestion (beta)
8
+ ym.mend("Mo fe lo si oja", "yor_Latn").suggestion # autocorrect + tone marks (beta)
9
+
10
+ Models download from the Hugging Face Hub on first use and are cached (set YELLOWMIST_CACHE to choose where;
11
+ HF_HUB_OFFLINE=1 to run offline afterwards). Everything runs locally with onnxruntime; no text leaves the machine.
12
+ Languages are FLORES-style labels: three-letter language code + script, e.g. "swh_Latn", "arb_Arab", "hin_Deva".
13
+ """
14
+ from __future__ import annotations
15
+
16
+ from .manifest import YellowMistError, languages, register
17
+ from .manifest import manifest as _manifest # keep yellowmist.manifest = the module
18
+ from .runtime import load
19
+ from .tasks.punct import punct
20
+ from .tasks.segment import segment
21
+ from .tasks.switch import Word, switch
22
+ from .tasks.glide import Suggestion, suggest
23
+ from .tasks.glide import settings as suggest_settings
24
+ from .tasks.mend import flag, mend
25
+ from .mend.system import MendResult
26
+
27
+ __version__ = "0.1.0"
28
+ __all__ = ["punct", "switch", "segment", "suggest", "suggest_settings", "mend", "flag", "Word", "Suggestion", "MendResult", "languages", "register", "preload", "tasks", "YellowMistError", "__version__"]
29
+
30
+
31
+ def tasks() -> dict:
32
+ """{task: stability} for every task this version ships, e.g. {"punct": "stable", ...}."""
33
+ return {k: v.get("stability", "stable") for k, v in _manifest()["tasks"].items()}
34
+
35
+
36
+ def preload(task: str, lang: str | None = None, region: str | None = None, precision: str = "auto",
37
+ model: str | None = None) -> None:
38
+ """Download and load a model ahead of time (e.g. at app start), so the first call is fast."""
39
+ from . import manifest as M
40
+ if model:
41
+ r = M.custom_ref(task, model)
42
+ elif region:
43
+ r = M.ref(task, region)
44
+ elif lang:
45
+ r = M.for_language(task, lang)
46
+ else:
47
+ raise YellowMistError("preload needs lang=... or region=...")
48
+ load(r, precision)
yellowmist/cli.py ADDED
@@ -0,0 +1,79 @@
1
+ """yellowmist command line.
2
+
3
+ yellowmist punct "e kaaro bawo ni" --lang yor_Latn
4
+ yellowmist switch "Niko busy sana leo" --langs swh_Latn,eng_Latn
5
+ yellowmist segment "ภาษาไทยไม่มีช่องว่างระหว่างคำ" --lang tha_Thai
6
+ yellowmist suggest "Nitakupigia simu bada" --lang swh_Latn
7
+ yellowmist languages punct
8
+ yellowmist download punct --lang yor_Latn (fetch ahead of time, e.g. before going offline)
9
+ Text can also come from stdin: echo "..." | yellowmist punct --lang hau_Latn
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import json
15
+ import sys
16
+
17
+
18
+ def _text(a) -> str:
19
+ return a.text if a.text is not None else sys.stdin.read()
20
+
21
+
22
+ def main(argv=None) -> int:
23
+ import yellowmist as ym
24
+ ap = argparse.ArgumentParser(prog="yellowmist", description="Tiny on-device text models for every language.")
25
+ ap.add_argument("--version", action="version", version=f"yellowmist {ym.__version__}")
26
+ sub = ap.add_subparsers(dest="cmd", required=True)
27
+ p = sub.add_parser("punct", help="put back punctuation and capitals")
28
+ p.add_argument("text", nargs="?")
29
+ p.add_argument("--lang", required=True)
30
+ s = sub.add_parser("switch", help="language of every word")
31
+ s.add_argument("text", nargs="?")
32
+ s.add_argument("--langs", default="", help="comma list, e.g. hin_Latn,eng_Latn")
33
+ s.add_argument("--region", default=None)
34
+ s.add_argument("--json", action="store_true")
35
+ g = sub.add_parser("segment", help="split Thai, Lao, Khmer or Burmese into words")
36
+ g.add_argument("text", nargs="?")
37
+ g.add_argument("--lang", required=True)
38
+ g.add_argument("--sep", default=" | ")
39
+ n = sub.add_parser("suggest", help="next-word / phrase suggestion for the text typed so far (beta)")
40
+ n.add_argument("text", nargs="?")
41
+ n.add_argument("--lang", required=True)
42
+ lg = sub.add_parser("languages", help="list the languages a task supports")
43
+ lg.add_argument("task", choices=list(ym.tasks()))
44
+ d = sub.add_parser("download", help="download a model now")
45
+ d.add_argument("task", choices=list(ym.tasks()))
46
+ d.add_argument("--lang")
47
+ d.add_argument("--region")
48
+ for x in (p, s, g, n, d):
49
+ x.add_argument("--precision", default="auto", choices=["auto", "int8", "fp32"])
50
+ a = ap.parse_args(argv)
51
+ try:
52
+ if a.cmd == "punct":
53
+ print(ym.punct(_text(a), a.lang, precision=a.precision))
54
+ elif a.cmd == "switch":
55
+ langs = [x for x in a.langs.split(",") if x] or None
56
+ words = ym.switch(_text(a), langs=langs, region=a.region, precision=a.precision)
57
+ if a.json:
58
+ print(json.dumps([{"text": w.text, "lang": w.lang, "score": round(w.score, 4)} for w in words],
59
+ ensure_ascii=False))
60
+ else:
61
+ print(" ".join(f"{w.text}/{w.lang.split('_')[0]}" for w in words))
62
+ elif a.cmd == "segment":
63
+ print(a.sep.join(ym.segment(_text(a), a.lang, precision=a.precision)))
64
+ elif a.cmd == "suggest":
65
+ r = ym.suggest(_text(a).rstrip("\n"), a.lang, precision=a.precision)
66
+ print(json.dumps({"text": r.text, "source": r.source, "score": round(r.score, 4)}, ensure_ascii=False))
67
+ elif a.cmd == "languages":
68
+ print("\n".join(ym.languages(a.task)))
69
+ elif a.cmd == "download":
70
+ ym.preload(a.task, lang=a.lang, region=a.region, precision=a.precision)
71
+ print("ok")
72
+ except ym.YellowMistError as e:
73
+ print(f"yellowmist: {e}", file=sys.stderr)
74
+ return 2
75
+ return 0
76
+
77
+
78
+ if __name__ == "__main__":
79
+ sys.exit(main())
yellowmist/eager.py ADDED
@@ -0,0 +1,45 @@
1
+ """One knob for how often suggestions appear: `eagerness`, 0-1. 0.5 keeps each language's calibrated settings;
2
+ higher shows more (confidence bars scaled down to a quarter at 1, shorter suggestions allowed), lower shows fewer
3
+ (bars scaled up to 4x at 0). For autocorrect, above 0.75 it also stops protecting words that are common as
4
+ typed, so tone marks go back on common unmarked words. Explicit settings (cutoff, threshold, ...) still win."""
5
+ from __future__ import annotations
6
+
7
+
8
+ def factor(e: float) -> float:
9
+ """Multiplier for confidence bars: 4 at 0, 1 at 0.5, 0.25 at 1."""
10
+ if not 0.0 <= float(e) <= 1.0:
11
+ raise ValueError("eagerness must be between 0 and 1")
12
+ return 4.0 ** (1.0 - 2.0 * float(e))
13
+
14
+
15
+ def prob(x: float, f: float) -> float:
16
+ return min(0.99, max(0.005, x * f))
17
+
18
+
19
+ def min_chars(mc: int, e: float) -> int:
20
+ """Shortest suggestion shown: up to 2 characters shorter at 1 (never below 2), up to 2 longer at 0."""
21
+ return max(2, int(mc) - round((float(e) - 0.5) * 4))
22
+
23
+
24
+ def glide_settings(s: dict, e: float) -> dict:
25
+ f = factor(e)
26
+ s = dict(s)
27
+ if s.get("glide_cutoff") is not None:
28
+ s["glide_cutoff"] = prob(float(s["glide_cutoff"]), f)
29
+ if s.get("bigram_cutoff") is not None:
30
+ s["bigram_cutoff"] = prob(float(s["bigram_cutoff"]), f)
31
+ s["min_chars"] = min_chars(int(s.get("min_chars", 4)), e)
32
+ return s
33
+
34
+
35
+ def mend_settings(s: dict, e: float) -> dict:
36
+ f = factor(e)
37
+ s = dict(s)
38
+ s["tau"] = prob(float(s["tau"]), f) # how sure a word is wrong before trying a fix
39
+ s["margin"] = float(s["margin"]) * f # how much better the fix must score
40
+ s["min_conf"] = prob(float(s["min_conf"]), f) # how sure before adding a tone mark
41
+ # the guard keeps words that are common as typed (e.g. unmarked Yoruba in web text) unchanged: above 0.75 it is
42
+ # off, so tone marks go back on common unmarked words too; below, it scales like the other bars
43
+ if s.get("guard") is not None:
44
+ s["guard"] = None if float(e) > 0.75 else min(1.0, float(s["guard"]) / f)
45
+ return s