moteml 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.

Potentially problematic release.


This version of moteml might be problematic. Click here for more details.

moteml-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
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 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 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 those 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
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
moteml-0.1.0/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ MoteML
2
+ Copyright 2026 VigilGuard LLC
3
+
4
+ Licensed under the Apache License, Version 2.0.
moteml-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,81 @@
1
+ Metadata-Version: 2.4
2
+ Name: moteml
3
+ Version: 0.1.0
4
+ Summary: Small open models that do one data job on a laptop CPU. First model: spend, a purchase-line classifier
5
+ Author-email: MoteML <sriram@vigilguard.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://huggingface.co/moteml
8
+ Project-URL: Repository, https://github.com/moteml/moteml
9
+ Requires-Python: <3.14,>=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ License-File: NOTICE
13
+ Requires-Dist: numpy
14
+ Requires-Dist: onnxruntime
15
+ Requires-Dist: tokenizers
16
+ Requires-Dist: huggingface_hub
17
+ Provides-Extra: hub
18
+ Requires-Dist: huggingface_hub; extra == "hub"
19
+ Dynamic: license-file
20
+
21
+ # MoteML
22
+
23
+ Small open models for data work. Each model does one job, runs on a laptop CPU, and ships with a
24
+ public test set so you can check the numbers yourself.
25
+
26
+ - License: Apache 2.0 for all weights and code
27
+ - Models: https://huggingface.co/moteml
28
+
29
+ ## spend: sort purchase lines into spend categories
30
+
31
+ Reads a purchase line such as `BRG BALL 6204-2RS 20X47X14` and returns one of 25 spend categories,
32
+ a confidence score, and a flag for the lines a person should check. 40 MB, no API key, no per-line
33
+ cost, and the purchase data stays on your machine.
34
+
35
+ ```
36
+ pip install moteml
37
+ ```
38
+
39
+ ```python
40
+ import moteml
41
+ model = moteml.load("spend") # downloads 40 MB on first use
42
+ model.predict(["HP LASERJET TONER CARTRIDGE BLACK", "MISC"])
43
+ # [{'category': 'Office supplies, furniture and equipment', 'confidence': 0.94, 'needs_review': False, ...},
44
+ # {'category': 'Industrial equipment and MRO supplies', 'confidence': 0.12, 'needs_review': True, ...}]
45
+ ```
46
+
47
+ Label a whole CSV file:
48
+
49
+ ```
50
+ moteml spend purchases.csv --column description --out labeled.csv --summary summary.txt
51
+ ```
52
+
53
+ The summary holds counts and percentages only, with no purchase text, so it is safe to share.
54
+
55
+ Results, limits and the comparison with other free models are on the model page:
56
+ https://huggingface.co/moteml/spend. The test files are at
57
+ https://huggingface.co/datasets/moteml/spend-bench.
58
+
59
+ ## How this repo is laid out
60
+
61
+ | Folder | What it holds |
62
+ |---|---|
63
+ | `models/` | One folder per model. Each has its own spec, data steps, test set, training and export |
64
+ | `models/_template/` | Copy this to start a new model (`scripts/new_model.sh <slug>`) |
65
+ | `pipeline/` | Code every model shares: metrics, export, benchmarking |
66
+ | `src/moteml/` | The installable library. One interface for every released model |
67
+ | `docs/` | House rules, the catalog, and the dataset license ledger |
68
+ | `scripts/` | Setup and helper scripts |
69
+ | `data/`, `runs/`, `artifacts/` | Local only. Never committed |
70
+
71
+ ## The seven steps every model goes through
72
+
73
+ 1. Spec: write down the problem, who has it, the data, and the tool to beat
74
+ 2. Data: download public data and record its license in `docs/LICENSE_LEDGER.md`
75
+ 3. Test set: build it and hand-check a sample before any training
76
+ 4. Baselines: score the existing free tools on the test set
77
+ 5. Train: fine-tune a small model and beat the baselines
78
+ 6. Export: ONNX, quantized, with CPU latency measured
79
+ 7. Release: model card, demo, packages, launch post
80
+
81
+ A model that cannot beat the baselines at step 5 does not ship.
moteml-0.1.0/README.md ADDED
@@ -0,0 +1,61 @@
1
+ # MoteML
2
+
3
+ Small open models for data work. Each model does one job, runs on a laptop CPU, and ships with a
4
+ public test set so you can check the numbers yourself.
5
+
6
+ - License: Apache 2.0 for all weights and code
7
+ - Models: https://huggingface.co/moteml
8
+
9
+ ## spend: sort purchase lines into spend categories
10
+
11
+ Reads a purchase line such as `BRG BALL 6204-2RS 20X47X14` and returns one of 25 spend categories,
12
+ a confidence score, and a flag for the lines a person should check. 40 MB, no API key, no per-line
13
+ cost, and the purchase data stays on your machine.
14
+
15
+ ```
16
+ pip install moteml
17
+ ```
18
+
19
+ ```python
20
+ import moteml
21
+ model = moteml.load("spend") # downloads 40 MB on first use
22
+ model.predict(["HP LASERJET TONER CARTRIDGE BLACK", "MISC"])
23
+ # [{'category': 'Office supplies, furniture and equipment', 'confidence': 0.94, 'needs_review': False, ...},
24
+ # {'category': 'Industrial equipment and MRO supplies', 'confidence': 0.12, 'needs_review': True, ...}]
25
+ ```
26
+
27
+ Label a whole CSV file:
28
+
29
+ ```
30
+ moteml spend purchases.csv --column description --out labeled.csv --summary summary.txt
31
+ ```
32
+
33
+ The summary holds counts and percentages only, with no purchase text, so it is safe to share.
34
+
35
+ Results, limits and the comparison with other free models are on the model page:
36
+ https://huggingface.co/moteml/spend. The test files are at
37
+ https://huggingface.co/datasets/moteml/spend-bench.
38
+
39
+ ## How this repo is laid out
40
+
41
+ | Folder | What it holds |
42
+ |---|---|
43
+ | `models/` | One folder per model. Each has its own spec, data steps, test set, training and export |
44
+ | `models/_template/` | Copy this to start a new model (`scripts/new_model.sh <slug>`) |
45
+ | `pipeline/` | Code every model shares: metrics, export, benchmarking |
46
+ | `src/moteml/` | The installable library. One interface for every released model |
47
+ | `docs/` | House rules, the catalog, and the dataset license ledger |
48
+ | `scripts/` | Setup and helper scripts |
49
+ | `data/`, `runs/`, `artifacts/` | Local only. Never committed |
50
+
51
+ ## The seven steps every model goes through
52
+
53
+ 1. Spec: write down the problem, who has it, the data, and the tool to beat
54
+ 2. Data: download public data and record its license in `docs/LICENSE_LEDGER.md`
55
+ 3. Test set: build it and hand-check a sample before any training
56
+ 4. Baselines: score the existing free tools on the test set
57
+ 5. Train: fine-tune a small model and beat the baselines
58
+ 6. Export: ONNX, quantized, with CPU latency measured
59
+ 7. Release: model card, demo, packages, launch post
60
+
61
+ A model that cannot beat the baselines at step 5 does not ship.
@@ -0,0 +1,30 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "moteml"
7
+ version = "0.1.0"
8
+ description = "Small open models that do one data job on a laptop CPU. First model: spend, a purchase-line classifier"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.10,<3.14"
12
+ authors = [{ name = "MoteML", email = "sriram@vigilguard.com" }]
13
+ dependencies = ["numpy", "onnxruntime", "tokenizers", "huggingface_hub"]
14
+
15
+ [project.optional-dependencies]
16
+ hub = ["huggingface_hub"]
17
+
18
+ [project.scripts]
19
+ moteml = "moteml.cli:main"
20
+
21
+ [project.urls]
22
+ Homepage = "https://huggingface.co/moteml"
23
+ Repository = "https://github.com/moteml/moteml"
24
+
25
+ [tool.setuptools.packages.find]
26
+ where = ["src"]
27
+
28
+ [tool.pytest.ini_options]
29
+ testpaths = ["tests"]
30
+ pythonpath = ["."]
moteml-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,46 @@
1
+ """MoteML: small open models for specific workloads."""
2
+ from __future__ import annotations
3
+
4
+ __version__ = "0.1.0"
5
+
6
+ # slug -> short description. A model is listed in RELEASED only once it is on Hugging Face.
7
+ CATALOG = {
8
+ "spend": "Put a purchase line into its spend category",
9
+ "tariff": "Put a product description into its customs (HS) code",
10
+ "match": "Decide if two records are the same company",
11
+ "secret": "Decide if a flagged string is a real credential",
12
+ "coltype": "Tell what a spreadsheet column holds",
13
+ }
14
+
15
+ RELEASED: dict[str, str] = {"spend": "moteml/spend"} # slug -> Hugging Face repo id
16
+
17
+
18
+ def available() -> list[str]:
19
+ """Models that can be loaded today."""
20
+ return sorted(RELEASED)
21
+
22
+
23
+ def load(slug: str, path: str | None = None):
24
+ """Load a model by slug.
25
+
26
+ path: a local folder with the model files. Without it, the released model is
27
+ downloaded from Hugging Face on first use and cached.
28
+ """
29
+ if slug not in CATALOG:
30
+ raise KeyError(f"unknown model '{slug}'. Known: {', '.join(sorted(CATALOG))}")
31
+ if slug not in _LOADERS:
32
+ raise NotImplementedError(f"'{slug}' is planned and not built yet")
33
+ if path is None:
34
+ if slug not in RELEASED:
35
+ raise NotImplementedError(f"'{slug}' is not on Hugging Face yet. Pass path= with a local model folder")
36
+ from huggingface_hub import snapshot_download
37
+ path = snapshot_download(RELEASED[slug])
38
+ return _LOADERS[slug](path)
39
+
40
+
41
+ def _load_spend(path):
42
+ from .spend import SpendModel
43
+ return SpendModel(path)
44
+
45
+
46
+ _LOADERS = {"spend": _load_spend}
@@ -0,0 +1,91 @@
1
+ """Command line: label a whole CSV file.
2
+
3
+ moteml spend purchases.csv --column description --out labeled.csv
4
+ moteml spend purchases.csv --column description --out labeled.csv --truth-column category --summary summary.txt
5
+
6
+ The summary holds counts and percentages only. No purchase text goes into it, so it can be shared.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import csv
12
+ import sys
13
+
14
+
15
+ def main(argv: list[str] | None = None) -> int:
16
+ ap = argparse.ArgumentParser(prog="moteml")
17
+ sub = ap.add_subparsers(dest="model", required=True)
18
+ sp = sub.add_parser("spend", help="put each purchase line into a spend category")
19
+ sp.add_argument("file", help="CSV file to label")
20
+ sp.add_argument("--column", required=True, help="name of the column holding the purchase description")
21
+ sp.add_argument("--out", required=True, help="where to write the labeled CSV")
22
+ sp.add_argument("--model", default="", help="folder with the model files (default: download the released model)")
23
+ sp.add_argument("--truth-column", default="", help="column with your own category for each line, if you have one. The summary then reports accuracy")
24
+ sp.add_argument("--summary", default="", help="also save the summary to this file. It contains no purchase text")
25
+ args = ap.parse_args(argv)
26
+
27
+ import moteml
28
+ model = moteml.load("spend", path=args.model or None)
29
+ known = {"".join(ch for ch in c.lower() if ch.isalpha()) for c in model.categories} if hasattr(model, "categories") else set()
30
+ csv.field_size_limit(1 << 30)
31
+ with open(args.file, encoding="utf-8-sig", newline="") as f:
32
+ reader = csv.DictReader(f)
33
+ if args.column not in (reader.fieldnames or []):
34
+ print(f"column '{args.column}' not found. Columns: {', '.join(reader.fieldnames or [])}", file=sys.stderr)
35
+ return 2
36
+ rows = list(reader)
37
+ fields = list(reader.fieldnames)
38
+ added = ["spend_category", "spend_confidence", "spend_second_choice", "spend_needs_review"]
39
+ if args.truth_column and args.truth_column not in fields:
40
+ print(f"column '{args.truth_column}' not found. Columns: {', '.join(fields)}", file=sys.stderr)
41
+ return 2
42
+ import re
43
+ from collections import Counter
44
+ key = lambda t: re.sub(r"[^a-z]", "", (t or "").lower())
45
+ per_cat, per_cat_review, bands = Counter(), Counter(), Counter()
46
+ n_review = n_truth = right = right_auto = n_auto_truth = 0
47
+ with open(args.out, "w", encoding="utf-8", newline="") as f:
48
+ w = csv.DictWriter(f, fieldnames=fields + added)
49
+ w.writeheader()
50
+ for i in range(0, len(rows), 512):
51
+ chunk = rows[i:i + 512]
52
+ for row, res in zip(chunk, model.predict([r[args.column] or "" for r in chunk])):
53
+ row.update({"spend_category": res["category"], "spend_confidence": res["confidence"],
54
+ "spend_second_choice": res["second_choice"],
55
+ "spend_needs_review": "yes" if res["needs_review"] else "no"})
56
+ n_review += res["needs_review"]
57
+ per_cat[res["category"]] += 1
58
+ per_cat_review[res["category"]] += res["needs_review"]
59
+ bands[min(int(res["confidence"] * 10), 9)] += 1
60
+ if args.truth_column and key(row.get(args.truth_column)) in known:
61
+ ok = key(row[args.truth_column]) == key(res["category"])
62
+ n_truth += 1
63
+ right += ok
64
+ if not res["needs_review"]:
65
+ n_auto_truth += 1
66
+ right_auto += ok
67
+ w.writerow(row)
68
+ n = len(rows)
69
+ done = n - n_review
70
+ out = [f"moteml spend summary (model review setting {model.review_below}). Counts only, no purchase text.",
71
+ f"{n:,} lines labeled. {done:,} need no review ({done / max(n, 1):.0%}), {n_review:,} flagged for a person."]
72
+ if args.truth_column:
73
+ if n_truth:
74
+ out.append(f"Your own category matched one of the model's 25 names on {n_truth:,} lines. On those: "
75
+ f"{right / n_truth:.1%} right overall, {n_auto_truth / n_truth:.1%} labeled without review, "
76
+ + (f"{right_auto / n_auto_truth:.1%} right among those." if n_auto_truth else "none labeled without review."))
77
+ else:
78
+ out.append("Your own categories use other names than the model's 25, so accuracy cannot be computed directly.")
79
+ out.append("Lines per category (share flagged for review):")
80
+ out += [f" {c}: {k:,} ({per_cat_review[c] / k:.0%})" for c, k in per_cat.most_common()]
81
+ out.append("Lines by confidence: " + ", ".join(f"{b / 10:.1f} to {(b + 1) / 10:.1f}: {bands[b]:,}" for b in range(10) if bands[b]))
82
+ text = "\n".join(out)
83
+ print(text)
84
+ if args.summary:
85
+ with open(args.summary, "w", encoding="utf-8") as f:
86
+ f.write(text + "\n")
87
+ return 0
88
+
89
+
90
+ if __name__ == "__main__":
91
+ sys.exit(main())
@@ -0,0 +1,114 @@
1
+ """Spend classifier: put a purchase line into one of 25 business spend categories.
2
+
3
+ Runs on a CPU with numpy, onnxruntime and tokenizers. No PyTorch needed.
4
+
5
+ from moteml.spend import SpendModel
6
+ model = SpendModel("path/to/spend-0.1.0")
7
+ model.predict(["HP LASERJET TONER CARTRIDGE BLACK"])
8
+
9
+ The model has two parts whose probabilities are averaged:
10
+ - a small transformer (ONNX, int8) that reads the meaning of the line
11
+ - a word-count model (TF-IDF plus a linear layer) that steadies the confidence
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import math
17
+ import re
18
+ from pathlib import Path
19
+
20
+ import numpy as np
21
+
22
+ _WORD = re.compile(r"\b\w\w+\b")
23
+ _HAS_WORD = re.compile(r"[A-Za-z]{3,}")
24
+
25
+
26
+ class SpendModel:
27
+ def __init__(self, folder: str | Path, threads: int = 0):
28
+ import onnxruntime as ort
29
+ from tokenizers import Tokenizer
30
+
31
+ folder = Path(folder)
32
+ cfg = json.loads((folder / "moteml.json").read_text(encoding="utf-8"))
33
+ self.config = cfg
34
+ self.categories: list[str] = cfg["categories"]
35
+ self.temperature: float = cfg["temperature"]
36
+ self.neural_weight: float = cfg["neural_weight"]
37
+ self.review_below: float = cfg["review_below"]
38
+
39
+ self._tok = Tokenizer.from_file(str(folder / "tokenizer.json"))
40
+ self._tok.enable_truncation(max_length=cfg["max_len"])
41
+ opts = ort.SessionOptions()
42
+ if threads:
43
+ opts.intra_op_num_threads = threads
44
+ self._sess = ort.InferenceSession(str(folder / cfg["neural_file"]), sess_options=opts,
45
+ providers=["CPUExecutionProvider"])
46
+ self._inputs = {i.name for i in self._sess.get_inputs()}
47
+
48
+ lin = np.load(folder / "linear.npz")
49
+ self._coef = lin["coef_q"] # int8, shape (categories, terms)
50
+ self._scale = lin["scale"].astype(np.float32) # one scale per category
51
+ self._bias = lin["bias"].astype(np.float32)
52
+ self._idf = lin["idf"].astype(np.float32)
53
+ terms = (folder / "linear_vocab.txt").read_text(encoding="utf-8").split("\n")
54
+ self._vocab = {t: i for i, t in enumerate(terms)}
55
+
56
+ # ---- the two parts
57
+ def _neural(self, texts: list[str]) -> np.ndarray:
58
+ # One line at a time, on purpose. The int8 model sets its number ranges per call,
59
+ # so in a batch a line's answer would shift with its neighbours. Alone, the same
60
+ # line always gets the same answer. It is also faster than padded batches on a CPU.
61
+ out = np.zeros((len(texts), len(self.categories)), dtype=np.float32)
62
+ for r, text in enumerate(texts):
63
+ enc = self._tok.encode(text.lower())
64
+ feed = {"input_ids": np.array([enc.ids], dtype=np.int64),
65
+ "attention_mask": np.array([enc.attention_mask], dtype=np.int64),
66
+ "token_type_ids": np.array([enc.type_ids], dtype=np.int64)}
67
+ z = self._sess.run(None, {k: v for k, v in feed.items() if k in self._inputs})[0][0] / self.temperature
68
+ e = np.exp(z - z.max())
69
+ out[r] = e / e.sum()
70
+ return out
71
+
72
+ def _linear(self, texts: list[str]) -> np.ndarray:
73
+ out = np.zeros((len(texts), len(self.categories)), dtype=np.float32)
74
+ for r, text in enumerate(texts):
75
+ words = _WORD.findall(text.lower())
76
+ counts: dict[int, int] = {}
77
+ for term in words + [a + " " + b for a, b in zip(words, words[1:])]:
78
+ j = self._vocab.get(term)
79
+ if j is not None:
80
+ counts[j] = counts.get(j, 0) + 1
81
+ z = self._bias.copy()
82
+ if counts:
83
+ idx = np.fromiter(counts, dtype=np.int64)
84
+ val = np.array([1.0 + math.log(c) for c in counts.values()], dtype=np.float32) * self._idf[idx]
85
+ val /= np.linalg.norm(val)
86
+ z += (self._coef[:, idx].astype(np.float32) @ val) * self._scale
87
+ p = 1.0 / (1.0 + np.exp(-z))
88
+ out[r] = p / p.sum()
89
+ return out
90
+
91
+ # ---- public
92
+ def predict_proba(self, texts: list[str]) -> np.ndarray:
93
+ """Probabilities, shape (rows, categories), columns in the order of `self.categories`."""
94
+ texts = [str(t) for t in texts]
95
+ w = self.neural_weight
96
+ return w * self._neural(texts) + (1.0 - w) * self._linear(texts)
97
+
98
+ def predict(self, texts: list[str]) -> list[dict]:
99
+ """One result per line: category, confidence, second choice, and whether a person should look."""
100
+ texts = [str(t) for t in texts]
101
+ p = self.predict_proba(texts)
102
+ order = np.argsort(-p, axis=1)[:, :2]
103
+ results = []
104
+ for r, text in enumerate(texts):
105
+ a, b = int(order[r, 0]), int(order[r, 1])
106
+ conf = float(p[r, a])
107
+ vague = len(text.strip()) < 8 or not _HAS_WORD.search(text)
108
+ results.append({
109
+ "category": self.categories[a],
110
+ "confidence": round(conf, 4),
111
+ "second_choice": self.categories[b],
112
+ "needs_review": bool(vague or conf < self.review_below),
113
+ })
114
+ return results
@@ -0,0 +1,81 @@
1
+ Metadata-Version: 2.4
2
+ Name: moteml
3
+ Version: 0.1.0
4
+ Summary: Small open models that do one data job on a laptop CPU. First model: spend, a purchase-line classifier
5
+ Author-email: MoteML <sriram@vigilguard.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://huggingface.co/moteml
8
+ Project-URL: Repository, https://github.com/moteml/moteml
9
+ Requires-Python: <3.14,>=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ License-File: NOTICE
13
+ Requires-Dist: numpy
14
+ Requires-Dist: onnxruntime
15
+ Requires-Dist: tokenizers
16
+ Requires-Dist: huggingface_hub
17
+ Provides-Extra: hub
18
+ Requires-Dist: huggingface_hub; extra == "hub"
19
+ Dynamic: license-file
20
+
21
+ # MoteML
22
+
23
+ Small open models for data work. Each model does one job, runs on a laptop CPU, and ships with a
24
+ public test set so you can check the numbers yourself.
25
+
26
+ - License: Apache 2.0 for all weights and code
27
+ - Models: https://huggingface.co/moteml
28
+
29
+ ## spend: sort purchase lines into spend categories
30
+
31
+ Reads a purchase line such as `BRG BALL 6204-2RS 20X47X14` and returns one of 25 spend categories,
32
+ a confidence score, and a flag for the lines a person should check. 40 MB, no API key, no per-line
33
+ cost, and the purchase data stays on your machine.
34
+
35
+ ```
36
+ pip install moteml
37
+ ```
38
+
39
+ ```python
40
+ import moteml
41
+ model = moteml.load("spend") # downloads 40 MB on first use
42
+ model.predict(["HP LASERJET TONER CARTRIDGE BLACK", "MISC"])
43
+ # [{'category': 'Office supplies, furniture and equipment', 'confidence': 0.94, 'needs_review': False, ...},
44
+ # {'category': 'Industrial equipment and MRO supplies', 'confidence': 0.12, 'needs_review': True, ...}]
45
+ ```
46
+
47
+ Label a whole CSV file:
48
+
49
+ ```
50
+ moteml spend purchases.csv --column description --out labeled.csv --summary summary.txt
51
+ ```
52
+
53
+ The summary holds counts and percentages only, with no purchase text, so it is safe to share.
54
+
55
+ Results, limits and the comparison with other free models are on the model page:
56
+ https://huggingface.co/moteml/spend. The test files are at
57
+ https://huggingface.co/datasets/moteml/spend-bench.
58
+
59
+ ## How this repo is laid out
60
+
61
+ | Folder | What it holds |
62
+ |---|---|
63
+ | `models/` | One folder per model. Each has its own spec, data steps, test set, training and export |
64
+ | `models/_template/` | Copy this to start a new model (`scripts/new_model.sh <slug>`) |
65
+ | `pipeline/` | Code every model shares: metrics, export, benchmarking |
66
+ | `src/moteml/` | The installable library. One interface for every released model |
67
+ | `docs/` | House rules, the catalog, and the dataset license ledger |
68
+ | `scripts/` | Setup and helper scripts |
69
+ | `data/`, `runs/`, `artifacts/` | Local only. Never committed |
70
+
71
+ ## The seven steps every model goes through
72
+
73
+ 1. Spec: write down the problem, who has it, the data, and the tool to beat
74
+ 2. Data: download public data and record its license in `docs/LICENSE_LEDGER.md`
75
+ 3. Test set: build it and hand-check a sample before any training
76
+ 4. Baselines: score the existing free tools on the test set
77
+ 5. Train: fine-tune a small model and beat the baselines
78
+ 6. Export: ONNX, quantized, with CPU latency measured
79
+ 7. Release: model card, demo, packages, launch post
80
+
81
+ A model that cannot beat the baselines at step 5 does not ship.
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ NOTICE
3
+ README.md
4
+ pyproject.toml
5
+ src/moteml/__init__.py
6
+ src/moteml/cli.py
7
+ src/moteml/spend.py
8
+ src/moteml.egg-info/PKG-INFO
9
+ src/moteml.egg-info/SOURCES.txt
10
+ src/moteml.egg-info/dependency_links.txt
11
+ src/moteml.egg-info/entry_points.txt
12
+ src/moteml.egg-info/requires.txt
13
+ src/moteml.egg-info/top_level.txt
14
+ tests/test_metrics.py
15
+ tests/test_package.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ moteml = moteml.cli:main
@@ -0,0 +1,7 @@
1
+ numpy
2
+ onnxruntime
3
+ tokenizers
4
+ huggingface_hub
5
+
6
+ [hub]
7
+ huggingface_hub
@@ -0,0 +1 @@
1
+ moteml
@@ -0,0 +1,64 @@
1
+ import pytest
2
+
3
+ from pipeline import metrics as m
4
+
5
+
6
+ def test_accuracy():
7
+ assert m.accuracy([1, 0, 1, 1], [1, 0, 0, 1]) == 0.75
8
+
9
+
10
+ def test_length_mismatch():
11
+ with pytest.raises(ValueError):
12
+ m.accuracy([1, 2], [1])
13
+
14
+
15
+ def test_top_k():
16
+ assert m.top_k_accuracy(["a", "b"], [["x", "a"], ["y", "z"]], k=2) == 0.5
17
+ assert m.top_k_accuracy(["a", "b"], [["x", "a"], ["y", "z"]], k=1) == 0.0
18
+
19
+
20
+ def test_precision_recall_f1():
21
+ r = m.precision_recall_f1([1, 1, 0, 0], [1, 0, 1, 0])
22
+ assert r["precision"] == 0.5 and r["recall"] == 0.5 and r["f1"] == 0.5
23
+
24
+
25
+ def test_macro_f1_perfect():
26
+ assert m.macro_f1(["a", "b", "c"], ["a", "b", "c"]) == 1.0
27
+
28
+
29
+ def test_macro_f1_counts_rare_class():
30
+ # 9 of 10 right, but the rare class is always missed
31
+ y_true = ["a"] * 9 + ["b"]
32
+ y_pred = ["a"] * 10
33
+ assert m.accuracy(y_true, y_pred) == 0.9
34
+ assert m.macro_f1(y_true, y_pred) < 0.5
35
+
36
+
37
+ def test_auto_accept_basic():
38
+ # the 8 most confident are right, the 2 least confident are wrong
39
+ correct = [True] * 8 + [False] * 2
40
+ conf = [0.99, 0.98, 0.97, 0.96, 0.95, 0.94, 0.93, 0.92, 0.40, 0.30]
41
+ r = m.auto_accept(correct, conf, target_precision=1.0)
42
+ assert r["coverage"] == 0.8
43
+ assert r["threshold"] == 0.92
44
+ assert r["precision"] == 1.0
45
+
46
+
47
+ def test_auto_accept_allows_some_errors():
48
+ correct = [True] * 9 + [False]
49
+ conf = [0.9 - i * 0.01 for i in range(10)]
50
+ r = m.auto_accept(correct, conf, target_precision=0.9)
51
+ assert r["coverage"] == 1.0
52
+
53
+
54
+ def test_auto_accept_none_qualify():
55
+ r = m.auto_accept([False, False], [0.9, 0.8], target_precision=0.99)
56
+ assert r["coverage"] == 0.0 and r["threshold"] is None
57
+
58
+
59
+ def test_auto_accept_ties_are_not_split():
60
+ # two rows share a confidence value: accept both or neither
61
+ correct = [True, True, False]
62
+ conf = [0.9, 0.5, 0.5]
63
+ r = m.auto_accept(correct, conf, target_precision=1.0)
64
+ assert r["accepted"] == 1
@@ -0,0 +1,28 @@
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ import pytest
5
+
6
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
7
+ import moteml # noqa: E402
8
+
9
+
10
+ def test_released_models():
11
+ assert moteml.available() == ["spend"]
12
+ assert moteml.RELEASED["spend"] == "moteml/spend"
13
+
14
+
15
+ def test_unknown_model():
16
+ with pytest.raises(KeyError):
17
+ moteml.load("nope")
18
+
19
+
20
+ def test_planned_model_is_not_loadable():
21
+ with pytest.raises(NotImplementedError):
22
+ moteml.load("tariff")
23
+
24
+
25
+ def test_spend_needs_a_path_until_released():
26
+ if "spend" not in moteml.RELEASED:
27
+ with pytest.raises(NotImplementedError):
28
+ moteml.load("spend")