Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 66 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,20 @@ const datasetId = await edgeML.sendDataset("backendUrl", "deviceApiKey", {
{ name: "accY", unit: "g", quantity: "acceleration", data: [[1618760114000, 0.98]] }, // with unit
],
metaData: { key: "value" }, // optional
labeling: "labeling_label", // optional
labeling: "labeling_label", // optional: one label for the whole dataset
labels: [ // optional: labels over time ranges (unix ms)
{ labeling: "activity", label: "walk", start: 1618760114000, end: 1618760124000 },
],
});

// label a dataset later, e.g. one that holds recordings
await edgeML.addLabels("backendUrl", "deviceApiKey", datasetId, [
{ labeling: "activity", label: "run", start: 1618760125000, end: 1618760130000 },
]);
```

Labelings and labels that do not exist yet are created. Labels of one labeling must not overlap.

### Audio and video

A dataset can hold audio and video recordings next to its time-series, to view and label them in the web app. A recording is placed on the dataset's timeline by `start`, the unix ms at which it begins, so it lines up with the sensor data. Recordings are not used for training.
Expand Down Expand Up @@ -169,6 +179,25 @@ Leaving out `pipeline` uses the defaults above. `listPipelines(url, key)` return

To run in the browser, a model has to be exportable to ONNX. It needs **sample-based windowing**, the **SimpleFeatureExtractor** or **Raw Time-Series** features, a **MinMax** or **Z** normalizer, and a **Decision Tree**, **Random Forest** or **PyTorch** classifier.

### Train on sound

Datasets can hold audio and video recordings (see [Audio and video](#audio-and-video)). Models can learn from a recording's sound, alone or together with the sensors:

```js
// sound only: windows of 1 s, the sound as a log-mel spectrogram, a CNN
await edgeML.trainModel(url, key, { name: "kitchen", labeling: "activity", preset: "audio_cnn" });

// sound and the time-series all datasets share
await edgeML.trainModel(url, key, { name: "kitchen", labeling: "activity", preset: "mixed_cnn" });

// name the recording when the datasets have more than one, and pick sensors
await edgeML.trainModel(url, key, { name: "kitchen", labeling: "activity", audio: "mic", timeSeries: ["accX", "accY", "accZ"] });
```

- `audio` names the recording (by its name in the datasets). Without it, the recording every selected dataset has is used when there is exactly one. Video files count when they have a sound track.
- Without `datasets`, every dataset labeled with `labeling` that has the recording is used.
- Sound is converted to mono at 16 kHz. Sound models can be exported to ONNX (browser, Node.js), ExecuTorch (phones) and PyTorch, not to C.

Other functions:

| Function | |
Expand Down Expand Up @@ -205,6 +234,30 @@ await predictor.predictWindow(rows); // classify your own window: win
predictor.reset(); // clear the buffer
```

### Models that take sound

Models trained on sound take it with `addAudio`, at any sample rate (it is mixed to mono and resampled to the model's rate, e.g. 16 kHz). Sensors go in as before. Their windows have a fixed duration (`windowMs`); `predict()` classifies the latest window of sound and sensors, aligned in time.

```js
const predictor = await edgeML.loadModel(url, key, modelId);
predictor.audioSampleRate; // 16000: rate the model takes (null for sensor models)
predictor.windowMs; // 1000: window duration

// e.g. from the Web Audio API (an AudioWorklet posting Float32Array chunks)
predictor.addAudio(chunk, { sampleRate: audioContext.sampleRate }); // optional: channels, time (unix ms of the last sample)
predictor.addPcm16(int16Chunk, { sampleRate: 48000 }); // 16-bit PCM
predictor.addSample({ accX, accY, accZ }); // mixed models: sensors too

if (predictor.isReady) console.log((await predictor.predict()).prediction);

// classify your own window: sensor rows on the model's grid, sound at audioSampleRate
await predictor.predictInputs({ sensors: rows, audio: float32Samples });
```

`examples/example-audio-web` classifies the microphone live in the browser.

`edgeML.Resampler` is the resampler the predictor uses, if you need it yourself: `new Resampler(48000, 16000).process(chunk)` returns the converted samples of each chunk.

### Sensor units

Every model knows the unit it expects for each input (`predictor.inputUnits`). Tell the predictor which unit your sensors deliver, and it converts the values before predicting:
Expand Down Expand Up @@ -251,6 +304,18 @@ catalog.quantities.map((q) => [q.id, q.defaultUnit, q.units.map((u) => u.id)]);
// [["acceleration", "m/s^2", ["m/s^2", "g", "mg", "cm/s^2"]], ["angular_velocity", "deg/s", ["deg/s", "rad/s", "rpm"]], ...]
```

## 4.4.0: sound

- Train on the sound of recordings: the presets `audio_cnn` and `mixed_cnn`, or `audio` in the training options.
- `OnnxPredictor` runs models that take sound (manifest schema 2): `addAudio` / `addPcm16` with any sample rate, `predictInputs`, `isReady`, `windowMs`, `audioSampleRate`. Sensor models (schema 1) work as before.
- `edgeML.Resampler`: streaming sample-rate conversion with anti-aliasing.
- Earlier versions can't load models that take sound.

## 4.3.0: labels over time ranges

- `sendDataset` takes `labels: [{ labeling, label, start, end }]`, and `addLabels` adds them to an existing dataset.
- A `labeling` for the whole dataset is no longer dropped for a dataset that only holds recordings, and covers the recordings of a dataset that also has time-series. This needs an edge-ml server that spans recordings; older servers refuse it for a dataset without time-series.

## 4.2.0: audio and video

- `uploadMedia` adds an audio or video recording to a dataset; `sendDataset` takes them as `media`, also without any time-series.
Expand Down
19 changes: 19 additions & 0 deletions __tests__/fixtures/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,22 @@ tests, `input_units.json` is the `input.units` block the backend
(`ml/app/units/deploy.py`) writes for a model trained on x in m/s^2
(acceleration), y in degC (temperature) and z in a custom unit, and
`unit_catalog.json` is the backend's `GET /ml/units/` response.

## Models that take sound (manifest schema 2)

`audio_mixed/` (sensors acc_x/acc_y at 50 Hz + sound at 8 kHz) and
`audio_only/` (sound only) come from the backend's audio pipeline (#100):
time-based windows of 500 ms, log-mel spectrogram, per-channel Z
normalization and the audio & sensor CNN, trained on the synthetic recordings
of `ml/tests/test_audio_export.py` (class 0 "still": a tone, device still;
class 1 "shaking": noise, device moving). 8 kHz keeps the fixtures small.

`reference.json` holds 4 windows: `sensors` (rows of the sensor grid),
`audio` (base64 little-endian float32 at 8 kHz), the scores of the Python
pipeline and of onnxruntime for the export, and per window a `streams` entry:
the same sound at 48 kHz from 200 ms before the window (`lead_ms`), to test
streaming microphone input through the resampler.

Regenerate with `make_audio_fixtures.py OUT_DIR`, run from the ml/ directory
of the backend in its Docker image. It also writes `model.pte` (ExecuTorch)
for the Flutter library's fixtures.
91 changes: 91 additions & 0 deletions __tests__/fixtures/audio_mixed/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
{
"schema_version": 2,
"format": "onnx",
"model_name": "audio_mixed",
"model_id": "222222222222222222222222",
"opset": 17,
"window": {
"duration_ms": 500.0,
"stride_ms": 500.0
},
"inputs": [
{
"name": "raw_window",
"kind": "sensors",
"shape": [
1,
25,
2
],
"dtype": "float32",
"layout": "window x channel",
"sampling_rate": 50.0,
"timeseries": [
"acc_x",
"acc_y"
],
"units": [
{
"name": "acc_x",
"quantity": null,
"unit": "",
"conversions": {}
},
{
"name": "acc_y",
"quantity": null,
"unit": "",
"conversions": {}
}
]
},
{
"name": "audio",
"kind": "audio",
"shape": [
1,
4000
],
"dtype": "float32",
"sample_rate": 8000,
"channels": 1,
"range": [
-1.0,
1.0
],
"recording": "mic"
}
],
"preprocessing": {
"baked": [
"Log-mel spectrogram & sensors",
"Per-channel ZNormalizer"
],
"on_device": [
"windowing",
"resampling"
],
"spectrogram": {
"sample_rate": 8000,
"n_fft": 200,
"hop": 80,
"n_mels": 40,
"window": "hann",
"mel_scale": "htk",
"log_offset": 1e-06
}
},
"output": {
"name": "scores",
"type": "logits",
"shape": [
1,
2
],
"labels": [
"still",
"shaking"
]
},
"classification_frequency_hint_hz": 2.0
}
Binary file added __tests__/fixtures/audio_mixed/model.onnx
Binary file not shown.
1 change: 1 addition & 0 deletions __tests__/fixtures/audio_mixed/reference.json

Large diffs are not rendered by default.

61 changes: 61 additions & 0 deletions __tests__/fixtures/audio_only/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
{
"schema_version": 2,
"format": "onnx",
"model_name": "audio_only",
"model_id": "222222222222222222222222",
"opset": 17,
"window": {
"duration_ms": 500.0,
"stride_ms": 500.0
},
"inputs": [
{
"name": "audio",
"kind": "audio",
"shape": [
1,
4000
],
"dtype": "float32",
"sample_rate": 8000,
"channels": 1,
"range": [
-1.0,
1.0
],
"recording": "mic"
}
],
"preprocessing": {
"baked": [
"Log-mel spectrogram & sensors",
"Per-channel ZNormalizer"
],
"on_device": [
"windowing",
"resampling"
],
"spectrogram": {
"sample_rate": 8000,
"n_fft": 200,
"hop": 80,
"n_mels": 40,
"window": "hann",
"mel_scale": "htk",
"log_offset": 1e-06
}
},
"output": {
"name": "scores",
"type": "logits",
"shape": [
1,
2
],
"labels": [
"still",
"shaking"
]
},
"classification_frequency_hint_hz": 2.0
}
Binary file added __tests__/fixtures/audio_only/model.onnx
Binary file not shown.
1 change: 1 addition & 0 deletions __tests__/fixtures/audio_only/reference.json

Large diffs are not rendered by default.

95 changes: 95 additions & 0 deletions __tests__/fixtures/make_audio_fixtures.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
"""Schema-2 ONNX fixtures for the JS and Dart libraries (#100).

Run in the ml image from the ml/ directory:
python make_audio_fixtures.py OUT_DIR
Writes OUT_DIR/{audio_mixed,audio_only}/{model.onnx,manifest.json,reference.json}
(and model.pte with manifest_executorch.json for the Flutter library)."""
import base64, json, os, sys
sys.path.insert(0, "tests"); sys.path.insert(0, "tests/fixtures")
import test_audio_export as t # sets the test environment
import numpy as np, torch, onnxruntime as ort
from scipy.signal import resample_poly
from app.DataProcessor.DataLoader import media
from app.ml.Pipeline import Pipeline
from app.ml.Pipelines.AudioClassificationPipeline import AUDIO_CATEGORIES
from app.ml.Pipelines.Abstract.StepType import StepType
from app.ml.Pipelines.PipelineContainer import PipelineContainer
from app.ml.Pipelines.Categories.Windowing.SyncedTimeWindower import SyncedTimeWindower
from app.ml.Pipelines.Categories.FeatureExtraction.LogMelSensorExtractor import LogMelSensorExtractor
from app.ml.Pipelines.Categories.Normalizer.ChannelZNormalizer import ChannelZNormalizer
from app.ml.Pipelines.Categories.Classifier.TorchMultimodalCNN import TorchMultimodalCNN
from app.ml.Pipelines.Categories.Evaluation.TestTrainSplitEvaluation import TestTrainSplitEvaluation
from app.ml.PipelineExport import torch_export
from app.DataModels.model import AudioInput
from types import SimpleNamespace

OUT = sys.argv[1]
RATE = 8000
b64 = lambda a: base64.b64encode(np.asarray(a, dtype="<f4").tobytes()).decode()

for name, sensors in (("audio_mixed", True), ("audio_only", False)):
torch.manual_seed(0)
srcs, pcm = [], {}
for seed in (0, 1):
src, mid, p = t.synthetic(seed, sensors, True)
# the synthetic sound is 16 kHz; this fixture's model takes 8 kHz
pcm[mid] = resample_poly(p.astype(np.float64), 1, 2).astype(np.int16)
srcs.append(src)
media.load_audio = lambda media_id, rate: pcm[str(media_id)]
options = [
SyncedTimeWindower(t.params(SyncedTimeWindower, window_ms=500, stride_ms=500, audio_rate_hz="8000")),
LogMelSensorExtractor(LogMelSensorExtractor.get_parameters()),
ChannelZNormalizer([]),
TorchMultimodalCNN(t.params(TorchMultimodalCNN, size="small", epochs=6)),
TestTrainSplitEvaluation(t.params(TestTrainSplitEvaluation, Train_test_split=75)),
]
pipeline = Pipeline(options, AUDIO_CATEGORIES)
w = options[0]
metrics = pipeline.eval(PipelineContainer(srcs, None, [s.meta for s in srcs]), ["still", "shaking"])
rows = pipeline.exec(PipelineContainer(srcs, None, None), StepType.PRE).data
# windows of both classes from the first dataset: 0-0.5 s still, 2-2.5 s shaking, ...
picks = [0, 4, 9, 13]
rows = rows[picks]
python = t.AudioPipelineCase.python_scores(pipeline, rows)
model = SimpleNamespace(name=name, id="2" * 24, timeSeries=w.channels, samplingRate=w.sensor_rate,
labels=[SimpleNamespace(name="still"), SimpleNamespace(name="shaking")],
inputUnits=None, audioInputs=[AudioInput(name="mic", sampleRate=RATE)])
files = {f.name: f.content for f in torch_export.onnx_files(options, model)}
os.makedirs(os.path.join(OUT, name), exist_ok=True)
open(os.path.join(OUT, name, "model.onnx"), "wb").write(files["model.onnx"])
open(os.path.join(OUT, name, "manifest.json"), "w").write(files["manifest.json"])
manifest = json.loads(files["manifest.json"])
open(os.path.join(OUT, name, "model.pte"), "wb").write(torch_export.build_pte(options))
# the Flutter library runs the .pte with the ExecuTorch manifest
open(os.path.join(OUT, name, "manifest_executorch.json"), "w").write(
json.dumps(torch_export.executorch_manifest(options, model), indent=2))
sess = ort.InferenceSession(files["model.onnx"])
audio = w.audio_for(rows)
feeds = {"audio": audio}
windows = []
if sensors:
feeds["raw_window"] = w.sensors_for(rows)
onnx_scores = sess.run(None, feeds)[0]
# the stream around each window at 48 kHz (from 200 ms before it), for the resampler
streams = []
full = pcm[str(srcs[0].audio.id)].astype(np.float64) / 32768
for k, row in enumerate(rows):
first = int(row[2])
lead = int(0.2 * RATE)
seg = full[first - lead if first >= lead else 0: first + w.audio_samples]
streams.append({"lead_ms": (first - max(0, first - lead)) * 1000 / RATE,
"audio_48k": b64(resample_poly(seg, 6, 1))})
ref = {
"accuracy": metrics["metrics"]["accuracy_score"],
"window_ms": 500, "sensor_samples": w.sensor_samples, "audio_samples": w.audio_samples,
"sensors": [w.sensors_for(rows)[k].tolist() for k in range(len(rows))] if sensors else None,
"audio": [b64(a) for a in audio],
"streams": streams,
"onnx_scores": onnx_scores.tolist(),
"python_scores": python.tolist(),
"python_predictions": [int(x) for x in python.argmax(1)],
}
json.dump(ref, open(os.path.join(OUT, name, "reference.json"), "w"))
w.release()
print(name, "accuracy", ref["accuracy"], "predictions", ref["python_predictions"],
"max |onnx - python|", float(np.abs(onnx_scores - python).max()), manifest["inputs"])
Loading
Loading