Commit ·
a187b6b
1
Parent(s): 66362c0
Add model repository contents
Browse files- .gitattributes +3 -0
- .gitignore +2 -0
- LICENSE.md +159 -0
- PROVENANCE.json +60 -0
- PUBLISHING.md +19 -0
- README.md +113 -0
- SHA256SUMS +23 -0
- batdetect2-uk-same.onnx +3 -0
- environment/pyproject.toml +18 -0
- environment/uv.lock +0 -0
- export-metadata.json +76 -0
- golden/class_probs.npy +3 -0
- golden/detection_probs.npy +3 -0
- golden/input.npy +3 -0
- golden/manifest.json +57 -0
- golden/pyproject.toml +11 -0
- golden/uv.lock +94 -0
- labels.json +7 -0
- preprocessing/README.md +12 -0
- preprocessing/upstream/__init__.py +17 -0
- preprocessing/upstream/audio.py +240 -0
- preprocessing/upstream/common.py +60 -0
- preprocessing/upstream/config.py +75 -0
- preprocessing/upstream/preprocessor.py +253 -0
- preprocessing/upstream/spectrogram.py +820 -0
- preprocessing/upstream/types.py +31 -0
- scripts/export_batdetect2_onnx.py +171 -0
- scripts/fetch-upstream.sh +31 -0
- scripts/rebuild-and-verify.sh +41 -0
- scripts/verify_golden.py +92 -0
- upstream/README.md +8 -0
- upstream/batdetect2_uk_same.ckpt +3 -0
.gitattributes
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
golden/*.npy filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.repro/
|
| 2 |
+
.venv/
|
LICENSE.md
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Creative Commons Attribution-NonCommercial 4.0 International
|
| 2 |
+
|
| 3 |
+
Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
|
| 4 |
+
|
| 5 |
+
**Using Creative Commons Public Licenses**
|
| 6 |
+
|
| 7 |
+
Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
|
| 8 |
+
|
| 9 |
+
* __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors).
|
| 10 |
+
|
| 11 |
+
* __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees).
|
| 12 |
+
|
| 13 |
+
## Creative Commons Attribution-NonCommercial 4.0 International Public License
|
| 14 |
+
|
| 15 |
+
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
|
| 16 |
+
|
| 17 |
+
### Section 1 – Definitions.
|
| 18 |
+
|
| 19 |
+
a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
|
| 20 |
+
|
| 21 |
+
b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
|
| 22 |
+
|
| 23 |
+
c. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
|
| 24 |
+
|
| 25 |
+
d. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
|
| 26 |
+
|
| 27 |
+
e. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
|
| 28 |
+
|
| 29 |
+
f. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
|
| 30 |
+
|
| 31 |
+
g. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
|
| 32 |
+
|
| 33 |
+
h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
|
| 34 |
+
|
| 35 |
+
i. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
|
| 36 |
+
|
| 37 |
+
j. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
|
| 38 |
+
|
| 39 |
+
k. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
|
| 40 |
+
|
| 41 |
+
l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. __Your__ has a corresponding meaning.
|
| 42 |
+
|
| 43 |
+
### Section 2 – Scope.
|
| 44 |
+
|
| 45 |
+
a. ___License grant.___
|
| 46 |
+
|
| 47 |
+
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
|
| 48 |
+
|
| 49 |
+
A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
|
| 50 |
+
|
| 51 |
+
B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
|
| 52 |
+
|
| 53 |
+
2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
|
| 54 |
+
|
| 55 |
+
3. __Term.__ The term of this Public License is specified in Section 6(a).
|
| 56 |
+
|
| 57 |
+
4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
|
| 58 |
+
|
| 59 |
+
5. __Downstream recipients.__
|
| 60 |
+
|
| 61 |
+
A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
|
| 62 |
+
|
| 63 |
+
B. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
|
| 64 |
+
|
| 65 |
+
6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
|
| 66 |
+
|
| 67 |
+
b. ___Other rights.___
|
| 68 |
+
|
| 69 |
+
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
|
| 70 |
+
|
| 71 |
+
2. Patent and trademark rights are not licensed under this Public License.
|
| 72 |
+
|
| 73 |
+
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
|
| 74 |
+
|
| 75 |
+
### Section 3 – License Conditions.
|
| 76 |
+
|
| 77 |
+
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
|
| 78 |
+
|
| 79 |
+
a. ___Attribution.___
|
| 80 |
+
|
| 81 |
+
1. If You Share the Licensed Material (including in modified form), You must:
|
| 82 |
+
|
| 83 |
+
A. retain the following if it is supplied by the Licensor with the Licensed Material:
|
| 84 |
+
|
| 85 |
+
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
|
| 86 |
+
|
| 87 |
+
ii. a copyright notice;
|
| 88 |
+
|
| 89 |
+
iii. a notice that refers to this Public License;
|
| 90 |
+
|
| 91 |
+
iv. a notice that refers to the disclaimer of warranties;
|
| 92 |
+
|
| 93 |
+
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
|
| 94 |
+
|
| 95 |
+
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
|
| 96 |
+
|
| 97 |
+
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
|
| 98 |
+
|
| 99 |
+
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
|
| 100 |
+
|
| 101 |
+
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
|
| 102 |
+
|
| 103 |
+
4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License.
|
| 104 |
+
|
| 105 |
+
### Section 4 – Sui Generis Database Rights.
|
| 106 |
+
|
| 107 |
+
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
|
| 108 |
+
|
| 109 |
+
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;
|
| 110 |
+
|
| 111 |
+
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and
|
| 112 |
+
|
| 113 |
+
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
|
| 114 |
+
|
| 115 |
+
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
|
| 116 |
+
|
| 117 |
+
### Section 5 – Disclaimer of Warranties and Limitation of Liability.
|
| 118 |
+
|
| 119 |
+
a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__
|
| 120 |
+
|
| 121 |
+
b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__
|
| 122 |
+
|
| 123 |
+
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
|
| 124 |
+
|
| 125 |
+
### Section 6 – Term and Termination.
|
| 126 |
+
|
| 127 |
+
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
|
| 128 |
+
|
| 129 |
+
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
|
| 130 |
+
|
| 131 |
+
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
|
| 132 |
+
|
| 133 |
+
2. upon express reinstatement by the Licensor.
|
| 134 |
+
|
| 135 |
+
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
|
| 136 |
+
|
| 137 |
+
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
|
| 138 |
+
|
| 139 |
+
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
|
| 140 |
+
|
| 141 |
+
### Section 7 – Other Terms and Conditions.
|
| 142 |
+
|
| 143 |
+
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
|
| 144 |
+
|
| 145 |
+
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
|
| 146 |
+
|
| 147 |
+
### Section 8 – Interpretation.
|
| 148 |
+
|
| 149 |
+
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
|
| 150 |
+
|
| 151 |
+
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
|
| 152 |
+
|
| 153 |
+
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
|
| 154 |
+
|
| 155 |
+
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
|
| 156 |
+
|
| 157 |
+
> Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
|
| 158 |
+
>
|
| 159 |
+
> Creative Commons may be contacted at creativecommons.org
|
PROVENANCE.json
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": 1,
|
| 3 |
+
"publication_status": "ready-to-publish-noncommercial-only",
|
| 4 |
+
"artifact": {
|
| 5 |
+
"path": "batdetect2-uk-same.onnx",
|
| 6 |
+
"bytes": 7603041,
|
| 7 |
+
"sha256": "9eddc08f1a22695ffdb1cdb52d947752d83777cd8596554f108bcf701481d340",
|
| 8 |
+
"opset": 17,
|
| 9 |
+
"modifications": "Converted from the pinned PyTorch checkpoint to ONNX."
|
| 10 |
+
},
|
| 11 |
+
"source": {
|
| 12 |
+
"repository": "https://github.com/macaodha/batdetect2",
|
| 13 |
+
"revision": "9e2697458d3b3b03c30ccd7e49ed5409c8ac330d",
|
| 14 |
+
"path": "src/batdetect2/models/checkpoints/batdetect2_uk_same.ckpt",
|
| 15 |
+
"archived_path": "upstream/batdetect2_uk_same.ckpt",
|
| 16 |
+
"bytes": 7610085,
|
| 17 |
+
"sha256": "52e3f329a046e434d16751005b252b4fd1b142b8b63a4edc2740aeb81f48adcf"
|
| 18 |
+
},
|
| 19 |
+
"exporter": {
|
| 20 |
+
"path": "scripts/export_batdetect2_onnx.py",
|
| 21 |
+
"sha256": "654aefbf39ebfb0815ecb85dff34382ea9a9dd32f28690474f44774514ece66f",
|
| 22 |
+
"project": "environment/pyproject.toml",
|
| 23 |
+
"project_sha256": "1dae942acf443726fc72cec3398e308c7c1c57eef36814b720c1fe30bacd8383",
|
| 24 |
+
"lock": "environment/uv.lock",
|
| 25 |
+
"lock_sha256": "6a18952a219703f0f03e6f091ed898f7b23bc886e6bdd96dd933d5b94dc57e92"
|
| 26 |
+
},
|
| 27 |
+
"export_environment": {
|
| 28 |
+
"python": "3.11.15",
|
| 29 |
+
"batdetect2": "2.0.0b3",
|
| 30 |
+
"torch": "2.13.0",
|
| 31 |
+
"onnx": "1.22.0",
|
| 32 |
+
"onnxruntime": "1.28.0"
|
| 33 |
+
},
|
| 34 |
+
"source_runtime_parity": {
|
| 35 |
+
"fixture": "seeded random float32 tensor (seed 20260818)",
|
| 36 |
+
"detection_maximum_absolute_error": 1.0579824447631836e-06,
|
| 37 |
+
"class_maximum_absolute_error": 5.364418029785156e-07,
|
| 38 |
+
"tolerance": 0.0001
|
| 39 |
+
},
|
| 40 |
+
"contract": {
|
| 41 |
+
"input": "float32 NCHW [1,1,128,256] named input",
|
| 42 |
+
"outputs": {
|
| 43 |
+
"detection_probs": [1, 1, 128, 256],
|
| 44 |
+
"class_probs": [1, 17, 128, 256]
|
| 45 |
+
},
|
| 46 |
+
"labels": "labels.json",
|
| 47 |
+
"region": "United Kingdom"
|
| 48 |
+
},
|
| 49 |
+
"preprocessing": {
|
| 50 |
+
"repository_revision": "9e2697458d3b3b03c30ccd7e49ed5409c8ac330d",
|
| 51 |
+
"path": "preprocessing/upstream"
|
| 52 |
+
},
|
| 53 |
+
"golden_fixture": "golden/manifest.json",
|
| 54 |
+
"rights": {
|
| 55 |
+
"license": "CC-BY-NC-4.0",
|
| 56 |
+
"attribution": "BatDetect2 contributors",
|
| 57 |
+
"commercial_use": false,
|
| 58 |
+
"redistribution": "noncommercial only, with attribution, licence link, and change notice"
|
| 59 |
+
}
|
| 60 |
+
}
|
PUBLISHING.md
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Publishing checklist
|
| 2 |
+
|
| 3 |
+
Status: **READY TO PUBLISH — NONCOMMERCIAL ONLY**
|
| 4 |
+
|
| 5 |
+
- [x] The upstream CC BY-NC 4.0 licence is preserved unchanged.
|
| 6 |
+
- [x] The model card attributes the original authors and cites the upstream work.
|
| 7 |
+
- [x] The model card identifies the ONNX file as an unofficial conversion.
|
| 8 |
+
- [x] Source revision, environment, parity result, file sizes, and hashes are pinned.
|
| 9 |
+
- [x] The byte-identical original PyTorch checkpoint is archived with a safety warning.
|
| 10 |
+
- [x] The exporter, locked environment, source verifier, and rebuild verifier are included.
|
| 11 |
+
- [x] Exact label order, pinned preprocessing, and a deterministic golden fixture are included.
|
| 12 |
+
- [x] The private staging repository is `legojoey17/batdetect2-uk-same-onnx`.
|
| 13 |
+
- [x] The remote ONNX, checkpoint, and golden-fixture SHA-256 values match the local manifest.
|
| 14 |
+
- [x] The rendered private repository has been reviewed.
|
| 15 |
+
- [x] The intended public distribution has been confirmed as noncommercial under CC BY-NC 4.0.
|
| 16 |
+
- [ ] Obtain separate rights before using this repository to support commercial distribution.
|
| 17 |
+
|
| 18 |
+
Publishing from another namespace makes that account the uploader. It does not make the
|
| 19 |
+
conversion official or imply endorsement by BatDetect2 or its authors.
|
README.md
CHANGED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: cc-by-nc-4.0
|
| 3 |
+
library_name: onnxruntime
|
| 4 |
+
tags:
|
| 5 |
+
- onnx
|
| 6 |
+
- onnxruntime
|
| 7 |
+
- bioacoustics
|
| 8 |
+
- bats
|
| 9 |
+
- audio-classification
|
| 10 |
+
- object-detection
|
| 11 |
+
- united-kingdom
|
| 12 |
+
- non-commercial
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
# BatDetect2 UK `same` ONNX
|
| 16 |
+
|
| 17 |
+
> **Noncommercial only.** The source checkpoint is CC BY-NC 4.0. Commercial use or distribution
|
| 18 |
+
> requires separate permission from the rights holder.
|
| 19 |
+
|
| 20 |
+
This repository contains the original BatDetect2 UK `same` checkpoint and the reproducible ONNX
|
| 21 |
+
export used by OpenBat. It is an unofficial conversion, not a BatDetect2 release.
|
| 22 |
+
|
| 23 |
+
`UK same` is the paper's evaluation split where test files come from the same UK recording data
|
| 24 |
+
sources represented in training. It contrasts with `UK different`, which holds out a complete
|
| 25 |
+
recording source to measure transfer to unseen conditions. See the
|
| 26 |
+
[BatDetect2 paper](https://www.biorxiv.org/content/10.1101/2022.12.14.520490v2.full).
|
| 27 |
+
|
| 28 |
+
## Artifact
|
| 29 |
+
|
| 30 |
+
| File | Size | SHA-256 |
|
| 31 |
+
|---|---:|---|
|
| 32 |
+
| `batdetect2-uk-same.onnx` | 7,603,041 bytes | `9eddc08f1a22695ffdb1cdb52d947752d83777cd8596554f108bcf701481d340` |
|
| 33 |
+
| `upstream/batdetect2_uk_same.ckpt` | 7,610,085 bytes | `52e3f329a046e434d16751005b252b4fd1b142b8b63a4edc2740aeb81f48adcf` |
|
| 34 |
+
|
| 35 |
+
## Source and conversion
|
| 36 |
+
|
| 37 |
+
- Source repository: [`macaodha/batdetect2`](https://github.com/macaodha/batdetect2).
|
| 38 |
+
- Source revision: `9e2697458d3b3b03c30ccd7e49ed5409c8ac330d`.
|
| 39 |
+
- Source checkpoint: `src/batdetect2/models/checkpoints/batdetect2_uk_same.ckpt`.
|
| 40 |
+
- Conversion: PyTorch checkpoint to ONNX opset 17.
|
| 41 |
+
- Export environment: CPython 3.11.15, BatDetect2 2.0.0b3, PyTorch 2.13.0,
|
| 42 |
+
ONNX 1.22.0, and ONNX Runtime 1.28.0.
|
| 43 |
+
- Seeded source-runtime parity: detection maximum absolute error `1.0579824447631836e-06`;
|
| 44 |
+
class maximum absolute error `5.364418029785156e-07`; tolerance `0.0001`.
|
| 45 |
+
|
| 46 |
+
The original checkpoint is archived byte-identically under `upstream/`. The exact exporter is in
|
| 47 |
+
`scripts/`, the complete `uv` lock is in `environment/`, and `PROVENANCE.json` records the source
|
| 48 |
+
and output contract.
|
| 49 |
+
|
| 50 |
+
## Reproduce the conversion
|
| 51 |
+
|
| 52 |
+
The rebuild requires Git, `uv`, and CPython 3.11.15. Fetch the pinned BatDetect2 revision, compare
|
| 53 |
+
its checkpoint with the archived copy, then run the locked exporter and parity check:
|
| 54 |
+
|
| 55 |
+
```sh
|
| 56 |
+
./scripts/fetch-upstream.sh
|
| 57 |
+
./scripts/rebuild-and-verify.sh --accept-noncommercial-license
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
The explicit flag acknowledges that the checkpoint and conversion remain subject to CC BY-NC
|
| 61 |
+
4.0. The first run downloads the checksum-locked Python environment. Output goes to the ignored
|
| 62 |
+
`.repro/output/` directory. A passing rebuild establishes byte identity and seeded runtime
|
| 63 |
+
agreement; it does not validate classification accuracy.
|
| 64 |
+
|
| 65 |
+
The `.ckpt` file is a Python/PyTorch checkpoint. Treat it as trusted upstream archival input and
|
| 66 |
+
do not load checkpoints from untrusted sources. Use the ONNX file for ordinary inference.
|
| 67 |
+
|
| 68 |
+
## Model contract
|
| 69 |
+
|
| 70 |
+
- Input: `input`, `float32`, NCHW `[1, 1, 128, 256]`, mono spectrogram.
|
| 71 |
+
- Outputs: `detection_probs` `[1, 1, 128, 256]` and `class_probs`
|
| 72 |
+
`[1, 17, 128, 256]`.
|
| 73 |
+
- Exact class order: [`labels.json`](labels.json).
|
| 74 |
+
- Region: United Kingdom.
|
| 75 |
+
|
| 76 |
+
The model does not accept raw audio. Callers must reproduce the BatDetect2 spectrogram and
|
| 77 |
+
normalization contract.
|
| 78 |
+
|
| 79 |
+
## Preprocessing
|
| 80 |
+
|
| 81 |
+
[`preprocessing/README.md`](preprocessing/README.md) links directly to the pinned BatDetect2
|
| 82 |
+
implementation and includes an unchanged copy of its complete `preprocess` package.
|
| 83 |
+
|
| 84 |
+
## Golden fixture
|
| 85 |
+
|
| 86 |
+
`golden/` contains a deterministic model-ready spectrogram tensor and expected detection and class
|
| 87 |
+
outputs. It checks the published model contract separately from raw-audio preprocessing.
|
| 88 |
+
|
| 89 |
+
```sh
|
| 90 |
+
uv run --project golden --frozen --python 3.11.15 python scripts/verify_golden.py
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
The generation seed, runtime versions, hashes, and tolerances are recorded in
|
| 94 |
+
`golden/manifest.json`.
|
| 95 |
+
|
| 96 |
+
## Licence and attribution
|
| 97 |
+
|
| 98 |
+
The upstream project and checkpoint are licensed under Creative Commons
|
| 99 |
+
Attribution-NonCommercial 4.0 International. The upstream licence is included unchanged as
|
| 100 |
+
`LICENSE.md`, and the ONNX file is identified as a conversion.
|
| 101 |
+
|
| 102 |
+
Upstream reference:
|
| 103 |
+
|
| 104 |
+
> Mac Aodha, O. et al. (2023), “Towards a General Approach for Bat Echolocation Detection and
|
| 105 |
+
> Classification,” bioRxiv, https://www.biorxiv.org/content/10.1101/2022.12.14.520490v2.
|
| 106 |
+
|
| 107 |
+
## Limitations
|
| 108 |
+
|
| 109 |
+
- The original authors have not authorized or endorsed this conversion.
|
| 110 |
+
- It is noncommercial-only unless separate rights are obtained.
|
| 111 |
+
- Exact preprocessing is part of the model contract.
|
| 112 |
+
- Source-runtime parity measures conversion fidelity, not biological accuracy.
|
| 113 |
+
- The model is geographically scoped and should not be treated as a global classifier.
|
SHA256SUMS
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
9eddc08f1a22695ffdb1cdb52d947752d83777cd8596554f108bcf701481d340 batdetect2-uk-same.onnx
|
| 2 |
+
52e3f329a046e434d16751005b252b4fd1b142b8b63a4edc2740aeb81f48adcf upstream/batdetect2_uk_same.ckpt
|
| 3 |
+
654aefbf39ebfb0815ecb85dff34382ea9a9dd32f28690474f44774514ece66f scripts/export_batdetect2_onnx.py
|
| 4 |
+
82b7d4f46c7a0bfe21be53d5cf0d83f37fe002fd73f28c3f6b28ee803a25d0e6 scripts/fetch-upstream.sh
|
| 5 |
+
833d7472dbea173977481dde86b26d622de10cb8f4d6be392c35bcdaa9e86845 scripts/rebuild-and-verify.sh
|
| 6 |
+
0ea516a80751bbb4a5d048917a5c58fb9068583ec9fce80b8a015c3628ae3e64 scripts/verify_golden.py
|
| 7 |
+
1dae942acf443726fc72cec3398e308c7c1c57eef36814b720c1fe30bacd8383 environment/pyproject.toml
|
| 8 |
+
6a18952a219703f0f03e6f091ed898f7b23bc886e6bdd96dd933d5b94dc57e92 environment/uv.lock
|
| 9 |
+
0a82dcd7a2a5d86a32ca3dcf22b9ced20fdb8c04bd2a78589cfaebd412e32122 labels.json
|
| 10 |
+
28de21910f625e8d14935cb30151660a5139f060bc48197854ec873b7210e2aa export-metadata.json
|
| 11 |
+
6ef2dc2fd3cd8ad1a201ac07cabfe873f67ff0be40006671a890cbef5521eb43 golden/input.npy
|
| 12 |
+
5440e3d980f0bb594881bbaba0d41b69b267b9d2ba08e50ee5ee485a84f759eb golden/detection_probs.npy
|
| 13 |
+
fd1d40e8e7399b3310c0679dd948028427dbb336963ada0ab5cba6440e464657 golden/class_probs.npy
|
| 14 |
+
334ff9d8f923c200aa2e1b232277dfb29070d927ede85580711a5a2ce1916650 golden/manifest.json
|
| 15 |
+
38170f35c4b4a7c73360fc2d454fb2c60dcadafea7fb6bf03602f6165ea48c7f golden/pyproject.toml
|
| 16 |
+
ff27ad09676f47e1f396e636c7379a95b904d8ac8bcada5aa04da8256a4f859a golden/uv.lock
|
| 17 |
+
db79d1f9935f9d545ea7e25bf38fee12a3b763d1ad26125845e50a767c17a9ee preprocessing/upstream/__init__.py
|
| 18 |
+
a838a668cc91c421f5774cc0eb0469c9ec9d6017efadf8e4193245842f99367a preprocessing/upstream/audio.py
|
| 19 |
+
cae8b4f54a1ce21aeb94ee54a288903efb74afd9a1e1563b6f1df5f8ad36fd21 preprocessing/upstream/common.py
|
| 20 |
+
7050a0491b8a798b6954815ee2efd79bb8329ea0e4a069d805aca419f4b1284e preprocessing/upstream/config.py
|
| 21 |
+
1d97dd8cf84cf53df67727d7445dc70edc9bb257d97b2013b28921678bdc1672 preprocessing/upstream/preprocessor.py
|
| 22 |
+
370bca8e29bec523ea71a958c6d44a80ce33e540653181d9d62c42ea409ce6fe preprocessing/upstream/spectrogram.py
|
| 23 |
+
cd896d3b98919851aa130c009f57107167fba696cc4a41d75fbeb3d3d59fbec8 preprocessing/upstream/types.py
|
batdetect2-uk-same.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9eddc08f1a22695ffdb1cdb52d947752d83777cd8596554f108bcf701481d340
|
| 3 |
+
size 7603041
|
environment/pyproject.toml
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[project]
|
| 2 |
+
name = "bat-ml-batdetect2-exporter"
|
| 3 |
+
version = "0.0.0"
|
| 4 |
+
requires-python = "==3.11.15"
|
| 5 |
+
dependencies = [
|
| 6 |
+
"batdetect2",
|
| 7 |
+
"numpy==2.4.6",
|
| 8 |
+
"onnx==1.22.0",
|
| 9 |
+
"onnxruntime==1.28.0",
|
| 10 |
+
"torch==2.13.0",
|
| 11 |
+
"torchaudio==2.11.0",
|
| 12 |
+
]
|
| 13 |
+
|
| 14 |
+
[tool.uv]
|
| 15 |
+
package = false
|
| 16 |
+
|
| 17 |
+
[tool.uv.sources]
|
| 18 |
+
batdetect2 = { git = "https://github.com/macaodha/batdetect2.git", rev = "9e2697458d3b3b03c30ccd7e49ed5409c8ac330d" }
|
environment/uv.lock
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
export-metadata.json
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"backend": "batdetect2",
|
| 3 |
+
"source": "https://github.com/macaodha/batdetect2",
|
| 4 |
+
"source_revision": "9e2697458d3b3b03c30ccd7e49ed5409c8ac330d",
|
| 5 |
+
"checkpoint": "src/batdetect2/models/checkpoints/batdetect2_uk_same.ckpt",
|
| 6 |
+
"input_name": "input",
|
| 7 |
+
"input_shape": [
|
| 8 |
+
1,
|
| 9 |
+
1,
|
| 10 |
+
128,
|
| 11 |
+
256
|
| 12 |
+
],
|
| 13 |
+
"outputs": {
|
| 14 |
+
"detection_probs": [
|
| 15 |
+
1,
|
| 16 |
+
1,
|
| 17 |
+
128,
|
| 18 |
+
256
|
| 19 |
+
],
|
| 20 |
+
"class_probs": [
|
| 21 |
+
1,
|
| 22 |
+
17,
|
| 23 |
+
128,
|
| 24 |
+
256
|
| 25 |
+
]
|
| 26 |
+
},
|
| 27 |
+
"labels": [
|
| 28 |
+
"MYOMYS",
|
| 29 |
+
"MYOALC",
|
| 30 |
+
"CNESER",
|
| 31 |
+
"PIPNAT",
|
| 32 |
+
"BARBAR",
|
| 33 |
+
"MYONAT",
|
| 34 |
+
"MYODAU",
|
| 35 |
+
"MYOBRA",
|
| 36 |
+
"PIPPIP",
|
| 37 |
+
"MYOBEC",
|
| 38 |
+
"PIPPYG",
|
| 39 |
+
"RHIHIP",
|
| 40 |
+
"NYCLEI",
|
| 41 |
+
"RHIFER",
|
| 42 |
+
"PLEAUR",
|
| 43 |
+
"NYCNOC",
|
| 44 |
+
"PLEAUS"
|
| 45 |
+
],
|
| 46 |
+
"source_labels": [
|
| 47 |
+
"myomys",
|
| 48 |
+
"myoalc",
|
| 49 |
+
"cneser",
|
| 50 |
+
"pipnat",
|
| 51 |
+
"barbar",
|
| 52 |
+
"myonat",
|
| 53 |
+
"myodau",
|
| 54 |
+
"myobra",
|
| 55 |
+
"pippip",
|
| 56 |
+
"myobec",
|
| 57 |
+
"pippyg",
|
| 58 |
+
"rhihip",
|
| 59 |
+
"nyclei",
|
| 60 |
+
"rhifer",
|
| 61 |
+
"pleaur",
|
| 62 |
+
"nycnoc",
|
| 63 |
+
"pleaus"
|
| 64 |
+
],
|
| 65 |
+
"opset": 17,
|
| 66 |
+
"license": "CC BY-NC 4.0",
|
| 67 |
+
"commercial_use": false,
|
| 68 |
+
"onnx_bytes": 7603041,
|
| 69 |
+
"onnx_sha256": "9eddc08f1a22695ffdb1cdb52d947752d83777cd8596554f108bcf701481d340",
|
| 70 |
+
"source_runtime_parity": {
|
| 71 |
+
"fixture": "seeded random float32 tensor (seed 20260818)",
|
| 72 |
+
"detection_maximum_absolute_error": 1.0579824447631836e-06,
|
| 73 |
+
"class_maximum_absolute_error": 5.364418029785156e-07,
|
| 74 |
+
"tolerance": 0.0001
|
| 75 |
+
}
|
| 76 |
+
}
|
golden/class_probs.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fd1d40e8e7399b3310c0679dd948028427dbb336963ada0ab5cba6440e464657
|
| 3 |
+
size 2228352
|
golden/detection_probs.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5440e3d980f0bb594881bbaba0d41b69b267b9d2ba08e50ee5ee485a84f759eb
|
| 3 |
+
size 131200
|
golden/input.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6ef2dc2fd3cd8ad1a201ac07cabfe873f67ff0be40006671a890cbef5521eb43
|
| 3 |
+
size 131200
|
golden/manifest.json
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": 1,
|
| 3 |
+
"purpose": "Deterministic model-ready tensor fixture for the ONNX runtime contract; it does not test raw-audio preprocessing.",
|
| 4 |
+
"seed": 20260818,
|
| 5 |
+
"model": {
|
| 6 |
+
"path": "batdetect2-uk-same.onnx",
|
| 7 |
+
"sha256": "9eddc08f1a22695ffdb1cdb52d947752d83777cd8596554f108bcf701481d340"
|
| 8 |
+
},
|
| 9 |
+
"runtime": {
|
| 10 |
+
"numpy": "2.4.6",
|
| 11 |
+
"onnxruntime": "1.28.0",
|
| 12 |
+
"provider": "CPUExecutionProvider"
|
| 13 |
+
},
|
| 14 |
+
"input": {
|
| 15 |
+
"path": "input.npy",
|
| 16 |
+
"name": "input",
|
| 17 |
+
"dtype": "float32",
|
| 18 |
+
"shape": [
|
| 19 |
+
1,
|
| 20 |
+
1,
|
| 21 |
+
128,
|
| 22 |
+
256
|
| 23 |
+
],
|
| 24 |
+
"generator": "numpy.default_rng(seed).random(dtype=float32)",
|
| 25 |
+
"sha256": "6ef2dc2fd3cd8ad1a201ac07cabfe873f67ff0be40006671a890cbef5521eb43"
|
| 26 |
+
},
|
| 27 |
+
"outputs": [
|
| 28 |
+
{
|
| 29 |
+
"path": "detection_probs.npy",
|
| 30 |
+
"name": "detection_probs",
|
| 31 |
+
"dtype": "float32",
|
| 32 |
+
"shape": [
|
| 33 |
+
1,
|
| 34 |
+
1,
|
| 35 |
+
128,
|
| 36 |
+
256
|
| 37 |
+
],
|
| 38 |
+
"sha256": "5440e3d980f0bb594881bbaba0d41b69b267b9d2ba08e50ee5ee485a84f759eb"
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"path": "class_probs.npy",
|
| 42 |
+
"name": "class_probs",
|
| 43 |
+
"dtype": "float32",
|
| 44 |
+
"shape": [
|
| 45 |
+
1,
|
| 46 |
+
17,
|
| 47 |
+
128,
|
| 48 |
+
256
|
| 49 |
+
],
|
| 50 |
+
"sha256": "fd1d40e8e7399b3310c0679dd948028427dbb336963ada0ab5cba6440e464657"
|
| 51 |
+
}
|
| 52 |
+
],
|
| 53 |
+
"tolerance": {
|
| 54 |
+
"rtol": 1e-05,
|
| 55 |
+
"atol": 1e-06
|
| 56 |
+
}
|
| 57 |
+
}
|
golden/pyproject.toml
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[project]
|
| 2 |
+
name = "batdetect2-uk-same-onnx-fixture"
|
| 3 |
+
version = "0.0.0"
|
| 4 |
+
requires-python = "==3.11.15"
|
| 5 |
+
dependencies = [
|
| 6 |
+
"numpy==2.4.6",
|
| 7 |
+
"onnxruntime==1.28.0",
|
| 8 |
+
]
|
| 9 |
+
|
| 10 |
+
[tool.uv]
|
| 11 |
+
package = false
|
golden/uv.lock
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version = 1
|
| 2 |
+
revision = 3
|
| 3 |
+
requires-python = "==3.11.15"
|
| 4 |
+
|
| 5 |
+
[[package]]
|
| 6 |
+
name = "batdetect2-uk-same-onnx-fixture"
|
| 7 |
+
version = "0.0.0"
|
| 8 |
+
source = { virtual = "." }
|
| 9 |
+
dependencies = [
|
| 10 |
+
{ name = "numpy" },
|
| 11 |
+
{ name = "onnxruntime" },
|
| 12 |
+
]
|
| 13 |
+
|
| 14 |
+
[package.metadata]
|
| 15 |
+
requires-dist = [
|
| 16 |
+
{ name = "numpy", specifier = "==2.4.6" },
|
| 17 |
+
{ name = "onnxruntime", specifier = "==1.28.0" },
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
[[package]]
|
| 21 |
+
name = "flatbuffers"
|
| 22 |
+
version = "25.12.19"
|
| 23 |
+
source = { registry = "https://pypi.org/simple" }
|
| 24 |
+
wheels = [
|
| 25 |
+
{ url = "https://files.pythonhosted.org/packages/e8/2d/d2a548598be01649e2d46231d151a6c56d10b964d94043a335ae56ea2d92/flatbuffers-25.12.19-py2.py3-none-any.whl", hash = "sha256:7634f50c427838bb021c2d66a3d1168e9d199b0607e6329399f04846d42e20b4", size = 26661, upload-time = "2025-12-19T23:16:13.622Z" },
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
[[package]]
|
| 29 |
+
name = "numpy"
|
| 30 |
+
version = "2.4.6"
|
| 31 |
+
source = { registry = "https://pypi.org/simple" }
|
| 32 |
+
sdist = { url = "https://files.pythonhosted.org/packages/d0/ad/fed0499ce6a338d2a03ebae59cd15093910c8875328855781952abf6c2fe/numpy-2.4.6.tar.gz", hash = "sha256:f3a3570c4a2a16746ac2c31a7c7c7b0c186b95ce902e33db6f28094ed7387dda", size = 20735807, upload-time = "2026-05-18T23:37:14.07Z" }
|
| 33 |
+
wheels = [
|
| 34 |
+
{ url = "https://files.pythonhosted.org/packages/b3/49/ec46835a70be8fa6446c495126ac84fdb28cb2558e1620ffb87a10c8b64c/numpy-2.4.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:0280e0356c0829a18d9de1cb7eee50ec22ca639878d7240307ca0943d73cd2c4", size = 16969194, upload-time = "2026-05-18T23:33:13.503Z" },
|
| 35 |
+
{ url = "https://files.pythonhosted.org/packages/0e/0d/f5957185c0ee2f3e12f78715aa9e3b353fd83633316c8532b38faa37e3f6/numpy-2.4.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:110f8b71aacb688ec69062bb7f6938a0f8acb01b7c1c4beb453c65b6d234584d", size = 14964111, upload-time = "2026-05-18T23:33:17.795Z" },
|
| 36 |
+
{ url = "https://files.pythonhosted.org/packages/ad/40/40a40ee0ddf7ceb782c49af278894b686e586d65d8c1889c8b5da01a3d7d/numpy-2.4.6-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:4cfe66903cc32a9921a6733d96b19bb6abf310397581bbad89c228f5abaf0ee8", size = 5469159, upload-time = "2026-05-18T23:33:20.654Z" },
|
| 37 |
+
{ url = "https://files.pythonhosted.org/packages/63/13/f9a8046535cb21deae82f8d03de9617e08882d274fad2539630761888228/numpy-2.4.6-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:8155154c7c691289fe18f510b5d4657c68c67989f293f0535a91360392ff6538", size = 6798936, upload-time = "2026-05-18T23:33:22.987Z" },
|
| 38 |
+
{ url = "https://files.pythonhosted.org/packages/33/a8/6fa8c1a345a8c85dbb21932c447bee07c30a2c2a3f31e369c0a84b300147/numpy-2.4.6-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0ab0a9c4ffb1a6d95ef519fe4247dba8eb6b18ad93999f76b7f657039acabd47", size = 15966692, upload-time = "2026-05-18T23:33:26.62Z" },
|
| 39 |
+
{ url = "https://files.pythonhosted.org/packages/02/03/74fe2a4cb3817d94d86402f2506554130a2f01414e299b5a843e5a8a957f/numpy-2.4.6-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:89cd468399cfd2504718f0ba50e410dca55a170b61a02ad92bb18c8a65186e93", size = 16918164, upload-time = "2026-05-18T23:33:29.955Z" },
|
| 40 |
+
{ url = "https://files.pythonhosted.org/packages/c5/80/3615be3313f7e7696609bc194b9f0101da809df79e859bdb84e0cd043f46/numpy-2.4.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:c2d37ab77531417474168eb79d6d80b14f821a966818505d03013d0833edb7a8", size = 17322877, upload-time = "2026-05-18T23:33:34.724Z" },
|
| 41 |
+
{ url = "https://files.pythonhosted.org/packages/ca/ac/a691e0fe2675e370d0e08ff905adc49a1c8830e8cae03efe4477e92cd55d/numpy-2.4.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f407cb6b8e9d6d8c626bc73c945db1706035af8fd632295547bf1c9e46d092d6", size = 18651487, upload-time = "2026-05-18T23:33:38.217Z" },
|
| 42 |
+
{ url = "https://files.pythonhosted.org/packages/15/a7/9bc1cd626d7bf6869bfedf27b91b6ab5dd607758bf8e959d6fa80c6a59cb/numpy-2.4.6-cp311-cp311-win32.whl", hash = "sha256:ddea102b48f9e339f3948bf22040944184627a30fdf7f858667673b9c5f033c8", size = 6233945, upload-time = "2026-05-18T23:33:41.331Z" },
|
| 43 |
+
{ url = "https://files.pythonhosted.org/packages/c5/31/7fc6239c12bce7e931463251cca4426c465e1876ba3cc785402ef4dd8f4e/numpy-2.4.6-cp311-cp311-win_amd64.whl", hash = "sha256:1e254a00cdf42b1e4d5b3d68d33af63268d41340d8885df2ab6470f2e1500147", size = 12608406, upload-time = "2026-05-18T23:33:44.131Z" },
|
| 44 |
+
{ url = "https://files.pythonhosted.org/packages/27/83/140f85a466595a16382996a1bf06b2b54bcd597488921b0c9daaeeda72af/numpy-2.4.6-cp311-cp311-win_arm64.whl", hash = "sha256:ed9749eef4cbd126da3dc1d6bcb3a57f5eb7ac6a6484146bdbf743f552dfc577", size = 10479528, upload-time = "2026-05-18T23:33:50.725Z" },
|
| 45 |
+
{ url = "https://files.pythonhosted.org/packages/de/12/b422cc84439adc0d00de605bf4a308890ae5c26f2c71fbd73e5d08fbb0dd/numpy-2.4.6-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:55cced7c52e981362f708ad635198e97a752dfba412cc03c23bbf3bd8d5cd662", size = 16847511, upload-time = "2026-05-18T23:36:50.673Z" },
|
| 46 |
+
{ url = "https://files.pythonhosted.org/packages/44/53/f481bef68011740f8849418d82db07230e825013f31f4eef5ba5b805316a/numpy-2.4.6-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:d6da64deb6b8ed903e7560180a92f2d804ee1ba5eeb849ac2748b8c1aba1f6d7", size = 14889064, upload-time = "2026-05-18T23:36:53.879Z" },
|
| 47 |
+
{ url = "https://files.pythonhosted.org/packages/7f/57/42ed575c10ced8af951d426bc4e1f8aff16fd851db33f067036215a7f860/numpy-2.4.6-pp311-pypy311_pp73-macosx_14_0_arm64.whl", hash = "sha256:68a5124b13fa6cc2086764a20005d30bc0548146f7f5322f02fce212ca14317f", size = 5394157, upload-time = "2026-05-18T23:36:57.194Z" },
|
| 48 |
+
{ url = "https://files.pythonhosted.org/packages/6a/ef/f66cc724fcc36c1e364c67f51ae9146090b8b584f27d58b97fdae3edd737/numpy-2.4.6-pp311-pypy311_pp73-macosx_14_0_x86_64.whl", hash = "sha256:948424b06129ce883307e8cff868c31396d8dc7630a59c61d70d98dbe70f222c", size = 6708728, upload-time = "2026-05-18T23:36:59.575Z" },
|
| 49 |
+
{ url = "https://files.pythonhosted.org/packages/1a/9c/c531f2293b91265d8b48e9b329f54fdd7ffae73cb4134ea10cca4237e9cc/numpy-2.4.6-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5dbbdb29840ca3d91ee0fece42fc29278886d908280bfec0a5846c6f901a3eb0", size = 15798374, upload-time = "2026-05-18T23:37:02.674Z" },
|
| 50 |
+
{ url = "https://files.pythonhosted.org/packages/1a/b0/413077f6b1153ed3cba361401c6783bbad6114804a000cc22eb71c13e190/numpy-2.4.6-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8ad03c0965fb3c692200e74d458ca28c1dbb4ce96f9a479a8aa041ad5fabca02", size = 16747286, upload-time = "2026-05-18T23:37:06.327Z" },
|
| 51 |
+
{ url = "https://files.pythonhosted.org/packages/15/ce/e5ec180bc41812edcd8daeb8639d205622c0e8c02259d8ab25a0201b3c2a/numpy-2.4.6-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:2803abfebfc990042cd494d8ce2d5f82e9d847af6d35ec486923aa19dbad5e73", size = 12504263, upload-time = "2026-05-18T23:37:09.715Z" },
|
| 52 |
+
]
|
| 53 |
+
|
| 54 |
+
[[package]]
|
| 55 |
+
name = "onnxruntime"
|
| 56 |
+
version = "1.28.0"
|
| 57 |
+
source = { registry = "https://pypi.org/simple" }
|
| 58 |
+
dependencies = [
|
| 59 |
+
{ name = "flatbuffers" },
|
| 60 |
+
{ name = "numpy" },
|
| 61 |
+
{ name = "packaging" },
|
| 62 |
+
{ name = "protobuf" },
|
| 63 |
+
]
|
| 64 |
+
wheels = [
|
| 65 |
+
{ url = "https://files.pythonhosted.org/packages/17/4d/5014667e2a3a77d6e1b74cc3d88948d06163b8e0a33a84c85073322b5dec/onnxruntime-1.28.0-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:f5c5daabd28aad610f83fdcf32acec8fb57e6adc6c6a39fe2a3c755db957b410", size = 19130506, upload-time = "2026-07-25T01:22:34.489Z" },
|
| 66 |
+
{ url = "https://files.pythonhosted.org/packages/ea/97/b7ce1bc8bb6048b5fe9129f55d6506dc19499068ef2e0a0af1ae3c8aa4e7/onnxruntime-1.28.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8d66f9ceb29909c70839e4e4fb3435c7b490050d8f162bd5f3aba4ca01ee517f", size = 17039880, upload-time = "2026-07-25T01:21:37.538Z" },
|
| 67 |
+
{ url = "https://files.pythonhosted.org/packages/f3/17/4e5ecd8764f87573c495d834ce79e61ecca47f7a01d1e444a606e570edcb/onnxruntime-1.28.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a166b78ee04f3a37fa1ef82034b6a3ce96d9684e582d4d30b296de83e9998bb5", size = 19193162, upload-time = "2026-07-25T01:21:59.151Z" },
|
| 68 |
+
{ url = "https://files.pythonhosted.org/packages/9f/10/3d946d5d5f2cdcc3c8da36cae63190c516d16349edaffd944bda60ca4c3e/onnxruntime-1.28.0-cp311-cp311-win_amd64.whl", hash = "sha256:0d650aeee29368414367b65529e90afe4bf1bab76254789063b8b2f7ea3013c8", size = 13752539, upload-time = "2026-07-25T01:22:24.524Z" },
|
| 69 |
+
{ url = "https://files.pythonhosted.org/packages/8f/74/1c440be7af1e026280b139caa1be5d11bd4dc368011ddbe8f5362b58e12f/onnxruntime-1.28.0-cp311-cp311-win_arm64.whl", hash = "sha256:0faf85fb447a663c9cdadc39bd6b19bdf7bedded6699e45731b9b36c46fd993d", size = 13449940, upload-time = "2026-07-25T01:22:14.97Z" },
|
| 70 |
+
]
|
| 71 |
+
|
| 72 |
+
[[package]]
|
| 73 |
+
name = "packaging"
|
| 74 |
+
version = "26.3"
|
| 75 |
+
source = { registry = "https://pypi.org/simple" }
|
| 76 |
+
sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" }
|
| 77 |
+
wheels = [
|
| 78 |
+
{ url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" },
|
| 79 |
+
]
|
| 80 |
+
|
| 81 |
+
[[package]]
|
| 82 |
+
name = "protobuf"
|
| 83 |
+
version = "7.35.1"
|
| 84 |
+
source = { registry = "https://pypi.org/simple" }
|
| 85 |
+
sdist = { url = "https://files.pythonhosted.org/packages/da/01/9ef0afd7999eb9badb3a768b4aedd78c86d4c65cfaf1958ab276199e76b4/protobuf-7.35.1.tar.gz", hash = "sha256:ce115a26fe0c39a2c29973d914d327e516a6455464489fe3cd1e51a1b354f81a", size = 458717, upload-time = "2026-06-11T21:55:40.257Z" }
|
| 86 |
+
wheels = [
|
| 87 |
+
{ url = "https://files.pythonhosted.org/packages/10/03/8aeeb7458d22546bf64b5250ca1daeb5ff757d900e8e4a7476c6f0db843e/protobuf-7.35.1-cp310-abi3-macosx_10_9_universal2.whl", hash = "sha256:24f857477359a85c0c235261b8ba905fd51b2562f4a64ca1df5473f29850cbf6", size = 433226, upload-time = "2026-06-11T21:55:31.719Z" },
|
| 88 |
+
{ url = "https://files.pythonhosted.org/packages/37/4b/dfb89eb0e652a1ff073c39a59fb5e3a83cfe9b57a2c83fa6d78270101767/protobuf-7.35.1-cp310-abi3-manylinux2014_aarch64.whl", hash = "sha256:11d6b0ec246892d85215b0a13ca6e0233cf5284b68f0ac02646427f4ff88a799", size = 328847, upload-time = "2026-06-11T21:55:34.035Z" },
|
| 89 |
+
{ url = "https://files.pythonhosted.org/packages/0f/58/dc12f2cd484951524af6e3382c785869b9b3fb5e52ee95ae23add53ee8f9/protobuf-7.35.1-cp310-abi3-manylinux2014_s390x.whl", hash = "sha256:b73f9489a4b8b1c9cb1f8ed951c736392592edb24b9d6819f36d2e10b171d5b4", size = 344030, upload-time = "2026-06-11T21:55:34.941Z" },
|
| 90 |
+
{ url = "https://files.pythonhosted.org/packages/e4/be/5b3cfe508bfab6761414ff944e3366eb13be4fd71efcd69450f89ba39f43/protobuf-7.35.1-cp310-abi3-manylinux2014_x86_64.whl", hash = "sha256:74758715c53d7158fb76caf4f0cfdacc5329a4b1bb994f865d6cf302d413a1c4", size = 327130, upload-time = "2026-06-11T21:55:35.921Z" },
|
| 91 |
+
{ url = "https://files.pythonhosted.org/packages/d8/bc/6d6c7ba8709c85f8f2c390b2b118d6fb08a783676a572271851bf45a7d22/protobuf-7.35.1-cp310-abi3-win32.whl", hash = "sha256:353652e4efd0bca5b5fc2656abf8307ef351f0cf938c9eba09f0e09c20a25c30", size = 428945, upload-time = "2026-06-11T21:55:37.034Z" },
|
| 92 |
+
{ url = "https://files.pythonhosted.org/packages/0a/19/8d0cb6f20a1ef7b18f1c8986ad5783f22f84cce39c6ce9a6e645ea55192e/protobuf-7.35.1-cp310-abi3-win_amd64.whl", hash = "sha256:230a75ddfc2de4806e56696ce9640c1cdfdb6543b7cfce98d42a4c0a0e7bdb87", size = 439996, upload-time = "2026-06-11T21:55:38.123Z" },
|
| 93 |
+
{ url = "https://files.pythonhosted.org/packages/19/c7/5f7c636ec43e0c545e28d1f1db71990108306f7bdcb89f069ba97e428e7f/protobuf-7.35.1-py3-none-any.whl", hash = "sha256:4bc97768d8fe4ad6743c8a19403e314511ed9f6d13205b687e52421c023ac1b9", size = 171659, upload-time = "2026-06-11T21:55:39.155Z" },
|
| 94 |
+
]
|
labels.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"labels": [
|
| 3 |
+
"MYOMYS", "MYOALC", "CNESER", "PIPNAT", "BARBAR", "MYONAT",
|
| 4 |
+
"MYODAU", "MYOBRA", "PIPPIP", "MYOBEC", "PIPPYG", "RHIHIP",
|
| 5 |
+
"NYCLEI", "RHIFER", "PLEAUR", "NYCNOC", "PLEAUS"
|
| 6 |
+
]
|
| 7 |
+
}
|
preprocessing/README.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Preprocessing reference
|
| 2 |
+
|
| 3 |
+
The ONNX model starts at a normalized mono spectrogram tensor with shape `[1, 1, 128, 256]`. It
|
| 4 |
+
does not accept raw audio.
|
| 5 |
+
|
| 6 |
+
The Python files under [`upstream/`](upstream/) are an unchanged copy of BatDetect2's complete
|
| 7 |
+
`src/batdetect2/preprocess` package at revision
|
| 8 |
+
`9e2697458d3b3b03c30ccd7e49ed5409c8ac330d`. [View the same pinned directory upstream](https://github.com/macaodha/batdetect2/tree/9e2697458d3b3b03c30ccd7e49ed5409c8ac330d/src/batdetect2/preprocess).
|
| 9 |
+
|
| 10 |
+
These files depend on the rest of the BatDetect2 package. Use `scripts/fetch-upstream.sh` to
|
| 11 |
+
retrieve the complete pinned checkout, or the locked environment in `environment/` when
|
| 12 |
+
rebuilding the export. The reference copy remains subject to CC BY-NC 4.0.
|
preprocessing/upstream/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Main entry point for the BatDetect2 preprocessing subsystem."""
|
| 2 |
+
|
| 3 |
+
from batdetect2.audio import TARGET_SAMPLERATE_HZ
|
| 4 |
+
from batdetect2.preprocess.config import PreprocessingConfig
|
| 5 |
+
from batdetect2.preprocess.preprocessor import Preprocessor, build_preprocessor
|
| 6 |
+
from batdetect2.preprocess.spectrogram import MAX_FREQ, MIN_FREQ
|
| 7 |
+
from batdetect2.preprocess.types import PreprocessorProtocol
|
| 8 |
+
|
| 9 |
+
__all__ = [
|
| 10 |
+
"PreprocessorProtocol",
|
| 11 |
+
"MAX_FREQ",
|
| 12 |
+
"MIN_FREQ",
|
| 13 |
+
"PreprocessingConfig",
|
| 14 |
+
"Preprocessor",
|
| 15 |
+
"TARGET_SAMPLERATE_HZ",
|
| 16 |
+
"build_preprocessor",
|
| 17 |
+
]
|
preprocessing/upstream/audio.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Audio-level transforms applied to waveforms before spectrogram computation.
|
| 2 |
+
|
| 3 |
+
This module defines ``torch.nn.Module`` transforms that operate on raw
|
| 4 |
+
audio tensors and the Pydantic configuration classes that control them.
|
| 5 |
+
Each transform is registered in the ``audio_transforms`` registry so that
|
| 6 |
+
the pipeline can be assembled from a configuration object.
|
| 7 |
+
|
| 8 |
+
The supported transforms are:
|
| 9 |
+
|
| 10 |
+
* ``CenterAudio`` — subtract the DC offset (mean) from the waveform.
|
| 11 |
+
* ``ScaleAudio`` — peak-normalise the waveform to the range ``[-1, 1]``.
|
| 12 |
+
* ``FixDuration`` — truncate or zero-pad the waveform to a fixed length.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from typing import Annotated, Literal
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
from pydantic import Field
|
| 19 |
+
|
| 20 |
+
from batdetect2.audio import TARGET_SAMPLERATE_HZ
|
| 21 |
+
from batdetect2.core import (
|
| 22 |
+
BaseConfig,
|
| 23 |
+
ImportConfig,
|
| 24 |
+
Registry,
|
| 25 |
+
add_import_config,
|
| 26 |
+
)
|
| 27 |
+
from batdetect2.preprocess.common import center_tensor, peak_normalize
|
| 28 |
+
|
| 29 |
+
__all__ = [
|
| 30 |
+
"AudioTransformImportConfig",
|
| 31 |
+
"CenterAudioConfig",
|
| 32 |
+
"ScaleAudioConfig",
|
| 33 |
+
"FixDurationConfig",
|
| 34 |
+
"build_audio_transform",
|
| 35 |
+
]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
audio_transforms: Registry[torch.nn.Module, [int]] = Registry(
|
| 39 |
+
"audio_transform"
|
| 40 |
+
)
|
| 41 |
+
"""Registry mapping audio transform config classes to their builder methods."""
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@add_import_config(audio_transforms)
|
| 45 |
+
class AudioTransformImportConfig(ImportConfig):
|
| 46 |
+
"""Use any callable as an audio transform.
|
| 47 |
+
|
| 48 |
+
Set ``name="import"`` and provide a ``target`` pointing to any
|
| 49 |
+
callable to use it instead of a built-in option.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
name: Literal["import"] = "import"
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class CenterAudioConfig(BaseConfig):
|
| 56 |
+
"""Configuration for the DC-offset removal transform.
|
| 57 |
+
|
| 58 |
+
Attributes
|
| 59 |
+
----------
|
| 60 |
+
name : str
|
| 61 |
+
Fixed identifier; always ``"center_audio"``.
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
name: Literal["center_audio"] = "center_audio"
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class CenterAudio(torch.nn.Module):
|
| 68 |
+
"""Remove the DC offset from an audio waveform.
|
| 69 |
+
|
| 70 |
+
Subtracts the global mean of the waveform from every sample,
|
| 71 |
+
centring the signal around zero. This is useful when an analogue
|
| 72 |
+
recording chain introduces a constant voltage bias.
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
def forward(self, wav: torch.Tensor) -> torch.Tensor:
|
| 76 |
+
"""Subtract the mean from the waveform.
|
| 77 |
+
|
| 78 |
+
Parameters
|
| 79 |
+
----------
|
| 80 |
+
wav : torch.Tensor
|
| 81 |
+
Input waveform tensor of shape ``(samples,)`` or
|
| 82 |
+
``(channels, samples)``.
|
| 83 |
+
|
| 84 |
+
Returns
|
| 85 |
+
-------
|
| 86 |
+
torch.Tensor
|
| 87 |
+
Zero-centred waveform with the same shape as the input.
|
| 88 |
+
"""
|
| 89 |
+
return center_tensor(wav)
|
| 90 |
+
|
| 91 |
+
@audio_transforms.register(CenterAudioConfig)
|
| 92 |
+
@staticmethod
|
| 93 |
+
def from_config(config: CenterAudioConfig, samplerate: int):
|
| 94 |
+
return CenterAudio()
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class ScaleAudioConfig(BaseConfig):
|
| 98 |
+
"""Configuration for the peak-normalisation transform.
|
| 99 |
+
|
| 100 |
+
Attributes
|
| 101 |
+
----------
|
| 102 |
+
name : str
|
| 103 |
+
Fixed identifier; always ``"scale_audio"``.
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
name: Literal["scale_audio"] = "scale_audio"
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class ScaleAudio(torch.nn.Module):
|
| 110 |
+
"""Peak-normalise an audio waveform to the range ``[-1, 1]``.
|
| 111 |
+
|
| 112 |
+
Divides the waveform by its largest absolute sample value. If the
|
| 113 |
+
waveform is identically zero it is returned unchanged.
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
def forward(self, wav: torch.Tensor) -> torch.Tensor:
|
| 117 |
+
"""Peak-normalise the waveform.
|
| 118 |
+
|
| 119 |
+
Parameters
|
| 120 |
+
----------
|
| 121 |
+
wav : torch.Tensor
|
| 122 |
+
Input waveform tensor of any shape.
|
| 123 |
+
|
| 124 |
+
Returns
|
| 125 |
+
-------
|
| 126 |
+
torch.Tensor
|
| 127 |
+
Normalised waveform with the same shape as the input and
|
| 128 |
+
values in the range ``[-1, 1]``.
|
| 129 |
+
"""
|
| 130 |
+
return peak_normalize(wav)
|
| 131 |
+
|
| 132 |
+
@audio_transforms.register(ScaleAudioConfig)
|
| 133 |
+
@staticmethod
|
| 134 |
+
def from_config(config: ScaleAudioConfig, samplerate: int):
|
| 135 |
+
return ScaleAudio()
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class FixDurationConfig(BaseConfig):
|
| 139 |
+
"""Configuration for the fixed-duration transform.
|
| 140 |
+
|
| 141 |
+
Attributes
|
| 142 |
+
----------
|
| 143 |
+
name : str
|
| 144 |
+
Fixed identifier; always ``"fix_duration"``.
|
| 145 |
+
duration : float, default=0.5
|
| 146 |
+
Target duration in seconds. The waveform will be truncated or
|
| 147 |
+
zero-padded to match this length.
|
| 148 |
+
"""
|
| 149 |
+
|
| 150 |
+
name: Literal["fix_duration"] = "fix_duration"
|
| 151 |
+
duration: float = 0.5
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
class FixDuration(torch.nn.Module):
|
| 155 |
+
"""Ensure a waveform has exactly a specified number of samples.
|
| 156 |
+
|
| 157 |
+
If the input is longer than the target length it is truncated from
|
| 158 |
+
the end. If it is shorter, it is zero-padded at the end.
|
| 159 |
+
|
| 160 |
+
Parameters
|
| 161 |
+
----------
|
| 162 |
+
samplerate : int
|
| 163 |
+
Sample rate of the audio in Hz. Used with ``duration`` to
|
| 164 |
+
compute the target number of samples.
|
| 165 |
+
duration : float
|
| 166 |
+
Target duration in seconds.
|
| 167 |
+
"""
|
| 168 |
+
|
| 169 |
+
def __init__(self, samplerate: int, duration: float):
|
| 170 |
+
super().__init__()
|
| 171 |
+
self.samplerate = samplerate
|
| 172 |
+
self.duration = duration
|
| 173 |
+
self.length = int(samplerate * duration)
|
| 174 |
+
|
| 175 |
+
def forward(self, wav: torch.Tensor) -> torch.Tensor:
|
| 176 |
+
"""Truncate or pad the waveform to the target length.
|
| 177 |
+
|
| 178 |
+
Parameters
|
| 179 |
+
----------
|
| 180 |
+
wav : torch.Tensor
|
| 181 |
+
Input waveform tensor of shape ``(samples,)`` or
|
| 182 |
+
``(channels, samples)``. The last dimension is adjusted.
|
| 183 |
+
|
| 184 |
+
Returns
|
| 185 |
+
-------
|
| 186 |
+
torch.Tensor
|
| 187 |
+
Waveform with exactly ``self.length`` samples along the last
|
| 188 |
+
dimension.
|
| 189 |
+
"""
|
| 190 |
+
length = wav.shape[-1]
|
| 191 |
+
|
| 192 |
+
if length == self.length:
|
| 193 |
+
return wav
|
| 194 |
+
|
| 195 |
+
if length > self.length:
|
| 196 |
+
return wav[: self.length]
|
| 197 |
+
|
| 198 |
+
return torch.nn.functional.pad(wav, (0, self.length - length))
|
| 199 |
+
|
| 200 |
+
@audio_transforms.register(FixDurationConfig)
|
| 201 |
+
@staticmethod
|
| 202 |
+
def from_config(config: FixDurationConfig, samplerate: int):
|
| 203 |
+
return FixDuration(samplerate=samplerate, duration=config.duration)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
AudioTransform = Annotated[
|
| 207 |
+
FixDurationConfig | ScaleAudioConfig | CenterAudioConfig,
|
| 208 |
+
Field(discriminator="name"),
|
| 209 |
+
]
|
| 210 |
+
"""Discriminated union of all audio transform configuration types.
|
| 211 |
+
|
| 212 |
+
Use this type when a field should accept any of the supported audio
|
| 213 |
+
transforms. Pydantic will select the correct config class based on the
|
| 214 |
+
``name`` field.
|
| 215 |
+
"""
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def build_audio_transform(
|
| 219 |
+
config: AudioTransform,
|
| 220 |
+
samplerate: int = TARGET_SAMPLERATE_HZ,
|
| 221 |
+
) -> torch.nn.Module:
|
| 222 |
+
"""Build an audio transform module from a configuration object.
|
| 223 |
+
|
| 224 |
+
Parameters
|
| 225 |
+
----------
|
| 226 |
+
config : AudioTransform
|
| 227 |
+
A configuration object for one of the supported audio transforms
|
| 228 |
+
(``CenterAudioConfig``, ``ScaleAudioConfig``, or
|
| 229 |
+
``FixDurationConfig``).
|
| 230 |
+
samplerate : int, default=256000
|
| 231 |
+
Sample rate of the audio in Hz. Passed to the transform builder;
|
| 232 |
+
some transforms (e.g. ``FixDuration``) use it to convert seconds
|
| 233 |
+
to samples.
|
| 234 |
+
|
| 235 |
+
Returns
|
| 236 |
+
-------
|
| 237 |
+
torch.nn.Module
|
| 238 |
+
The constructed audio transform module.
|
| 239 |
+
"""
|
| 240 |
+
return audio_transforms.build(config, samplerate)
|
preprocessing/upstream/common.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared tensor primitives used across the preprocessing pipeline.
|
| 2 |
+
|
| 3 |
+
This module provides small, stateless helper functions that operate on
|
| 4 |
+
PyTorch tensors. They are used by both audio-level and spectrogram-level
|
| 5 |
+
transforms, and are kept here to avoid duplication.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
__all__ = [
|
| 11 |
+
"center_tensor",
|
| 12 |
+
"peak_normalize",
|
| 13 |
+
]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def center_tensor(tensor: torch.Tensor) -> torch.Tensor:
|
| 17 |
+
"""Subtract the mean of a tensor from all of its values.
|
| 18 |
+
|
| 19 |
+
This centres the signal around zero, removing any constant DC offset.
|
| 20 |
+
|
| 21 |
+
Parameters
|
| 22 |
+
----------
|
| 23 |
+
tensor : torch.Tensor
|
| 24 |
+
Input tensor of any shape.
|
| 25 |
+
|
| 26 |
+
Returns
|
| 27 |
+
-------
|
| 28 |
+
torch.Tensor
|
| 29 |
+
A new tensor of the same shape and dtype with the global mean
|
| 30 |
+
subtracted from every element.
|
| 31 |
+
"""
|
| 32 |
+
return tensor - tensor.mean()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def peak_normalize(tensor: torch.Tensor) -> torch.Tensor:
|
| 36 |
+
"""Scale a tensor so that its largest absolute value equals one.
|
| 37 |
+
|
| 38 |
+
Divides the tensor by its peak absolute value. If the tensor is
|
| 39 |
+
identically zero, it is returned unchanged (no division by zero).
|
| 40 |
+
|
| 41 |
+
Parameters
|
| 42 |
+
----------
|
| 43 |
+
tensor : torch.Tensor
|
| 44 |
+
Input tensor of any shape.
|
| 45 |
+
|
| 46 |
+
Returns
|
| 47 |
+
-------
|
| 48 |
+
torch.Tensor
|
| 49 |
+
A new tensor of the same shape and dtype with values in the range
|
| 50 |
+
``[-1, 1]`` (or exactly ``[0, 0]`` for a zero tensor).
|
| 51 |
+
"""
|
| 52 |
+
max_value = tensor.abs().max()
|
| 53 |
+
|
| 54 |
+
denominator = torch.where(
|
| 55 |
+
max_value == 0,
|
| 56 |
+
torch.tensor(1.0, device=tensor.device, dtype=tensor.dtype),
|
| 57 |
+
max_value,
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
return tensor / denominator
|
preprocessing/upstream/config.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Configuration for the full batdetect2 preprocessing pipeline.
|
| 2 |
+
|
| 3 |
+
This module defines :class:`PreprocessingConfig`, which aggregates all
|
| 4 |
+
configuration needed to convert a raw audio waveform into a normalised
|
| 5 |
+
spectrogram ready for the detection model.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from typing import List
|
| 9 |
+
|
| 10 |
+
from pydantic import Field
|
| 11 |
+
|
| 12 |
+
from batdetect2.core.configs import BaseConfig
|
| 13 |
+
from batdetect2.preprocess.audio import AudioTransform
|
| 14 |
+
from batdetect2.preprocess.spectrogram import (
|
| 15 |
+
FrequencyConfig,
|
| 16 |
+
PcenConfig,
|
| 17 |
+
ResizeConfig,
|
| 18 |
+
SpectralMeanSubtractionConfig,
|
| 19 |
+
SpectrogramTransform,
|
| 20 |
+
STFTConfig,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
__all__ = [
|
| 24 |
+
"AudioTransform",
|
| 25 |
+
"PreprocessingConfig",
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _default_spectrogram_transforms() -> list[SpectrogramTransform]:
|
| 30 |
+
return [
|
| 31 |
+
PcenConfig(),
|
| 32 |
+
SpectralMeanSubtractionConfig(),
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class PreprocessingConfig(BaseConfig):
|
| 37 |
+
"""Unified configuration for the audio preprocessing pipeline.
|
| 38 |
+
|
| 39 |
+
Aggregates the parameters for every stage of the pipeline:
|
| 40 |
+
audio-level transforms, STFT computation, frequency cropping,
|
| 41 |
+
spectrogram-level transforms, and the final resize step.
|
| 42 |
+
|
| 43 |
+
Attributes
|
| 44 |
+
----------
|
| 45 |
+
audio_transforms : list of AudioTransform, default=[]
|
| 46 |
+
Ordered list of transforms applied to the raw audio waveform
|
| 47 |
+
before the STFT is computed. Each entry is a configuration
|
| 48 |
+
object for one of the supported audio transforms
|
| 49 |
+
(``"center_audio"``, ``"scale_audio"``, or ``"fix_duration"``).
|
| 50 |
+
spectrogram_transforms : list of SpectrogramTransform
|
| 51 |
+
Ordered list of transforms applied to the cropped spectrogram
|
| 52 |
+
after the STFT and frequency crop steps. Defaults to
|
| 53 |
+
``[PcenConfig(), SpectralMeanSubtractionConfig()]``, which
|
| 54 |
+
applies PCEN followed by spectral mean subtraction.
|
| 55 |
+
stft : STFTConfig
|
| 56 |
+
Parameters for the Short-Time Fourier Transform (window
|
| 57 |
+
duration, overlap, and window function).
|
| 58 |
+
frequencies : FrequencyConfig
|
| 59 |
+
Frequency range (in Hz) to retain after the STFT.
|
| 60 |
+
size : ResizeConfig
|
| 61 |
+
Target height (number of frequency bins) and time-axis scaling
|
| 62 |
+
factor for the final resize step.
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
audio_transforms: List[AudioTransform] = Field(default_factory=list)
|
| 66 |
+
|
| 67 |
+
spectrogram_transforms: List[SpectrogramTransform] = Field(
|
| 68 |
+
default_factory=_default_spectrogram_transforms
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
stft: STFTConfig = Field(default_factory=STFTConfig)
|
| 72 |
+
|
| 73 |
+
frequencies: FrequencyConfig = Field(default_factory=FrequencyConfig)
|
| 74 |
+
|
| 75 |
+
size: ResizeConfig = Field(default_factory=ResizeConfig)
|
preprocessing/upstream/preprocessor.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Assembles the full batdetect2 preprocessing pipeline.
|
| 2 |
+
|
| 3 |
+
This module defines :class:`Preprocessor`, the concrete implementation of
|
| 4 |
+
:class:`~batdetect2.preprocess.types.PreprocessorProtocol`, and the
|
| 5 |
+
:func:`build_preprocessor` factory function that constructs it from a
|
| 6 |
+
:class:`~batdetect2.preprocess.config.PreprocessingConfig`.
|
| 7 |
+
|
| 8 |
+
The preprocessing pipeline converts a raw audio waveform (as a
|
| 9 |
+
``torch.Tensor``) into a normalised, cropped, and resized spectrogram ready
|
| 10 |
+
for the detection model. The stages are applied in this order:
|
| 11 |
+
|
| 12 |
+
1. **Audio transforms** — optional waveform-level operations such as DC
|
| 13 |
+
removal, peak normalisation, or duration fixing.
|
| 14 |
+
2. **STFT** — Short-Time Fourier Transform to produce an amplitude
|
| 15 |
+
spectrogram.
|
| 16 |
+
3. **Frequency crop** — retain only the frequency band of interest.
|
| 17 |
+
4. **Spectrogram transforms** — normalisation operations such as PCEN and
|
| 18 |
+
spectral mean subtraction.
|
| 19 |
+
5. **Resize** — scale the spectrogram to the model's expected height and
|
| 20 |
+
reduce the time resolution.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
from loguru import logger
|
| 25 |
+
|
| 26 |
+
from batdetect2.audio import TARGET_SAMPLERATE_HZ
|
| 27 |
+
from batdetect2.preprocess.audio import build_audio_transform
|
| 28 |
+
from batdetect2.preprocess.config import PreprocessingConfig
|
| 29 |
+
from batdetect2.preprocess.spectrogram import (
|
| 30 |
+
_spec_params_from_config,
|
| 31 |
+
build_spectrogram_builder,
|
| 32 |
+
build_spectrogram_crop,
|
| 33 |
+
build_spectrogram_resizer,
|
| 34 |
+
build_spectrogram_transform,
|
| 35 |
+
)
|
| 36 |
+
from batdetect2.preprocess.types import PreprocessorProtocol
|
| 37 |
+
|
| 38 |
+
__all__ = [
|
| 39 |
+
"Preprocessor",
|
| 40 |
+
"build_preprocessor",
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class Preprocessor(torch.nn.Module, PreprocessorProtocol):
|
| 45 |
+
"""Standard implementation of the :class:`~batdetect2.preprocess.types.PreprocessorProtocol`.
|
| 46 |
+
|
| 47 |
+
Wraps all preprocessing stages as ``torch.nn.Module`` submodules so
|
| 48 |
+
that parameters (e.g. PCEN filter coefficients) can be tracked and
|
| 49 |
+
moved between devices.
|
| 50 |
+
|
| 51 |
+
Parameters
|
| 52 |
+
----------
|
| 53 |
+
config : PreprocessingConfig
|
| 54 |
+
Full pipeline configuration.
|
| 55 |
+
input_samplerate : int
|
| 56 |
+
Sample rate of the audio that will be passed to this preprocessor,
|
| 57 |
+
in Hz.
|
| 58 |
+
|
| 59 |
+
Attributes
|
| 60 |
+
----------
|
| 61 |
+
input_samplerate : int
|
| 62 |
+
Sample rate of the input audio in Hz.
|
| 63 |
+
output_samplerate : float
|
| 64 |
+
Effective frame rate of the output spectrogram in frames per second.
|
| 65 |
+
Computed from the STFT hop length and the time-axis resize factor.
|
| 66 |
+
min_freq : float
|
| 67 |
+
Lower bound of the retained frequency band in Hz.
|
| 68 |
+
max_freq : float
|
| 69 |
+
Upper bound of the retained frequency band in Hz.
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
input_samplerate: int
|
| 73 |
+
output_samplerate: float
|
| 74 |
+
|
| 75 |
+
max_freq: float
|
| 76 |
+
min_freq: float
|
| 77 |
+
|
| 78 |
+
def __init__(
|
| 79 |
+
self,
|
| 80 |
+
config: PreprocessingConfig,
|
| 81 |
+
input_samplerate: int,
|
| 82 |
+
) -> None:
|
| 83 |
+
super().__init__()
|
| 84 |
+
|
| 85 |
+
self.audio_transforms = torch.nn.Sequential(
|
| 86 |
+
*(
|
| 87 |
+
build_audio_transform(step, samplerate=input_samplerate)
|
| 88 |
+
for step in config.audio_transforms
|
| 89 |
+
)
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
self.spectrogram_transforms = torch.nn.Sequential(
|
| 93 |
+
*(
|
| 94 |
+
build_spectrogram_transform(step, samplerate=input_samplerate)
|
| 95 |
+
for step in config.spectrogram_transforms
|
| 96 |
+
)
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
self.spectrogram_builder = build_spectrogram_builder(
|
| 100 |
+
config.stft,
|
| 101 |
+
samplerate=input_samplerate,
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
self.spectrogram_crop = build_spectrogram_crop(
|
| 105 |
+
config.frequencies,
|
| 106 |
+
stft=config.stft,
|
| 107 |
+
samplerate=input_samplerate,
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
self.spectrogram_resizer = build_spectrogram_resizer(config.size)
|
| 111 |
+
|
| 112 |
+
self.min_freq = config.frequencies.min_freq
|
| 113 |
+
self.max_freq = config.frequencies.max_freq
|
| 114 |
+
|
| 115 |
+
self.input_samplerate = input_samplerate
|
| 116 |
+
self.output_samplerate = compute_output_samplerate(
|
| 117 |
+
config,
|
| 118 |
+
input_samplerate=input_samplerate,
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
def forward(self, wav: torch.Tensor) -> torch.Tensor:
|
| 122 |
+
"""Run the full preprocessing pipeline on a waveform.
|
| 123 |
+
|
| 124 |
+
Applies audio transforms, then the STFT, then
|
| 125 |
+
:meth:`process_spectrogram`.
|
| 126 |
+
|
| 127 |
+
Parameters
|
| 128 |
+
----------
|
| 129 |
+
wav : torch.Tensor
|
| 130 |
+
Input waveform of shape ``(samples,)``.
|
| 131 |
+
|
| 132 |
+
Returns
|
| 133 |
+
-------
|
| 134 |
+
torch.Tensor
|
| 135 |
+
Preprocessed spectrogram of shape
|
| 136 |
+
``(freq_bins, time_frames)``.
|
| 137 |
+
"""
|
| 138 |
+
wav = self.audio_transforms(wav)
|
| 139 |
+
spec = self.spectrogram_builder(wav)
|
| 140 |
+
return self.process_spectrogram(spec)
|
| 141 |
+
|
| 142 |
+
def generate_spectrogram(self, wav: torch.Tensor) -> torch.Tensor:
|
| 143 |
+
"""Compute the raw STFT spectrogram without any further processing.
|
| 144 |
+
|
| 145 |
+
Parameters
|
| 146 |
+
----------
|
| 147 |
+
wav : torch.Tensor
|
| 148 |
+
Input waveform of shape ``(samples,)``.
|
| 149 |
+
|
| 150 |
+
Returns
|
| 151 |
+
-------
|
| 152 |
+
torch.Tensor
|
| 153 |
+
Amplitude spectrogram of shape ``(n_fft//2 + 1, time_frames)``
|
| 154 |
+
with no frequency cropping, normalisation, or resizing applied.
|
| 155 |
+
"""
|
| 156 |
+
return self.spectrogram_builder(wav)
|
| 157 |
+
|
| 158 |
+
def process_audio(self, wav: torch.Tensor) -> torch.Tensor:
|
| 159 |
+
"""Alias for :meth:`forward`.
|
| 160 |
+
|
| 161 |
+
Parameters
|
| 162 |
+
----------
|
| 163 |
+
wav : torch.Tensor
|
| 164 |
+
Input waveform of shape ``(samples,)``.
|
| 165 |
+
|
| 166 |
+
Returns
|
| 167 |
+
-------
|
| 168 |
+
torch.Tensor
|
| 169 |
+
Preprocessed spectrogram (same as calling the object directly).
|
| 170 |
+
"""
|
| 171 |
+
return self(wav)
|
| 172 |
+
|
| 173 |
+
def process_spectrogram(self, spec: torch.Tensor) -> torch.Tensor:
|
| 174 |
+
"""Apply the post-STFT processing stages to an existing spectrogram.
|
| 175 |
+
|
| 176 |
+
Applies frequency cropping, spectrogram-level transforms (e.g.
|
| 177 |
+
PCEN, spectral mean subtraction), and the final resize step.
|
| 178 |
+
|
| 179 |
+
Parameters
|
| 180 |
+
----------
|
| 181 |
+
spec : torch.Tensor
|
| 182 |
+
Raw amplitude spectrogram of shape
|
| 183 |
+
``(..., n_fft//2 + 1, time_frames)``.
|
| 184 |
+
|
| 185 |
+
Returns
|
| 186 |
+
-------
|
| 187 |
+
torch.Tensor
|
| 188 |
+
Normalised and resized spectrogram of shape
|
| 189 |
+
``(..., height, scaled_time_frames)``.
|
| 190 |
+
"""
|
| 191 |
+
spec = self.spectrogram_crop(spec)
|
| 192 |
+
spec = self.spectrogram_transforms(spec)
|
| 193 |
+
return self.spectrogram_resizer(spec)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def compute_output_samplerate(
|
| 197 |
+
config: PreprocessingConfig,
|
| 198 |
+
input_samplerate: int = TARGET_SAMPLERATE_HZ,
|
| 199 |
+
) -> float:
|
| 200 |
+
"""Compute the effective frame rate of the preprocessor's output.
|
| 201 |
+
|
| 202 |
+
The output frame rate (in frames per second) depends on the STFT hop
|
| 203 |
+
length and the time-axis resize factor applied by the final resize step.
|
| 204 |
+
|
| 205 |
+
Parameters
|
| 206 |
+
----------
|
| 207 |
+
config : PreprocessingConfig
|
| 208 |
+
Pipeline configuration.
|
| 209 |
+
input_samplerate : int, default=256000
|
| 210 |
+
Sample rate of the input audio in Hz.
|
| 211 |
+
|
| 212 |
+
Returns
|
| 213 |
+
-------
|
| 214 |
+
float
|
| 215 |
+
Output frame rate in frames per second.
|
| 216 |
+
For example, at the default settings (256 kHz, hop=128,
|
| 217 |
+
resize_factor=0.5) this equals ``1000.0``.
|
| 218 |
+
"""
|
| 219 |
+
_, hop_size = _spec_params_from_config(
|
| 220 |
+
config.stft, samplerate=input_samplerate
|
| 221 |
+
)
|
| 222 |
+
factor = config.size.resize_factor
|
| 223 |
+
return input_samplerate * factor / hop_size
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def build_preprocessor(
|
| 227 |
+
config: PreprocessingConfig | None = None,
|
| 228 |
+
input_samplerate: int = TARGET_SAMPLERATE_HZ,
|
| 229 |
+
) -> PreprocessorProtocol:
|
| 230 |
+
"""Build the standard preprocessor from a configuration object.
|
| 231 |
+
|
| 232 |
+
Parameters
|
| 233 |
+
----------
|
| 234 |
+
config : PreprocessingConfig, optional
|
| 235 |
+
Pipeline configuration. If ``None``, the default
|
| 236 |
+
``PreprocessingConfig()`` is used (PCEN + spectral mean
|
| 237 |
+
subtraction, 256 kHz, standard STFT parameters).
|
| 238 |
+
input_samplerate : int, default=256000
|
| 239 |
+
Sample rate of the audio that will be fed to the preprocessor,
|
| 240 |
+
in Hz.
|
| 241 |
+
|
| 242 |
+
Returns
|
| 243 |
+
-------
|
| 244 |
+
PreprocessorProtocol
|
| 245 |
+
A :class:`Preprocessor` instance ready to convert waveforms to
|
| 246 |
+
spectrograms.
|
| 247 |
+
"""
|
| 248 |
+
config = config or PreprocessingConfig()
|
| 249 |
+
logger.opt(lazy=True).debug(
|
| 250 |
+
"Building preprocessor with config: \n{}",
|
| 251 |
+
lambda: config.to_yaml_string(),
|
| 252 |
+
)
|
| 253 |
+
return Preprocessor(config=config, input_samplerate=input_samplerate)
|
preprocessing/upstream/spectrogram.py
ADDED
|
@@ -0,0 +1,820 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Computes spectrograms from audio waveforms with configurable parameters.
|
| 2 |
+
|
| 3 |
+
This module defines the STFT-based spectrogram builder and a collection of
|
| 4 |
+
spectrogram-level transforms (PCEN, spectral mean subtraction, amplitude
|
| 5 |
+
scaling, peak normalisation, frequency cropping, and resizing) that form the
|
| 6 |
+
signal-processing stage of the batdetect2 preprocessing pipeline.
|
| 7 |
+
|
| 8 |
+
Each transform is paired with a Pydantic configuration class and registered
|
| 9 |
+
in the ``spectrogram_transforms`` registry so that the pipeline can be fully
|
| 10 |
+
specified via a YAML or Python configuration object.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from typing import Annotated, Callable, Literal
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
import torch
|
| 17 |
+
import torchaudio
|
| 18 |
+
from pydantic import Field
|
| 19 |
+
|
| 20 |
+
from batdetect2.audio import TARGET_SAMPLERATE_HZ
|
| 21 |
+
from batdetect2.core.configs import BaseConfig
|
| 22 |
+
from batdetect2.core.registries import (
|
| 23 |
+
ImportConfig,
|
| 24 |
+
Registry,
|
| 25 |
+
add_import_config,
|
| 26 |
+
)
|
| 27 |
+
from batdetect2.preprocess.common import peak_normalize
|
| 28 |
+
|
| 29 |
+
__all__ = [
|
| 30 |
+
"STFTConfig",
|
| 31 |
+
"SpectrogramTransformImportConfig",
|
| 32 |
+
"build_spectrogram_transform",
|
| 33 |
+
"build_spectrogram_builder",
|
| 34 |
+
]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
MIN_FREQ = 10_000
|
| 38 |
+
"""Default minimum frequency (Hz) for spectrogram frequency cropping."""
|
| 39 |
+
|
| 40 |
+
MAX_FREQ = 120_000
|
| 41 |
+
"""Default maximum frequency (Hz) for spectrogram frequency cropping."""
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class STFTConfig(BaseConfig):
|
| 45 |
+
"""Configuration for the Short-Time Fourier Transform (STFT).
|
| 46 |
+
|
| 47 |
+
Attributes
|
| 48 |
+
----------
|
| 49 |
+
window_duration : float, default=0.002
|
| 50 |
+
Duration of the STFT analysis window in seconds (e.g. 0.002 for
|
| 51 |
+
2 ms). Must be > 0. A longer window gives finer frequency resolution
|
| 52 |
+
but coarser time resolution.
|
| 53 |
+
window_overlap : float, default=0.75
|
| 54 |
+
Fraction of overlap between consecutive windows (e.g. 0.75 for
|
| 55 |
+
75 %). Must be >= 0 and < 1. Higher overlap gives finer time
|
| 56 |
+
resolution at the cost of more computation.
|
| 57 |
+
window_fn : str, default="hann"
|
| 58 |
+
Name of the tapering window applied to each frame before the FFT.
|
| 59 |
+
Supported values: ``"hann"``, ``"hamming"``, ``"kaiser"``,
|
| 60 |
+
``"blackman"``, ``"bartlett"``.
|
| 61 |
+
|
| 62 |
+
Notes
|
| 63 |
+
-----
|
| 64 |
+
At the default sample rate of 256 kHz, ``window_duration=0.002`` and
|
| 65 |
+
``window_overlap=0.75`` give ``n_fft=512`` and ``hop_length=128``.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
window_duration: float = Field(default=0.002, gt=0)
|
| 69 |
+
window_overlap: float = Field(default=0.75, ge=0, lt=1)
|
| 70 |
+
window_fn: str = "hann"
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def build_spectrogram_builder(
|
| 74 |
+
config: STFTConfig,
|
| 75 |
+
samplerate: int = TARGET_SAMPLERATE_HZ,
|
| 76 |
+
) -> torch.nn.Module:
|
| 77 |
+
"""Build a torchaudio STFT spectrogram module from an ``STFTConfig``.
|
| 78 |
+
|
| 79 |
+
Parameters
|
| 80 |
+
----------
|
| 81 |
+
config : STFTConfig
|
| 82 |
+
STFT parameters (window duration, overlap, and window function).
|
| 83 |
+
samplerate : int, default=256000
|
| 84 |
+
Sample rate of the input audio in Hz. Used to convert the
|
| 85 |
+
window duration into a number of samples.
|
| 86 |
+
|
| 87 |
+
Returns
|
| 88 |
+
-------
|
| 89 |
+
torch.nn.Module
|
| 90 |
+
A ``torchaudio.transforms.Spectrogram`` module configured to
|
| 91 |
+
produce an amplitude (``power=1``) spectrogram with centred
|
| 92 |
+
frames.
|
| 93 |
+
"""
|
| 94 |
+
n_fft, hop_length = _spec_params_from_config(config, samplerate=samplerate)
|
| 95 |
+
return torchaudio.transforms.Spectrogram(
|
| 96 |
+
n_fft=n_fft,
|
| 97 |
+
hop_length=hop_length,
|
| 98 |
+
window_fn=get_spectrogram_window(config.window_fn),
|
| 99 |
+
center=True,
|
| 100 |
+
power=1,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def get_spectrogram_window(name: str) -> Callable[..., torch.Tensor]:
|
| 105 |
+
"""Return the PyTorch window function matching the given name.
|
| 106 |
+
|
| 107 |
+
Parameters
|
| 108 |
+
----------
|
| 109 |
+
name : str
|
| 110 |
+
Name of the window function. One of ``"hann"``, ``"hamming"``,
|
| 111 |
+
``"kaiser"``, ``"blackman"``, or ``"bartlett"``.
|
| 112 |
+
|
| 113 |
+
Returns
|
| 114 |
+
-------
|
| 115 |
+
Callable[..., torch.Tensor]
|
| 116 |
+
A PyTorch window function that accepts a window length and returns
|
| 117 |
+
a 1-D tensor of weights.
|
| 118 |
+
|
| 119 |
+
Raises
|
| 120 |
+
------
|
| 121 |
+
NotImplementedError
|
| 122 |
+
If ``name`` does not match any supported window function.
|
| 123 |
+
"""
|
| 124 |
+
if name == "hann":
|
| 125 |
+
return torch.hann_window
|
| 126 |
+
|
| 127 |
+
if name == "hamming":
|
| 128 |
+
return torch.hamming_window
|
| 129 |
+
|
| 130 |
+
if name == "kaiser":
|
| 131 |
+
return torch.kaiser_window
|
| 132 |
+
|
| 133 |
+
if name == "blackman":
|
| 134 |
+
return torch.blackman_window
|
| 135 |
+
|
| 136 |
+
if name == "bartlett":
|
| 137 |
+
return torch.bartlett_window
|
| 138 |
+
|
| 139 |
+
raise NotImplementedError(
|
| 140 |
+
f"Spectrogram window function {name} not implemented"
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _spec_params_from_config(
|
| 145 |
+
config: STFTConfig,
|
| 146 |
+
samplerate: int = TARGET_SAMPLERATE_HZ,
|
| 147 |
+
) -> tuple[int, int]:
|
| 148 |
+
"""Compute ``n_fft`` and ``hop_length`` from an ``STFTConfig``.
|
| 149 |
+
|
| 150 |
+
Parameters
|
| 151 |
+
----------
|
| 152 |
+
config : STFTConfig
|
| 153 |
+
STFT parameters.
|
| 154 |
+
samplerate : int, default=256000
|
| 155 |
+
Sample rate of the input audio in Hz.
|
| 156 |
+
|
| 157 |
+
Returns
|
| 158 |
+
-------
|
| 159 |
+
tuple[int, int]
|
| 160 |
+
A pair ``(n_fft, hop_length)`` giving the FFT size and the step
|
| 161 |
+
between consecutive frames in samples.
|
| 162 |
+
"""
|
| 163 |
+
n_fft = int(samplerate * config.window_duration)
|
| 164 |
+
hop_length = int(n_fft * (1 - config.window_overlap))
|
| 165 |
+
return n_fft, hop_length
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _frequency_to_index(
|
| 169 |
+
freq: float,
|
| 170 |
+
n_fft: int,
|
| 171 |
+
samplerate: int = TARGET_SAMPLERATE_HZ,
|
| 172 |
+
) -> int | None:
|
| 173 |
+
"""Convert a frequency in Hz to the nearest STFT frequency bin index.
|
| 174 |
+
|
| 175 |
+
Parameters
|
| 176 |
+
----------
|
| 177 |
+
freq : float
|
| 178 |
+
Frequency in Hz to convert.
|
| 179 |
+
n_fft : int
|
| 180 |
+
FFT size used by the STFT.
|
| 181 |
+
samplerate : int, default=256000
|
| 182 |
+
Sample rate of the audio in Hz.
|
| 183 |
+
|
| 184 |
+
Returns
|
| 185 |
+
-------
|
| 186 |
+
int or None
|
| 187 |
+
The bin index corresponding to ``freq``, or ``None`` if the
|
| 188 |
+
frequency is outside the valid range (i.e. <= 0 Hz or >= the
|
| 189 |
+
Nyquist frequency).
|
| 190 |
+
"""
|
| 191 |
+
alpha = freq * 2 / samplerate
|
| 192 |
+
height = np.floor(n_fft / 2) + 1
|
| 193 |
+
index = int(np.floor(alpha * height))
|
| 194 |
+
|
| 195 |
+
if index <= 0:
|
| 196 |
+
return None
|
| 197 |
+
|
| 198 |
+
if index >= height:
|
| 199 |
+
return None
|
| 200 |
+
|
| 201 |
+
return index
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
class FrequencyConfig(BaseConfig):
|
| 205 |
+
"""Configuration for frequency axis parameters.
|
| 206 |
+
|
| 207 |
+
Attributes
|
| 208 |
+
----------
|
| 209 |
+
max_freq : int, default=120000
|
| 210 |
+
Maximum frequency in Hz to retain after STFT. Frequency bins
|
| 211 |
+
above this value are discarded. Must be >= 0.
|
| 212 |
+
min_freq : int, default=10000
|
| 213 |
+
Minimum frequency in Hz to retain after STFT. Frequency bins
|
| 214 |
+
below this value are discarded. Must be >= 0.
|
| 215 |
+
"""
|
| 216 |
+
|
| 217 |
+
max_freq: int = Field(default=MAX_FREQ, ge=0)
|
| 218 |
+
min_freq: int = Field(default=MIN_FREQ, ge=0)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
class FrequencyCrop(torch.nn.Module):
|
| 222 |
+
"""Crop a spectrogram to a specified frequency band.
|
| 223 |
+
|
| 224 |
+
On construction the Hz boundaries are converted to STFT bin indices.
|
| 225 |
+
During the forward pass the spectrogram is sliced along its
|
| 226 |
+
frequency axis (second-to-last dimension) to retain only the bins
|
| 227 |
+
that fall within ``[min_freq, max_freq)``.
|
| 228 |
+
|
| 229 |
+
Parameters
|
| 230 |
+
----------
|
| 231 |
+
samplerate : int
|
| 232 |
+
Sample rate of the audio in Hz.
|
| 233 |
+
n_fft : int
|
| 234 |
+
FFT size used by the STFT.
|
| 235 |
+
min_freq : int, optional
|
| 236 |
+
Lower frequency bound in Hz. If ``None``, no lower crop is
|
| 237 |
+
applied and the DC bin is retained.
|
| 238 |
+
max_freq : int, optional
|
| 239 |
+
Upper frequency bound in Hz. If ``None``, no upper crop is
|
| 240 |
+
applied and all bins up to Nyquist are retained.
|
| 241 |
+
"""
|
| 242 |
+
|
| 243 |
+
def __init__(
|
| 244 |
+
self,
|
| 245 |
+
samplerate: int,
|
| 246 |
+
n_fft: int,
|
| 247 |
+
min_freq: int | None = None,
|
| 248 |
+
max_freq: int | None = None,
|
| 249 |
+
):
|
| 250 |
+
super().__init__()
|
| 251 |
+
self.n_fft = n_fft
|
| 252 |
+
self.samplerate = samplerate
|
| 253 |
+
self.min_freq = min_freq
|
| 254 |
+
self.max_freq = max_freq
|
| 255 |
+
|
| 256 |
+
low_index = None
|
| 257 |
+
if min_freq is not None:
|
| 258 |
+
low_index = _frequency_to_index(
|
| 259 |
+
min_freq,
|
| 260 |
+
n_fft=self.n_fft,
|
| 261 |
+
samplerate=self.samplerate,
|
| 262 |
+
)
|
| 263 |
+
self.low_index = low_index
|
| 264 |
+
|
| 265 |
+
high_index = None
|
| 266 |
+
if max_freq is not None:
|
| 267 |
+
high_index = _frequency_to_index(
|
| 268 |
+
max_freq,
|
| 269 |
+
n_fft=self.n_fft,
|
| 270 |
+
samplerate=self.samplerate,
|
| 271 |
+
)
|
| 272 |
+
self.high_index = high_index
|
| 273 |
+
|
| 274 |
+
def forward(self, spec: torch.Tensor) -> torch.Tensor:
|
| 275 |
+
"""Crop the spectrogram to the configured frequency band.
|
| 276 |
+
|
| 277 |
+
Parameters
|
| 278 |
+
----------
|
| 279 |
+
spec : torch.Tensor
|
| 280 |
+
Spectrogram tensor of shape ``(..., freq_bins, time_frames)``.
|
| 281 |
+
|
| 282 |
+
Returns
|
| 283 |
+
-------
|
| 284 |
+
torch.Tensor
|
| 285 |
+
Cropped spectrogram with shape
|
| 286 |
+
``(..., n_retained_bins, time_frames)``.
|
| 287 |
+
"""
|
| 288 |
+
low_index = self.low_index
|
| 289 |
+
if low_index is None:
|
| 290 |
+
low_index = 0
|
| 291 |
+
|
| 292 |
+
if self.high_index is None:
|
| 293 |
+
length = spec.shape[-2] - low_index
|
| 294 |
+
else:
|
| 295 |
+
length = self.high_index - low_index
|
| 296 |
+
|
| 297 |
+
return torch.narrow(
|
| 298 |
+
spec,
|
| 299 |
+
dim=-2,
|
| 300 |
+
start=low_index,
|
| 301 |
+
length=length,
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def build_spectrogram_crop(
|
| 306 |
+
config: FrequencyConfig,
|
| 307 |
+
stft: STFTConfig | None = None,
|
| 308 |
+
samplerate: int = TARGET_SAMPLERATE_HZ,
|
| 309 |
+
) -> torch.nn.Module:
|
| 310 |
+
"""Build a ``FrequencyCrop`` module from configuration objects.
|
| 311 |
+
|
| 312 |
+
Parameters
|
| 313 |
+
----------
|
| 314 |
+
config : FrequencyConfig
|
| 315 |
+
Frequency boundary configuration specifying ``min_freq`` and
|
| 316 |
+
``max_freq`` in Hz.
|
| 317 |
+
stft : STFTConfig, optional
|
| 318 |
+
STFT configuration used to derive ``n_fft``. Defaults to
|
| 319 |
+
``STFTConfig()`` if not provided.
|
| 320 |
+
samplerate : int, default=256000
|
| 321 |
+
Sample rate of the audio in Hz.
|
| 322 |
+
|
| 323 |
+
Returns
|
| 324 |
+
-------
|
| 325 |
+
torch.nn.Module
|
| 326 |
+
A ``FrequencyCrop`` module ready to crop spectrograms.
|
| 327 |
+
"""
|
| 328 |
+
stft = stft or STFTConfig()
|
| 329 |
+
n_fft, _ = _spec_params_from_config(stft, samplerate=samplerate)
|
| 330 |
+
return FrequencyCrop(
|
| 331 |
+
samplerate=samplerate,
|
| 332 |
+
n_fft=n_fft,
|
| 333 |
+
min_freq=config.min_freq,
|
| 334 |
+
max_freq=config.max_freq,
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
class ResizeConfig(BaseConfig):
|
| 339 |
+
"""Configuration for the final spectrogram resize step.
|
| 340 |
+
|
| 341 |
+
Attributes
|
| 342 |
+
----------
|
| 343 |
+
name : str
|
| 344 |
+
Fixed identifier; always ``"resize_spec"``.
|
| 345 |
+
height : int, default=128
|
| 346 |
+
Target number of frequency bins in the output spectrogram.
|
| 347 |
+
The spectrogram is resized to this height using bilinear
|
| 348 |
+
interpolation.
|
| 349 |
+
resize_factor : float, default=0.5
|
| 350 |
+
Fraction by which the time axis is scaled. For example, ``0.5``
|
| 351 |
+
halves the number of time frames, reducing computational cost
|
| 352 |
+
downstream.
|
| 353 |
+
"""
|
| 354 |
+
|
| 355 |
+
name: Literal["resize_spec"] = "resize_spec"
|
| 356 |
+
height: int = 128
|
| 357 |
+
resize_factor: float = 0.5
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
class ResizeSpec(torch.nn.Module):
|
| 361 |
+
"""Resize a spectrogram to a fixed height and scaled width.
|
| 362 |
+
|
| 363 |
+
Uses bilinear interpolation so it handles arbitrary input shapes
|
| 364 |
+
gracefully. Input tensors with fewer than four dimensions are
|
| 365 |
+
temporarily unsqueezed to satisfy ``torch.nn.functional.interpolate``.
|
| 366 |
+
|
| 367 |
+
Parameters
|
| 368 |
+
----------
|
| 369 |
+
height : int
|
| 370 |
+
Target number of frequency bins (output height).
|
| 371 |
+
time_factor : float
|
| 372 |
+
Multiplicative scaling applied to the time axis length.
|
| 373 |
+
"""
|
| 374 |
+
|
| 375 |
+
def __init__(self, height: int, time_factor: float):
|
| 376 |
+
super().__init__()
|
| 377 |
+
self.height = height
|
| 378 |
+
self.time_factor = time_factor
|
| 379 |
+
|
| 380 |
+
def forward(self, spec: torch.Tensor) -> torch.Tensor:
|
| 381 |
+
"""Resize the spectrogram to the configured output dimensions.
|
| 382 |
+
|
| 383 |
+
Parameters
|
| 384 |
+
----------
|
| 385 |
+
spec : torch.Tensor
|
| 386 |
+
Input spectrogram of shape ``(..., freq_bins, time_frames)``.
|
| 387 |
+
|
| 388 |
+
Returns
|
| 389 |
+
-------
|
| 390 |
+
torch.Tensor
|
| 391 |
+
Resized spectrogram with shape
|
| 392 |
+
``(..., height, int(time_factor * time_frames))``.
|
| 393 |
+
"""
|
| 394 |
+
current_length = spec.shape[-1]
|
| 395 |
+
target_length = int(self.time_factor * current_length)
|
| 396 |
+
|
| 397 |
+
original_ndim = spec.ndim
|
| 398 |
+
while spec.ndim < 4:
|
| 399 |
+
spec = spec.unsqueeze(0)
|
| 400 |
+
|
| 401 |
+
resized = torch.nn.functional.interpolate(
|
| 402 |
+
spec,
|
| 403 |
+
size=(self.height, target_length),
|
| 404 |
+
mode="bilinear",
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
while resized.ndim != original_ndim:
|
| 408 |
+
resized = resized.squeeze(0)
|
| 409 |
+
|
| 410 |
+
return resized
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def build_spectrogram_resizer(config: ResizeConfig) -> torch.nn.Module:
|
| 414 |
+
"""Build a ``ResizeSpec`` module from a ``ResizeConfig``.
|
| 415 |
+
|
| 416 |
+
Parameters
|
| 417 |
+
----------
|
| 418 |
+
config : ResizeConfig
|
| 419 |
+
Resize configuration specifying ``height`` and ``resize_factor``.
|
| 420 |
+
|
| 421 |
+
Returns
|
| 422 |
+
-------
|
| 423 |
+
torch.nn.Module
|
| 424 |
+
A ``ResizeSpec`` module configured with the given parameters.
|
| 425 |
+
"""
|
| 426 |
+
return ResizeSpec(height=config.height, time_factor=config.resize_factor)
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
spectrogram_transforms: Registry[torch.nn.Module, [int]] = Registry(
|
| 430 |
+
"spectrogram_transform"
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
@add_import_config(spectrogram_transforms)
|
| 435 |
+
class SpectrogramTransformImportConfig(ImportConfig):
|
| 436 |
+
"""Use any callable as a spectrogram transform.
|
| 437 |
+
|
| 438 |
+
Set ``name="import"`` and provide a ``target`` pointing to any
|
| 439 |
+
callable to use it instead of a built-in option.
|
| 440 |
+
"""
|
| 441 |
+
|
| 442 |
+
name: Literal["import"] = "import"
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
class PcenConfig(BaseConfig):
|
| 446 |
+
"""Configuration for Per-Channel Energy Normalisation (PCEN).
|
| 447 |
+
|
| 448 |
+
PCEN is a frontend processing technique that replaces simple log
|
| 449 |
+
compression. It applies a learnable automatic gain control followed
|
| 450 |
+
by a stabilised root compression, making the representation more
|
| 451 |
+
robust to variations in recording level.
|
| 452 |
+
|
| 453 |
+
Attributes
|
| 454 |
+
----------
|
| 455 |
+
name : str
|
| 456 |
+
Fixed identifier; always ``"pcen"``.
|
| 457 |
+
time_constant : float, default=0.4
|
| 458 |
+
Time constant (in seconds) of the IIR smoothing filter used
|
| 459 |
+
for the background estimate. Larger values produce a slower-
|
| 460 |
+
adapting background.
|
| 461 |
+
gain : float, default=0.98
|
| 462 |
+
Exponent controlling how strongly the background estimate
|
| 463 |
+
suppresses the signal.
|
| 464 |
+
bias : float, default=2
|
| 465 |
+
Stabilisation bias added inside the root-compression step to
|
| 466 |
+
avoid division by zero.
|
| 467 |
+
power : float, default=0.5
|
| 468 |
+
Root-compression exponent. A value of 0.5 gives square-root
|
| 469 |
+
compression, similar to log compression but differentiable at
|
| 470 |
+
zero.
|
| 471 |
+
"""
|
| 472 |
+
|
| 473 |
+
name: Literal["pcen"] = "pcen"
|
| 474 |
+
time_constant: float = 0.4
|
| 475 |
+
gain: float = 0.98
|
| 476 |
+
bias: float = 2
|
| 477 |
+
power: float = 0.5
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
class PCEN(torch.nn.Module):
|
| 481 |
+
"""Per-Channel Energy Normalisation (PCEN) transform.
|
| 482 |
+
|
| 483 |
+
Applies automatic gain control and root compression to a spectrogram.
|
| 484 |
+
The background estimate is computed with a first-order IIR filter
|
| 485 |
+
applied along the time axis.
|
| 486 |
+
|
| 487 |
+
Parameters
|
| 488 |
+
----------
|
| 489 |
+
smoothing_constant : float
|
| 490 |
+
IIR filter coefficient ``alpha``. Derived from the time constant
|
| 491 |
+
and sample rate via ``_compute_smoothing_constant``.
|
| 492 |
+
gain : float, default=0.98
|
| 493 |
+
AGC gain exponent.
|
| 494 |
+
bias : float, default=2.0
|
| 495 |
+
Root-compression stabilisation bias.
|
| 496 |
+
power : float, default=0.5
|
| 497 |
+
Root-compression exponent.
|
| 498 |
+
eps : float, default=1e-6
|
| 499 |
+
Small constant for numerical stability.
|
| 500 |
+
dtype : torch.dtype, default=torch.float32
|
| 501 |
+
Floating-point precision used for internal computation.
|
| 502 |
+
|
| 503 |
+
Notes
|
| 504 |
+
-----
|
| 505 |
+
The smoothing constant is computed to match the original batdetect2
|
| 506 |
+
implementation for numerical compatibility. See
|
| 507 |
+
``_compute_smoothing_constant`` for details.
|
| 508 |
+
"""
|
| 509 |
+
|
| 510 |
+
def __init__(
|
| 511 |
+
self,
|
| 512 |
+
smoothing_constant: float,
|
| 513 |
+
gain: float = 0.98,
|
| 514 |
+
bias: float = 2.0,
|
| 515 |
+
power: float = 0.5,
|
| 516 |
+
eps: float = 1e-6,
|
| 517 |
+
dtype=torch.float32,
|
| 518 |
+
):
|
| 519 |
+
super().__init__()
|
| 520 |
+
self.smoothing_constant = smoothing_constant
|
| 521 |
+
self.gain = torch.tensor(gain, dtype=dtype)
|
| 522 |
+
self.bias = torch.tensor(bias, dtype=dtype)
|
| 523 |
+
self.power = torch.tensor(power, dtype=dtype)
|
| 524 |
+
self.eps = torch.tensor(eps, dtype=dtype)
|
| 525 |
+
self.dtype = dtype
|
| 526 |
+
|
| 527 |
+
self._b = torch.tensor([self.smoothing_constant, 0.0], dtype=dtype)
|
| 528 |
+
self._a = torch.tensor(
|
| 529 |
+
[1.0, self.smoothing_constant - 1.0], dtype=dtype
|
| 530 |
+
)
|
| 531 |
+
|
| 532 |
+
def forward(self, spec: torch.Tensor) -> torch.Tensor:
|
| 533 |
+
"""Apply PCEN to a spectrogram.
|
| 534 |
+
|
| 535 |
+
Parameters
|
| 536 |
+
----------
|
| 537 |
+
spec : torch.Tensor
|
| 538 |
+
Input amplitude spectrogram of shape
|
| 539 |
+
``(..., freq_bins, time_frames)``.
|
| 540 |
+
|
| 541 |
+
Returns
|
| 542 |
+
-------
|
| 543 |
+
torch.Tensor
|
| 544 |
+
PCEN-normalised spectrogram with the same shape and dtype as
|
| 545 |
+
the input.
|
| 546 |
+
"""
|
| 547 |
+
S = spec.to(self.dtype) * 2**31
|
| 548 |
+
|
| 549 |
+
M = (
|
| 550 |
+
torchaudio.functional.lfilter(
|
| 551 |
+
S,
|
| 552 |
+
self._a,
|
| 553 |
+
self._b,
|
| 554 |
+
clamp=False,
|
| 555 |
+
)
|
| 556 |
+
).clamp(min=0)
|
| 557 |
+
|
| 558 |
+
smooth = torch.exp(
|
| 559 |
+
-self.gain * (torch.log(self.eps) + torch.log1p(M / self.eps))
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
return (
|
| 563 |
+
(self.bias**self.power)
|
| 564 |
+
* torch.expm1(self.power * torch.log1p(S * smooth / self.bias))
|
| 565 |
+
).to(spec.dtype)
|
| 566 |
+
|
| 567 |
+
@spectrogram_transforms.register(PcenConfig)
|
| 568 |
+
@staticmethod
|
| 569 |
+
def from_config(config: PcenConfig, samplerate: int):
|
| 570 |
+
smooth = _compute_smoothing_constant(samplerate, config.time_constant)
|
| 571 |
+
return PCEN(
|
| 572 |
+
smoothing_constant=smooth,
|
| 573 |
+
gain=config.gain,
|
| 574 |
+
bias=config.bias,
|
| 575 |
+
power=config.power,
|
| 576 |
+
)
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
def _compute_smoothing_constant(
|
| 580 |
+
samplerate: int,
|
| 581 |
+
time_constant: float,
|
| 582 |
+
) -> float:
|
| 583 |
+
"""Compute the IIR smoothing coefficient for PCEN.
|
| 584 |
+
|
| 585 |
+
Parameters
|
| 586 |
+
----------
|
| 587 |
+
samplerate : int
|
| 588 |
+
Sample rate of the audio in Hz.
|
| 589 |
+
time_constant : float
|
| 590 |
+
Desired smoothing time constant in seconds.
|
| 591 |
+
|
| 592 |
+
Returns
|
| 593 |
+
-------
|
| 594 |
+
float
|
| 595 |
+
IIR filter coefficient ``alpha`` used by ``PCEN``.
|
| 596 |
+
|
| 597 |
+
Notes
|
| 598 |
+
-----
|
| 599 |
+
The hop length (512) and the sample-rate divisor (10) are fixed to
|
| 600 |
+
reproduce the numerical behaviour of the original batdetect2
|
| 601 |
+
implementation, which used ``librosa.pcen`` with ``sr=samplerate/10``
|
| 602 |
+
and the default ``hop_length=512``. These values do not reflect the
|
| 603 |
+
actual STFT hop length used in the pipeline; they are retained
|
| 604 |
+
solely for backward compatibility.
|
| 605 |
+
"""
|
| 606 |
+
# NOTE: These parameters are fixed to match the original implementation.
|
| 607 |
+
hop_length = 512
|
| 608 |
+
sr = samplerate / 10
|
| 609 |
+
t_frames = time_constant * sr / float(hop_length)
|
| 610 |
+
return (np.sqrt(1 + 4 * t_frames**2) - 1) / (2 * t_frames**2)
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
class ScaleAmplitudeConfig(BaseConfig):
|
| 614 |
+
"""Configuration for amplitude scaling of a spectrogram.
|
| 615 |
+
|
| 616 |
+
Attributes
|
| 617 |
+
----------
|
| 618 |
+
name : str
|
| 619 |
+
Fixed identifier; always ``"scale_amplitude"``.
|
| 620 |
+
scale : str, default="db"
|
| 621 |
+
Scaling mode. Either ``"db"`` (convert amplitude to decibels
|
| 622 |
+
using ``torchaudio.transforms.AmplitudeToDB``) or ``"power"``
|
| 623 |
+
(square the amplitude values).
|
| 624 |
+
"""
|
| 625 |
+
|
| 626 |
+
name: Literal["scale_amplitude"] = "scale_amplitude"
|
| 627 |
+
scale: Literal["power", "db"] = "db"
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
class ToPower(torch.nn.Module):
|
| 631 |
+
"""Square the values of a spectrogram (amplitude → power).
|
| 632 |
+
|
| 633 |
+
Raises each element to the power of two, converting an amplitude
|
| 634 |
+
spectrogram into a power spectrogram.
|
| 635 |
+
"""
|
| 636 |
+
|
| 637 |
+
def forward(self, spec: torch.Tensor) -> torch.Tensor:
|
| 638 |
+
"""Square all elements of the spectrogram.
|
| 639 |
+
|
| 640 |
+
Parameters
|
| 641 |
+
----------
|
| 642 |
+
spec : torch.Tensor
|
| 643 |
+
Input amplitude spectrogram.
|
| 644 |
+
|
| 645 |
+
Returns
|
| 646 |
+
-------
|
| 647 |
+
torch.Tensor
|
| 648 |
+
Power spectrogram (same shape as input).
|
| 649 |
+
"""
|
| 650 |
+
return spec**2
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
_scalers = {
|
| 654 |
+
"db": torchaudio.transforms.AmplitudeToDB,
|
| 655 |
+
"power": ToPower,
|
| 656 |
+
}
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
class ScaleAmplitude(torch.nn.Module):
|
| 660 |
+
"""Convert spectrogram amplitude values to a different scale.
|
| 661 |
+
|
| 662 |
+
Supports conversion to decibels (dB) or to power (squared amplitude).
|
| 663 |
+
|
| 664 |
+
Parameters
|
| 665 |
+
----------
|
| 666 |
+
scale : str
|
| 667 |
+
Either ``"db"`` or ``"power"``.
|
| 668 |
+
"""
|
| 669 |
+
|
| 670 |
+
def __init__(self, scale: Literal["power", "db"]):
|
| 671 |
+
super().__init__()
|
| 672 |
+
self.scale = scale
|
| 673 |
+
self.scaler = _scalers[scale]()
|
| 674 |
+
|
| 675 |
+
def forward(self, spec: torch.Tensor) -> torch.Tensor:
|
| 676 |
+
"""Apply the configured amplitude scaling.
|
| 677 |
+
|
| 678 |
+
Parameters
|
| 679 |
+
----------
|
| 680 |
+
spec : torch.Tensor
|
| 681 |
+
Input spectrogram tensor.
|
| 682 |
+
|
| 683 |
+
Returns
|
| 684 |
+
-------
|
| 685 |
+
torch.Tensor
|
| 686 |
+
Scaled spectrogram with the same shape as the input.
|
| 687 |
+
"""
|
| 688 |
+
return self.scaler(spec)
|
| 689 |
+
|
| 690 |
+
@spectrogram_transforms.register(ScaleAmplitudeConfig)
|
| 691 |
+
@staticmethod
|
| 692 |
+
def from_config(config: ScaleAmplitudeConfig, samplerate: int):
|
| 693 |
+
return ScaleAmplitude(scale=config.scale)
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
class SpectralMeanSubtractionConfig(BaseConfig):
|
| 697 |
+
"""Configuration for spectral mean subtraction.
|
| 698 |
+
|
| 699 |
+
Attributes
|
| 700 |
+
----------
|
| 701 |
+
name : str
|
| 702 |
+
Fixed identifier; always ``"spectral_mean_subtraction"``.
|
| 703 |
+
"""
|
| 704 |
+
|
| 705 |
+
name: Literal["spectral_mean_subtraction"] = "spectral_mean_subtraction"
|
| 706 |
+
|
| 707 |
+
|
| 708 |
+
class SpectralMeanSubtraction(torch.nn.Module):
|
| 709 |
+
"""Remove the time-averaged background noise from a spectrogram.
|
| 710 |
+
|
| 711 |
+
For each frequency bin, the mean value across all time frames is
|
| 712 |
+
computed and subtracted. The result is then clamped to zero so that
|
| 713 |
+
no values fall below the baseline. This is a simple form of spectral
|
| 714 |
+
denoising that suppresses stationary background noise.
|
| 715 |
+
"""
|
| 716 |
+
|
| 717 |
+
def forward(self, spec: torch.Tensor) -> torch.Tensor:
|
| 718 |
+
"""Subtract the time-axis mean from each frequency bin.
|
| 719 |
+
|
| 720 |
+
Parameters
|
| 721 |
+
----------
|
| 722 |
+
spec : torch.Tensor
|
| 723 |
+
Input spectrogram of shape ``(..., freq_bins, time_frames)``.
|
| 724 |
+
|
| 725 |
+
Returns
|
| 726 |
+
-------
|
| 727 |
+
torch.Tensor
|
| 728 |
+
Denoised spectrogram with the same shape as the input. All
|
| 729 |
+
values are non-negative (clamped to 0).
|
| 730 |
+
"""
|
| 731 |
+
mean = spec.mean(-1, keepdim=True)
|
| 732 |
+
return (spec - mean).clamp(min=0)
|
| 733 |
+
|
| 734 |
+
@spectrogram_transforms.register(SpectralMeanSubtractionConfig)
|
| 735 |
+
@staticmethod
|
| 736 |
+
def from_config(
|
| 737 |
+
config: SpectralMeanSubtractionConfig,
|
| 738 |
+
samplerate: int,
|
| 739 |
+
):
|
| 740 |
+
return SpectralMeanSubtraction()
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
class PeakNormalizeConfig(BaseConfig):
|
| 744 |
+
"""Configuration for peak normalisation of a spectrogram.
|
| 745 |
+
|
| 746 |
+
Attributes
|
| 747 |
+
----------
|
| 748 |
+
name : str
|
| 749 |
+
Fixed identifier; always ``"peak_normalize"``.
|
| 750 |
+
"""
|
| 751 |
+
|
| 752 |
+
name: Literal["peak_normalize"] = "peak_normalize"
|
| 753 |
+
|
| 754 |
+
|
| 755 |
+
class PeakNormalize(torch.nn.Module):
|
| 756 |
+
"""Scale a spectrogram so that its largest absolute value equals one.
|
| 757 |
+
|
| 758 |
+
Wraps :func:`batdetect2.preprocess.common.peak_normalize` as a
|
| 759 |
+
``torch.nn.Module`` for use inside a sequential transform pipeline.
|
| 760 |
+
"""
|
| 761 |
+
|
| 762 |
+
def forward(self, spec: torch.Tensor) -> torch.Tensor:
|
| 763 |
+
"""Peak-normalise the spectrogram.
|
| 764 |
+
|
| 765 |
+
Parameters
|
| 766 |
+
----------
|
| 767 |
+
spec : torch.Tensor
|
| 768 |
+
Input spectrogram tensor of any shape.
|
| 769 |
+
|
| 770 |
+
Returns
|
| 771 |
+
-------
|
| 772 |
+
torch.Tensor
|
| 773 |
+
Normalised spectrogram where the maximum absolute value is 1.
|
| 774 |
+
If the input is identically zero, it is returned unchanged.
|
| 775 |
+
"""
|
| 776 |
+
return peak_normalize(spec)
|
| 777 |
+
|
| 778 |
+
@spectrogram_transforms.register(PeakNormalizeConfig)
|
| 779 |
+
@staticmethod
|
| 780 |
+
def from_config(config: PeakNormalizeConfig, samplerate: int):
|
| 781 |
+
return PeakNormalize()
|
| 782 |
+
|
| 783 |
+
|
| 784 |
+
SpectrogramTransform = Annotated[
|
| 785 |
+
PcenConfig
|
| 786 |
+
| ScaleAmplitudeConfig
|
| 787 |
+
| SpectralMeanSubtractionConfig
|
| 788 |
+
| PeakNormalizeConfig,
|
| 789 |
+
Field(discriminator="name"),
|
| 790 |
+
]
|
| 791 |
+
"""Discriminated union of all spectrogram transform configuration types.
|
| 792 |
+
|
| 793 |
+
Use this type when a field should accept any of the supported spectrogram
|
| 794 |
+
transforms. Pydantic will select the correct config class based on the
|
| 795 |
+
``name`` field.
|
| 796 |
+
"""
|
| 797 |
+
|
| 798 |
+
|
| 799 |
+
def build_spectrogram_transform(
|
| 800 |
+
config: SpectrogramTransform,
|
| 801 |
+
samplerate: int,
|
| 802 |
+
) -> torch.nn.Module:
|
| 803 |
+
"""Build a spectrogram transform module from a configuration object.
|
| 804 |
+
|
| 805 |
+
Parameters
|
| 806 |
+
----------
|
| 807 |
+
config : SpectrogramTransform
|
| 808 |
+
A configuration object for one of the supported spectrogram
|
| 809 |
+
transforms (PCEN, amplitude scaling, spectral mean subtraction,
|
| 810 |
+
or peak normalisation).
|
| 811 |
+
samplerate : int
|
| 812 |
+
Sample rate of the audio in Hz. Some transforms (e.g. PCEN) use
|
| 813 |
+
this to set internal parameters.
|
| 814 |
+
|
| 815 |
+
Returns
|
| 816 |
+
-------
|
| 817 |
+
torch.nn.Module
|
| 818 |
+
The constructed transform module.
|
| 819 |
+
"""
|
| 820 |
+
return spectrogram_transforms.build(config, samplerate)
|
preprocessing/upstream/types.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Protocol
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
__all__ = [
|
| 7 |
+
"PreprocessorProtocol",
|
| 8 |
+
"SpectrogramBuilder",
|
| 9 |
+
]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class SpectrogramBuilder(Protocol):
|
| 13 |
+
def __call__(self, wav: torch.Tensor) -> torch.Tensor: ...
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class PreprocessorProtocol(Protocol):
|
| 17 |
+
max_freq: float
|
| 18 |
+
min_freq: float
|
| 19 |
+
input_samplerate: int
|
| 20 |
+
output_samplerate: float
|
| 21 |
+
|
| 22 |
+
def __call__(self, wav: torch.Tensor) -> torch.Tensor: ...
|
| 23 |
+
|
| 24 |
+
def generate_spectrogram(self, wav: torch.Tensor) -> torch.Tensor: ...
|
| 25 |
+
|
| 26 |
+
def process_audio(self, wav: torch.Tensor) -> torch.Tensor: ...
|
| 27 |
+
|
| 28 |
+
def process_spectrogram(self, spec: torch.Tensor) -> torch.Tensor: ...
|
| 29 |
+
|
| 30 |
+
def process_numpy(self, wav: np.ndarray) -> np.ndarray:
|
| 31 |
+
return self(torch.tensor(wav)).numpy()
|
scripts/export_batdetect2_onnx.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Export the authoritative BatDetect2 detector/classifier checkpoint to ONNX."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import hashlib
|
| 8 |
+
import json
|
| 9 |
+
import subprocess
|
| 10 |
+
import sys
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
EXPECTED_UK_LABELS = [
|
| 14 |
+
"MYOMYS",
|
| 15 |
+
"MYOALC",
|
| 16 |
+
"CNESER",
|
| 17 |
+
"PIPNAT",
|
| 18 |
+
"BARBAR",
|
| 19 |
+
"MYONAT",
|
| 20 |
+
"MYODAU",
|
| 21 |
+
"MYOBRA",
|
| 22 |
+
"PIPPIP",
|
| 23 |
+
"MYOBEC",
|
| 24 |
+
"PIPPYG",
|
| 25 |
+
"RHIHIP",
|
| 26 |
+
"NYCLEI",
|
| 27 |
+
"RHIFER",
|
| 28 |
+
"PLEAUR",
|
| 29 |
+
"NYCNOC",
|
| 30 |
+
"PLEAUS",
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def parse_args() -> argparse.Namespace:
|
| 35 |
+
parser = argparse.ArgumentParser()
|
| 36 |
+
parser.add_argument("--source", type=Path, required=True, help="BatDetect2 repository checkout")
|
| 37 |
+
parser.add_argument(
|
| 38 |
+
"--checkpoint",
|
| 39 |
+
type=Path,
|
| 40 |
+
help="defaults to the checkout's bundled batdetect2_uk_same.ckpt",
|
| 41 |
+
)
|
| 42 |
+
parser.add_argument("--output", type=Path, default=Path("models/batdetect2-uk-same.onnx"))
|
| 43 |
+
parser.add_argument("--opset", type=int, default=17)
|
| 44 |
+
parser.add_argument(
|
| 45 |
+
"--accept-noncommercial-license",
|
| 46 |
+
action="store_true",
|
| 47 |
+
help="acknowledge that the checkpoint is CC BY-NC 4.0",
|
| 48 |
+
)
|
| 49 |
+
return parser.parse_args()
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def main() -> None:
|
| 53 |
+
args = parse_args()
|
| 54 |
+
if not args.accept_noncommercial_license:
|
| 55 |
+
raise SystemExit(
|
| 56 |
+
"BatDetect2's bundled model is CC BY-NC 4.0; rerun with "
|
| 57 |
+
"--accept-noncommercial-license after reviewing those terms"
|
| 58 |
+
)
|
| 59 |
+
source = args.source.resolve()
|
| 60 |
+
checkpoint = args.checkpoint or (
|
| 61 |
+
source / "src/batdetect2/models/checkpoints/batdetect2_uk_same.ckpt"
|
| 62 |
+
)
|
| 63 |
+
if not checkpoint.is_file() or not (source / "src/batdetect2").is_dir():
|
| 64 |
+
raise SystemExit("--source or --checkpoint does not contain the expected BatDetect2 files")
|
| 65 |
+
sys.path.insert(0, str(source / "src"))
|
| 66 |
+
try:
|
| 67 |
+
import numpy as np
|
| 68 |
+
import onnx
|
| 69 |
+
import onnxruntime as ort
|
| 70 |
+
import torch
|
| 71 |
+
from batdetect2.train import load_model_from_checkpoint
|
| 72 |
+
except ImportError as exc:
|
| 73 |
+
raise SystemExit(
|
| 74 |
+
"Install BatDetect2 and ONNX export dependencies in an isolated environment; "
|
| 75 |
+
"see docs/MODELS.md"
|
| 76 |
+
) from exc
|
| 77 |
+
|
| 78 |
+
model, _ = load_model_from_checkpoint(checkpoint)
|
| 79 |
+
source_labels = list(model.class_names)
|
| 80 |
+
labels = [label.upper() for label in source_labels]
|
| 81 |
+
if labels != EXPECTED_UK_LABELS:
|
| 82 |
+
raise SystemExit(
|
| 83 |
+
"checkpoint class order differs from the locked Android contract:\n"
|
| 84 |
+
f"expected={EXPECTED_UK_LABELS}\nactual={source_labels}"
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
class DetectorOnly(torch.nn.Module):
|
| 88 |
+
def __init__(self, detector: torch.nn.Module) -> None:
|
| 89 |
+
super().__init__()
|
| 90 |
+
self.detector = detector
|
| 91 |
+
|
| 92 |
+
def forward(self, input: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 93 |
+
output = self.detector(input)
|
| 94 |
+
return output.detection_probs, output.class_probs
|
| 95 |
+
|
| 96 |
+
wrapper = DetectorOnly(model.detector).eval()
|
| 97 |
+
dummy = torch.zeros((1, 1, 128, 256), dtype=torch.float32)
|
| 98 |
+
args.output.parent.mkdir(parents=True, exist_ok=True)
|
| 99 |
+
with torch.inference_mode():
|
| 100 |
+
torch.onnx.export(
|
| 101 |
+
wrapper,
|
| 102 |
+
(dummy,),
|
| 103 |
+
args.output,
|
| 104 |
+
input_names=["input"],
|
| 105 |
+
output_names=["detection_probs", "class_probs"],
|
| 106 |
+
opset_version=args.opset,
|
| 107 |
+
do_constant_folding=True,
|
| 108 |
+
dynamo=False,
|
| 109 |
+
)
|
| 110 |
+
onnx.checker.check_model(onnx.load(args.output))
|
| 111 |
+
with torch.inference_mode():
|
| 112 |
+
detection, classes = wrapper(dummy)
|
| 113 |
+
torch.manual_seed(20260818)
|
| 114 |
+
parity_input = torch.rand((1, 1, 128, 256), dtype=torch.float32)
|
| 115 |
+
reference_detection, reference_classes = wrapper(parity_input)
|
| 116 |
+
runtime = ort.InferenceSession(str(args.output), providers=["CPUExecutionProvider"])
|
| 117 |
+
converted_detection, converted_classes = runtime.run(
|
| 118 |
+
["detection_probs", "class_probs"],
|
| 119 |
+
{runtime.get_inputs()[0].name: parity_input.numpy()},
|
| 120 |
+
)
|
| 121 |
+
detection_error = float(np.max(np.abs(reference_detection.numpy() - converted_detection)))
|
| 122 |
+
class_error = float(np.max(np.abs(reference_classes.numpy() - converted_classes)))
|
| 123 |
+
maximum_absolute_error = max(detection_error, class_error)
|
| 124 |
+
if maximum_absolute_error > 1e-4:
|
| 125 |
+
raise SystemExit(
|
| 126 |
+
f"PyTorch/ONNX parity failed: max absolute error {maximum_absolute_error:.8g}"
|
| 127 |
+
)
|
| 128 |
+
try:
|
| 129 |
+
source_revision = subprocess.run(
|
| 130 |
+
["git", "-C", str(source), "rev-parse", "HEAD"],
|
| 131 |
+
check=True,
|
| 132 |
+
capture_output=True,
|
| 133 |
+
text=True,
|
| 134 |
+
).stdout.strip()
|
| 135 |
+
except (OSError, subprocess.CalledProcessError):
|
| 136 |
+
source_revision = "unknown"
|
| 137 |
+
try:
|
| 138 |
+
checkpoint_identity = str(checkpoint.resolve().relative_to(source))
|
| 139 |
+
except ValueError:
|
| 140 |
+
checkpoint_identity = checkpoint.name
|
| 141 |
+
metadata = {
|
| 142 |
+
"backend": "batdetect2",
|
| 143 |
+
"source": "https://github.com/macaodha/batdetect2",
|
| 144 |
+
"source_revision": source_revision,
|
| 145 |
+
"checkpoint": checkpoint_identity,
|
| 146 |
+
"input_name": "input",
|
| 147 |
+
"input_shape": [1, 1, 128, 256],
|
| 148 |
+
"outputs": {
|
| 149 |
+
"detection_probs": list(detection.shape),
|
| 150 |
+
"class_probs": list(classes.shape),
|
| 151 |
+
},
|
| 152 |
+
"labels": labels,
|
| 153 |
+
"source_labels": source_labels,
|
| 154 |
+
"opset": args.opset,
|
| 155 |
+
"license": "CC BY-NC 4.0",
|
| 156 |
+
"commercial_use": False,
|
| 157 |
+
"onnx_bytes": args.output.stat().st_size,
|
| 158 |
+
"onnx_sha256": hashlib.sha256(args.output.read_bytes()).hexdigest(),
|
| 159 |
+
"source_runtime_parity": {
|
| 160 |
+
"fixture": "seeded random float32 tensor (seed 20260818)",
|
| 161 |
+
"detection_maximum_absolute_error": detection_error,
|
| 162 |
+
"class_maximum_absolute_error": class_error,
|
| 163 |
+
"tolerance": 1e-4,
|
| 164 |
+
},
|
| 165 |
+
}
|
| 166 |
+
args.output.with_suffix(".json").write_text(json.dumps(metadata, indent=2) + "\n")
|
| 167 |
+
print(f"wrote {args.output}")
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
if __name__ == "__main__":
|
| 171 |
+
main()
|
scripts/fetch-upstream.sh
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/sh
|
| 2 |
+
set -eu
|
| 3 |
+
|
| 4 |
+
repository_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
| 5 |
+
target=${1:-"$repository_root/.repro/batdetect2"}
|
| 6 |
+
url='https://github.com/macaodha/batdetect2.git'
|
| 7 |
+
revision='9e2697458d3b3b03c30ccd7e49ed5409c8ac330d'
|
| 8 |
+
checkpoint='src/batdetect2/models/checkpoints/batdetect2_uk_same.ckpt'
|
| 9 |
+
expected_sha256='52e3f329a046e434d16751005b252b4fd1b142b8b63a4edc2740aeb81f48adcf'
|
| 10 |
+
|
| 11 |
+
if test ! -e "$target"; then
|
| 12 |
+
mkdir -p "$(dirname -- "$target")"
|
| 13 |
+
git clone --filter=blob:none --no-checkout "$url" "$target"
|
| 14 |
+
git -C "$target" checkout --detach "$revision"
|
| 15 |
+
elif test ! -d "$target/.git"; then
|
| 16 |
+
echo "$target exists but is not a Git checkout" >&2
|
| 17 |
+
exit 1
|
| 18 |
+
fi
|
| 19 |
+
|
| 20 |
+
actual_revision=$(git -C "$target" rev-parse HEAD)
|
| 21 |
+
test "$actual_revision" = "$revision" || {
|
| 22 |
+
echo "$target: expected revision $revision, got $actual_revision" >&2
|
| 23 |
+
exit 1
|
| 24 |
+
}
|
| 25 |
+
actual_sha256=$(shasum -a 256 "$target/$checkpoint" | awk '{print $1}')
|
| 26 |
+
test "$actual_sha256" = "$expected_sha256" || {
|
| 27 |
+
echo "$target/$checkpoint: expected SHA-256 $expected_sha256, got $actual_sha256" >&2
|
| 28 |
+
exit 1
|
| 29 |
+
}
|
| 30 |
+
cmp "$target/$checkpoint" "$repository_root/upstream/batdetect2_uk_same.ckpt"
|
| 31 |
+
echo "$target: pinned source revision and archived checkpoint verified"
|
scripts/rebuild-and-verify.sh
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/sh
|
| 2 |
+
set -eu
|
| 3 |
+
|
| 4 |
+
if test "${1:-}" != '--accept-noncommercial-license'; then
|
| 5 |
+
echo 'Review CC BY-NC 4.0, then rerun with --accept-noncommercial-license' >&2
|
| 6 |
+
exit 1
|
| 7 |
+
fi
|
| 8 |
+
|
| 9 |
+
repository_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
| 10 |
+
source_checkout="$repository_root/.repro/batdetect2"
|
| 11 |
+
output_dir="$repository_root/.repro/output"
|
| 12 |
+
output="$output_dir/batdetect2-uk-same.onnx"
|
| 13 |
+
checkpoint='src/batdetect2/models/checkpoints/batdetect2_uk_same.ckpt'
|
| 14 |
+
expected_bytes='7603041'
|
| 15 |
+
expected_sha256='9eddc08f1a22695ffdb1cdb52d947752d83777cd8596554f108bcf701481d340'
|
| 16 |
+
|
| 17 |
+
command -v uv >/dev/null 2>&1 || {
|
| 18 |
+
echo 'uv is required: https://docs.astral.sh/uv/' >&2
|
| 19 |
+
exit 1
|
| 20 |
+
}
|
| 21 |
+
"$repository_root/scripts/fetch-upstream.sh" "$source_checkout"
|
| 22 |
+
mkdir -p "$output_dir"
|
| 23 |
+
cd "$repository_root"
|
| 24 |
+
uv run --project environment --frozen --python 3.11.15 python \
|
| 25 |
+
scripts/export_batdetect2_onnx.py \
|
| 26 |
+
--source "$source_checkout" \
|
| 27 |
+
--checkpoint "$source_checkout/$checkpoint" \
|
| 28 |
+
--output "$output" \
|
| 29 |
+
--accept-noncommercial-license
|
| 30 |
+
|
| 31 |
+
actual_bytes=$(wc -c < "$output" | tr -d ' ')
|
| 32 |
+
actual_sha256=$(shasum -a 256 "$output" | awk '{print $1}')
|
| 33 |
+
test "$actual_bytes" = "$expected_bytes" || {
|
| 34 |
+
echo "$output: expected $expected_bytes bytes, got $actual_bytes" >&2
|
| 35 |
+
exit 1
|
| 36 |
+
}
|
| 37 |
+
test "$actual_sha256" = "$expected_sha256" || {
|
| 38 |
+
echo "$output: expected SHA-256 $expected_sha256, got $actual_sha256" >&2
|
| 39 |
+
exit 1
|
| 40 |
+
}
|
| 41 |
+
echo "$output: byte-identical ONNX rebuild verified"
|
scripts/verify_golden.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Create or verify the deterministic ONNX contract fixture."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import hashlib
|
| 8 |
+
import json
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import onnxruntime as ort
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 16 |
+
SEED = 20260818
|
| 17 |
+
INPUT_SHAPE = (1, 1, 128, 256)
|
| 18 |
+
RTOL = 1e-5
|
| 19 |
+
ATOL = 1e-6
|
| 20 |
+
OUTPUTS = ("detection_probs", "class_probs")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def sha256(path: Path) -> str:
|
| 24 |
+
digest = hashlib.sha256()
|
| 25 |
+
with path.open("rb") as stream:
|
| 26 |
+
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
| 27 |
+
digest.update(chunk)
|
| 28 |
+
return digest.hexdigest()
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def generated_input() -> np.ndarray:
|
| 32 |
+
return np.random.default_rng(SEED).random(INPUT_SHAPE, dtype=np.float32)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def write_fixture(model: Path, golden: Path) -> None:
|
| 36 |
+
golden.mkdir(parents=True, exist_ok=True)
|
| 37 |
+
input_path = golden / "input.npy"
|
| 38 |
+
input_tensor = generated_input()
|
| 39 |
+
session = ort.InferenceSession(str(model), providers=["CPUExecutionProvider"])
|
| 40 |
+
outputs = session.run(list(OUTPUTS), {"input": input_tensor})
|
| 41 |
+
np.save(input_path, input_tensor, allow_pickle=False)
|
| 42 |
+
output_entries = []
|
| 43 |
+
for name, output in zip(OUTPUTS, outputs, strict=True):
|
| 44 |
+
output_path = golden / f"{name}.npy"
|
| 45 |
+
np.save(output_path, output, allow_pickle=False)
|
| 46 |
+
output_entries.append({"path": output_path.name, "name": name, "dtype": str(output.dtype), "shape": list(output.shape), "sha256": sha256(output_path)})
|
| 47 |
+
manifest = {
|
| 48 |
+
"schema_version": 1,
|
| 49 |
+
"purpose": "Deterministic model-ready tensor fixture for the ONNX runtime contract; it does not test raw-audio preprocessing.",
|
| 50 |
+
"seed": SEED,
|
| 51 |
+
"model": {"path": "batdetect2-uk-same.onnx", "sha256": sha256(model)},
|
| 52 |
+
"runtime": {"numpy": np.__version__, "onnxruntime": ort.__version__, "provider": "CPUExecutionProvider"},
|
| 53 |
+
"input": {"path": "input.npy", "name": "input", "dtype": str(input_tensor.dtype), "shape": list(input_tensor.shape), "generator": "numpy.default_rng(seed).random(dtype=float32)", "sha256": sha256(input_path)},
|
| 54 |
+
"outputs": output_entries,
|
| 55 |
+
"tolerance": {"rtol": RTOL, "atol": ATOL},
|
| 56 |
+
}
|
| 57 |
+
(golden / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def verify_fixture(model: Path, golden: Path) -> None:
|
| 61 |
+
manifest = json.loads((golden / "manifest.json").read_text(encoding="utf-8"))
|
| 62 |
+
if sha256(model) != manifest["model"]["sha256"]:
|
| 63 |
+
raise SystemExit("model SHA-256 does not match golden/manifest.json")
|
| 64 |
+
input_path = golden / manifest["input"]["path"]
|
| 65 |
+
if sha256(input_path) != manifest["input"]["sha256"]:
|
| 66 |
+
raise SystemExit("golden input SHA-256 mismatch")
|
| 67 |
+
input_tensor = np.load(input_path, allow_pickle=False)
|
| 68 |
+
np.testing.assert_array_equal(input_tensor, generated_input())
|
| 69 |
+
session = ort.InferenceSession(str(model), providers=["CPUExecutionProvider"])
|
| 70 |
+
actual_outputs = session.run(list(OUTPUTS), {"input": input_tensor})
|
| 71 |
+
for actual, entry in zip(actual_outputs, manifest["outputs"], strict=True):
|
| 72 |
+
expected_path = golden / entry["path"]
|
| 73 |
+
if sha256(expected_path) != entry["sha256"]:
|
| 74 |
+
raise SystemExit(f"golden output SHA-256 mismatch: {entry['path']}")
|
| 75 |
+
expected = np.load(expected_path, allow_pickle=False)
|
| 76 |
+
np.testing.assert_allclose(actual, expected, rtol=manifest["tolerance"]["rtol"], atol=manifest["tolerance"]["atol"])
|
| 77 |
+
print(f"{entry['name']} passed; max_abs_error={float(np.max(np.abs(actual - expected))):.9g}")
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def main() -> None:
|
| 81 |
+
parser = argparse.ArgumentParser()
|
| 82 |
+
parser.add_argument("--model", type=Path, default=ROOT / "batdetect2-uk-same.onnx")
|
| 83 |
+
parser.add_argument("--golden-dir", type=Path, default=ROOT / "golden")
|
| 84 |
+
parser.add_argument("--write", action="store_true", help="regenerate the committed fixture")
|
| 85 |
+
args = parser.parse_args()
|
| 86 |
+
if args.write:
|
| 87 |
+
write_fixture(args.model, args.golden_dir)
|
| 88 |
+
verify_fixture(args.model, args.golden_dir)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
if __name__ == "__main__":
|
| 92 |
+
main()
|
upstream/README.md
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Archived upstream checkpoint
|
| 2 |
+
|
| 3 |
+
`batdetect2_uk_same.ckpt` is a byte-identical copy of
|
| 4 |
+
`src/batdetect2/models/checkpoints/batdetect2_uk_same.ckpt` from BatDetect2 revision
|
| 5 |
+
`9e2697458d3b3b03c30ccd7e49ed5409c8ac330d`.
|
| 6 |
+
|
| 7 |
+
From the repository root, run `./scripts/fetch-upstream.sh` to clone that revision and compare its
|
| 8 |
+
checkpoint with this archive. The checkpoint remains subject to CC BY-NC 4.0.
|
upstream/batdetect2_uk_same.ckpt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:52e3f329a046e434d16751005b252b4fd1b142b8b63a4edc2740aeb81f48adcf
|
| 3 |
+
size 7610085
|