markovonnx 0.3.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.
@@ -0,0 +1,177 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to the Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by the Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding any notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,27 @@
1
+ Metadata-Version: 2.4
2
+ Name: markovonnx
3
+ Version: 0.3.0
4
+ Summary: Markov chains and HMMs with ONNX export and inference
5
+ License: Apache-2.0
6
+ Requires-Python: >=3.10
7
+ License-File: LICENSE
8
+ Requires-Dist: numpy
9
+ Requires-Dist: onnx
10
+ Requires-Dist: onnxruntime
11
+ Provides-Extra: bpe
12
+ Requires-Dist: tokenizers; extra == "bpe"
13
+ Provides-Extra: viz
14
+ Requires-Dist: matplotlib; extra == "viz"
15
+ Provides-Extra: quantize
16
+ Requires-Dist: onnxruntime-tools; extra == "quantize"
17
+ Requires-Dist: onnxconverter-common; extra == "quantize"
18
+ Provides-Extra: test
19
+ Requires-Dist: pytest; extra == "test"
20
+ Requires-Dist: pytest-cov; extra == "test"
21
+ Requires-Dist: hypothesis; extra == "test"
22
+ Provides-Extra: ovos
23
+ Requires-Dist: ovos-plugin-manager>=0.0.1; extra == "ovos"
24
+ Requires-Dist: ovos-bus-client>=0.1.0; extra == "ovos"
25
+ Requires-Dist: ovos-utils>=0.1.0; extra == "ovos"
26
+ Requires-Dist: ovos-config>=0.1.0; extra == "ovos"
27
+ Dynamic: license-file
@@ -0,0 +1,166 @@
1
+ # markovonnx
2
+
3
+ Markov chains and Hidden Markov Models with ONNX export and Kneser-Ney smoothing.
4
+
5
+ ## Let's Be Honest
6
+
7
+ This library implements algorithms from the 1990s. In 2026, a fine-tuned transformer will beat it on every benchmark that matters. You should probably use sentence-transformers or a small LLM for anything production-critical.
8
+
9
+ **So why does this exist?**
10
+
11
+ 1. **Baseline benchmarking.** You can't claim your fancy neural model is good unless you know how much better it is than the dumbest thing that could possibly work. markovonnx _is_ that dumb baseline. If your 400MB model only beats an n-gram chain by 3%, you have a problem.
12
+
13
+ 2. **Running on a potato.** Raspberry Pi Zero. ESP32. A browser via WASM. A 15-year-old Android phone. Places where "just pip install torch" isn't an option. markovonnx models are kilobytes and train in milliseconds. They run anywhere ONNX Runtime runs, which is basically everywhere.
14
+
15
+ 3. **When you have 10 training examples.** Neural models need hundreds or thousands of examples. Markov chains give you _something_ useful from 5-50 samples. It won't be great, but it'll be better than random — and for a voice assistant skill with 8 example utterances, that's the reality.
16
+
17
+ 4. **Teaching.** If you're learning NLP, Markov chains and HMMs are where you start. This library gives you a complete, tested, documented implementation with 25 runnable examples.
18
+
19
+ 5. **Fun.** Training a character-level Markov chain on black metal lyrics and letting it generate text is entertaining. The persona chat agent exists because it's funny, not because it's useful.
20
+
21
+ ### What It's Actually Good At
22
+
23
+ - **Language detection** — char n-gram perplexity is genuinely competitive for this task
24
+ - **POS tagging** — HMM Viterbi gets 97.5% on Brown corpus, which was state-of-the-art in 1995
25
+ - **Anomaly detection** — "does this log line look normal?" is a legitimate use case for perplexity
26
+ - **Providing a floor** — every benchmark needs a lower bound
27
+
28
+ ### What You Should Use Instead
29
+
30
+ | Task | Use markovonnx if... | Use this instead for production |
31
+ |------|---------------------|--------------------------------|
32
+ | Intent classification | You have <20 examples, no GPU | fine-tuned BERT, Model2Vec |
33
+ | Language detection | Truly offline, no model downloads | fastText langdetect |
34
+ | POS tagging | Teaching, embedded systems | spaCy, Stanza, flair |
35
+ | Text generation | Fun/creative, persona chatbot | Any LLM |
36
+ | G2P | Tiny model requirement | espeak, DeepPhonemizer |
37
+ | STT rescoring | Domain-specific vocab boost | Neural LM rescoring, KenLM |
38
+
39
+ ## Install
40
+
41
+ ```bash
42
+ pip install markovonnx # core (numpy, onnx, onnxruntime)
43
+ pip install markovonnx[ovos] # + OVOS voice assistant plugins
44
+ pip install markovonnx[bpe] # + BPE tokenizer support
45
+ pip install markovonnx[quantize] # + INT8 quantization
46
+ ```
47
+
48
+ ## Quick Start
49
+
50
+ ```python
51
+ from markovonnx import Vocabulary, MarkovChain, export_markov_onnx, MarkovONNXRuntime
52
+
53
+ # Train
54
+ vocab = Vocabulary()
55
+ vocab.build_from_sequences(corpus)
56
+ mc = MarkovChain(order=2, vocab=vocab, kneser_ney=True, backoff=True)
57
+ mc.fit(corpus)
58
+
59
+ # Export to ONNX
60
+ export_markov_onnx(mc, "model.onnx")
61
+
62
+ # Inference (3.5x faster than Python)
63
+ rt = MarkovONNXRuntime("model.onnx", vocab, order=2)
64
+ probs = rt.predict_probs(["the", "cat"])
65
+ ```
66
+
67
+ ## Features
68
+
69
+ | Feature | Description |
70
+ |---------|-------------|
71
+ | **Markov Chains** | N-gram models with sparse storage, Modified Kneser-Ney, interpolated backoff |
72
+ | **Hidden Markov Models** | Supervised MLE + log-space Baum-Welch, vectorized Viterbi |
73
+ | **ONNX Export** | Dense and sparse graphs, INT8 quantization, ~75% compression |
74
+ | **Pretrained Models** | save/load for MarkovChain and HMM, NLTK training scripts |
75
+ | **CLI** | `markovonnx train/generate/info` |
76
+ | **OVOS Plugins** | 8 native OPM entry points |
77
+
78
+ ## 25 Examples
79
+
80
+ | Category | Examples |
81
+ |----------|----------|
82
+ | **Text Generation** | char-level, word-level, predictive text, name generator, music |
83
+ | **Classification** | language ID, intent, spam/ham, code language, authorship, style scoring |
84
+ | **Sequence Tagging** | POS tagging, weather/activity HMM, G2P, slot extraction |
85
+ | **Analysis** | perplexity comparison, DNA motif discovery, keyword extraction |
86
+ | **Audio** | audio event classifier (speech, bark, doorbell, knock, music) |
87
+ | **Operations** | anomaly detection, streaming training, quantization benchmark |
88
+
89
+ See [examples/](examples/) for all 25 runnable scripts with toy datasets.
90
+
91
+ ## OVOS Integration
92
+
93
+ 8 native [OpenVoiceOS](https://openvoiceos.org) plugins via `markovonnx.opm`:
94
+
95
+ | Plugin | OPM Entry Point | What It Does |
96
+ |--------|-----------------|--------------|
97
+ | `MarkovPipeline` | `opm.pipeline` | Intent matching via perplexity ensemble |
98
+ | `MarkovUtteranceTransformer` | `opm.transformer.text` | STT rescoring with domain LM |
99
+ | `MarkovLangDetector` | `opm.lang.detect` | Language detection |
100
+ | `MarkovPosTagger` | `opm.postag` | POS tagging (97.5% on Brown corpus) |
101
+ | `MarkovKeywordExtractor` | `opm.keywords` | Keyword extraction |
102
+ | `MarkovSegmenter` | `opm.segmentation` | Sentence boundary detection |
103
+ | `MarkovG2P` | `opm.g2p` | Grapheme-to-phoneme |
104
+ | `MarkovChatEngine` | `opm.agents.chat` | Persona chat (metal lyricist, Shakespeare, pirate) |
105
+
106
+ All OVOS imports confined to `markovonnx/opm.py`. Core library has zero OVOS deps.
107
+
108
+ See [docs/ovos-integration.md](docs/ovos-integration.md) for configuration, training, and pretrained model setup.
109
+
110
+ ## Training Scripts
111
+
112
+ ```bash
113
+ # POS tagger from NLTK Brown corpus (97.5% accuracy)
114
+ python scripts/train_pos_tagger.py --corpus brown -o models/en_pos.json
115
+
116
+ # Language detection from NLTK UDHR corpus
117
+ python scripts/train_lang_detect.py --nltk --langs en fr de es pt -o models/
118
+
119
+ # G2P from CMUDict
120
+ python scripts/train_g2p.py -o models/en_g2p.json
121
+ ```
122
+
123
+ See [scripts/README.md](scripts/README.md) for details.
124
+
125
+ ## Documentation
126
+
127
+ 16 pages in [docs/](docs/) covering [getting started](docs/getting-started.md), [usage guide](docs/guide.md) (when to use, when to avoid), [OVOS integration](docs/ovos-integration.md), [API reference](docs/api-reference.md), [architecture](docs/architecture.md), [CLI](docs/cli.md), and more.
128
+
129
+ ## AI Transparency
130
+
131
+ This project was built entirely by an AI agent with human oversight.
132
+
133
+ ### AI Model
134
+
135
+ **Claude Opus 4.6** (Anthropic) via Claude Code CLI. All code, tests, documentation, and examples were generated in a single extended conversation.
136
+
137
+ ### Human Oversight
138
+
139
+ - **Architecture decisions** were human-approved before implementation (plan mode review)
140
+ - **Feature lists** were proposed by the AI, reviewed and approved by the human before building
141
+ - **Every commit** was staged locally — the human controls all `git push` operations
142
+ - **Bug fixes and improvements** were guided by human feedback
143
+
144
+ ### What the AI Did
145
+
146
+ - Extracted a Jupyter notebook into a standalone library (9 source modules)
147
+ - Wrote 150 unit tests achieving 99% code coverage
148
+ - Created 25 runnable examples across 10+ domains
149
+ - Built 8 OVOS plugins with full OPM integration and E2E tests
150
+ - Wrote 16 documentation pages including API reference and usage guide
151
+ - Performed comprehensive code audit (31 issues found and fixed)
152
+ - Implemented Modified Kneser-Ney smoothing, log-space Baum-Welch, vectorized Viterbi, sparse ONNX export, domain LM STT rescoring
153
+
154
+ ### What the Human Did
155
+
156
+ - Provided the original notebook with the core algorithms
157
+ - Directed the overall vision and feature priorities
158
+ - Reviewed and approved plans before implementation
159
+ - Made final decisions on architecture
160
+ - Controls publishing, pushing, and deployment
161
+
162
+ Every AI-generated commit includes an `AI-Generated Change` footer with the model name, intent, impact, and verification method.
163
+
164
+ ## License
165
+
166
+ Apache 2.0
@@ -0,0 +1,45 @@
1
+ """markovonnx — Markov chains and HMMs with ONNX export/inference."""
2
+
3
+ from markovonnx.archive import load_markov_archive, save_markov_archive
4
+ from markovonnx.config import MarkovConfig
5
+ from markovonnx.generate import generate_markov
6
+ from markovonnx.hmm import HiddenMarkovModel
7
+ from markovonnx.markov import MarkovChain
8
+ from markovonnx.onnx_export import (
9
+ export_hmm_onnx,
10
+ export_markov_onnx,
11
+ export_markov_sparse_onnx,
12
+ quantize_model,
13
+ )
14
+ from markovonnx.onnx_runtime import HMMONNXRuntime, MarkovONNXRuntime
15
+ from markovonnx.tokenizers import (
16
+ SubwordTokenizer,
17
+ char_tokenize,
18
+ corpus_iter,
19
+ get_tokenize_fn,
20
+ word_tokenize,
21
+ )
22
+ from markovonnx.version import __version__
23
+ from markovonnx.vocabulary import Vocabulary
24
+
25
+ __all__ = [
26
+ "MarkovConfig",
27
+ "MarkovChain",
28
+ "HiddenMarkovModel",
29
+ "Vocabulary",
30
+ "SubwordTokenizer",
31
+ "char_tokenize",
32
+ "word_tokenize",
33
+ "corpus_iter",
34
+ "get_tokenize_fn",
35
+ "export_markov_onnx",
36
+ "export_markov_sparse_onnx",
37
+ "export_hmm_onnx",
38
+ "quantize_model",
39
+ "MarkovONNXRuntime",
40
+ "HMMONNXRuntime",
41
+ "generate_markov",
42
+ "save_markov_archive",
43
+ "load_markov_archive",
44
+ "__version__",
45
+ ]
@@ -0,0 +1,132 @@
1
+ """Save and load portable .markov archive files.
2
+
3
+ A ``.markov`` archive is a ZIP file containing:
4
+ - ``model.onnx`` — the exported ONNX model
5
+ - ``vocab.json`` — the serialized :class:`Vocabulary`
6
+ - ``config.json`` — metadata (model_type, order, etc.)
7
+ """
8
+
9
+ import json
10
+ import tempfile
11
+ import zipfile
12
+ from pathlib import Path
13
+ from typing import Union
14
+
15
+ from markovonnx.config import MarkovConfig
16
+ from markovonnx.hmm import HiddenMarkovModel
17
+ from markovonnx.markov import MarkovChain
18
+ from markovonnx.onnx_export import export_hmm_onnx, export_markov_onnx
19
+ from markovonnx.vocabulary import Vocabulary
20
+
21
+
22
+ def save_markov_archive(
23
+ model: Union[MarkovChain, HiddenMarkovModel],
24
+ archive_path: str,
25
+ ) -> str:
26
+ """Save a trained model + vocabulary to a portable ``.markov`` archive.
27
+
28
+ Args:
29
+ model: A trained :class:`MarkovChain` or :class:`HiddenMarkovModel`.
30
+ archive_path: Destination path (should end in ``.markov``).
31
+
32
+ Returns:
33
+ The archive path.
34
+ """
35
+ Path(archive_path).parent.mkdir(parents=True, exist_ok=True)
36
+
37
+ with tempfile.TemporaryDirectory() as tmpdir:
38
+ onnx_path = str(Path(tmpdir) / "model.onnx")
39
+ vocab_path = str(Path(tmpdir) / "vocab.json")
40
+ config_path = str(Path(tmpdir) / "config.json")
41
+
42
+ if isinstance(model, MarkovChain):
43
+ export_markov_onnx(model, onnx_path)
44
+ model.vocab.save(vocab_path)
45
+ config = {
46
+ "model_type": "markov_chain",
47
+ "order": model.order,
48
+ "smoothing": model.smoothing,
49
+ "vocab_size": model.vocab.size,
50
+ "backoff": model.backoff,
51
+ }
52
+ elif isinstance(model, HiddenMarkovModel):
53
+ export_hmm_onnx(model, onnx_path)
54
+ model.obs_vocab.save(vocab_path)
55
+ config = {
56
+ "model_type": "hmm",
57
+ "n_states": model.n_states,
58
+ "smoothing": model.smoothing,
59
+ "vocab_size": model.obs_vocab.size,
60
+ }
61
+ else:
62
+ raise TypeError(f"Unsupported model type: {type(model)}")
63
+
64
+ with open(config_path, "w") as f:
65
+ json.dump(config, f, indent=2)
66
+
67
+ with zipfile.ZipFile(archive_path, "w", zipfile.ZIP_DEFLATED) as zf:
68
+ zf.write(onnx_path, "model.onnx")
69
+ zf.write(vocab_path, "vocab.json")
70
+ zf.write(config_path, "config.json")
71
+
72
+ print(f"Saved archive: {archive_path} ({Path(archive_path).stat().st_size / 1024:.1f} KB)")
73
+ return archive_path
74
+
75
+
76
+ def load_markov_archive(archive_path: str) -> dict:
77
+ """Load a ``.markov`` archive and return runtime components.
78
+
79
+ Args:
80
+ archive_path: Path to a ``.markov`` file.
81
+
82
+ Returns:
83
+ A dict with keys:
84
+ - ``"runtime"``: :class:`MarkovONNXRuntime` or :class:`HMMONNXRuntime`
85
+ - ``"vocab"``: :class:`Vocabulary`
86
+ - ``"config"``: dict of metadata (model_type, order, etc.)
87
+ - ``"onnx_path"``: path to the extracted ONNX file (in temp dir)
88
+ """
89
+ # Lazy imports to avoid circular dependency
90
+ from markovonnx.onnx_runtime import HMMONNXRuntime, MarkovONNXRuntime
91
+
92
+ import atexit
93
+ import shutil
94
+
95
+ tmpdir = tempfile.mkdtemp(prefix="markovonnx_")
96
+ atexit.register(shutil.rmtree, tmpdir, True) # clean up on exit
97
+
98
+ with zipfile.ZipFile(archive_path, "r") as zf:
99
+ zf.extractall(tmpdir)
100
+
101
+ onnx_path = str(Path(tmpdir) / "model.onnx")
102
+ vocab_path = str(Path(tmpdir) / "vocab.json")
103
+ config_path = str(Path(tmpdir) / "config.json")
104
+
105
+ vocab = Vocabulary.load(vocab_path)
106
+ with open(config_path, "r") as f:
107
+ config = json.load(f)
108
+
109
+ model_type = config["model_type"]
110
+
111
+ if model_type == "markov_chain":
112
+ rt = MarkovONNXRuntime(onnx_path, vocab, config["order"])
113
+ elif model_type == "hmm":
114
+ # Create a minimal HMM for the runtime wrapper (needs pi, obs_vocab)
115
+ import numpy as np
116
+ hmm = HiddenMarkovModel(
117
+ n_states=config["n_states"],
118
+ obs_vocab=vocab,
119
+ smoothing=config.get("smoothing", 1e-5),
120
+ )
121
+ # ORT expects float32 for alpha_in
122
+ hmm.pi = hmm.pi.astype(np.float32)
123
+ rt = HMMONNXRuntime(onnx_path, hmm)
124
+ else:
125
+ raise ValueError(f"Unknown model_type in archive: {model_type}")
126
+
127
+ return {
128
+ "runtime": rt,
129
+ "vocab": vocab,
130
+ "config": config,
131
+ "onnx_path": onnx_path,
132
+ }
@@ -0,0 +1,113 @@
1
+ """Command-line interface for markovonnx."""
2
+
3
+ import argparse
4
+ import sys
5
+
6
+ from markovonnx.version import __version__
7
+
8
+
9
+ def cmd_train(args: argparse.Namespace) -> None:
10
+ """Train a Markov chain and save as .markov archive."""
11
+ from markovonnx.archive import save_markov_archive
12
+ from markovonnx.markov import MarkovChain
13
+ from markovonnx.tokenizers import char_tokenize, corpus_iter, get_tokenize_fn, word_tokenize
14
+ from markovonnx.vocabulary import Vocabulary
15
+
16
+ tokenize_fn = get_tokenize_fn(args.mode)
17
+
18
+ print(f"Building vocabulary from {args.corpus}...")
19
+ vocab = Vocabulary(max_vocab=args.max_vocab)
20
+ vocab.build_streaming(args.corpus, tokenize_fn=tokenize_fn, max_lines=args.max_lines)
21
+ print(f"Vocabulary: {vocab.size} tokens")
22
+
23
+ print(f"Training MarkovChain(order={args.order}, backoff={args.backoff})...")
24
+ mc = MarkovChain(
25
+ order=args.order,
26
+ vocab=vocab,
27
+ smoothing=args.smoothing,
28
+ backoff=args.backoff,
29
+ )
30
+ mc.fit_streaming(args.corpus, tokenize_fn=tokenize_fn, max_lines=args.max_lines)
31
+
32
+ save_markov_archive(mc, args.output)
33
+
34
+
35
+ def cmd_generate(args: argparse.Namespace) -> None:
36
+ """Generate text from a .markov archive."""
37
+ from markovonnx.archive import load_markov_archive
38
+ from markovonnx.generate import generate_markov
39
+
40
+ loaded = load_markov_archive(args.archive)
41
+ rt = loaded["runtime"]
42
+ config = loaded["config"]
43
+ order = config.get("order", 2)
44
+ mode = args.mode
45
+
46
+ text = generate_markov(
47
+ rt, args.seed, args.length,
48
+ temperature=args.temperature, mode=mode, order=order,
49
+ )
50
+ print(text)
51
+
52
+
53
+ def cmd_info(args: argparse.Namespace) -> None:
54
+ """Show metadata from a .markov archive."""
55
+ import json
56
+ import zipfile
57
+ from pathlib import Path
58
+
59
+ with zipfile.ZipFile(args.archive, "r") as zf:
60
+ config = json.loads(zf.read("config.json"))
61
+
62
+ size_kb = Path(args.archive).stat().st_size / 1024
63
+ print(f"Archive: {args.archive} ({size_kb:.1f} KB)")
64
+ for key, val in config.items():
65
+ print(f" {key}: {val}")
66
+
67
+
68
+ def main() -> None:
69
+ """Entry point for ``markovonnx`` CLI."""
70
+ parser = argparse.ArgumentParser(
71
+ prog="markovonnx",
72
+ description="Markov chains and HMMs with ONNX export/inference",
73
+ )
74
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
75
+ sub = parser.add_subparsers(dest="command")
76
+
77
+ # -- train ----------------------------------------------------------------
78
+ p_train = sub.add_parser("train", help="Train a Markov chain from a text corpus")
79
+ p_train.add_argument("corpus", help="Path to text corpus (one line per sequence)")
80
+ p_train.add_argument("-o", "--output", default="model.markov", help="Output .markov archive path")
81
+ p_train.add_argument("--mode", choices=["char", "word"], default="char", help="Tokenization mode")
82
+ p_train.add_argument("--order", type=int, default=3, help="N-gram order")
83
+ p_train.add_argument("--smoothing", type=float, default=1e-5, help="Laplace smoothing alpha")
84
+ p_train.add_argument("--max-vocab", type=int, default=0, help="Max vocabulary size (0=unlimited)")
85
+ p_train.add_argument("--max-lines", type=int, default=0, help="Max corpus lines (0=unlimited)")
86
+ p_train.add_argument("--backoff", action="store_true", help="Enable interpolated backoff")
87
+
88
+ # -- generate -------------------------------------------------------------
89
+ p_gen = sub.add_parser("generate", help="Generate text from a .markov archive")
90
+ p_gen.add_argument("archive", help="Path to .markov archive")
91
+ p_gen.add_argument("--seed", default="", help="Seed text")
92
+ p_gen.add_argument("--length", type=int, default=100, help="Tokens to generate")
93
+ p_gen.add_argument("--temperature", type=float, default=0.7, help="Sampling temperature")
94
+ p_gen.add_argument("--mode", choices=["char", "word"], default="char", help="Tokenization mode")
95
+
96
+ # -- info -----------------------------------------------------------------
97
+ p_info = sub.add_parser("info", help="Show metadata from a .markov archive")
98
+ p_info.add_argument("archive", help="Path to .markov archive")
99
+
100
+ args = parser.parse_args()
101
+ if args.command == "train":
102
+ cmd_train(args)
103
+ elif args.command == "generate":
104
+ cmd_generate(args)
105
+ elif args.command == "info":
106
+ cmd_info(args)
107
+ else:
108
+ parser.print_help()
109
+ sys.exit(1)
110
+
111
+
112
+ if __name__ == "__main__":
113
+ main()