kinglet-bio 0.3.1__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.
@@ -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.
@@ -0,0 +1,14 @@
1
+ Kinglet
2
+ Copyright 2026 Ryotaro Okamoto
3
+
4
+ Kinglet models are knowledge-distilled from Perch 2.0
5
+ (https://github.com/google-research/perch), Copyright Google LLC,
6
+ licensed under the Apache License, Version 2.0.
7
+
8
+ Training audio was sourced from Xeno-canto (https://xeno-canto.org, per-recording
9
+ Creative Commons licenses), iNaturalist (https://www.inaturalist.org, per-recording
10
+ Creative Commons licenses), the Macaulay Library at the Cornell Lab of Ornithology
11
+ (https://www.macaulaylibrary.org), the BirdSet dataset
12
+ (https://huggingface.co/datasets/DBD-research-group/BirdSet), and unlabeled Japanese
13
+ passive acoustic monitoring recordings. The audio itself is NOT redistributed with
14
+ this project; see MODEL_CARD.md for details.
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: kinglet-bio
3
+ Version: 0.3.1
4
+ Summary: Kinglet: kinglet-sized bioacoustic embedding and classification models distilled from Perch 2.0
5
+ Author: Ryotaro Okamoto
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/0kam/kinglet
8
+ Project-URL: Releases, https://github.com/0kam/kinglet/releases
9
+ Project-URL: Model Card, https://github.com/0kam/kinglet/blob/main/MODEL_CARD.md
10
+ Keywords: bioacoustics,birds,sound-event-detection,onnx,knowledge-distillation
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ License-File: NOTICE
19
+ Requires-Dist: numpy>=1.24
20
+ Requires-Dist: onnxruntime>=1.17
21
+ Dynamic: license-file
22
+
23
+ # Kinglet 🐦
24
+
25
+ **Kinglet-sized bioacoustic embedding and classification models, distilled from
26
+ [Perch 2.0](https://github.com/google-research/perch).**
27
+
28
+ Kinglets are among the smallest birds in the northern hemisphere. Kinglet models are among the
29
+ smallest bioacoustic models: a trunk ONNX (~22–53 MB, preprocessing included) plus a ~2 MB regional
30
+ head pack that process **months of field recordings in hours on an ordinary laptop CPU** — no GPU,
31
+ no Python ML stack — while staying close to Perch 2.0 on Japanese soundscape benchmarks. Each model
32
+ outputs species scores, sound-group scores (human voice, vehicles, rain/wind, ...), and a 1536-d
33
+ embedding projected into the Perch 2.0 embedding space.
34
+
35
+ ## Models (v0.3.1)
36
+
37
+ | model | backbone | trunk size | speed* | Kasumigaura macro AUPRC** |
38
+ |---|---|---|---|---|
39
+ | Kinglet-B | RegNetY-016 | 51 MB | ~600x realtime | 0.714 |
40
+ | Kinglet-S | EfficientNet-Lite0 | 26 MB | ~1,250x realtime | 0.698 |
41
+ | Kinglet-XS | MobileNetV4-Conv-S | 22 MB | ~2,200x realtime | 0.714 |
42
+
43
+ Since v0.3 the models are distilled from the teacher's **full 14,795-class vocabulary** and folded
44
+ to a region at deployment time ("distill once, fold anywhere"): a prebuilt Japan pack (317 species)
45
+ ships with the release, and `kinglet build-pack` folds the same trunk onto **any species list** in
46
+ seconds, no audio needed. Scores are **softmax probabilities with an explicit background channel**;
47
+ use a fixed species threshold of **0.1** (the Perch operating point). Every pack also carries
48
+ **sound groups** with operating thresholds (since v0.3.1): a calibrated `human_voice` detector
49
+ (threshold 0.005) for privacy masking before sharing field audio, calibrated `gunshot` and
50
+ `domestic_animal` detectors, and provisional `geophony` / `vehicle` / `music` flags for
51
+ rain-and-traffic noise screening (details in [MODEL_CARD.md](https://github.com/0kam/kinglet/blob/main/MODEL_CARD.md)).
52
+
53
+ \* 4 CPU threads, log-mel preprocessing included (Ryzen 9950X3D; expect roughly half on a typical
54
+ laptop). \** Perch 2.0 (the ~47x-realtime teacher) scores 0.737; for Kinglet-B the 95% CI of the
55
+ paired difference includes 0. Download from [GitHub Releases](https://github.com/0kam/kinglet/releases).
56
+ The `.gemm-mel` trunk variants trade a slightly larger file for a mel frontend that is faster on
57
+ some ARM CPUs — on x86, use the default files.
58
+
59
+ ## Quickstart
60
+
61
+ ```bash
62
+ pip install kinglet-bio # needs ffmpeg on PATH
63
+ kinglet analyze recordings/ --model kinglet-s-v0.3.1.onnx --pack kinglet-s-v0.3.1.pack-jp.npz --out detections.csv
64
+ ```
65
+
66
+ The CLI keeps, per 5 s window, the top-3 species scoring at least 0.1 (adjustable with
67
+ `--top-k` / `--min-score`), adds one row per calibrated sound group that passes its own threshold
68
+ (`human_voice` windows are what you mute before sharing audio), and can dump embeddings with
69
+ `--embeddings emb/`.
70
+
71
+ Deploying outside Japan (or with your own species list)? Fold a pack from the `.headpack.npz`
72
+ release asset — the CSV needs `ebird_code, scientific_name` columns:
73
+
74
+ ```bash
75
+ kinglet build-pack --headpack kinglet-s-v0.3.1.headpack.npz --species my_region.csv --out my_region.npz
76
+ ```
77
+
78
+ Or from Python / any ONNX runtime:
79
+
80
+ ```python
81
+ from kinglet import Kinglet, decode, windows
82
+ m = Kinglet("kinglet-s-v0.3.1.onnx", "kinglet-s-v0.3.1.pack-jp.npz")
83
+ starts, wins = windows(decode("field_recording.wav")) # 5 s windows at 32 kHz mono
84
+ embeddings, scores, groups = m.run(wins) # (n, 1536), (n, 317), {group: (n,)}
85
+ mask = groups["human_voice"] >= m.groups["human_voice"] # windows to mute before sharing
86
+ ```
87
+
88
+ ## Model I/O
89
+
90
+ - Input `waveform`: float32 `(batch, 160000)` — 5 s, 32 kHz, mono, amplitude in [-1, 1]
91
+ - Output `embedding`: `(batch, 1536)` — projection into the Perch 2.0 embedding space
92
+ (mean cosine ~0.84–0.87 to the teacher on held-out focal validation)
93
+ - Output `feature`: `(batch, d)` — the trunk feature; scores = `softmax(feature @ W.T + b)` with
94
+ `W, b` from the pack `.npz`, background column dropped (this is what `Kinglet.run` does).
95
+ Row order: pack `codes` (species, then group-member classes, then "other").
96
+ - v0.2 single-file models (`logits` in the graph) are not supported by the v0.3 package — use the
97
+ v0.2 release assets with `kinglet-bio==0.2.0` if you need them.
98
+
99
+ ## License
100
+
101
+ [Apache License 2.0](https://github.com/0kam/kinglet/blob/main/LICENSE). Kinglet models are distilled from Perch 2.0 (Apache-2.0, Google);
102
+ see [NOTICE](https://github.com/0kam/kinglet/blob/main/NOTICE) and [MODEL_CARD.md](https://github.com/0kam/kinglet/blob/main/MODEL_CARD.md) for training-data provenance.
@@ -0,0 +1,80 @@
1
+ # Kinglet 🐦
2
+
3
+ **Kinglet-sized bioacoustic embedding and classification models, distilled from
4
+ [Perch 2.0](https://github.com/google-research/perch).**
5
+
6
+ Kinglets are among the smallest birds in the northern hemisphere. Kinglet models are among the
7
+ smallest bioacoustic models: a trunk ONNX (~22–53 MB, preprocessing included) plus a ~2 MB regional
8
+ head pack that process **months of field recordings in hours on an ordinary laptop CPU** — no GPU,
9
+ no Python ML stack — while staying close to Perch 2.0 on Japanese soundscape benchmarks. Each model
10
+ outputs species scores, sound-group scores (human voice, vehicles, rain/wind, ...), and a 1536-d
11
+ embedding projected into the Perch 2.0 embedding space.
12
+
13
+ ## Models (v0.3.1)
14
+
15
+ | model | backbone | trunk size | speed* | Kasumigaura macro AUPRC** |
16
+ |---|---|---|---|---|
17
+ | Kinglet-B | RegNetY-016 | 51 MB | ~600x realtime | 0.714 |
18
+ | Kinglet-S | EfficientNet-Lite0 | 26 MB | ~1,250x realtime | 0.698 |
19
+ | Kinglet-XS | MobileNetV4-Conv-S | 22 MB | ~2,200x realtime | 0.714 |
20
+
21
+ Since v0.3 the models are distilled from the teacher's **full 14,795-class vocabulary** and folded
22
+ to a region at deployment time ("distill once, fold anywhere"): a prebuilt Japan pack (317 species)
23
+ ships with the release, and `kinglet build-pack` folds the same trunk onto **any species list** in
24
+ seconds, no audio needed. Scores are **softmax probabilities with an explicit background channel**;
25
+ use a fixed species threshold of **0.1** (the Perch operating point). Every pack also carries
26
+ **sound groups** with operating thresholds (since v0.3.1): a calibrated `human_voice` detector
27
+ (threshold 0.005) for privacy masking before sharing field audio, calibrated `gunshot` and
28
+ `domestic_animal` detectors, and provisional `geophony` / `vehicle` / `music` flags for
29
+ rain-and-traffic noise screening (details in [MODEL_CARD.md](https://github.com/0kam/kinglet/blob/main/MODEL_CARD.md)).
30
+
31
+ \* 4 CPU threads, log-mel preprocessing included (Ryzen 9950X3D; expect roughly half on a typical
32
+ laptop). \** Perch 2.0 (the ~47x-realtime teacher) scores 0.737; for Kinglet-B the 95% CI of the
33
+ paired difference includes 0. Download from [GitHub Releases](https://github.com/0kam/kinglet/releases).
34
+ The `.gemm-mel` trunk variants trade a slightly larger file for a mel frontend that is faster on
35
+ some ARM CPUs — on x86, use the default files.
36
+
37
+ ## Quickstart
38
+
39
+ ```bash
40
+ pip install kinglet-bio # needs ffmpeg on PATH
41
+ kinglet analyze recordings/ --model kinglet-s-v0.3.1.onnx --pack kinglet-s-v0.3.1.pack-jp.npz --out detections.csv
42
+ ```
43
+
44
+ The CLI keeps, per 5 s window, the top-3 species scoring at least 0.1 (adjustable with
45
+ `--top-k` / `--min-score`), adds one row per calibrated sound group that passes its own threshold
46
+ (`human_voice` windows are what you mute before sharing audio), and can dump embeddings with
47
+ `--embeddings emb/`.
48
+
49
+ Deploying outside Japan (or with your own species list)? Fold a pack from the `.headpack.npz`
50
+ release asset — the CSV needs `ebird_code, scientific_name` columns:
51
+
52
+ ```bash
53
+ kinglet build-pack --headpack kinglet-s-v0.3.1.headpack.npz --species my_region.csv --out my_region.npz
54
+ ```
55
+
56
+ Or from Python / any ONNX runtime:
57
+
58
+ ```python
59
+ from kinglet import Kinglet, decode, windows
60
+ m = Kinglet("kinglet-s-v0.3.1.onnx", "kinglet-s-v0.3.1.pack-jp.npz")
61
+ starts, wins = windows(decode("field_recording.wav")) # 5 s windows at 32 kHz mono
62
+ embeddings, scores, groups = m.run(wins) # (n, 1536), (n, 317), {group: (n,)}
63
+ mask = groups["human_voice"] >= m.groups["human_voice"] # windows to mute before sharing
64
+ ```
65
+
66
+ ## Model I/O
67
+
68
+ - Input `waveform`: float32 `(batch, 160000)` — 5 s, 32 kHz, mono, amplitude in [-1, 1]
69
+ - Output `embedding`: `(batch, 1536)` — projection into the Perch 2.0 embedding space
70
+ (mean cosine ~0.84–0.87 to the teacher on held-out focal validation)
71
+ - Output `feature`: `(batch, d)` — the trunk feature; scores = `softmax(feature @ W.T + b)` with
72
+ `W, b` from the pack `.npz`, background column dropped (this is what `Kinglet.run` does).
73
+ Row order: pack `codes` (species, then group-member classes, then "other").
74
+ - v0.2 single-file models (`logits` in the graph) are not supported by the v0.3 package — use the
75
+ v0.2 release assets with `kinglet-bio==0.2.0` if you need them.
76
+
77
+ ## License
78
+
79
+ [Apache License 2.0](https://github.com/0kam/kinglet/blob/main/LICENSE). Kinglet models are distilled from Perch 2.0 (Apache-2.0, Google);
80
+ see [NOTICE](https://github.com/0kam/kinglet/blob/main/NOTICE) and [MODEL_CARD.md](https://github.com/0kam/kinglet/blob/main/MODEL_CARD.md) for training-data provenance.
@@ -0,0 +1,79 @@
1
+ """Kinglet: kinglet-sized bioacoustic embedding and classification models distilled from Perch 2.0.
2
+
3
+ Since v0.3 a model is two files: a trunk ONNX (preprocessing included) mapping waveform
4
+ (batch, 160000) float32 in [-1, 1] at 32 kHz mono to "embedding" (batch, 1536; a projection into
5
+ the Perch 2.0 embedding space) and "feature" (batch, d; the trunk feature), plus a regional head
6
+ pack (.npz, see kinglet.pack) folding the full 14,795-class Perch vocabulary onto
7
+ <region species> + <sound groups such as human_voice / vehicle / geophony> + "other".
8
+ Scores are softmax probabilities over the pack rows; a group's score is the sum of its member
9
+ probabilities. Prebuilt packs ship for Japan; `kinglet build-pack` folds any species list.
10
+ v0.2 single-file models (logits in the graph) are not supported by this version.
11
+ """
12
+
13
+ import subprocess
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+
18
+ from .pack import load_pack
19
+
20
+ SR = 32_000
21
+ WIN = 5 * SR
22
+
23
+ __version__ = "0.3.1"
24
+
25
+
26
+ def decode(path: str | Path, ffmpeg: str = "ffmpeg") -> np.ndarray:
27
+ """Any audio file -> mono float32 waveform at 32 kHz (requires ffmpeg on PATH)."""
28
+ res = subprocess.run([ffmpeg, "-v", "error", "-nostdin", "-i", str(path),
29
+ "-ac", "1", "-ar", str(SR), "-f", "f32le", "-"], capture_output=True)
30
+ if res.returncode != 0 or not res.stdout:
31
+ raise RuntimeError(f"ffmpeg failed on {path}: {res.stderr.decode(errors='replace')[:200]}")
32
+ return np.frombuffer(res.stdout, dtype=np.float32)
33
+
34
+
35
+ def windows(audio: np.ndarray, hop_s: float = 5.0) -> tuple[np.ndarray, np.ndarray]:
36
+ """(start times in s, stacked 5 s windows); short audio is zero-padded to one window."""
37
+ if len(audio) < WIN:
38
+ audio = np.pad(audio, (0, WIN - len(audio)))
39
+ hop = int(hop_s * SR)
40
+ starts = np.arange(0, len(audio) - WIN + 1, hop)
41
+ return starts / SR, np.stack([audio[s : s + WIN] for s in starts])
42
+
43
+
44
+ class Kinglet:
45
+ """Trunk ONNX + head pack. `classes` rows: (ebird_code, scientific_name, japanese_name);
46
+ `groups` maps group name -> operating threshold (or None if not calibrated)."""
47
+
48
+ def __init__(self, model_path: str | Path, pack_path: str | Path, threads: int = 4):
49
+ import onnxruntime as ort
50
+
51
+ opt = ort.SessionOptions()
52
+ opt.intra_op_num_threads, opt.inter_op_num_threads = threads, 1
53
+ self.sess = ort.InferenceSession(str(model_path), opt, providers=["CPUExecutionProvider"])
54
+ assert [o.name for o in self.sess.get_outputs()] == ["embedding", "feature"], \
55
+ "not a v0.3 split model (expected outputs: embedding, feature)"
56
+ p = load_pack(pack_path)
57
+ n = p["n_species"]
58
+ self.W, self.b, self.n_species = p["W"], p["b"], n
59
+ self.classes = list(zip([str(c) for c in p["codes"][:n]],
60
+ [str(s) for s in p["scientific_name"]],
61
+ [str(j) for j in p["japanese_name"]]))
62
+ self.group_cols = p["group_cols"]
63
+ self.groups = p["group_thresholds"]
64
+
65
+ def run(self, wins: np.ndarray, batch: int = 64) -> tuple[np.ndarray, np.ndarray, dict]:
66
+ """(n, 160000) float32 windows -> (embeddings (n, 1536), species scores (n, n_species),
67
+ {group: scores (n,)}): softmax probabilities over the pack rows; the trailing
68
+ background/"other" channel is dropped from species scores."""
69
+ embs, probs = [], []
70
+ for i in range(0, len(wins), batch):
71
+ e, h = self.sess.run(None, {"waveform": wins[i : i + batch]})
72
+ lg = h @ self.W.T + self.b
73
+ p = np.exp(lg - lg.max(axis=1, keepdims=True))
74
+ p /= p.sum(axis=1, keepdims=True)
75
+ embs.append(e)
76
+ probs.append(p)
77
+ emb, p = np.concatenate(embs), np.concatenate(probs)
78
+ gscores = {g: p[:, cols].sum(axis=1) for g, cols in self.group_cols.items()}
79
+ return emb, p[:, : self.n_species], gscores
@@ -0,0 +1,121 @@
1
+ """kinglet CLI: analyze audio on a laptop CPU; build regional head packs.
2
+
3
+ kinglet analyze
4
+ Writes one detections CSV (file, start_s, end_s, label, scientific_name, japanese_name, score)
5
+ with every window x species whose score >= --min-score, plus one row per sound group
6
+ (human_voice, vehicle, ...) whose score passes that group's own operating threshold
7
+ (groups without a calibrated threshold are skipped; see MODEL_CARD.md). Optionally one .npz
8
+ of embeddings per audio file (t_start, embedding) for downstream probes / similarity search.
9
+
10
+ kinglet build-pack
11
+ Folds the full-vocabulary head (the .headpack.npz release asset) onto your species list:
12
+ a CSV with columns ebird_code, scientific_name (+ optional japanese_name, vocab_index).
13
+
14
+ Usage:
15
+ kinglet analyze recordings/ --model kinglet-s.onnx --pack kinglet-s.pack-jp.npz --out det.csv
16
+ kinglet build-pack --headpack kinglet-s.headpack.npz --species my_region.csv --out pack_my.npz
17
+ """
18
+
19
+ import argparse
20
+ import csv
21
+ import json
22
+ import sys
23
+ import time
24
+ from pathlib import Path
25
+
26
+ import numpy as np
27
+
28
+ from . import Kinglet, decode, windows
29
+ from .pack import build_pack, read_species_csv
30
+
31
+ AUDIO_EXTS = {".wav", ".flac", ".mp3", ".ogg", ".m4a", ".wma", ".aac", ".opus"}
32
+
33
+
34
+ def gather(paths: list[Path]) -> list[Path]:
35
+ out = []
36
+ for p in paths:
37
+ out += sorted(q for q in p.rglob("*") if q.suffix.lower() in AUDIO_EXTS) if p.is_dir() else [p]
38
+ return out
39
+
40
+
41
+ def analyze(args) -> None:
42
+ model = Kinglet(args.model, args.pack, threads=args.threads)
43
+ files = gather(args.audio)
44
+ if not files:
45
+ sys.exit("no audio files found")
46
+ if args.embeddings:
47
+ args.embeddings.mkdir(parents=True, exist_ok=True)
48
+ live_groups = {g: t for g, t in model.groups.items() if t is not None}
49
+ t0, audio_s, n_det = time.time(), 0.0, 0
50
+ with args.out.open("w", newline="") as f:
51
+ w = csv.writer(f)
52
+ w.writerow(["file", "start_s", "end_s", "label", "scientific_name", "japanese_name", "score"])
53
+ for k, path in enumerate(files, 1):
54
+ a = decode(path)
55
+ audio_s += len(a) / 32_000
56
+ starts, wins = windows(a, args.hop)
57
+ emb, scores, gscores = model.run(wins)
58
+ top = np.argsort(-scores, axis=1)[:, : args.top_k]
59
+ for i, row in enumerate(top):
60
+ for j in row:
61
+ if scores[i, j] < args.min_score:
62
+ break
63
+ code, sci, ja = model.classes[j]
64
+ w.writerow([path.name, f"{starts[i]:.1f}", f"{starts[i] + 5.0:.1f}", code, sci,
65
+ ja, f"{scores[i, j]:.3f}"])
66
+ n_det += 1
67
+ for g, thr in live_groups.items():
68
+ if gscores[g][i] >= thr:
69
+ w.writerow([path.name, f"{starts[i]:.1f}", f"{starts[i] + 5.0:.1f}", g, "",
70
+ "", f"{gscores[g][i]:.4f}"])
71
+ n_det += 1
72
+ if args.embeddings:
73
+ np.savez(args.embeddings / (path.stem + ".npz"), t_start=starts,
74
+ embedding=emb.astype(np.float16))
75
+ el = time.time() - t0
76
+ print(f"[{k}/{len(files)}] {path.name}: {len(wins)} windows | total {audio_s / 3600:.2f} h "
77
+ f"in {el:.0f} s ({audio_s / el:.0f}x realtime)", flush=True)
78
+ print(f"{n_det} rows (species top {args.top_k}/window >= {args.min_score}; groups: "
79
+ f"{', '.join(f'{g} >= {t}' for g, t in live_groups.items()) or 'none'}) -> {args.out}")
80
+
81
+
82
+ def build(args) -> None:
83
+ report = build_pack(args.headpack, read_species_csv(args.species), args.out)
84
+ print(json.dumps(report, indent=1))
85
+ if report["unmatched"]:
86
+ print(f"WARNING: {len(report['unmatched'])} species not in the Perch vocabulary "
87
+ f"(dead rows, never detected): {', '.join(report['unmatched'])}")
88
+ print(f"wrote {args.out}")
89
+
90
+
91
+ def main() -> None:
92
+ ap = argparse.ArgumentParser(prog="kinglet", description=__doc__.splitlines()[0])
93
+ sub = ap.add_subparsers(dest="cmd", required=True)
94
+
95
+ an = sub.add_parser("analyze", help="detect species / sound groups, extract embeddings")
96
+ an.add_argument("audio", nargs="+", type=Path, help="audio files and/or directories")
97
+ an.add_argument("--model", type=Path, required=True, help="Kinglet trunk .onnx")
98
+ an.add_argument("--pack", type=Path, required=True, help="regional head pack .npz")
99
+ an.add_argument("--out", type=Path, default=Path("kinglet_detections.csv"))
100
+ an.add_argument("--top-k", type=int, default=3, help="keep at most the k best species per window")
101
+ an.add_argument("--min-score", type=float, default=0.1,
102
+ help="drop species rows below this softmax probability; 0.1 is the operating "
103
+ "point used by the Perch ecosystem and in the Kinglet evaluations")
104
+ an.add_argument("--hop", type=float, default=5.0, help="window hop in seconds")
105
+ an.add_argument("--threads", type=int, default=4)
106
+ an.add_argument("--embeddings", type=Path, default=None, help="directory for per-file .npz embeddings")
107
+ an.set_defaults(fn=analyze)
108
+
109
+ bp = sub.add_parser("build-pack", help="fold the full-vocabulary head onto a species list")
110
+ bp.add_argument("--headpack", type=Path, required=True, help=".headpack.npz release asset")
111
+ bp.add_argument("--species", type=Path, required=True,
112
+ help="CSV: ebird_code, scientific_name (+ japanese_name, vocab_index)")
113
+ bp.add_argument("--out", type=Path, required=True, help="output pack .npz")
114
+ bp.set_defaults(fn=build)
115
+
116
+ args = ap.parse_args()
117
+ args.fn(args)
118
+
119
+
120
+ if __name__ == "__main__":
121
+ main()
@@ -0,0 +1,229 @@
1
+ {
2
+ "note": "Perch 2.0 FSD50K class -> group mapping for Kinglet packs (owner decision 2026-11-06). A group score is the sum of member softmax probs. Calibrated thresholds (clean TPR >= 0.8 at the domestic-PAM FPR-1% point on every tier): human_voice 0.005, gunshot 0.0003, domestic_animal 0.003. Provisional operating points (the FPR-1% quantile is contaminated by genuine wind/rain/vehicles in field audio; these flag the ~0.1-2% most group-like windows): geophony 0.1, vehicle 0.05, music 0.05. other_anthrophony is a catch-all, no threshold. ungrouped = overlaps species classes or source-ambiguous onomatopoeia; kept as individual rows only.",
3
+ "groups": {
4
+ "human_voice": [
5
+ "Child_speech_and_kid_speaking",
6
+ "Chuckle_and_chortle",
7
+ "Conversation",
8
+ "Crying_and_sobbing",
9
+ "Female_singing",
10
+ "Female_speech_and_woman_speaking",
11
+ "Giggle",
12
+ "Homo sapiens",
13
+ "Human_group_actions",
14
+ "Human_voice",
15
+ "Laughter",
16
+ "Male_singing",
17
+ "Male_speech_and_man_speaking",
18
+ "Screaming",
19
+ "Shout",
20
+ "Singing",
21
+ "Speech",
22
+ "Speech_synthesizer",
23
+ "Whispering",
24
+ "Yell"
25
+ ],
26
+ "vehicle": [
27
+ "Accelerating_and_revving_and_vroom",
28
+ "Aircraft",
29
+ "Bicycle",
30
+ "Bicycle_bell",
31
+ "Boat_and_Water_vehicle",
32
+ "Bus",
33
+ "Car",
34
+ "Car_passing_by",
35
+ "Engine",
36
+ "Engine_starting",
37
+ "Fixed-wing_aircraft_and_airplane",
38
+ "Idling",
39
+ "Motor_vehicle_(road)",
40
+ "Motorcycle",
41
+ "Race_car_and_auto_racing",
42
+ "Rail_transport",
43
+ "Siren",
44
+ "Skateboard",
45
+ "Subway_and_metro_and_underground",
46
+ "Traffic_noise_and_roadway_noise",
47
+ "Train",
48
+ "Truck",
49
+ "Vehicle",
50
+ "Vehicle_horn_and_car_horn_and_honking"
51
+ ],
52
+ "geophony": [
53
+ "Fire",
54
+ "Gurgling",
55
+ "Liquid",
56
+ "Ocean",
57
+ "Rain",
58
+ "Raindrop",
59
+ "Splash_and_splatter",
60
+ "Stream",
61
+ "Thunder",
62
+ "Thunderstorm",
63
+ "Trickle_and_dribble",
64
+ "Water",
65
+ "Waves_and_surf",
66
+ "Wind",
67
+ "Drip"
68
+ ],
69
+ "music": [
70
+ "Accordion",
71
+ "Acoustic_guitar",
72
+ "Bass_drum",
73
+ "Bass_guitar",
74
+ "Bowed_string_instrument",
75
+ "Brass_instrument",
76
+ "Cowbell",
77
+ "Crash_cymbal",
78
+ "Cymbal",
79
+ "Drum",
80
+ "Drum_kit",
81
+ "Electric_guitar",
82
+ "Glockenspiel",
83
+ "Gong",
84
+ "Guitar",
85
+ "Harmonica",
86
+ "Harp",
87
+ "Hi-hat",
88
+ "Keyboard_(musical)",
89
+ "Mallet_percussion",
90
+ "Marimba_and_xylophone",
91
+ "Music",
92
+ "Musical_instrument",
93
+ "Organ",
94
+ "Percussion",
95
+ "Piano",
96
+ "Plucked_string_instrument",
97
+ "Rattle_(instrument)",
98
+ "Scratching_(performance_technique)",
99
+ "Snare_drum",
100
+ "Strum",
101
+ "Tabla",
102
+ "Tambourine",
103
+ "Trumpet",
104
+ "Wind_instrument_and_woodwind_instrument"
105
+ ],
106
+ "gunshot": [
107
+ "Gunshot_and_gunfire"
108
+ ],
109
+ "domestic_animal": [
110
+ "Bark",
111
+ "Cat",
112
+ "Chicken_and_rooster",
113
+ "Dog",
114
+ "Domestic_animals_and_pets",
115
+ "Fowl",
116
+ "Growling",
117
+ "Livestock_and_farm_animals_and_working_animals",
118
+ "Meow",
119
+ "Purr"
120
+ ],
121
+ "other_anthrophony": [
122
+ "Alarm",
123
+ "Applause",
124
+ "Bathtub_(filling_or_washing)",
125
+ "Bell",
126
+ "Boiling",
127
+ "Breathing",
128
+ "Burping_and_eructation",
129
+ "Camera",
130
+ "Chatter",
131
+ "Cheering",
132
+ "Chewing_and_mastication",
133
+ "Chime",
134
+ "Chink_and_clink",
135
+ "Church_bell",
136
+ "Clapping",
137
+ "Clock",
138
+ "Coin_(dropping)",
139
+ "Computer_keyboard",
140
+ "Cough",
141
+ "Crowd",
142
+ "Crumpling_and_crinkling",
143
+ "Crushing",
144
+ "Cupboard_open_or_close",
145
+ "Cutlery_and_silverware",
146
+ "Dishes_and_pots_and_pans",
147
+ "Domestic_sounds_and_home_sounds",
148
+ "Door",
149
+ "Doorbell",
150
+ "Drawer_open_or_close",
151
+ "Drill",
152
+ "Explosion",
153
+ "Fart",
154
+ "Fill_(with_liquid)",
155
+ "Finger_snapping",
156
+ "Fireworks",
157
+ "Frying_(food)",
158
+ "Gasp",
159
+ "Glass",
160
+ "Hammer",
161
+ "Hands",
162
+ "Keys_jangling",
163
+ "Knock",
164
+ "Mechanical_fan",
165
+ "Mechanisms",
166
+ "Microwave_oven",
167
+ "Packing_tape_and_duct_tape",
168
+ "Pour",
169
+ "Power_tool",
170
+ "Printer",
171
+ "Ratchet_and_pawl",
172
+ "Respiratory_sounds",
173
+ "Ringtone",
174
+ "Run",
175
+ "Sawing",
176
+ "Scissors",
177
+ "Shatter",
178
+ "Sigh",
179
+ "Sink_(filling_or_washing)",
180
+ "Slam",
181
+ "Sliding_door",
182
+ "Sneeze",
183
+ "Tap",
184
+ "Tearing",
185
+ "Telephone",
186
+ "Tick",
187
+ "Tick-tock",
188
+ "Toilet_flush",
189
+ "Tools",
190
+ "Typewriter",
191
+ "Typing",
192
+ "Walk_and_footsteps",
193
+ "Water_tap_and_faucet",
194
+ "Wind_chime",
195
+ "Wood",
196
+ "Writing",
197
+ "Zipper_(clothing)"
198
+ ]
199
+ },
200
+ "thresholds": {
201
+ "human_voice": 0.005,
202
+ "vehicle": 0.05,
203
+ "geophony": 0.1,
204
+ "music": 0.05,
205
+ "gunshot": 0.0003,
206
+ "domestic_animal": 0.003,
207
+ "other_anthrophony": null
208
+ },
209
+ "ungrouped": [
210
+ "Animal",
211
+ "Wild_animals",
212
+ "Chirp_and_tweet",
213
+ "Crow",
214
+ "Gull_and_seagull",
215
+ "Insect",
216
+ "Cricket",
217
+ "Frog",
218
+ "Buzz",
219
+ "Boom",
220
+ "Crack",
221
+ "Crackle",
222
+ "Hiss",
223
+ "Screech",
224
+ "Squeak",
225
+ "Whoosh_and_swoosh_and_swish",
226
+ "Thump_and_thud",
227
+ "Rattle"
228
+ ]
229
+ }
@@ -0,0 +1,134 @@
1
+ """Regional head packs: build one from a headpack bundle, load one for scoring.
2
+
3
+ A v0.3 model is a trunk ONNX (waveform -> embedding + trunk feature h) plus a head pack:
4
+ a linear map folding the full 14,795-class Perch vocabulary onto
5
+ <region species> + <sound-group member classes> + "other". Species rows slice exactly from the
6
+ full head; the "other" row is a ridge fit of the exact out-of-pack logsumexp on calibration
7
+ features shipped inside the headpack (closed form, seconds on a laptop). Scores are softmax
8
+ probabilities over the pack rows; group scores are sums of member probabilities.
9
+
10
+ Pack npz fields: W (R, d) f32, b (R,) f32, codes (R,) str (species codes, member class names,
11
+ "other" last), n_species, scientific_name/japanese_name (n_species,), groups json,
12
+ group_thresholds json, meta json (build report included).
13
+ """
14
+
15
+ import csv
16
+ import json
17
+ from importlib import resources
18
+ from pathlib import Path
19
+
20
+ import numpy as np
21
+
22
+ RIDGE_LAMBDA = 1.0
23
+ DEAD_BIAS = -1.0e9 # species absent from the vocabulary keep an exact-0 probability row
24
+ CHUNK = 2048
25
+
26
+
27
+ def default_groups() -> tuple[dict[str, list[str]], dict[str, float | None]]:
28
+ """The shipped FSD50K class -> group mapping and per-group operating thresholds."""
29
+ d = json.loads(resources.files("kinglet").joinpath("groups.json").read_text())
30
+ return d["groups"], d["thresholds"]
31
+
32
+
33
+ def load_pack(path: str | Path) -> dict:
34
+ z = np.load(path, allow_pickle=False)
35
+ pack = {k: z[k] for k in z.files}
36
+ for k in ("groups", "group_thresholds", "meta"):
37
+ pack[k] = json.loads(str(pack[k]))
38
+ pack["n_species"] = int(pack["n_species"])
39
+ codes = [str(c) for c in pack["codes"]]
40
+ pack["group_cols"] = {g: np.array([codes.index(m) for m in members])
41
+ for g, members in pack["groups"].items()}
42
+ return pack
43
+
44
+
45
+ def read_species_csv(path: str | Path) -> list[dict]:
46
+ """Rows need ebird_code + scientific_name (+ optional japanese_name, vocab_index).
47
+ vocab_index pins the Perch vocabulary row exactly; otherwise scientific_name is matched
48
+ against the vocabulary (exact match only — synonyms become dead rows, listed in the report)."""
49
+ with Path(path).open() as f:
50
+ return list(csv.DictReader(f))
51
+
52
+
53
+ def build_pack(headpack: str | Path, species: list[dict], out: str | Path,
54
+ groups: dict[str, list[str]] | None = None,
55
+ group_thresholds: dict[str, float | None] | None = None,
56
+ ridge_lambda: float = RIDGE_LAMBDA) -> dict:
57
+ """Fold the full head onto a species list; returns the build report (also stored in meta)."""
58
+ hp = np.load(headpack, allow_pickle=False)
59
+ W, b, labels = hp["W"].astype(np.float32), hp["b"].astype(np.float32), hp["labels"]
60
+ lab_idx = {str(n): i for i, n in enumerate(labels)}
61
+ if groups is None:
62
+ groups, dft = default_groups()
63
+ group_thresholds = group_thresholds or dft
64
+ group_thresholds = group_thresholds or {}
65
+
66
+ vidx, unmatched = [], []
67
+ for r in species:
68
+ if r.get("vocab_index") not in (None, ""):
69
+ vidx.append(int(r["vocab_index"]))
70
+ else:
71
+ i = lab_idx.get(r["scientific_name"], -1)
72
+ vidx.append(i)
73
+ if i < 0:
74
+ unmatched.append(r["ebird_code"])
75
+ vidx = np.array(vidx)
76
+ members = [m for ms in groups.values() for m in ms]
77
+ assert len(set(members)) == len(members), "a class may belong to one group only"
78
+ midx = np.array([lab_idx[m] for m in members]) # shipped groups always resolve
79
+ overlap = set(vidx[vidx >= 0]) & set(midx)
80
+ assert not overlap, f"species rows overlap group members: {sorted(overlap)}"
81
+
82
+ in_mask = np.zeros(len(labels), bool)
83
+ in_mask[vidx[vidx >= 0]] = True
84
+ in_mask[midx] = True
85
+ out_idx = np.flatnonzero(~in_mask)
86
+
87
+ # exact out-of-pack logsumexp on the calibration features, chunked (W alone is ~40 MB)
88
+ h = hp["calib_h"].astype(np.float32)
89
+ is_ho = hp["calib_is_holdout"]
90
+ n_sp = len(vidx)
91
+ cols = np.concatenate([np.where(vidx >= 0, vidx, 0), midx])
92
+ z = np.empty(len(h), np.float32)
93
+ p_in = np.empty((len(h), len(cols)), np.float32) # exact folded probs for the report
94
+ for i in range(0, len(h), CHUNK):
95
+ lg = h[i : i + CHUNK] @ W.T + b
96
+ mx = lg.max(1, keepdims=True)
97
+ e = np.exp(lg - mx)
98
+ z[i : i + CHUNK] = np.log(e[:, out_idx].sum(1)) + mx[:, 0]
99
+ p_in[i : i + CHUNK] = e[:, cols] / e.sum(1, keepdims=True)
100
+ p_in[:, :n_sp][:, vidx < 0] = 0.0
101
+
102
+ ht = np.hstack([h[~is_ho], np.ones((int((~is_ho).sum()), 1))]).astype(np.float64)
103
+ A = ht.T @ ht + ridge_lambda * np.eye(ht.shape[1])
104
+ wb = np.linalg.solve(A, ht.T @ z[~is_ho].astype(np.float64))
105
+ w_o, b_o = wb[:-1].astype(np.float32), float(wb[-1])
106
+
107
+ d = W.shape[1]
108
+ Wp = np.zeros((len(cols) + 1, d), np.float32)
109
+ bp = np.full(len(cols) + 1, DEAD_BIAS, np.float32)
110
+ Wp[:-1], bp[:-1] = W[cols], b[cols]
111
+ Wp[:n_sp][vidx < 0], bp[:n_sp][vidx < 0] = 0.0, DEAD_BIAS
112
+ Wp[-1], bp[-1] = w_o, b_o
113
+
114
+ # holdout report in probability space (where the operating threshold lives)
115
+ hh, pe = h[is_ho], p_in[is_ho]
116
+ lg = hh @ Wp.T + bp
117
+ e = np.exp(lg - lg.max(1, keepdims=True))
118
+ pp = (e / e.sum(1, keepdims=True))[:, :-1]
119
+ fire_pack, fire_full = (pp[:, :n_sp] > 0.1).any(1), (pe[:, :n_sp] > 0.1).any(1)
120
+ report = {
121
+ "n_species": n_sp, "unmatched": unmatched, "n_group_rows": len(midx),
122
+ "holdout_windows": int(is_ho.sum()),
123
+ "prob_err_mean": float(np.abs(pp - pe).mean()), "prob_err_max": float(np.abs(pp - pe).max()),
124
+ "fire@0.1_disagree": float((fire_pack != fire_full).mean()),
125
+ }
126
+
127
+ codes = ([r["ebird_code"] for r in species] + members + ["other"])
128
+ np.savez(Path(out), W=Wp, b=bp, codes=np.array(codes), n_species=n_sp,
129
+ scientific_name=np.array([r.get("scientific_name", "") for r in species]),
130
+ japanese_name=np.array([r.get("japanese_name", "") for r in species]),
131
+ groups=json.dumps(groups), group_thresholds=json.dumps(group_thresholds),
132
+ meta=json.dumps({"headpack_meta": json.loads(str(hp["meta"])),
133
+ "ridge_lambda": ridge_lambda} | report))
134
+ return report
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: kinglet-bio
3
+ Version: 0.3.1
4
+ Summary: Kinglet: kinglet-sized bioacoustic embedding and classification models distilled from Perch 2.0
5
+ Author: Ryotaro Okamoto
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/0kam/kinglet
8
+ Project-URL: Releases, https://github.com/0kam/kinglet/releases
9
+ Project-URL: Model Card, https://github.com/0kam/kinglet/blob/main/MODEL_CARD.md
10
+ Keywords: bioacoustics,birds,sound-event-detection,onnx,knowledge-distillation
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ License-File: NOTICE
19
+ Requires-Dist: numpy>=1.24
20
+ Requires-Dist: onnxruntime>=1.17
21
+ Dynamic: license-file
22
+
23
+ # Kinglet 🐦
24
+
25
+ **Kinglet-sized bioacoustic embedding and classification models, distilled from
26
+ [Perch 2.0](https://github.com/google-research/perch).**
27
+
28
+ Kinglets are among the smallest birds in the northern hemisphere. Kinglet models are among the
29
+ smallest bioacoustic models: a trunk ONNX (~22–53 MB, preprocessing included) plus a ~2 MB regional
30
+ head pack that process **months of field recordings in hours on an ordinary laptop CPU** — no GPU,
31
+ no Python ML stack — while staying close to Perch 2.0 on Japanese soundscape benchmarks. Each model
32
+ outputs species scores, sound-group scores (human voice, vehicles, rain/wind, ...), and a 1536-d
33
+ embedding projected into the Perch 2.0 embedding space.
34
+
35
+ ## Models (v0.3.1)
36
+
37
+ | model | backbone | trunk size | speed* | Kasumigaura macro AUPRC** |
38
+ |---|---|---|---|---|
39
+ | Kinglet-B | RegNetY-016 | 51 MB | ~600x realtime | 0.714 |
40
+ | Kinglet-S | EfficientNet-Lite0 | 26 MB | ~1,250x realtime | 0.698 |
41
+ | Kinglet-XS | MobileNetV4-Conv-S | 22 MB | ~2,200x realtime | 0.714 |
42
+
43
+ Since v0.3 the models are distilled from the teacher's **full 14,795-class vocabulary** and folded
44
+ to a region at deployment time ("distill once, fold anywhere"): a prebuilt Japan pack (317 species)
45
+ ships with the release, and `kinglet build-pack` folds the same trunk onto **any species list** in
46
+ seconds, no audio needed. Scores are **softmax probabilities with an explicit background channel**;
47
+ use a fixed species threshold of **0.1** (the Perch operating point). Every pack also carries
48
+ **sound groups** with operating thresholds (since v0.3.1): a calibrated `human_voice` detector
49
+ (threshold 0.005) for privacy masking before sharing field audio, calibrated `gunshot` and
50
+ `domestic_animal` detectors, and provisional `geophony` / `vehicle` / `music` flags for
51
+ rain-and-traffic noise screening (details in [MODEL_CARD.md](https://github.com/0kam/kinglet/blob/main/MODEL_CARD.md)).
52
+
53
+ \* 4 CPU threads, log-mel preprocessing included (Ryzen 9950X3D; expect roughly half on a typical
54
+ laptop). \** Perch 2.0 (the ~47x-realtime teacher) scores 0.737; for Kinglet-B the 95% CI of the
55
+ paired difference includes 0. Download from [GitHub Releases](https://github.com/0kam/kinglet/releases).
56
+ The `.gemm-mel` trunk variants trade a slightly larger file for a mel frontend that is faster on
57
+ some ARM CPUs — on x86, use the default files.
58
+
59
+ ## Quickstart
60
+
61
+ ```bash
62
+ pip install kinglet-bio # needs ffmpeg on PATH
63
+ kinglet analyze recordings/ --model kinglet-s-v0.3.1.onnx --pack kinglet-s-v0.3.1.pack-jp.npz --out detections.csv
64
+ ```
65
+
66
+ The CLI keeps, per 5 s window, the top-3 species scoring at least 0.1 (adjustable with
67
+ `--top-k` / `--min-score`), adds one row per calibrated sound group that passes its own threshold
68
+ (`human_voice` windows are what you mute before sharing audio), and can dump embeddings with
69
+ `--embeddings emb/`.
70
+
71
+ Deploying outside Japan (or with your own species list)? Fold a pack from the `.headpack.npz`
72
+ release asset — the CSV needs `ebird_code, scientific_name` columns:
73
+
74
+ ```bash
75
+ kinglet build-pack --headpack kinglet-s-v0.3.1.headpack.npz --species my_region.csv --out my_region.npz
76
+ ```
77
+
78
+ Or from Python / any ONNX runtime:
79
+
80
+ ```python
81
+ from kinglet import Kinglet, decode, windows
82
+ m = Kinglet("kinglet-s-v0.3.1.onnx", "kinglet-s-v0.3.1.pack-jp.npz")
83
+ starts, wins = windows(decode("field_recording.wav")) # 5 s windows at 32 kHz mono
84
+ embeddings, scores, groups = m.run(wins) # (n, 1536), (n, 317), {group: (n,)}
85
+ mask = groups["human_voice"] >= m.groups["human_voice"] # windows to mute before sharing
86
+ ```
87
+
88
+ ## Model I/O
89
+
90
+ - Input `waveform`: float32 `(batch, 160000)` — 5 s, 32 kHz, mono, amplitude in [-1, 1]
91
+ - Output `embedding`: `(batch, 1536)` — projection into the Perch 2.0 embedding space
92
+ (mean cosine ~0.84–0.87 to the teacher on held-out focal validation)
93
+ - Output `feature`: `(batch, d)` — the trunk feature; scores = `softmax(feature @ W.T + b)` with
94
+ `W, b` from the pack `.npz`, background column dropped (this is what `Kinglet.run` does).
95
+ Row order: pack `codes` (species, then group-member classes, then "other").
96
+ - v0.2 single-file models (`logits` in the graph) are not supported by the v0.3 package — use the
97
+ v0.2 release assets with `kinglet-bio==0.2.0` if you need them.
98
+
99
+ ## License
100
+
101
+ [Apache License 2.0](https://github.com/0kam/kinglet/blob/main/LICENSE). Kinglet models are distilled from Perch 2.0 (Apache-2.0, Google);
102
+ see [NOTICE](https://github.com/0kam/kinglet/blob/main/NOTICE) and [MODEL_CARD.md](https://github.com/0kam/kinglet/blob/main/MODEL_CARD.md) for training-data provenance.
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ NOTICE
3
+ README.md
4
+ pyproject.toml
5
+ kinglet/__init__.py
6
+ kinglet/cli.py
7
+ kinglet/groups.json
8
+ kinglet/pack.py
9
+ kinglet_bio.egg-info/PKG-INFO
10
+ kinglet_bio.egg-info/SOURCES.txt
11
+ kinglet_bio.egg-info/dependency_links.txt
12
+ kinglet_bio.egg-info/entry_points.txt
13
+ kinglet_bio.egg-info/requires.txt
14
+ kinglet_bio.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ kinglet = kinglet.cli:main
@@ -0,0 +1,2 @@
1
+ numpy>=1.24
2
+ onnxruntime>=1.17
@@ -0,0 +1 @@
1
+ kinglet
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "kinglet-bio"
7
+ version = "0.3.1"
8
+ description = "Kinglet: kinglet-sized bioacoustic embedding and classification models distilled from Perch 2.0"
9
+ readme = "README.md"
10
+ license = { text = "Apache-2.0" }
11
+ requires-python = ">=3.10"
12
+ dependencies = ["numpy>=1.24", "onnxruntime>=1.17"]
13
+ authors = [{ name = "Ryotaro Okamoto" }]
14
+ keywords = ["bioacoustics", "birds", "sound-event-detection", "onnx", "knowledge-distillation"]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Operating System :: OS Independent",
18
+ "Intended Audience :: Science/Research",
19
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
20
+ ]
21
+
22
+ [project.urls]
23
+ Homepage = "https://github.com/0kam/kinglet"
24
+ Releases = "https://github.com/0kam/kinglet/releases"
25
+ "Model Card" = "https://github.com/0kam/kinglet/blob/main/MODEL_CARD.md"
26
+
27
+ [project.scripts]
28
+ kinglet = "kinglet.cli:main"
29
+
30
+ [tool.setuptools]
31
+ packages = ["kinglet"]
32
+
33
+ [tool.setuptools.package-data]
34
+ kinglet = ["groups.json"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+