pitch-transcription 4.0.0

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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2020-present Jimmy Chen
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,7 @@
1
+ pitch-transcription
2
+ Copyright Jimmy Chen
3
+
4
+ This package is derived from basic-pitch-ts (https://github.com/spotify/basic-pitch-ts),
5
+ Copyright 2022 Spotify AB, licensed under the Apache License, Version 2.0. Its note
6
+ creation, audio preparation and model call are rewritten from that source, and the
7
+ trained model under `model/` is Spotify's Basic Pitch model, distributed unmodified.
package/README.md ADDED
@@ -0,0 +1,86 @@
1
+ # pitch-transcription
2
+
3
+ [![Apache-2.0 licensed][badge-license]][url-license]
4
+ [![NPM version][badge-npm-version]][url-npm]
5
+ [![NPM downloads][badge-npm-downloads]][url-npm]
6
+ [![NPM Unpacked Size (with version)][badge-npm-unpacked-size]][url-npm]
7
+
8
+ The notes played in a recording: each note's pitch, start, length, loudness and pitch bend, heard by Spotify's Basic Pitch model on the current TensorFlow.js and written as MIDI if you want a file. It hears several notes at once, on any instrument. The trained model ships with the package, and the step that turns the model's readings into notes imports without TensorFlow.js.
9
+
10
+ ## Table of Contents
11
+
12
+ - 🚀 [Getting Started](#getting-started)
13
+ - 📖 [Documentation](#documentation)
14
+ - ⚖️ [License](#license)
15
+
16
+ ---
17
+
18
+ ## <a name="getting-started">🚀 Getting Started</a>
19
+
20
+ ```bash
21
+ pnpm i pitch-transcription @tensorflow/tfjs
22
+ ```
23
+
24
+ ```ts
25
+ import { loadGraphModelSync } from "@tensorflow/tfjs";
26
+ import { readFile } from "node:fs/promises";
27
+ import {
28
+ addPitchBends,
29
+ convertNotesToSeconds,
30
+ createNotes,
31
+ MODEL_URL,
32
+ MODEL_WEIGHTS_URL,
33
+ readModel,
34
+ writeMidi,
35
+ } from "pitch-transcription";
36
+
37
+ // Under Node, the model is built from its two files; in a browser, `await loadGraphModel(servedModelUrl)` instead
38
+ const [modelJson, weights] = await Promise.all([readFile(MODEL_URL, "utf8"), readFile(MODEL_WEIGHTS_URL)]);
39
+ const model = loadGraphModelSync([JSON.parse(modelJson), new Uint8Array(weights).buffer]);
40
+ // One channel at 22050 Hz as a Float32Array, or an AudioBuffer at 22050 Hz with any number of channels
41
+ const readings = await readModel(model, samples, (_windowReadings, progress) => console.log(progress));
42
+ const notes = createNotes(readings, { minNoteLength: 11 });
43
+ const bentNotes = addPitchBends(readings.contours, notes);
44
+ const timedNotes = convertNotesToSeconds(bentNotes);
45
+ // Each note's startTimeSeconds, durationSeconds, pitchMidi, amplitude and pitchBends
46
+ const midiBytes = writeMidi(timedNotes);
47
+ ```
48
+
49
+ A worker or a server that already holds the readings imports note creation from `pitch-transcription/notes`, which never loads TensorFlow.js.
50
+
51
+ ## <a name="documentation">📖 Documentation</a>
52
+
53
+ We highly recommend you take a look at the [documentation](https://esposter.com/docs/api/modules/pitch-transcription.html) to level up, and the [package's page](https://esposter.com/docs/pitch-transcription) for how it works and the absorption of `@spotify/basic-pitch` it replaced.
54
+
55
+ ### Key exports
56
+
57
+ | Export | Role |
58
+ | -------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
59
+ | `readModel` | The model's frame, onset and contour readings over a recording, a window at a time, each window's tensors freed |
60
+ | `createNotes` | The readings turned into notes, with Basic Pitch's thresholds, inferred onsets, frequency range and melodia trick |
61
+ | `addPitchBends` | Each note's bend at every frame, in contour bins of a third of a semitone |
62
+ | `convertNotesToSeconds` | Notes timed in seconds rather than the model's frames |
63
+ | `writeMidi` | Notes as a MIDI file's bytes, each bend written as its share of the bend's range |
64
+ | `MODEL_URL`, `MODEL_WEIGHTS_URL` | The shipped model's two files |
65
+
66
+ ### Commands
67
+
68
+ Run from `packages/pitch-transcription/`:
69
+
70
+ ```bash
71
+ pnpm build # compile to dist/
72
+ pnpm test # vitest watch mode (coverage is run from the repo root)
73
+ pnpm lint:fix # auto-fix lint
74
+ pnpm typecheck # type check
75
+ ```
76
+
77
+ ## <a name="license">⚖️ License</a>
78
+
79
+ This project is licensed under the [Apache-2.0 license](https://github.com/Esposter/Esposter/blob/main/LICENSE). It is derived from [basic-pitch-ts](https://github.com/spotify/basic-pitch-ts), Copyright 2022 Spotify AB, and ships its trained model unmodified, both under the Apache-2.0 license; see `NOTICE`.
80
+
81
+ [badge-license]: https://img.shields.io/github/license/Esposter/Esposter.svg?color=blue
82
+ [url-license]: https://github.com/Esposter/Esposter/blob/main/LICENSE
83
+ [badge-npm-version]: https://img.shields.io/npm/v/pitch-transcription/latest?color=brightgreen
84
+ [url-npm]: https://www.npmjs.com/package/pitch-transcription/v/latest
85
+ [badge-npm-unpacked-size]: https://img.shields.io/npm/unpacked-size/pitch-transcription/latest?label=npm
86
+ [badge-npm-downloads]: https://img.shields.io/npm/dm/pitch-transcription.svg
@@ -0,0 +1,37 @@
1
+ import { ANNOTATIONS_FPS, ANNOTATIONS_FRAMES_PER_WINDOW, ANNOTATIONS_SEMITONES, AUDIO_SAMPLE_RATE, AUDIO_WINDOW_LENGTH_SECONDS, AUDIO_WINDOW_SAMPLES, CONTOURS_TENSOR, CONTOUR_BINS, CONTOUR_BINS_PER_SEMITONE, ENERGY_TOLERANCE, FFT_HOP, FRAMES_TENSOR, FRAME_THRESHOLD, MIDI_OFFSET, MIDI_PITCH_BEND_SEMITONES, MIDI_PITCH_BEND_STEPS, MIN_NOTE_LENGTH, MODEL_URL, MODEL_WEIGHTS_URL, ModelReadings, NoteCreationOptions, NoteEvent, NoteEventTime, ONSETS_TENSOR, ONSET_THRESHOLD, OVERLAPPING_FRAMES, OVERLAP_SAMPLES, PITCH_BEND_STANDARD_DEVIATION, PITCH_BEND_TOLERANCE, WINDOW_HOP_SAMPLES, WINDOW_OFFSET_SECONDS, addPitchBends, convertNotesToSeconds, createNotes, writeMidi } from "./notes.js";
2
+ import { GraphModel, Tensor2D, Tensor3D } from "@tensorflow/tfjs";
3
+ //#region src/models/AudioChannels.d.ts
4
+ export interface AudioChannels {
5
+ getChannelData: (channel: number) => Float32Array;
6
+ numberOfChannels: number;
7
+ sampleRate: number;
8
+ }
9
+ //#endregion
10
+ //#region src/services/clearPitch.d.ts
11
+ export declare const clearPitch: (energy: number[][], frame: number, pitch: number) => void;
12
+ //#endregion
13
+ //#region src/services/constrainFrequency.d.ts
14
+ export declare const constrainFrequency: (readings: number[][], maxFrequency?: number, minFrequency?: number) => number[][];
15
+ //#endregion
16
+ //#region src/services/findLargestReading.d.ts
17
+ export declare const findLargestReading: (readings: number[][]) => number;
18
+ //#endregion
19
+ //#region src/services/findOnsetPeaks.d.ts
20
+ export declare const findOnsetPeaks: (onsets: number[][], threshold: number) => [number, number][];
21
+ //#endregion
22
+ //#region src/services/inferOnsets.d.ts
23
+ export declare const inferOnsets: (onsets: number[][], frames: number[][]) => number[][];
24
+ //#endregion
25
+ //#region src/services/mixDownChannels.d.ts
26
+ export declare const mixDownChannels: (audio: AudioChannels | Float32Array) => Float32Array;
27
+ //#endregion
28
+ //#region src/services/prepareAudioWindows.d.ts
29
+ export declare const prepareAudioWindows: (samples: Float32Array) => Tensor3D;
30
+ //#endregion
31
+ //#region src/services/readModel.d.ts
32
+ export declare const readModel: (model: Pick<GraphModel, "execute">, audio: AudioChannels | Float32Array, onWindow?: (readings: ModelReadings, progress: number) => void) => Promise<ModelReadings>;
33
+ //#endregion
34
+ //#region src/services/unwrapWindowReadings.d.ts
35
+ export declare const unwrapWindowReadings: (readings: Tensor3D) => Tensor2D;
36
+ //#endregion
37
+ export { ANNOTATIONS_FPS, ANNOTATIONS_FRAMES_PER_WINDOW, ANNOTATIONS_SEMITONES, AUDIO_SAMPLE_RATE, AUDIO_WINDOW_LENGTH_SECONDS, AUDIO_WINDOW_SAMPLES, CONTOURS_TENSOR, CONTOUR_BINS, CONTOUR_BINS_PER_SEMITONE, ENERGY_TOLERANCE, FFT_HOP, FRAMES_TENSOR, FRAME_THRESHOLD, MIDI_OFFSET, MIDI_PITCH_BEND_SEMITONES, MIDI_PITCH_BEND_STEPS, MIN_NOTE_LENGTH, MODEL_URL, MODEL_WEIGHTS_URL, ModelReadings, NoteCreationOptions, NoteEvent, NoteEventTime, ONSETS_TENSOR, ONSET_THRESHOLD, OVERLAPPING_FRAMES, OVERLAP_SAMPLES, PITCH_BEND_STANDARD_DEVIATION, PITCH_BEND_TOLERANCE, WINDOW_HOP_SAMPLES, WINDOW_OFFSET_SECONDS, addPitchBends, convertNotesToSeconds, createNotes, writeMidi };
package/dist/index.js ADDED
@@ -0,0 +1,75 @@
1
+ import { A as ONSET_THRESHOLD, C as MIDI_OFFSET, D as MODEL_URL, E as MIN_NOTE_LENGTH, F as WINDOW_HOP_SAMPLES, I as WINDOW_OFFSET_SECONDS, M as OVERLAP_SAMPLES, N as PITCH_BEND_STANDARD_DEVIATION, O as MODEL_WEIGHTS_URL, P as PITCH_BEND_TOLERANCE, S as FRAME_THRESHOLD, T as MIDI_PITCH_BEND_STEPS, _ as CONTOUR_BINS, a as findOnsetPeaks, b as FFT_HOP, c as convertNotesToSeconds, d as ANNOTATIONS_FRAMES_PER_WINDOW, f as ANNOTATIONS_SEMITONES, g as CONTOURS_TENSOR, h as AUDIO_WINDOW_SAMPLES, i as findLargestReading, j as OVERLAPPING_FRAMES, k as ONSETS_TENSOR, l as addPitchBends, m as AUDIO_WINDOW_LENGTH_SECONDS, n as createNotes, o as constrainFrequency, p as AUDIO_SAMPLE_RATE, r as inferOnsets, s as clearPitch, t as writeMidi, u as ANNOTATIONS_FPS, v as CONTOUR_BINS_PER_SEMITONE, w as MIDI_PITCH_BEND_SEMITONES, x as FRAMES_TENSOR, y as ENERGY_TOLERANCE } from "./notes-zj___s9N.js";
2
+ import { InvalidOperationError, Operation, withFinalizerAsync } from "@esposter/shared";
3
+ import { concat1d, dispose, expandDims, signal, slice, tensor1d, tidy, zeros } from "@tensorflow/tfjs";
4
+ //#region src/services/mixDownChannels.ts
5
+ const mixDownChannels = (audio) => {
6
+ if (audio instanceof Float32Array) return audio;
7
+ if (audio.sampleRate !== 22050) throw new InvalidOperationError(Operation.Read, mixDownChannels.name, `audio at ${audio.sampleRate} Hz, the model reads ${AUDIO_SAMPLE_RATE} Hz`);
8
+ if (audio.numberOfChannels === 1) return audio.getChannelData(0);
9
+ const mixed = new Float32Array(audio.getChannelData(0).length);
10
+ for (let channel = 0; channel < audio.numberOfChannels; channel++) for (const [index, sample] of audio.getChannelData(channel).entries()) mixed[index] = (mixed[index] ?? 0) + sample / audio.numberOfChannels;
11
+ return mixed;
12
+ };
13
+ //#endregion
14
+ //#region src/services/prepareAudioWindows.ts
15
+ const prepareAudioWindows = (samples) => tidy(() => {
16
+ const padded = concat1d([zeros([OVERLAP_SAMPLES / 2]), tensor1d(samples)]);
17
+ return expandDims(signal.frame(padded, AUDIO_WINDOW_SAMPLES, WINDOW_HOP_SAMPLES, true, 0), -1);
18
+ });
19
+ //#endregion
20
+ //#region src/services/unwrapWindowReadings.ts
21
+ const unwrapWindowReadings = (readings) => {
22
+ const [windowCount, frameCount, binCount] = readings.shape;
23
+ return readings.slice([
24
+ 0,
25
+ 15,
26
+ 0
27
+ ], [
28
+ -1,
29
+ frameCount - 30,
30
+ -1
31
+ ]).reshape([windowCount * (frameCount - 30), binCount]);
32
+ };
33
+ //#endregion
34
+ //#region src/services/readModel.ts
35
+ const readModel = (model, audio, onWindow) => {
36
+ const samples = mixDownChannels(audio);
37
+ const frameCount = Math.floor(samples.length * ANNOTATIONS_FPS / AUDIO_SAMPLE_RATE);
38
+ const windows = prepareAudioWindows(samples);
39
+ return withFinalizerAsync(async () => {
40
+ const readings = {
41
+ contours: [],
42
+ frames: [],
43
+ onsets: []
44
+ };
45
+ for (let index = 0; index < windows.shape[0] && readings.frames.length < frameCount; index++) {
46
+ const remainingFrames = frameCount - readings.frames.length;
47
+ const outputs = tidy(() => {
48
+ const window = slice(windows, index, 1);
49
+ return model.execute(window, [
50
+ FRAMES_TENSOR,
51
+ ONSETS_TENSOR,
52
+ CONTOURS_TENSOR
53
+ ]).map((output) => {
54
+ const unwrapped = unwrapWindowReadings(output);
55
+ return unwrapped.slice(0, Math.min(remainingFrames, unwrapped.shape[0]));
56
+ });
57
+ });
58
+ const [frames = [], onsets = [], contours = []] = await Promise.all(outputs.map((output) => output.array()));
59
+ dispose(outputs);
60
+ readings.frames.push(...frames);
61
+ readings.onsets.push(...onsets);
62
+ readings.contours.push(...contours);
63
+ onWindow?.({
64
+ contours,
65
+ frames,
66
+ onsets
67
+ }, readings.frames.length / frameCount);
68
+ }
69
+ return readings;
70
+ }, () => {
71
+ windows.dispose();
72
+ });
73
+ };
74
+ //#endregion
75
+ export { ANNOTATIONS_FPS, ANNOTATIONS_FRAMES_PER_WINDOW, ANNOTATIONS_SEMITONES, AUDIO_SAMPLE_RATE, AUDIO_WINDOW_LENGTH_SECONDS, AUDIO_WINDOW_SAMPLES, CONTOURS_TENSOR, CONTOUR_BINS, CONTOUR_BINS_PER_SEMITONE, ENERGY_TOLERANCE, FFT_HOP, FRAMES_TENSOR, FRAME_THRESHOLD, MIDI_OFFSET, MIDI_PITCH_BEND_SEMITONES, MIDI_PITCH_BEND_STEPS, MIN_NOTE_LENGTH, MODEL_URL, MODEL_WEIGHTS_URL, ONSETS_TENSOR, ONSET_THRESHOLD, OVERLAPPING_FRAMES, OVERLAP_SAMPLES, PITCH_BEND_STANDARD_DEVIATION, PITCH_BEND_TOLERANCE, WINDOW_HOP_SAMPLES, WINDOW_OFFSET_SECONDS, addPitchBends, clearPitch, constrainFrequency, convertNotesToSeconds, createNotes, findLargestReading, findOnsetPeaks, inferOnsets, mixDownChannels, prepareAudioWindows, readModel, unwrapWindowReadings, writeMidi };
@@ -0,0 +1,221 @@
1
+ import { takeOne } from "@esposter/shared";
2
+ import tonejsMidi from "@tonejs/midi";
3
+ //#region src/constants.ts
4
+ const AUDIO_SAMPLE_RATE = 22050;
5
+ const FFT_HOP = 256;
6
+ const AUDIO_WINDOW_LENGTH_SECONDS = 2;
7
+ const AUDIO_WINDOW_SAMPLES = AUDIO_SAMPLE_RATE * 2 - 256;
8
+ const ANNOTATIONS_FPS = Math.floor(AUDIO_SAMPLE_RATE / 256);
9
+ const ANNOTATIONS_FRAMES_PER_WINDOW = 172;
10
+ const OVERLAPPING_FRAMES = 30;
11
+ const OVERLAP_SAMPLES = 7680;
12
+ const WINDOW_HOP_SAMPLES = 36164;
13
+ const WINDOW_OFFSET_SECONDS = .010326077097505668;
14
+ const MIDI_OFFSET = 21;
15
+ const ANNOTATIONS_SEMITONES = 88;
16
+ const CONTOUR_BINS_PER_SEMITONE = 3;
17
+ const CONTOUR_BINS = 264;
18
+ const FRAMES_TENSOR = "Identity_1";
19
+ const ONSETS_TENSOR = "Identity_2";
20
+ const CONTOURS_TENSOR = "Identity";
21
+ const MODEL_URL = new URL("../model/model.json", import.meta.url);
22
+ const MODEL_WEIGHTS_URL = new URL("group1-shard1of1.bin", MODEL_URL);
23
+ const ONSET_THRESHOLD = .5;
24
+ const FRAME_THRESHOLD = .3;
25
+ const MIN_NOTE_LENGTH = 11;
26
+ const ENERGY_TOLERANCE = 11;
27
+ const PITCH_BEND_TOLERANCE = 25;
28
+ const PITCH_BEND_STANDARD_DEVIATION = 5;
29
+ const MIDI_PITCH_BEND_SEMITONES = 2;
30
+ const MIDI_PITCH_BEND_STEPS = 8192;
31
+ //#endregion
32
+ //#region src/services/addPitchBends.ts
33
+ const PITCH_BEND_WEIGHTS = Array.from({ length: 51 }, (_value, offset) => Math.exp(-((offset - 25) ** 2) / 50));
34
+ const addPitchBends = (contours, notes) => notes.map((note) => {
35
+ const bin = (note.pitchMidi - 21) * 3;
36
+ const start = Math.max(bin - 25, 0);
37
+ const end = Math.min(bin + 25 + 1, 264);
38
+ const pitchBends = contours.slice(note.startFrame, note.startFrame + note.durationFrames).map((row) => {
39
+ let bestBin = start;
40
+ let bestReading = -Infinity;
41
+ for (let contourBin = start; contourBin < end; contourBin++) {
42
+ const reading = takeOne(row, contourBin) * takeOne(PITCH_BEND_WEIGHTS, contourBin - bin + 25);
43
+ if (reading <= bestReading) continue;
44
+ bestBin = contourBin;
45
+ bestReading = reading;
46
+ }
47
+ return bestBin - bin;
48
+ });
49
+ return {
50
+ ...note,
51
+ pitchBends
52
+ };
53
+ });
54
+ //#endregion
55
+ //#region src/services/convertNotesToSeconds.ts
56
+ const toSeconds = (frame) => frame * 256 / AUDIO_SAMPLE_RATE - WINDOW_OFFSET_SECONDS * Math.floor(frame / 172);
57
+ const convertNotesToSeconds = (notes) => notes.map(({ amplitude, durationFrames, pitchBends, pitchMidi, startFrame }) => {
58
+ const startTimeSeconds = toSeconds(startFrame);
59
+ return {
60
+ amplitude,
61
+ durationSeconds: toSeconds(startFrame + durationFrames) - startTimeSeconds,
62
+ pitchBends,
63
+ pitchMidi,
64
+ startTimeSeconds
65
+ };
66
+ });
67
+ //#endregion
68
+ //#region src/services/clearPitch.ts
69
+ const clearPitch = (energy, frame, pitch) => {
70
+ const row = takeOne(energy, frame);
71
+ row[pitch] = 0;
72
+ if (pitch + 1 < row.length) row[pitch + 1] = 0;
73
+ if (pitch > 0) row[pitch - 1] = 0;
74
+ };
75
+ //#endregion
76
+ //#region src/services/constrainFrequency.ts
77
+ const toPitchIndex = (frequency) => Math.round(12 * Math.log2(frequency / 440) + 69 - 21);
78
+ const constrainFrequency = (readings, maxFrequency, minFrequency) => {
79
+ if (maxFrequency === void 0 && minFrequency === void 0) return readings;
80
+ const end = maxFrequency === void 0 ? Infinity : toPitchIndex(maxFrequency);
81
+ const start = minFrequency === void 0 ? 0 : toPitchIndex(minFrequency);
82
+ return readings.map((row) => row.map((reading, pitch) => pitch >= start && pitch < end ? reading : 0));
83
+ };
84
+ //#endregion
85
+ //#region src/services/findOnsetPeaks.ts
86
+ const findOnsetPeaks = (onsets, threshold) => {
87
+ const peaks = [];
88
+ for (let frame = 1; frame < onsets.length - 1; frame++) {
89
+ const previous = takeOne(onsets, frame - 1);
90
+ const row = takeOne(onsets, frame);
91
+ const next = takeOne(onsets, frame + 1);
92
+ for (let pitch = 0; pitch < row.length; pitch++) {
93
+ const reading = takeOne(row, pitch);
94
+ if (reading > threshold && reading > takeOne(previous, pitch) && reading > takeOne(next, pitch)) peaks.push([frame, pitch]);
95
+ }
96
+ }
97
+ return peaks;
98
+ };
99
+ //#endregion
100
+ //#region src/services/findLargestReading.ts
101
+ const findLargestReading = (readings) => {
102
+ let largest = 0;
103
+ for (const row of readings) for (const reading of row) largest = Math.max(largest, reading);
104
+ return largest;
105
+ };
106
+ //#endregion
107
+ //#region src/services/inferOnsets.ts
108
+ const getJump = (row, previous, beforePrevious, pitch) => {
109
+ const reading = takeOne(row, pitch);
110
+ return Math.max(0, Math.min(reading - takeOne(previous, pitch), reading - takeOne(beforePrevious, pitch)));
111
+ };
112
+ const inferOnsets = (onsets, frames) => {
113
+ let largestJump = 0;
114
+ for (let frame = 2; frame < frames.length; frame++) {
115
+ const row = takeOne(frames, frame);
116
+ const previous = takeOne(frames, frame - 1);
117
+ const beforePrevious = takeOne(frames, frame - 2);
118
+ for (let pitch = 0; pitch < row.length; pitch++) largestJump = Math.max(largestJump, getJump(row, previous, beforePrevious, pitch));
119
+ }
120
+ if (largestJump === 0) return onsets;
121
+ const scale = findLargestReading(onsets) / largestJump;
122
+ return onsets.map((onsetRow, frame) => {
123
+ const row = takeOne(frames, frame);
124
+ const previous = frame < 2 ? row : takeOne(frames, frame - 1);
125
+ const beforePrevious = frame < 2 ? row : takeOne(frames, frame - 2);
126
+ return onsetRow.map((reading, pitch) => Math.max(reading, scale * getJump(row, previous, beforePrevious, pitch)));
127
+ });
128
+ };
129
+ //#endregion
130
+ //#region src/services/createNotes.ts
131
+ const getMeanReading = (frames, start, end, pitch) => {
132
+ let sum = 0;
133
+ for (let frame = start; frame < end; frame++) sum += takeOne(takeOne(frames, frame), pitch);
134
+ return sum / (end - start);
135
+ };
136
+ const createNotes = ({ frames, onsets }, { energyTolerance = 11, frameThreshold = FRAME_THRESHOLD, isInferringOnsets = true, isMelodiaTrick = true, maxFrequency, minFrequency, minNoteLength = 11, onsetThreshold = ONSET_THRESHOLD } = {}) => {
137
+ const frameCount = frames.length;
138
+ const constrainedFrames = constrainFrequency(frames, maxFrequency, minFrequency);
139
+ const constrainedOnsets = constrainFrequency(onsets, maxFrequency, minFrequency);
140
+ const peakOnsets = isInferringOnsets ? inferOnsets(constrainedOnsets, constrainedFrames) : constrainedOnsets;
141
+ const energy = constrainedFrames.map((row) => [...row]);
142
+ const notes = [];
143
+ for (const [startFrame, pitch] of findOnsetPeaks(peakOnsets, onsetThreshold).toReversed()) {
144
+ if (startFrame >= frameCount - 1) continue;
145
+ let end = startFrame + 1;
146
+ let quietFrames = 0;
147
+ for (; end < frameCount - 1 && quietFrames < energyTolerance; end++) quietFrames = takeOne(takeOne(energy, end), pitch) < frameThreshold ? quietFrames + 1 : 0;
148
+ end -= quietFrames;
149
+ if (end - startFrame <= minNoteLength) continue;
150
+ for (let frame = startFrame; frame < end; frame++) clearPitch(energy, frame, pitch);
151
+ notes.push({
152
+ amplitude: getMeanReading(constrainedFrames, startFrame, end, pitch),
153
+ durationFrames: end - startFrame,
154
+ pitchMidi: pitch + 21,
155
+ startFrame
156
+ });
157
+ }
158
+ if (!isMelodiaTrick) return notes;
159
+ const candidates = [];
160
+ for (const [frame, row] of energy.entries()) for (let pitch = 0; pitch < row.length; pitch++) {
161
+ const reading = takeOne(row, pitch);
162
+ if (reading > frameThreshold) candidates.push([
163
+ reading,
164
+ frame,
165
+ pitch
166
+ ]);
167
+ }
168
+ const sortedCandidates = candidates.toSorted(([firstReading, firstFrame, firstPitch], [secondReading, secondFrame, secondPitch]) => secondReading - firstReading || firstFrame - secondFrame || firstPitch - secondPitch);
169
+ for (const [reading, middle, pitch] of sortedCandidates) {
170
+ const middleRow = takeOne(energy, middle);
171
+ if (takeOne(middleRow, pitch) !== reading) continue;
172
+ middleRow[pitch] = 0;
173
+ let frame = middle + 1;
174
+ let quietFrames = 0;
175
+ for (; frame < frameCount - 1 && quietFrames < energyTolerance; frame++) {
176
+ quietFrames = takeOne(takeOne(energy, frame), pitch) < frameThreshold ? quietFrames + 1 : 0;
177
+ clearPitch(energy, frame, pitch);
178
+ }
179
+ const end = frame - 1 - quietFrames;
180
+ frame = middle - 1;
181
+ quietFrames = 0;
182
+ for (; frame > 0 && quietFrames < energyTolerance; frame--) {
183
+ quietFrames = takeOne(takeOne(energy, frame), pitch) < frameThreshold ? quietFrames + 1 : 0;
184
+ clearPitch(energy, frame, pitch);
185
+ }
186
+ const start = frame + 1 + quietFrames;
187
+ if (end - start <= minNoteLength) continue;
188
+ notes.push({
189
+ amplitude: getMeanReading(constrainedFrames, start, end, pitch),
190
+ durationFrames: end - start,
191
+ pitchMidi: pitch + 21,
192
+ startFrame: start
193
+ });
194
+ }
195
+ return notes;
196
+ };
197
+ //#endregion
198
+ //#region src/services/writeMidi.ts
199
+ const { Midi } = tonejsMidi;
200
+ const writeMidi = (notes) => {
201
+ const midi = new Midi();
202
+ const track = midi.addTrack();
203
+ for (const { amplitude, durationSeconds, pitchBends = [], pitchMidi, startTimeSeconds } of notes) {
204
+ track.addNote({
205
+ duration: durationSeconds,
206
+ midi: pitchMidi,
207
+ time: startTimeSeconds,
208
+ velocity: amplitude
209
+ });
210
+ for (const [index, bend] of pitchBends.entries()) {
211
+ const share = bend / 3 / 2;
212
+ track.addPitchBend({
213
+ time: startTimeSeconds + index * durationSeconds / pitchBends.length,
214
+ value: Math.max(-8192, Math.min(8191, Math.round(share * MIDI_PITCH_BEND_STEPS)))
215
+ });
216
+ }
217
+ }
218
+ return midi.toArray();
219
+ };
220
+ //#endregion
221
+ export { ONSET_THRESHOLD as A, MIDI_OFFSET as C, MODEL_URL as D, MIN_NOTE_LENGTH as E, WINDOW_HOP_SAMPLES as F, WINDOW_OFFSET_SECONDS as I, OVERLAP_SAMPLES as M, PITCH_BEND_STANDARD_DEVIATION as N, MODEL_WEIGHTS_URL as O, PITCH_BEND_TOLERANCE as P, FRAME_THRESHOLD as S, MIDI_PITCH_BEND_STEPS as T, CONTOUR_BINS as _, findOnsetPeaks as a, FFT_HOP as b, convertNotesToSeconds as c, ANNOTATIONS_FRAMES_PER_WINDOW as d, ANNOTATIONS_SEMITONES as f, CONTOURS_TENSOR as g, AUDIO_WINDOW_SAMPLES as h, findLargestReading as i, OVERLAPPING_FRAMES as j, ONSETS_TENSOR as k, addPitchBends as l, AUDIO_WINDOW_LENGTH_SECONDS as m, createNotes as n, constrainFrequency as o, AUDIO_SAMPLE_RATE as p, inferOnsets as r, clearPitch as s, writeMidi as t, ANNOTATIONS_FPS as u, CONTOUR_BINS_PER_SEMITONE as v, MIDI_PITCH_BEND_SEMITONES as w, FRAMES_TENSOR as x, ENERGY_TOLERANCE as y };