@hazeljs/ml 0.2.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/LICENSE +192 -0
  2. package/README.md +300 -0
  3. package/dist/decorators/index.d.ts +4 -0
  4. package/dist/decorators/index.d.ts.map +1 -0
  5. package/dist/decorators/index.js +15 -0
  6. package/dist/decorators/model.decorator.d.ts +26 -0
  7. package/dist/decorators/model.decorator.d.ts.map +1 -0
  8. package/dist/decorators/model.decorator.js +48 -0
  9. package/dist/decorators/model.decorator.test.d.ts +2 -0
  10. package/dist/decorators/model.decorator.test.d.ts.map +1 -0
  11. package/dist/decorators/model.decorator.test.js +128 -0
  12. package/dist/decorators/predict.decorator.d.ts +20 -0
  13. package/dist/decorators/predict.decorator.d.ts.map +1 -0
  14. package/dist/decorators/predict.decorator.js +40 -0
  15. package/dist/decorators/train.decorator.d.ts +21 -0
  16. package/dist/decorators/train.decorator.d.ts.map +1 -0
  17. package/dist/decorators/train.decorator.js +41 -0
  18. package/dist/evaluation/metrics.service.d.ts +54 -0
  19. package/dist/evaluation/metrics.service.d.ts.map +1 -0
  20. package/dist/evaluation/metrics.service.js +163 -0
  21. package/dist/evaluation/metrics.service.test.d.ts +2 -0
  22. package/dist/evaluation/metrics.service.test.d.ts.map +1 -0
  23. package/dist/evaluation/metrics.service.test.js +253 -0
  24. package/dist/index.d.ts +16 -0
  25. package/dist/index.d.ts.map +1 -0
  26. package/dist/index.js +42 -0
  27. package/dist/inference/batch.service.d.ts +16 -0
  28. package/dist/inference/batch.service.d.ts.map +1 -0
  29. package/dist/inference/batch.service.js +52 -0
  30. package/dist/inference/batch.service.test.d.ts +2 -0
  31. package/dist/inference/batch.service.test.d.ts.map +1 -0
  32. package/dist/inference/batch.service.test.js +86 -0
  33. package/dist/inference/predictor.service.d.ts +13 -0
  34. package/dist/inference/predictor.service.d.ts.map +1 -0
  35. package/dist/inference/predictor.service.js +65 -0
  36. package/dist/inference/predictor.service.test.d.ts +2 -0
  37. package/dist/inference/predictor.service.test.d.ts.map +1 -0
  38. package/dist/inference/predictor.service.test.js +115 -0
  39. package/dist/ml-model.base.d.ts +20 -0
  40. package/dist/ml-model.base.d.ts.map +1 -0
  41. package/dist/ml-model.base.js +33 -0
  42. package/dist/ml-model.base.test.d.ts +2 -0
  43. package/dist/ml-model.base.test.d.ts.map +1 -0
  44. package/dist/ml-model.base.test.js +57 -0
  45. package/dist/ml.module.d.ts +27 -0
  46. package/dist/ml.module.d.ts.map +1 -0
  47. package/dist/ml.module.js +126 -0
  48. package/dist/ml.module.test.d.ts +2 -0
  49. package/dist/ml.module.test.d.ts.map +1 -0
  50. package/dist/ml.module.test.js +60 -0
  51. package/dist/ml.types.d.ts +30 -0
  52. package/dist/ml.types.d.ts.map +1 -0
  53. package/dist/ml.types.js +5 -0
  54. package/dist/registry/model.registry.d.ts +21 -0
  55. package/dist/registry/model.registry.d.ts.map +1 -0
  56. package/dist/registry/model.registry.js +64 -0
  57. package/dist/registry/model.registry.test.d.ts +2 -0
  58. package/dist/registry/model.registry.test.d.ts.map +1 -0
  59. package/dist/registry/model.registry.test.js +93 -0
  60. package/dist/training/pipeline.service.d.ts +25 -0
  61. package/dist/training/pipeline.service.d.ts.map +1 -0
  62. package/dist/training/pipeline.service.js +65 -0
  63. package/dist/training/pipeline.service.test.d.ts +2 -0
  64. package/dist/training/pipeline.service.test.d.ts.map +1 -0
  65. package/dist/training/pipeline.service.test.js +52 -0
  66. package/dist/training/trainer.service.d.ts +13 -0
  67. package/dist/training/trainer.service.d.ts.map +1 -0
  68. package/dist/training/trainer.service.js +69 -0
  69. package/dist/training/trainer.service.test.d.ts +2 -0
  70. package/dist/training/trainer.service.test.d.ts.map +1 -0
  71. package/dist/training/trainer.service.test.js +99 -0
  72. package/package.json +52 -0
package/LICENSE ADDED
@@ -0,0 +1,192 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ Copyright 2024 HazelJS Team
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License");
8
+ you may not use this file except in compliance with the License.
9
+ You may obtain a copy of the License at
10
+
11
+ http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software
14
+ distributed under the License is distributed on an "AS IS" BASIS,
15
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ See the License for the specific language governing permissions and
17
+ limitations under the License.
18
+
19
+ ---
20
+
21
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
22
+
23
+ 1. Definitions.
24
+
25
+ "License" shall mean the terms and conditions for use, reproduction,
26
+ and distribution as defined by Sections 1 through 9 of this document.
27
+
28
+ "Licensor" shall mean the copyright owner or entity authorized by
29
+ the copyright owner that is granting the License.
30
+
31
+ "Legal Entity" shall mean the union of the acting entity and all
32
+ other entities that control, are controlled by, or are under common
33
+ control with that entity. For the purposes of this definition,
34
+ "control" means (i) the power, direct or indirect, to cause the
35
+ direction or management of such entity, whether by contract or
36
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
37
+ outstanding shares, or (iii) beneficial ownership of such entity.
38
+
39
+ "You" (or "Your") shall mean an individual or Legal Entity
40
+ exercising permissions granted by this License.
41
+
42
+ "Source" form shall mean the preferred form for making modifications,
43
+ including but not limited to software source code, documentation
44
+ source, and configuration files.
45
+
46
+ "Object" form shall mean any form resulting from mechanical
47
+ transformation or translation of a Source form, including but
48
+ not limited to compiled object code, generated documentation,
49
+ and conversions to other media types.
50
+
51
+ "Work" shall mean the work of authorship, whether in Source or
52
+ Object form, made available under the License, as indicated by a
53
+ copyright notice that is included in or attached to the work
54
+ (an example is provided in the Appendix below).
55
+
56
+ "Derivative Works" shall mean any work, whether in Source or Object
57
+ form, that is based on (or derived from) the Work and for which the
58
+ editorial revisions, annotations, elaborations, or other modifications
59
+ represent, as a whole, an original work of authorship. For the purposes
60
+ of this License, Derivative Works shall not include works that remain
61
+ separable from, or merely link (or bind by name) to the interfaces of,
62
+ the Work and Derivative Works thereof.
63
+
64
+ "Contribution" shall mean any work of authorship, including
65
+ the original version of the Work and any modifications or additions
66
+ to that Work or Derivative Works thereof, that is intentionally
67
+ submitted to Licensor for inclusion in the Work by the copyright owner
68
+ or by an individual or Legal Entity authorized to submit on behalf of
69
+ the copyright owner. For the purposes of this definition, "submitted"
70
+ means any form of electronic, verbal, or written communication sent
71
+ to the Licensor or its representatives, including but not limited to
72
+ communication on electronic mailing lists, source code control systems,
73
+ and issue tracking systems that are managed by, or on behalf of, the
74
+ Licensor for the purpose of discussing and improving the Work, but
75
+ excluding communication that is conspicuously marked or otherwise
76
+ designated in writing by the copyright owner as "Not a Contribution."
77
+
78
+ "Contributor" shall mean Licensor and any individual or Legal Entity
79
+ on behalf of whom a Contribution has been received by Licensor and
80
+ subsequently incorporated within the Work.
81
+
82
+ 2. Grant of Copyright License. Subject to the terms and conditions of
83
+ this License, each Contributor hereby grants to You a perpetual,
84
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
85
+ copyright license to reproduce, prepare Derivative Works of,
86
+ publicly display, publicly perform, sublicense, and distribute the
87
+ Work and such Derivative Works in Source or Object form.
88
+
89
+ 3. Grant of Patent License. Subject to the terms and conditions of
90
+ this License, each Contributor hereby grants to You a perpetual,
91
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
92
+ (except as stated in this section) patent license to make, have made,
93
+ use, offer to sell, sell, import, and otherwise transfer the Work,
94
+ where such license applies only to those patent claims licensable
95
+ by such Contributor that are necessarily infringed by their
96
+ Contribution(s) alone or by combination of their Contribution(s)
97
+ with the Work to which such Contribution(s) was submitted. If You
98
+ institute patent litigation against any entity (including a
99
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
100
+ or a Contribution incorporated within the Work constitutes direct
101
+ or contributory patent infringement, then any patent licenses
102
+ granted to You under this License for that Work shall terminate
103
+ as of the date such litigation is filed.
104
+
105
+ 4. Redistribution. You may reproduce and distribute copies of the
106
+ Work or Derivative Works thereof in any medium, with or without
107
+ modifications, and in Source or Object form, provided that You
108
+ meet the following conditions:
109
+
110
+ (a) You must give any other recipients of the Work or
111
+ Derivative Works a copy of this License; and
112
+
113
+ (b) You must cause any modified files to carry prominent notices
114
+ stating that You changed the files; and
115
+
116
+ (c) You must retain, in the Source form of any Derivative Works
117
+ that You distribute, all copyright, patent, trademark, and
118
+ attribution notices from the Source form of the Work,
119
+ excluding those notices that do not pertain to any part of
120
+ the Derivative Works; and
121
+
122
+ (d) If the Work includes a "NOTICE" text file as part of its
123
+ distribution, then any Derivative Works that You distribute must
124
+ include a readable copy of the attribution notices contained
125
+ within such NOTICE file, excluding those notices that do not
126
+ pertain to any part of the Derivative Works, in at least one
127
+ of the following places: within a NOTICE text file distributed
128
+ as part of the Derivative Works; within the Source form or
129
+ documentation, if provided along with the Derivative Works; or,
130
+ within a display generated by the Derivative Works, if and
131
+ wherever such third-party notices normally appear. The contents
132
+ of the NOTICE file are for informational purposes only and
133
+ do not modify the License. You may add Your own attribution
134
+ notices within Derivative Works that You distribute, alongside
135
+ or as an addendum to the NOTICE text from the Work, provided
136
+ that such additional attribution notices cannot be construed
137
+ as modifying the License.
138
+
139
+ You may add Your own copyright statement to Your modifications and
140
+ may provide additional or different license terms and conditions
141
+ for use, reproduction, or distribution of Your modifications, or
142
+ for any such Derivative Works as a whole, provided Your use,
143
+ reproduction, and distribution of the Work otherwise complies with
144
+ the conditions stated in this License.
145
+
146
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
147
+ any Contribution intentionally submitted for inclusion in the Work
148
+ by You to the Licensor shall be under the terms and conditions of
149
+ this License, without any additional terms or conditions.
150
+ Notwithstanding the above, nothing herein shall supersede or modify
151
+ the terms of any separate license agreement you may have executed
152
+ with Licensor regarding such Contributions.
153
+
154
+ 6. Trademarks. This License does not grant permission to use the trade
155
+ names, trademarks, service marks, or product names of the Licensor,
156
+ except as required for reasonable and customary use in describing the
157
+ origin of the Work and reproducing the content of the NOTICE file.
158
+
159
+ 7. Disclaimer of Warranty. Unless required by applicable law or
160
+ agreed to in writing, Licensor provides the Work (and each
161
+ Contributor provides its Contributions) on an "AS IS" BASIS,
162
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
163
+ implied, including, without limitation, any warranties or conditions
164
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
165
+ PARTICULAR PURPOSE. You are solely responsible for determining the
166
+ appropriateness of using or redistributing the Work and assume any
167
+ risks associated with Your exercise of permissions under this License.
168
+
169
+ 8. Limitation of Liability. In no event and under no legal theory,
170
+ whether in tort (including negligence), contract, or otherwise,
171
+ unless required by applicable law (such as deliberate and grossly
172
+ negligent acts) or agreed to in writing, shall any Contributor be
173
+ liable to You for damages, including any direct, indirect, special,
174
+ incidental, or consequential damages of any character arising as a
175
+ result of this License or out of the use or inability to use the
176
+ Work (including but not limited to damages for loss of goodwill,
177
+ work stoppage, computer failure or malfunction, or any and all
178
+ other commercial damages or losses), even if such Contributor
179
+ has been advised of the possibility of such damages.
180
+
181
+ 9. Accepting Warranty or Additional Liability. While redistributing
182
+ the Work or Derivative Works thereof, You may choose to offer,
183
+ and charge a fee for, acceptance of support, warranty, indemnity,
184
+ or other liability obligations and/or rights consistent with this
185
+ License. However, in accepting such obligations, You may act only
186
+ on Your own behalf and on Your sole responsibility, not on behalf
187
+ of any other Contributor, and only if You agree to indemnify,
188
+ defend, and hold each Contributor harmless for any liability
189
+ incurred by, or claims asserted against, such Contributor by reason
190
+ of your accepting any such warranty or additional liability.
191
+
192
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,300 @@
1
+ # @hazeljs/ml
2
+
3
+ Machine Learning & Model Management for HazelJS - training, prediction, model registry, and metrics.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@hazeljs/ml.svg)](https://www.npmjs.com/package/@hazeljs/ml)
6
+ [![npm downloads](https://img.shields.io/npm/dm/@hazeljs/ml)](https://www.npmjs.com/package/@hazeljs/ml)
7
+ [![License: Apache-2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0)
8
+
9
+ ## Features
10
+
11
+ - **Model registry** – Register and discover models by name and version
12
+ - **Decorators** – `@Model`, `@Train`, `@Predict` for declarative ML APIs
13
+ - **Training pipeline** – PipelineService for data preprocessing (normalize, filter)
14
+ - **Inference** – PredictorService for single and batch predictions
15
+ - **Metrics** – MetricsService for evaluation, A/B testing, and monitoring
16
+ - **Framework-agnostic** – Works with TensorFlow.js, ONNX, Transformers.js, or custom backends
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ npm install @hazeljs/ml @hazeljs/core
22
+ ```
23
+
24
+ ### Peer dependencies (optional, per use case)
25
+
26
+ ```bash
27
+ # TensorFlow.js
28
+ npm install @tensorflow/tfjs-node
29
+
30
+ # ONNX Runtime
31
+ npm install onnxruntime-node
32
+
33
+ # Hugging Face Transformers (embeddings, sentiment)
34
+ npm install @huggingface/transformers
35
+ ```
36
+
37
+ ## Quick Start
38
+
39
+ ### 1. Import MLModule
40
+
41
+ ```typescript
42
+ import { HazelApp } from '@hazeljs/core';
43
+ import { MLModule } from '@hazeljs/ml';
44
+
45
+ const app = new HazelApp({
46
+ imports: [
47
+ MLModule.forRoot({
48
+ models: [SentimentClassifier, SpamClassifier],
49
+ }),
50
+ ],
51
+ });
52
+
53
+ app.listen(3000);
54
+ ```
55
+
56
+ ### 2. Define a model with decorators
57
+
58
+ ```typescript
59
+ import { Injectable } from '@hazeljs/core';
60
+ import { Model, Train, Predict, ModelRegistry } from '@hazeljs/ml';
61
+
62
+ @Model({ name: 'sentiment-classifier', version: '1.0.0', framework: 'custom' })
63
+ @Injectable()
64
+ export class SentimentClassifier {
65
+ private labels = ['positive', 'negative', 'neutral'];
66
+ private weights: Record<string, number[]> = {};
67
+
68
+ constructor(private registry: ModelRegistry) {}
69
+
70
+ @Train()
71
+ async train(data: { text: string; label: string }[]): Promise<void> {
72
+ // Your training logic – e.g. bag-of-words, embeddings, etc.
73
+ const vocab = this.buildVocabulary(data);
74
+ this.weights = this.computeWeights(data, vocab);
75
+ }
76
+
77
+ @Predict()
78
+ async predict(input: { text: string }): Promise<{ sentiment: string; confidence: number }> {
79
+ const scores = this.score(input.text);
80
+ const idx = scores.indexOf(Math.max(...scores));
81
+ return {
82
+ sentiment: this.labels[idx],
83
+ confidence: scores[idx],
84
+ };
85
+ }
86
+ }
87
+ ```
88
+
89
+ ### 3. Predict from a controller or service
90
+
91
+ ```typescript
92
+ import { Controller, Post, Body, Inject } from '@hazeljs/core';
93
+ import { PredictorService } from '@hazeljs/ml';
94
+
95
+ @Controller('ml')
96
+ export class MLController {
97
+ constructor(private predictor: PredictorService) {}
98
+
99
+ @Post('predict')
100
+ async predict(@Body() body: { text: string; model?: string }) {
101
+ const result = await this.predictor.predict(
102
+ body.model ?? 'sentiment-classifier',
103
+ body
104
+ );
105
+ return { result };
106
+ }
107
+ }
108
+ ```
109
+
110
+ ## ML Decorators
111
+
112
+ The package uses three decorators to declare ML models and their behaviour. The registry and services discover them via reflection—no manual wiring needed.
113
+
114
+ ### `@Model` (class)
115
+
116
+ Marks a class as an ML model and attaches **registry metadata**. Required so the model can be registered and looked up by name/version.
117
+
118
+ | Property | Type | Required | Description |
119
+ |---------------|----------|----------|-------------|
120
+ | `name` | string | Yes | Unique model id (e.g. `'sentiment-classifier'`). |
121
+ | `version` | string | Yes | Semver (e.g. `'1.0.0'`). |
122
+ | `framework` | string | Yes | `'tensorflow'` \| `'onnx'` \| `'custom'`. |
123
+ | `description` | string | No | Human-readable description. |
124
+ | `tags` | string[] | No | Tags for filtering (default: `[]`). |
125
+
126
+ **Example:** One model per class; use `@Injectable()` so the app can construct it.
127
+
128
+ ```typescript
129
+ @Model({
130
+ name: 'spam-classifier',
131
+ version: '1.0.0',
132
+ framework: 'custom',
133
+ description: 'Binary spam/ham classifier',
134
+ tags: ['nlp', 'moderation'],
135
+ })
136
+ @Injectable()
137
+ export class SpamClassifier {
138
+ // ...
139
+ }
140
+ ```
141
+
142
+ ---
143
+
144
+ ### `@Train` (method)
145
+
146
+ Marks the **single method** that trains this model. `TrainerService.train(modelName, data)` will call it. Optional config is for documentation or pipeline wiring.
147
+
148
+ | Option | Type | Default | Description |
149
+ |-------------|--------|-----------|-------------|
150
+ | `pipeline` | string | `'default'` | Name of a registered `PipelineService` pipeline to run before training. |
151
+ | `batchSize` | number | `32` | Hint for batching (your logic can ignore it). |
152
+ | `epochs` | number | `10` | Hint for epochs (your logic can ignore it). |
153
+
154
+ **Example:** Exactly one `@Train()` method per model; it receives training data and can return metrics.
155
+
156
+ ```typescript
157
+ @Train({ pipeline: 'sentiment-preprocessing', epochs: 5 })
158
+ async train(data: { samples: Array<{ text: string; label: string }> }): Promise<TrainingResult> {
159
+ // Your training logic
160
+ return { accuracy: 0.95, loss: 0.05 };
161
+ }
162
+ ```
163
+
164
+ ---
165
+
166
+ ### `@Predict` (method)
167
+
168
+ Marks the **single method** that runs inference. `PredictorService.predict(modelName, input)` will call it.
169
+
170
+ | Option | Type | Default | Description |
171
+ |-----------|---------|------------|-------------|
172
+ | `batch` | boolean | `false` | Hint that the method supports batch input (semantic only). |
173
+ | `endpoint`| string | `'/predict'` | Hint for route naming (semantic only). |
174
+
175
+ **Example:** Exactly one `@Predict()` method per model; it receives one input and returns a prediction object.
176
+
177
+ ```typescript
178
+ @Predict({ batch: true, endpoint: '/predict' })
179
+ async predict(input: { text: string }): Promise<{ label: string; confidence: number }> {
180
+ // Your inference logic
181
+ return { label: 'ham', confidence: 0.92 };
182
+ }
183
+ ```
184
+
185
+ ---
186
+
187
+ ### Rules
188
+
189
+ - **One model class** = one `@Model`, one `@Train` method, one `@Predict` method.
190
+ - **Order:** Put `@Model` on the class, then `@Train` and `@Predict` on the methods. Use `@Injectable()` from `@hazeljs/core` so the app can instantiate the model.
191
+ - **Discovery:** When you pass model classes to `MLModule.forRoot({ models: [...] })`, the bootstrap finds the `@Train` and `@Predict` methods and registers them with the registry.
192
+
193
+ ## Model registration
194
+
195
+ Models are registered when passed to `MLModule.forRoot({ models: [...] })`. The bootstrap discovers `@Train` and `@Predict` methods via reflection.
196
+
197
+ ### Manual registration
198
+
199
+ ```typescript
200
+ import { registerMLModel, ModelRegistry, TrainerService, PredictorService } from '@hazeljs/ml';
201
+
202
+ // When injecting ModelRegistry in a custom service:
203
+ registerMLModel(
204
+ sentimentInstance,
205
+ modelRegistry,
206
+ trainerService,
207
+ predictorService
208
+ );
209
+ ```
210
+
211
+ ## Training pipeline
212
+
213
+ Preprocess data before training with `PipelineService`:
214
+
215
+ ```typescript
216
+ import { PipelineService } from '@hazeljs/ml';
217
+
218
+ const pipeline = new PipelineService();
219
+ const steps = [
220
+ { name: 'normalize', transform: (d: unknown) => ({ ...(d as object), text: (d as { text: string }).text?.toLowerCase() }) },
221
+ { name: 'filter', transform: (d: unknown) => (d as { text: string }).text?.length > 0 ? d : null },
222
+ ];
223
+ // Inline steps (no registration required)
224
+ const processed = await pipeline.run(data, steps);
225
+ await model.train(processed);
226
+
227
+ // Or register a named pipeline
228
+ pipeline.registerPipeline('default', steps);
229
+ const processed2 = await pipeline.run('default', data);
230
+ ```
231
+
232
+ ## Batch predictions
233
+
234
+ ```typescript
235
+ import { BatchService } from '@hazeljs/ml';
236
+
237
+ const batchService = new BatchService(predictorService);
238
+ const results = await batchService.predictBatch('sentiment-classifier', items, {
239
+ batchSize: 32,
240
+ concurrency: 4,
241
+ });
242
+ // Results are returned in the same order as inputs
243
+ ```
244
+
245
+ ## Metrics and evaluation
246
+
247
+ ```typescript
248
+ import { MetricsService } from '@hazeljs/ml';
249
+
250
+ // Evaluate model on test data (inject MetricsService via MLModule - it receives PredictorService)
251
+ @Injectable()
252
+ class EvaluationService {
253
+ constructor(private metricsService: MetricsService) {}
254
+
255
+ async runEvaluation() {
256
+ const testData = [
257
+ { text: 'great product', label: 'positive' },
258
+ { text: 'terrible', label: 'negative' },
259
+ ];
260
+ const evaluation = await this.metricsService.evaluate('sentiment-classifier', testData, {
261
+ metrics: ['accuracy', 'f1', 'precision', 'recall'],
262
+ labelKey: 'label', // key in test sample for ground truth
263
+ predictionKey: 'sentiment', // key in prediction result (auto-detect: label, sentiment, class)
264
+ });
265
+ // evaluation.metrics: { accuracy, precision, recall, f1Score }
266
+ // Result is automatically recorded via recordEvaluation()
267
+ }
268
+ }
269
+
270
+ // Manual recording
271
+ metricsService.recordEvaluation({
272
+ modelName: 'my-model',
273
+ version: '1.0.0',
274
+ metrics: { accuracy: 0.95, loss: 0.05 },
275
+ evaluatedAt: new Date(),
276
+ });
277
+ ```
278
+
279
+ ## API summary
280
+
281
+ | Service | Purpose |
282
+ |---------|---------|
283
+ | `ModelRegistry` | Register and lookup models by name/version |
284
+ | `TrainerService` | Discover and invoke `@Train` methods |
285
+ | `PredictorService` | Discover and invoke `@Predict` methods |
286
+ | `PipelineService` | Data preprocessing pipeline |
287
+ | `BatchService` | Batch prediction with configurable batch size |
288
+ | `MetricsService` | Model evaluation and metrics tracking |
289
+
290
+ ## Examples
291
+
292
+ - **[hazeljs-ml-starter](../../../hazeljs-ml-starter)** – Full app: sentiment, spam, intent classifiers, REST API, training pipeline, and metrics.
293
+ - **[example/src/ml](../../example/src/ml)** – Minimal runnable example of the three decorators (`npm run ml:decorators` from the example repo).
294
+
295
+ ## Links
296
+
297
+ - [Documentation](https://hazeljs.com/docs/packages/ml)
298
+ - [GitHub](https://github.com/hazel-js/hazeljs)
299
+ - [Issues](https://github.com/hazel-js/hazeljs/issues)
300
+ - [Homepage](https://hazeljs.com)
@@ -0,0 +1,4 @@
1
+ export { Model, getModelMetadata, hasModelMetadata } from './model.decorator';
2
+ export { Train, getTrainMetadata, hasTrainMetadata, type TrainOptions } from './train.decorator';
3
+ export { Predict, getPredictMetadata, hasPredictMetadata, type PredictOptions, } from './predict.decorator';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/decorators/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAAE,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,KAAK,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjG,OAAO,EACL,OAAO,EACP,kBAAkB,EAClB,kBAAkB,EAClB,KAAK,cAAc,GACpB,MAAM,qBAAqB,CAAC"}
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.hasPredictMetadata = exports.getPredictMetadata = exports.Predict = exports.hasTrainMetadata = exports.getTrainMetadata = exports.Train = exports.hasModelMetadata = exports.getModelMetadata = exports.Model = void 0;
4
+ var model_decorator_1 = require("./model.decorator");
5
+ Object.defineProperty(exports, "Model", { enumerable: true, get: function () { return model_decorator_1.Model; } });
6
+ Object.defineProperty(exports, "getModelMetadata", { enumerable: true, get: function () { return model_decorator_1.getModelMetadata; } });
7
+ Object.defineProperty(exports, "hasModelMetadata", { enumerable: true, get: function () { return model_decorator_1.hasModelMetadata; } });
8
+ var train_decorator_1 = require("./train.decorator");
9
+ Object.defineProperty(exports, "Train", { enumerable: true, get: function () { return train_decorator_1.Train; } });
10
+ Object.defineProperty(exports, "getTrainMetadata", { enumerable: true, get: function () { return train_decorator_1.getTrainMetadata; } });
11
+ Object.defineProperty(exports, "hasTrainMetadata", { enumerable: true, get: function () { return train_decorator_1.hasTrainMetadata; } });
12
+ var predict_decorator_1 = require("./predict.decorator");
13
+ Object.defineProperty(exports, "Predict", { enumerable: true, get: function () { return predict_decorator_1.Predict; } });
14
+ Object.defineProperty(exports, "getPredictMetadata", { enumerable: true, get: function () { return predict_decorator_1.getPredictMetadata; } });
15
+ Object.defineProperty(exports, "hasPredictMetadata", { enumerable: true, get: function () { return predict_decorator_1.hasPredictMetadata; } });
@@ -0,0 +1,26 @@
1
+ import 'reflect-metadata';
2
+ import { ModelMetadata } from '../ml.types';
3
+ /**
4
+ * @Model decorator - Register ML models with the registry
5
+ *
6
+ * @example
7
+ * ```typescript
8
+ * @Model({
9
+ * name: 'sentiment-classifier',
10
+ * version: '1.0.0',
11
+ * framework: 'tensorflow',
12
+ * })
13
+ * @Injectable()
14
+ * export class SentimentModel {
15
+ * @Train()
16
+ * async train(data: TrainingData) { ... }
17
+ *
18
+ * @Predict()
19
+ * async predict(text: string) { ... }
20
+ * }
21
+ * ```
22
+ */
23
+ export declare function Model(config: ModelMetadata): ClassDecorator;
24
+ export declare function getModelMetadata(target: object): ModelMetadata | undefined;
25
+ export declare function hasModelMetadata(target: object): boolean;
26
+ //# sourceMappingURL=model.decorator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model.decorator.d.ts","sourceRoot":"","sources":["../../src/decorators/model.decorator.ts"],"names":[],"mappings":"AAAA,OAAO,kBAAkB,CAAC;AAC1B,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAK5C;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,KAAK,CAAC,MAAM,EAAE,aAAa,GAAG,cAAc,CAW3D;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,aAAa,GAAG,SAAS,CAE1E;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAExD"}
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Model = Model;
7
+ exports.getModelMetadata = getModelMetadata;
8
+ exports.hasModelMetadata = hasModelMetadata;
9
+ require("reflect-metadata");
10
+ const core_1 = __importDefault(require("@hazeljs/core"));
11
+ const MODEL_METADATA_KEY = 'hazel:ml:model';
12
+ /**
13
+ * @Model decorator - Register ML models with the registry
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * @Model({
18
+ * name: 'sentiment-classifier',
19
+ * version: '1.0.0',
20
+ * framework: 'tensorflow',
21
+ * })
22
+ * @Injectable()
23
+ * export class SentimentModel {
24
+ * @Train()
25
+ * async train(data: TrainingData) { ... }
26
+ *
27
+ * @Predict()
28
+ * async predict(text: string) { ... }
29
+ * }
30
+ * ```
31
+ */
32
+ function Model(config) {
33
+ return (target) => {
34
+ const metadata = {
35
+ description: '',
36
+ tags: [],
37
+ ...config,
38
+ };
39
+ Reflect.defineMetadata(MODEL_METADATA_KEY, metadata, target);
40
+ core_1.default.debug(`Model decorator applied: ${metadata.name}@${metadata.version}`);
41
+ };
42
+ }
43
+ function getModelMetadata(target) {
44
+ return Reflect.getMetadata(MODEL_METADATA_KEY, target);
45
+ }
46
+ function hasModelMetadata(target) {
47
+ return Reflect.hasMetadata(MODEL_METADATA_KEY, target);
48
+ }
@@ -0,0 +1,2 @@
1
+ import 'reflect-metadata';
2
+ //# sourceMappingURL=model.decorator.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model.decorator.test.d.ts","sourceRoot":"","sources":["../../src/decorators/model.decorator.test.ts"],"names":[],"mappings":"AAAA,OAAO,kBAAkB,CAAC"}