yellowmist 0.1.0__tar.gz

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.
Files changed (31) hide show
  1. yellowmist-0.1.0/PKG-INFO +110 -0
  2. yellowmist-0.1.0/README.md +80 -0
  3. yellowmist-0.1.0/pyproject.toml +39 -0
  4. yellowmist-0.1.0/setup.cfg +4 -0
  5. yellowmist-0.1.0/tests/test_text_and_manifest.py +108 -0
  6. yellowmist-0.1.0/yellowmist/__init__.py +48 -0
  7. yellowmist-0.1.0/yellowmist/cli.py +79 -0
  8. yellowmist-0.1.0/yellowmist/eager.py +45 -0
  9. yellowmist-0.1.0/yellowmist/manifest.json +3753 -0
  10. yellowmist-0.1.0/yellowmist/manifest.py +131 -0
  11. yellowmist-0.1.0/yellowmist/mend/__init__.py +0 -0
  12. yellowmist-0.1.0/yellowmist/mend/lexicon.py +101 -0
  13. yellowmist-0.1.0/yellowmist/mend/marks.py +103 -0
  14. yellowmist-0.1.0/yellowmist/mend/system.py +223 -0
  15. yellowmist-0.1.0/yellowmist/runtime.py +80 -0
  16. yellowmist-0.1.0/yellowmist/tasks/__init__.py +0 -0
  17. yellowmist-0.1.0/yellowmist/tasks/glide.py +159 -0
  18. yellowmist-0.1.0/yellowmist/tasks/glide_decode.py +145 -0
  19. yellowmist-0.1.0/yellowmist/tasks/mend.py +59 -0
  20. yellowmist-0.1.0/yellowmist/tasks/punct.py +67 -0
  21. yellowmist-0.1.0/yellowmist/tasks/segment.py +36 -0
  22. yellowmist-0.1.0/yellowmist/tasks/switch.py +98 -0
  23. yellowmist-0.1.0/yellowmist/text.py +78 -0
  24. yellowmist-0.1.0/yellowmist/train/__init__.py +412 -0
  25. yellowmist-0.1.0/yellowmist/train/woq.py +42 -0
  26. yellowmist-0.1.0/yellowmist.egg-info/PKG-INFO +110 -0
  27. yellowmist-0.1.0/yellowmist.egg-info/SOURCES.txt +29 -0
  28. yellowmist-0.1.0/yellowmist.egg-info/dependency_links.txt +1 -0
  29. yellowmist-0.1.0/yellowmist.egg-info/entry_points.txt +2 -0
  30. yellowmist-0.1.0/yellowmist.egg-info/requires.txt +14 -0
  31. yellowmist-0.1.0/yellowmist.egg-info/top_level.txt +1 -0
@@ -0,0 +1,110 @@
1
+ Metadata-Version: 2.4
2
+ Name: yellowmist
3
+ Version: 0.1.0
4
+ Summary: Tiny on-device text models for every language your users type: punctuation, language of every word, word segmentation.
5
+ Author: Olaverse
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://huggingface.co/olaverse
8
+ Project-URL: Documentation, https://olaverse-labs.github.io/yellowmist/
9
+ Project-URL: Repository, https://github.com/Olaverse-Labs/yellowmist
10
+ Project-URL: Issues, https://github.com/Olaverse-Labs/yellowmist/issues
11
+ Keywords: nlp,multilingual,on-device,onnx,punctuation,code-switching,word-segmentation,low-resource
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Text Processing :: Linguistic
15
+ Classifier: Intended Audience :: Developers
16
+ Requires-Python: >=3.9
17
+ Description-Content-Type: text/markdown
18
+ Requires-Dist: numpy>=1.21
19
+ Requires-Dist: onnxruntime>=1.17
20
+ Requires-Dist: huggingface_hub>=0.23
21
+ Requires-Dist: tokenizers>=0.15
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest>=7; extra == "dev"
24
+ Provides-Extra: train
25
+ Requires-Dist: torch>=2.4; extra == "train"
26
+ Requires-Dist: dew-lm[hf]>=1.0; extra == "train"
27
+ Requires-Dist: transformers<4.47,>=4.44; extra == "train"
28
+ Requires-Dist: onnx>=1.15; extra == "train"
29
+ Requires-Dist: safetensors; extra == "train"
30
+
31
+ # yellowmist
32
+
33
+ Tiny on-device text models for every language your users type. Punctuation and capitals, the language of every word
34
+ in mixed text, and word boundaries for scripts without spaces, in 100+ languages. Everything runs locally with
35
+ onnxruntime: no API key, no server, and no text leaves the machine.
36
+
37
+ ```bash
38
+ pip install yellowmist
39
+ ```
40
+
41
+ ```python
42
+ import yellowmist as ym
43
+
44
+ ym.punct("e kaaro bawo ni ṣe wa", "yor_Latn")
45
+ # punctuation and capitals, in the language's own marks (। for Hindi, ። for Amharic, ، and ؟ for Arabic script)
46
+
47
+ ym.switch("Yaar aaj office mein bahut meetings thi", langs=["hin_Latn", "eng_Latn"])
48
+ # [Word(text='Yaar', lang='hin_Latn', score=...), Word(text='aaj', ...), Word(text='office', lang='eng_Latn', ...), ...]
49
+
50
+ ym.segment("ภาษาไทยไม่มีช่องว่างระหว่างคำ", "tha_Thai")
51
+ # ['ภาษาไทย', 'ไม่', 'มี', 'ช่องว่าง', 'ระหว่าง', 'คำ']
52
+
53
+ ym.suggest("Nitakupigia simu bada", "swh_Latn")
54
+ # Suggestion(text=..., source='glide' or 'bigram', score=...) text is "" when nothing is confident enough
55
+ ```
56
+
57
+ From the command line:
58
+
59
+ ```bash
60
+ yellowmist punct "sannu da zuwa yaya aiki" --lang hau_Latn
61
+ yellowmist switch "Niko busy sana leo" --langs swh_Latn,eng_Latn
62
+ yellowmist segment "ຂ້ອຍຮັກພາສາລາວ" --lang lao_Laoo
63
+ yellowmist languages punct
64
+ ```
65
+
66
+ ## Languages
67
+
68
+ Languages are FLORES-style labels: a three-letter language code and the script, such as `swh_Latn`, `arb_Arab`,
69
+ `hin_Deva` or `hin_Latn` (romanised Hindi). `ym.languages("punct")` lists every label a task supports. The right
70
+ regional model is chosen from the label, downloaded once (about 15 MB) and cached.
71
+
72
+ | Task | What it does | Status |
73
+ |---|---|---|
74
+ | `punct` | punctuation and capitals for lowercased, unpunctuated text | stable |
75
+ | `switch` | the language of every word | stable |
76
+ | `segment` | word boundaries for Thai, Lao, Khmer, Burmese | stable |
77
+ | `suggest` | next-word and phrase suggestions for the text typed so far | beta: good on written text, weak on chat |
78
+
79
+ ## Tips
80
+
81
+ - **Switch: name the user's languages** with `langs=[...]` when your app knows them. It is much more accurate than
82
+ choosing among every language of a region, and Latin-script text needs it (or `region=`), because five regions use
83
+ Latin script.
84
+ - **Load early:** `ym.preload("punct", lang="yor_Latn")` at app start makes the first call fast.
85
+ - **Offline:** after the first download, set `HF_HUB_OFFLINE=1`. `YELLOWMIST_CACHE` chooses the cache folder.
86
+ - **Precision:** models run in int8 by default where it matches the full model; pass `precision="fp32"` to force full
87
+ precision.
88
+
89
+ ## Your own models
90
+
91
+ Fine-tuned a model (for example with `yellowmist.train`, see the notebook) or want a different one? Pass it per call
92
+ with `model=` (a Hub repo id or a local folder), or register it once for its languages:
93
+
94
+ ```python
95
+ ym.punct("e kaaro bawo ni", "yor_Latn", model="you/yellowmist-punct-yor") # this call only
96
+ ym.register("switch", "./my-switch") # its languages now use it
97
+ ym.switch("Mo fẹ́ go to the market", langs=["yor_Latn", "eng_Latn"])
98
+ ```
99
+
100
+ `pip install "yellowmist[train]"` adds `yellowmist.train`: continue pretraining an encoder on your text, fine-tune
101
+ Switch or punctuation, and export the result in this library's format.
102
+
103
+ ## Versions
104
+
105
+ Each release pins exact model versions, so your results do not change under you. Upgrading the package brings the
106
+ newest models.
107
+
108
+ ## Licence
109
+
110
+ Apache-2.0, for the code and the models.
@@ -0,0 +1,80 @@
1
+ # yellowmist
2
+
3
+ Tiny on-device text models for every language your users type. Punctuation and capitals, the language of every word
4
+ in mixed text, and word boundaries for scripts without spaces, in 100+ languages. Everything runs locally with
5
+ onnxruntime: no API key, no server, and no text leaves the machine.
6
+
7
+ ```bash
8
+ pip install yellowmist
9
+ ```
10
+
11
+ ```python
12
+ import yellowmist as ym
13
+
14
+ ym.punct("e kaaro bawo ni ṣe wa", "yor_Latn")
15
+ # punctuation and capitals, in the language's own marks (। for Hindi, ። for Amharic, ، and ؟ for Arabic script)
16
+
17
+ ym.switch("Yaar aaj office mein bahut meetings thi", langs=["hin_Latn", "eng_Latn"])
18
+ # [Word(text='Yaar', lang='hin_Latn', score=...), Word(text='aaj', ...), Word(text='office', lang='eng_Latn', ...), ...]
19
+
20
+ ym.segment("ภาษาไทยไม่มีช่องว่างระหว่างคำ", "tha_Thai")
21
+ # ['ภาษาไทย', 'ไม่', 'มี', 'ช่องว่าง', 'ระหว่าง', 'คำ']
22
+
23
+ ym.suggest("Nitakupigia simu bada", "swh_Latn")
24
+ # Suggestion(text=..., source='glide' or 'bigram', score=...) text is "" when nothing is confident enough
25
+ ```
26
+
27
+ From the command line:
28
+
29
+ ```bash
30
+ yellowmist punct "sannu da zuwa yaya aiki" --lang hau_Latn
31
+ yellowmist switch "Niko busy sana leo" --langs swh_Latn,eng_Latn
32
+ yellowmist segment "ຂ້ອຍຮັກພາສາລາວ" --lang lao_Laoo
33
+ yellowmist languages punct
34
+ ```
35
+
36
+ ## Languages
37
+
38
+ Languages are FLORES-style labels: a three-letter language code and the script, such as `swh_Latn`, `arb_Arab`,
39
+ `hin_Deva` or `hin_Latn` (romanised Hindi). `ym.languages("punct")` lists every label a task supports. The right
40
+ regional model is chosen from the label, downloaded once (about 15 MB) and cached.
41
+
42
+ | Task | What it does | Status |
43
+ |---|---|---|
44
+ | `punct` | punctuation and capitals for lowercased, unpunctuated text | stable |
45
+ | `switch` | the language of every word | stable |
46
+ | `segment` | word boundaries for Thai, Lao, Khmer, Burmese | stable |
47
+ | `suggest` | next-word and phrase suggestions for the text typed so far | beta: good on written text, weak on chat |
48
+
49
+ ## Tips
50
+
51
+ - **Switch: name the user's languages** with `langs=[...]` when your app knows them. It is much more accurate than
52
+ choosing among every language of a region, and Latin-script text needs it (or `region=`), because five regions use
53
+ Latin script.
54
+ - **Load early:** `ym.preload("punct", lang="yor_Latn")` at app start makes the first call fast.
55
+ - **Offline:** after the first download, set `HF_HUB_OFFLINE=1`. `YELLOWMIST_CACHE` chooses the cache folder.
56
+ - **Precision:** models run in int8 by default where it matches the full model; pass `precision="fp32"` to force full
57
+ precision.
58
+
59
+ ## Your own models
60
+
61
+ Fine-tuned a model (for example with `yellowmist.train`, see the notebook) or want a different one? Pass it per call
62
+ with `model=` (a Hub repo id or a local folder), or register it once for its languages:
63
+
64
+ ```python
65
+ ym.punct("e kaaro bawo ni", "yor_Latn", model="you/yellowmist-punct-yor") # this call only
66
+ ym.register("switch", "./my-switch") # its languages now use it
67
+ ym.switch("Mo fẹ́ go to the market", langs=["yor_Latn", "eng_Latn"])
68
+ ```
69
+
70
+ `pip install "yellowmist[train]"` adds `yellowmist.train`: continue pretraining an encoder on your text, fine-tune
71
+ Switch or punctuation, and export the result in this library's format.
72
+
73
+ ## Versions
74
+
75
+ Each release pins exact model versions, so your results do not change under you. Upgrading the package brings the
76
+ newest models.
77
+
78
+ ## Licence
79
+
80
+ Apache-2.0, for the code and the models.
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "yellowmist"
7
+ version = "0.1.0"
8
+ description = "Tiny on-device text models for every language your users type: punctuation, language of every word, word segmentation."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = {text = "Apache-2.0"}
12
+ authors = [{name = "Olaverse"}]
13
+ keywords = ["nlp", "multilingual", "on-device", "onnx", "punctuation", "code-switching", "word-segmentation", "low-resource"]
14
+ classifiers = [
15
+ "License :: OSI Approved :: Apache Software License",
16
+ "Programming Language :: Python :: 3",
17
+ "Topic :: Text Processing :: Linguistic",
18
+ "Intended Audience :: Developers",
19
+ ]
20
+ dependencies = ["numpy>=1.21", "onnxruntime>=1.17", "huggingface_hub>=0.23", "tokenizers>=0.15"]
21
+
22
+ [project.optional-dependencies]
23
+ dev = ["pytest>=7"]
24
+ train = ["torch>=2.4", "dew-lm[hf]>=1.0", "transformers>=4.44,<4.47", "onnx>=1.15", "safetensors"]
25
+
26
+ [project.scripts]
27
+ yellowmist = "yellowmist.cli:main"
28
+
29
+ [project.urls]
30
+ Homepage = "https://huggingface.co/olaverse"
31
+ Documentation = "https://olaverse-labs.github.io/yellowmist/"
32
+ Repository = "https://github.com/Olaverse-Labs/yellowmist"
33
+ Issues = "https://github.com/Olaverse-Labs/yellowmist/issues"
34
+
35
+ [tool.setuptools.packages.find]
36
+ include = ["yellowmist*"]
37
+
38
+ [tool.setuptools.package-data]
39
+ yellowmist = ["manifest.json"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,108 @@
1
+ """Pure-Python tests (no models, no downloads): text cutting, script detection, manifest region choice."""
2
+ import json
3
+
4
+ import pytest
5
+
6
+ from yellowmist import manifest as M
7
+ from yellowmist.text import main_script, pieces_at_spaces, punct_map, word_groups
8
+
9
+ FAKE = {"version": 1, "tasks": {
10
+ "switch": {"stability": "stable", "home": {"hin_Latn": "AP", "eng_Latn": "EU", "zsm_Latn": "AP", "spa_Latn": "EU",
11
+ "rus_Cyrl": "CY", "kaz_Cyrl": "CY"},
12
+ "models": {"AP": {"repo": "o/S-AP", "revision": "a", "languages": ["hin_Latn", "eng_Latn", "zsm_Latn"]},
13
+ "EU": {"repo": "o/S-EU", "revision": "b", "languages": ["eng_Latn", "spa_Latn"]},
14
+ "CY": {"repo": "o/S-CY", "revision": "c", "languages": ["rus_Cyrl", "kaz_Cyrl"]}}},
15
+ "punct": {"stability": "stable", "home": {"yor_Latn": "WA"},
16
+ "models": {"WA": {"repo": "o/P-WA", "revision": "d", "languages": ["yor_Latn"]}}}}}
17
+
18
+
19
+ @pytest.fixture(autouse=True)
20
+ def fake_manifest(tmp_path, monkeypatch):
21
+ p = tmp_path / "m.json"
22
+ p.write_text(json.dumps(FAKE))
23
+ monkeypatch.setenv("YELLOWMIST_MANIFEST", str(p))
24
+ M.manifest.cache_clear()
25
+ yield
26
+ M.manifest.cache_clear()
27
+
28
+
29
+ def test_pieces_fit_and_keep_text():
30
+ t = "ab " * 200
31
+ ps = pieces_at_spaces(t.strip(), 50)
32
+ assert all(len(p) <= 50 for p in ps)
33
+ assert " ".join(ps) == t.strip()
34
+
35
+
36
+ def test_pieces_cut_long_runs():
37
+ ps = pieces_at_spaces("x" * 120, 50)
38
+ assert [len(p) for p in ps] == [50, 50, 20]
39
+
40
+
41
+ def test_word_groups_fit():
42
+ gs = word_groups(["hello"] * 100, 30)
43
+ assert all(len(" ".join(g)) <= 30 for g in gs)
44
+ assert sum(len(g) for g in gs) == 100
45
+
46
+
47
+ def test_greek_question_mark():
48
+ assert punct_map("ell_Grek")[";"] == 3 and punct_map("eng_Latn")[";"] == 2
49
+
50
+
51
+ def test_main_script():
52
+ assert main_script("Привет, как дела?") == "CYRILLIC"
53
+ assert main_script("hello 123") == "LATIN"
54
+
55
+
56
+ def test_home_region_and_errors():
57
+ assert M.for_language("punct", "yor_Latn").repo == "o/P-WA"
58
+ with pytest.raises(M.YellowMistError, match="FLORES"):
59
+ M.for_language("punct", "yoruba")
60
+
61
+
62
+ def test_langs_pick_shared_region():
63
+ assert M.for_languages("switch", ["hin_Latn", "eng_Latn"]).region == "AP"
64
+ assert M.for_languages("switch", ["spa_Latn", "eng_Latn"]).region == "EU"
65
+ with pytest.raises(M.YellowMistError, match="different regions"):
66
+ M.for_languages("switch", ["hin_Latn", "spa_Latn"])
67
+
68
+
69
+ def test_region_from_script():
70
+ assert M.for_text("switch", "Сәлем, как дела?").region == "CY"
71
+ with pytest.raises(M.YellowMistError, match="langs"):
72
+ M.for_text("switch", "Niko busy sana leo")
73
+
74
+
75
+ def test_model_override_and_register(tmp_path):
76
+ r = M.pick("punct", "yor_Latn", "me/my-punct", "abc")
77
+ assert (r.repo, r.revision, r.region) == ("me/my-punct", "abc", "CUSTOM")
78
+ assert M.pick("punct", "yor_Latn", None).repo == "o/P-WA"
79
+ d = tmp_path / "my-switch"
80
+ d.mkdir()
81
+ (d / "vocab.json").write_text(json.dumps({"vocab": [], "labels": ["yor_Latn", "eng_Latn"]}))
82
+ (d / "onnx.json").write_text(json.dumps({"classes": ["yor_Latn", "eng_Latn", "other"]}))
83
+ ref = M.register("switch", str(d))
84
+ assert ref.region.startswith("CUSTOM") and set(ref.languages) == {"yor_Latn", "eng_Latn"}
85
+ assert M.for_languages("switch", ["yor_Latn", "eng_Latn"]).repo == str(d)
86
+
87
+
88
+ def test_word_case():
89
+ from yellowmist.tasks.punct import _word_case
90
+ up = lambda s: [c == "1" for c in s]
91
+ # "HELLo" -> "Hello"; all-upper word stays upper; each hyphen part decides on its own; "I" stays upper
92
+ p = "hello nasa jean-pierre i"
93
+ flags = up("11110" + "0" + "1111" + "0" + "1000" + "0" + "100000" + "0" + "1")
94
+ assert _word_case(p, flags) == up("10000" + "0" + "1111" + "0" + "1000" + "0" + "100000" + "0" + "1")
95
+
96
+
97
+ def test_eagerness():
98
+ import pytest
99
+ from yellowmist import eager as E
100
+ s = {"glide_cutoff": 0.2, "bigram_cutoff": 0.4, "min_chars": 4}
101
+ assert E.glide_settings(s, 0.5) == {"glide_cutoff": 0.2, "bigram_cutoff": 0.4, "min_chars": 4}
102
+ more = E.glide_settings(s, 1.0)
103
+ assert abs(more["glide_cutoff"] - 0.05) < 1e-9 and more["min_chars"] == 2
104
+ assert E.glide_settings(s, 0.0)["min_chars"] == 6
105
+ m = E.mend_settings({"tau": 0.85, "margin": 3.0, "min_conf": 0.95, "guard": 0.05}, 1.0)
106
+ assert m["guard"] is None and m["margin"] == 0.75
107
+ with pytest.raises(ValueError):
108
+ E.factor(1.5)
@@ -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)
@@ -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())
@@ -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