moteml 0.2.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.
- moteml-0.2.0/LICENSE +202 -0
- moteml-0.2.0/NOTICE +4 -0
- moteml-0.2.0/PKG-INFO +89 -0
- moteml-0.2.0/README.md +69 -0
- moteml-0.2.0/pyproject.toml +30 -0
- moteml-0.2.0/setup.cfg +4 -0
- moteml-0.2.0/src/moteml/__init__.py +57 -0
- moteml-0.2.0/src/moteml/cli.py +104 -0
- moteml-0.2.0/src/moteml/spend.py +114 -0
- moteml-0.2.0/src/moteml.egg-info/PKG-INFO +89 -0
- moteml-0.2.0/src/moteml.egg-info/SOURCES.txt +15 -0
- moteml-0.2.0/src/moteml.egg-info/dependency_links.txt +1 -0
- moteml-0.2.0/src/moteml.egg-info/entry_points.txt +2 -0
- moteml-0.2.0/src/moteml.egg-info/requires.txt +7 -0
- moteml-0.2.0/src/moteml.egg-info/top_level.txt +1 -0
- moteml-0.2.0/tests/test_metrics.py +64 -0
- moteml-0.2.0/tests/test_package.py +36 -0
moteml-0.2.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.2.0/NOTICE
ADDED
moteml-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: moteml
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Small models for specific workloads: read, match and label business data on a laptop CPU
|
|
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 models for specific workloads.
|
|
24
|
+
|
|
25
|
+
Each model does one step of a data pipeline, runs on a laptop CPU, and ships with a public test set
|
|
26
|
+
so you can check the numbers yourself.
|
|
27
|
+
|
|
28
|
+
| Family | What it does | Models |
|
|
29
|
+
|---|---|---|
|
|
30
|
+
| **Read** | Turn a messy file into a clean table | in development |
|
|
31
|
+
| **Match** | Decide whether two records are the same thing | planned |
|
|
32
|
+
| **Label** | Put a row into a standard category or code | `label-spend` released, `label-tariff` in development |
|
|
33
|
+
|
|
34
|
+
- License: Apache 2.0 for all weights and code
|
|
35
|
+
- Models: https://huggingface.co/moteml
|
|
36
|
+
|
|
37
|
+
## label-spend: sort purchase lines into spend categories
|
|
38
|
+
|
|
39
|
+
Reads a purchase line such as `BRG BALL 6204-2RS 20X47X14` and returns one of 25 spend categories,
|
|
40
|
+
a confidence score, and a flag for the lines a person should check. 40 MB, no API key, no per-line
|
|
41
|
+
cost, and the purchase data stays on your machine.
|
|
42
|
+
|
|
43
|
+
```
|
|
44
|
+
pip install moteml
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
import moteml
|
|
49
|
+
model = moteml.load("label-spend") # downloads 40 MB on first use
|
|
50
|
+
model.predict(["HP LASERJET TONER CARTRIDGE BLACK", "MISC"])
|
|
51
|
+
# [{'category': 'Office supplies, furniture and equipment', 'confidence': 0.94, 'needs_review': False, ...},
|
|
52
|
+
# {'category': 'Industrial equipment and MRO supplies', 'confidence': 0.12, 'needs_review': True, ...}]
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Label a whole CSV file:
|
|
56
|
+
|
|
57
|
+
```
|
|
58
|
+
moteml label spend purchases.csv --column description --out labeled.csv --summary summary.txt
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
The summary holds counts and percentages only, with no purchase text, so it is safe to share.
|
|
62
|
+
|
|
63
|
+
Results, limits and the comparison with other free models are on the model page:
|
|
64
|
+
https://huggingface.co/moteml/label-spend. The test files are at
|
|
65
|
+
https://huggingface.co/datasets/moteml/label-spend-bench.
|
|
66
|
+
|
|
67
|
+
## How this repo is laid out
|
|
68
|
+
|
|
69
|
+
| Folder | What it holds |
|
|
70
|
+
|---|---|
|
|
71
|
+
| `models/` | One folder per model. Each has its own spec, data steps, test set, training and export |
|
|
72
|
+
| `models/_template/` | Copy this to start a new model (`scripts/new_model.sh <slug>`) |
|
|
73
|
+
| `pipeline/` | Code every model shares: metrics, export, benchmarking |
|
|
74
|
+
| `src/moteml/` | The installable library. One interface for every released model |
|
|
75
|
+
| `docs/` | House rules, the catalog, and the dataset license ledger |
|
|
76
|
+
| `scripts/` | Setup and helper scripts |
|
|
77
|
+
| `data/`, `runs/`, `artifacts/` | Local only. Never committed |
|
|
78
|
+
|
|
79
|
+
## The seven steps every model goes through
|
|
80
|
+
|
|
81
|
+
1. Spec: write down the problem, who has it, the data, and the tool to beat
|
|
82
|
+
2. Data: download public data and record its license in `docs/LICENSE_LEDGER.md`
|
|
83
|
+
3. Test set: build it and hand-check a sample before any training
|
|
84
|
+
4. Baselines: score the existing free tools on the test set
|
|
85
|
+
5. Train: fine-tune a small model and beat the baselines
|
|
86
|
+
6. Export: ONNX, quantized, with CPU latency measured
|
|
87
|
+
7. Release: model card, demo, packages, launch post
|
|
88
|
+
|
|
89
|
+
A model that cannot beat the baselines at step 5 does not ship.
|
moteml-0.2.0/README.md
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# MoteML
|
|
2
|
+
|
|
3
|
+
Small models for specific workloads.
|
|
4
|
+
|
|
5
|
+
Each model does one step of a data pipeline, runs on a laptop CPU, and ships with a public test set
|
|
6
|
+
so you can check the numbers yourself.
|
|
7
|
+
|
|
8
|
+
| Family | What it does | Models |
|
|
9
|
+
|---|---|---|
|
|
10
|
+
| **Read** | Turn a messy file into a clean table | in development |
|
|
11
|
+
| **Match** | Decide whether two records are the same thing | planned |
|
|
12
|
+
| **Label** | Put a row into a standard category or code | `label-spend` released, `label-tariff` in development |
|
|
13
|
+
|
|
14
|
+
- License: Apache 2.0 for all weights and code
|
|
15
|
+
- Models: https://huggingface.co/moteml
|
|
16
|
+
|
|
17
|
+
## label-spend: sort purchase lines into spend categories
|
|
18
|
+
|
|
19
|
+
Reads a purchase line such as `BRG BALL 6204-2RS 20X47X14` and returns one of 25 spend categories,
|
|
20
|
+
a confidence score, and a flag for the lines a person should check. 40 MB, no API key, no per-line
|
|
21
|
+
cost, and the purchase data stays on your machine.
|
|
22
|
+
|
|
23
|
+
```
|
|
24
|
+
pip install moteml
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
import moteml
|
|
29
|
+
model = moteml.load("label-spend") # downloads 40 MB on first use
|
|
30
|
+
model.predict(["HP LASERJET TONER CARTRIDGE BLACK", "MISC"])
|
|
31
|
+
# [{'category': 'Office supplies, furniture and equipment', 'confidence': 0.94, 'needs_review': False, ...},
|
|
32
|
+
# {'category': 'Industrial equipment and MRO supplies', 'confidence': 0.12, 'needs_review': True, ...}]
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Label a whole CSV file:
|
|
36
|
+
|
|
37
|
+
```
|
|
38
|
+
moteml label spend purchases.csv --column description --out labeled.csv --summary summary.txt
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
The summary holds counts and percentages only, with no purchase text, so it is safe to share.
|
|
42
|
+
|
|
43
|
+
Results, limits and the comparison with other free models are on the model page:
|
|
44
|
+
https://huggingface.co/moteml/label-spend. The test files are at
|
|
45
|
+
https://huggingface.co/datasets/moteml/label-spend-bench.
|
|
46
|
+
|
|
47
|
+
## How this repo is laid out
|
|
48
|
+
|
|
49
|
+
| Folder | What it holds |
|
|
50
|
+
|---|---|
|
|
51
|
+
| `models/` | One folder per model. Each has its own spec, data steps, test set, training and export |
|
|
52
|
+
| `models/_template/` | Copy this to start a new model (`scripts/new_model.sh <slug>`) |
|
|
53
|
+
| `pipeline/` | Code every model shares: metrics, export, benchmarking |
|
|
54
|
+
| `src/moteml/` | The installable library. One interface for every released model |
|
|
55
|
+
| `docs/` | House rules, the catalog, and the dataset license ledger |
|
|
56
|
+
| `scripts/` | Setup and helper scripts |
|
|
57
|
+
| `data/`, `runs/`, `artifacts/` | Local only. Never committed |
|
|
58
|
+
|
|
59
|
+
## The seven steps every model goes through
|
|
60
|
+
|
|
61
|
+
1. Spec: write down the problem, who has it, the data, and the tool to beat
|
|
62
|
+
2. Data: download public data and record its license in `docs/LICENSE_LEDGER.md`
|
|
63
|
+
3. Test set: build it and hand-check a sample before any training
|
|
64
|
+
4. Baselines: score the existing free tools on the test set
|
|
65
|
+
5. Train: fine-tune a small model and beat the baselines
|
|
66
|
+
6. Export: ONNX, quantized, with CPU latency measured
|
|
67
|
+
7. Release: model card, demo, packages, launch post
|
|
68
|
+
|
|
69
|
+
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.2.0"
|
|
8
|
+
description = "Small models for specific workloads: read, match and label business data on a laptop CPU"
|
|
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.2.0/setup.cfg
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""MoteML: small models for specific workloads.
|
|
2
|
+
|
|
3
|
+
Three families, one for each step of a data pipeline:
|
|
4
|
+
|
|
5
|
+
read turn a messy file into a clean table (planned)
|
|
6
|
+
match decide whether two records are the same thing (planned)
|
|
7
|
+
label put a row into a standard category or code (label-spend released)
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
__version__ = "0.2.0"
|
|
12
|
+
|
|
13
|
+
# name -> short description. A model is listed in RELEASED only once it is on Hugging Face.
|
|
14
|
+
CATALOG = {
|
|
15
|
+
"label-spend": "Put a purchase line into its spend category",
|
|
16
|
+
"label-tariff": "Put a product description into its customs (HS) code",
|
|
17
|
+
"read-sheet": "Turn a messy spreadsheet into a clean table",
|
|
18
|
+
"read-columns": "Tell what each column of a table holds",
|
|
19
|
+
"match-company": "Decide if two records are the same company",
|
|
20
|
+
}
|
|
21
|
+
FAMILIES = ("read", "match", "label")
|
|
22
|
+
|
|
23
|
+
RELEASED: dict[str, str] = {"label-spend": "moteml/label-spend"} # name -> Hugging Face repo id
|
|
24
|
+
|
|
25
|
+
ALIASES = {"spend": "label-spend", "tariff": "label-tariff"} # short names that keep working
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def available() -> list[str]:
|
|
29
|
+
"""Models that can be loaded today."""
|
|
30
|
+
return sorted(RELEASED)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def load(name: str, path: str | None = None):
|
|
34
|
+
"""Load a model by name, for example ``moteml.load("label-spend")``.
|
|
35
|
+
|
|
36
|
+
path: a local folder with the model files. Without it, the released model is
|
|
37
|
+
downloaded from Hugging Face on first use and cached.
|
|
38
|
+
"""
|
|
39
|
+
name = ALIASES.get(name, name)
|
|
40
|
+
if name not in CATALOG:
|
|
41
|
+
raise KeyError(f"unknown model '{name}'. Known: {', '.join(sorted(CATALOG))}")
|
|
42
|
+
if name not in _LOADERS:
|
|
43
|
+
raise NotImplementedError(f"'{name}' is planned and not built yet")
|
|
44
|
+
if path is None:
|
|
45
|
+
if name not in RELEASED:
|
|
46
|
+
raise NotImplementedError(f"'{name}' is not on Hugging Face yet. Pass path= with a local model folder")
|
|
47
|
+
from huggingface_hub import snapshot_download
|
|
48
|
+
path = snapshot_download(RELEASED[name])
|
|
49
|
+
return _LOADERS[name](path)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _load_spend(path):
|
|
53
|
+
from .spend import SpendModel
|
|
54
|
+
return SpendModel(path)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
_LOADERS = {"label-spend": _load_spend}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Command line: label a whole CSV file.
|
|
2
|
+
|
|
3
|
+
moteml label spend purchases.csv --column description --out labeled.csv
|
|
4
|
+
moteml label spend purchases.csv --column description --out labeled.csv --truth-column category --summary summary.txt
|
|
5
|
+
|
|
6
|
+
`moteml spend ...` is the same command under its old name.
|
|
7
|
+
|
|
8
|
+
The summary holds counts and percentages only. No purchase text goes into it, so it can be shared.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import csv
|
|
14
|
+
import sys
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def main(argv: list[str] | None = None) -> int:
|
|
18
|
+
ap = argparse.ArgumentParser(prog="moteml", description="Small models for specific workloads: read, match, label.")
|
|
19
|
+
sub = ap.add_subparsers(dest="family", required=True)
|
|
20
|
+
|
|
21
|
+
def spend_args(sp):
|
|
22
|
+
sp.add_argument("file", help="CSV file to label")
|
|
23
|
+
sp.add_argument("--column", required=True, help="name of the column holding the purchase description")
|
|
24
|
+
sp.add_argument("--out", required=True, help="where to write the labeled CSV")
|
|
25
|
+
sp.add_argument("--model", default="", help="folder with the model files (default: download the released model)")
|
|
26
|
+
sp.add_argument("--truth-column", default="", help="column with your own category for each line, if you have one. The summary then reports accuracy")
|
|
27
|
+
sp.add_argument("--summary", default="", help="also save the summary to this file. It contains no purchase text")
|
|
28
|
+
|
|
29
|
+
label = sub.add_parser("label", help="put each row into a standard category or code")
|
|
30
|
+
kinds = label.add_subparsers(dest="kind", required=True)
|
|
31
|
+
spend_args(kinds.add_parser("spend", help="purchase lines into 25 spend categories"))
|
|
32
|
+
spend_args(sub.add_parser("spend", help="same as: label spend"))
|
|
33
|
+
for fam, what in (("read", "turn a messy file into a clean table"), ("match", "decide whether two records are the same thing")):
|
|
34
|
+
sub.add_parser(fam, help=what + " (planned, not released yet)")
|
|
35
|
+
args = ap.parse_args(argv)
|
|
36
|
+
if args.family in ("read", "match"):
|
|
37
|
+
print(f"'moteml {args.family}' is planned and not released yet. Released today: moteml label spend", file=sys.stderr)
|
|
38
|
+
return 2
|
|
39
|
+
|
|
40
|
+
import moteml
|
|
41
|
+
model = moteml.load("label-spend", path=args.model or None)
|
|
42
|
+
known = {"".join(ch for ch in c.lower() if ch.isalpha()) for c in model.categories} if hasattr(model, "categories") else set()
|
|
43
|
+
csv.field_size_limit(1 << 30)
|
|
44
|
+
with open(args.file, encoding="utf-8-sig", newline="") as f:
|
|
45
|
+
reader = csv.DictReader(f)
|
|
46
|
+
if args.column not in (reader.fieldnames or []):
|
|
47
|
+
print(f"column '{args.column}' not found. Columns: {', '.join(reader.fieldnames or [])}", file=sys.stderr)
|
|
48
|
+
return 2
|
|
49
|
+
rows = list(reader)
|
|
50
|
+
fields = list(reader.fieldnames)
|
|
51
|
+
added = ["spend_category", "spend_confidence", "spend_second_choice", "spend_needs_review"]
|
|
52
|
+
if args.truth_column and args.truth_column not in fields:
|
|
53
|
+
print(f"column '{args.truth_column}' not found. Columns: {', '.join(fields)}", file=sys.stderr)
|
|
54
|
+
return 2
|
|
55
|
+
import re
|
|
56
|
+
from collections import Counter
|
|
57
|
+
key = lambda t: re.sub(r"[^a-z]", "", (t or "").lower())
|
|
58
|
+
per_cat, per_cat_review, bands = Counter(), Counter(), Counter()
|
|
59
|
+
n_review = n_truth = right = right_auto = n_auto_truth = 0
|
|
60
|
+
with open(args.out, "w", encoding="utf-8", newline="") as f:
|
|
61
|
+
w = csv.DictWriter(f, fieldnames=fields + added)
|
|
62
|
+
w.writeheader()
|
|
63
|
+
for i in range(0, len(rows), 512):
|
|
64
|
+
chunk = rows[i:i + 512]
|
|
65
|
+
for row, res in zip(chunk, model.predict([r[args.column] or "" for r in chunk])):
|
|
66
|
+
row.update({"spend_category": res["category"], "spend_confidence": res["confidence"],
|
|
67
|
+
"spend_second_choice": res["second_choice"],
|
|
68
|
+
"spend_needs_review": "yes" if res["needs_review"] else "no"})
|
|
69
|
+
n_review += res["needs_review"]
|
|
70
|
+
per_cat[res["category"]] += 1
|
|
71
|
+
per_cat_review[res["category"]] += res["needs_review"]
|
|
72
|
+
bands[min(int(res["confidence"] * 10), 9)] += 1
|
|
73
|
+
if args.truth_column and key(row.get(args.truth_column)) in known:
|
|
74
|
+
ok = key(row[args.truth_column]) == key(res["category"])
|
|
75
|
+
n_truth += 1
|
|
76
|
+
right += ok
|
|
77
|
+
if not res["needs_review"]:
|
|
78
|
+
n_auto_truth += 1
|
|
79
|
+
right_auto += ok
|
|
80
|
+
w.writerow(row)
|
|
81
|
+
n = len(rows)
|
|
82
|
+
done = n - n_review
|
|
83
|
+
out = [f"moteml label spend summary (model review setting {model.review_below}). Counts only, no purchase text.",
|
|
84
|
+
f"{n:,} lines labeled. {done:,} need no review ({done / max(n, 1):.0%}), {n_review:,} flagged for a person."]
|
|
85
|
+
if args.truth_column:
|
|
86
|
+
if n_truth:
|
|
87
|
+
out.append(f"Your own category matched one of the model's 25 names on {n_truth:,} lines. On those: "
|
|
88
|
+
f"{right / n_truth:.1%} right overall, {n_auto_truth / n_truth:.1%} labeled without review, "
|
|
89
|
+
+ (f"{right_auto / n_auto_truth:.1%} right among those." if n_auto_truth else "none labeled without review."))
|
|
90
|
+
else:
|
|
91
|
+
out.append("Your own categories use other names than the model's 25, so accuracy cannot be computed directly.")
|
|
92
|
+
out.append("Lines per category (share flagged for review):")
|
|
93
|
+
out += [f" {c}: {k:,} ({per_cat_review[c] / k:.0%})" for c, k in per_cat.most_common()]
|
|
94
|
+
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]))
|
|
95
|
+
text = "\n".join(out)
|
|
96
|
+
print(text)
|
|
97
|
+
if args.summary:
|
|
98
|
+
with open(args.summary, "w", encoding="utf-8") as f:
|
|
99
|
+
f.write(text + "\n")
|
|
100
|
+
return 0
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
if __name__ == "__main__":
|
|
104
|
+
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,89 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: moteml
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Small models for specific workloads: read, match and label business data on a laptop CPU
|
|
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 models for specific workloads.
|
|
24
|
+
|
|
25
|
+
Each model does one step of a data pipeline, runs on a laptop CPU, and ships with a public test set
|
|
26
|
+
so you can check the numbers yourself.
|
|
27
|
+
|
|
28
|
+
| Family | What it does | Models |
|
|
29
|
+
|---|---|---|
|
|
30
|
+
| **Read** | Turn a messy file into a clean table | in development |
|
|
31
|
+
| **Match** | Decide whether two records are the same thing | planned |
|
|
32
|
+
| **Label** | Put a row into a standard category or code | `label-spend` released, `label-tariff` in development |
|
|
33
|
+
|
|
34
|
+
- License: Apache 2.0 for all weights and code
|
|
35
|
+
- Models: https://huggingface.co/moteml
|
|
36
|
+
|
|
37
|
+
## label-spend: sort purchase lines into spend categories
|
|
38
|
+
|
|
39
|
+
Reads a purchase line such as `BRG BALL 6204-2RS 20X47X14` and returns one of 25 spend categories,
|
|
40
|
+
a confidence score, and a flag for the lines a person should check. 40 MB, no API key, no per-line
|
|
41
|
+
cost, and the purchase data stays on your machine.
|
|
42
|
+
|
|
43
|
+
```
|
|
44
|
+
pip install moteml
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
import moteml
|
|
49
|
+
model = moteml.load("label-spend") # downloads 40 MB on first use
|
|
50
|
+
model.predict(["HP LASERJET TONER CARTRIDGE BLACK", "MISC"])
|
|
51
|
+
# [{'category': 'Office supplies, furniture and equipment', 'confidence': 0.94, 'needs_review': False, ...},
|
|
52
|
+
# {'category': 'Industrial equipment and MRO supplies', 'confidence': 0.12, 'needs_review': True, ...}]
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Label a whole CSV file:
|
|
56
|
+
|
|
57
|
+
```
|
|
58
|
+
moteml label spend purchases.csv --column description --out labeled.csv --summary summary.txt
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
The summary holds counts and percentages only, with no purchase text, so it is safe to share.
|
|
62
|
+
|
|
63
|
+
Results, limits and the comparison with other free models are on the model page:
|
|
64
|
+
https://huggingface.co/moteml/label-spend. The test files are at
|
|
65
|
+
https://huggingface.co/datasets/moteml/label-spend-bench.
|
|
66
|
+
|
|
67
|
+
## How this repo is laid out
|
|
68
|
+
|
|
69
|
+
| Folder | What it holds |
|
|
70
|
+
|---|---|
|
|
71
|
+
| `models/` | One folder per model. Each has its own spec, data steps, test set, training and export |
|
|
72
|
+
| `models/_template/` | Copy this to start a new model (`scripts/new_model.sh <slug>`) |
|
|
73
|
+
| `pipeline/` | Code every model shares: metrics, export, benchmarking |
|
|
74
|
+
| `src/moteml/` | The installable library. One interface for every released model |
|
|
75
|
+
| `docs/` | House rules, the catalog, and the dataset license ledger |
|
|
76
|
+
| `scripts/` | Setup and helper scripts |
|
|
77
|
+
| `data/`, `runs/`, `artifacts/` | Local only. Never committed |
|
|
78
|
+
|
|
79
|
+
## The seven steps every model goes through
|
|
80
|
+
|
|
81
|
+
1. Spec: write down the problem, who has it, the data, and the tool to beat
|
|
82
|
+
2. Data: download public data and record its license in `docs/LICENSE_LEDGER.md`
|
|
83
|
+
3. Test set: build it and hand-check a sample before any training
|
|
84
|
+
4. Baselines: score the existing free tools on the test set
|
|
85
|
+
5. Train: fine-tune a small model and beat the baselines
|
|
86
|
+
6. Export: ONNX, quantized, with CPU latency measured
|
|
87
|
+
7. Release: model card, demo, packages, launch post
|
|
88
|
+
|
|
89
|
+
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 @@
|
|
|
1
|
+
|
|
@@ -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,36 @@
|
|
|
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() == ["label-spend"]
|
|
12
|
+
assert moteml.RELEASED["label-spend"] == "moteml/label-spend"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def test_every_model_belongs_to_a_family():
|
|
16
|
+
assert all(name.split("-")[0] in moteml.FAMILIES for name in moteml.CATALOG)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_old_short_name_still_resolves():
|
|
20
|
+
assert moteml.ALIASES["spend"] == "label-spend"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def test_unknown_model():
|
|
24
|
+
with pytest.raises(KeyError):
|
|
25
|
+
moteml.load("nope")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def test_planned_model_is_not_loadable():
|
|
29
|
+
with pytest.raises(NotImplementedError):
|
|
30
|
+
moteml.load("tariff")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def test_spend_needs_a_path_until_released():
|
|
34
|
+
if "label-spend" not in moteml.RELEASED:
|
|
35
|
+
with pytest.raises(NotImplementedError):
|
|
36
|
+
moteml.load("label-spend")
|