Commit ·
fba24bb
0
Parent(s):
Duplicate from FixedSeed/Robin
Browse filesCo-authored-by: Kytra <Mothersuperior@users.noreply.huggingface.co>
This view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +37 -0
- LICENSE +284 -0
- LICENSE-APACHE-2.0 +202 -0
- NOTICE +11 -0
- README.md +142 -0
- comfyui-robin/LICENSE +284 -0
- comfyui-robin/__init__.py +5 -0
- comfyui-robin/nodes.py +618 -0
- comfyui-robin/pyproject.toml +11 -0
- comfyui-robin/requirements.txt +7 -0
- comfyui-robin/robin/__init__.py +3 -0
- comfyui-robin/robin/__main__.py +107 -0
- comfyui-robin/robin/gui.py +508 -0
- comfyui-robin/robin/lora.py +94 -0
- comfyui-robin/robin/model.py +195 -0
- comfyui-robin/robin/pieces.py +181 -0
- comfyui-robin/robin/pipeline.py +248 -0
- comfyui-robin/robin/speech.py +50 -0
- comfyui-robin/robin/text.py +699 -0
- comfyui-robin/robin/train.py +381 -0
- comfyui-robin/robin/vae.py +81 -0
- comfyui-robin/web/fonts/FamiljenGrotesk.woff2 +0 -0
- comfyui-robin/web/fonts/IBMPlexMono-Medium.woff2 +0 -0
- comfyui-robin/web/fonts/IBMPlexMono-Regular.woff2 +0 -0
- comfyui-robin/web/fonts/OFL-FamiljenGrotesk.txt +93 -0
- comfyui-robin/web/fonts/OFL-IBMPlexMono.txt +93 -0
- comfyui-robin/web/robin.css +81 -0
- comfyui-robin/web/robin.js +923 -0
- comfyui-robin/web/robin_badge.svg +1 -0
- comfyui-workflow-examples/Robin - LoRA Voice Inference Official.json +229 -0
- comfyui-workflow-examples/Robin - LoRA Voice Training Official.json +204 -0
- config.json +38 -0
- images/banner.png +0 -0
- images/comfyui-speak.png +3 -0
- images/comfyui-train.png +3 -0
- images/pill-github.png +0 -0
- images/pill-project-page.png +0 -0
- package/LICENSE +284 -0
- package/pyproject.toml +16 -0
- package/requirements.txt +8 -0
- package/robin/__init__.py +3 -0
- package/robin/__main__.py +107 -0
- package/robin/gui.py +508 -0
- package/robin/lora.py +94 -0
- package/robin/model.py +195 -0
- package/robin/pieces.py +181 -0
- package/robin/pipeline.py +248 -0
- package/robin/speech.py +50 -0
- package/robin/text.py +699 -0
- package/robin/train.py +381 -0
.gitattributes
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
images/comfyui-speak.png filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
images/comfyui-train.png filter=lfs diff=lfs merge=lfs -text
|
LICENSE
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Fixed Seed Open License
|
| 3 |
+
Version 1.0, November 2026
|
| 4 |
+
|
| 5 |
+
This License is based on the Apache License, Version 2.0. It adds a
|
| 6 |
+
limit on Commercial Use above a revenue threshold (Section 5), a section
|
| 7 |
+
on Output (Section 6), termination (Section 12) and governing law
|
| 8 |
+
(Section 13), and makes the grants in Sections 2 and 3 subject to the
|
| 9 |
+
limit. Fixed Seed may publish new versions of this License; a Work
|
| 10 |
+
stays under the version it was released with.
|
| 11 |
+
|
| 12 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 13 |
+
|
| 14 |
+
1. Definitions.
|
| 15 |
+
|
| 16 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 17 |
+
and distribution as defined by Sections 1 through 13 of this document.
|
| 18 |
+
|
| 19 |
+
"Licensor" shall mean Fixed Seed LLC, a California limited liability
|
| 20 |
+
company doing business as Fixed Seed Research Laboratory ("Fixed
|
| 21 |
+
Seed").
|
| 22 |
+
|
| 23 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 24 |
+
other entities that control, are controlled by, or are under common
|
| 25 |
+
control with that entity. For the purposes of this definition,
|
| 26 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 27 |
+
direction or management of such entity, whether by contract or
|
| 28 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 29 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 30 |
+
|
| 31 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 32 |
+
exercising permissions granted by this License.
|
| 33 |
+
|
| 34 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 35 |
+
including but not limited to model weights and parameters, software
|
| 36 |
+
source code, documentation source, and configuration files.
|
| 37 |
+
|
| 38 |
+
"Object" form shall mean any form resulting from mechanical
|
| 39 |
+
transformation or translation of a Source form, including but
|
| 40 |
+
not limited to compiled object code, generated documentation,
|
| 41 |
+
and conversions to other media types.
|
| 42 |
+
|
| 43 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 44 |
+
Object form, made available under the License, as indicated by a
|
| 45 |
+
copyright notice that is included in or attached to the work
|
| 46 |
+
(an example is provided in the Appendix below).
|
| 47 |
+
|
| 48 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 49 |
+
form, that is based on (or derived from) the Work and for which the
|
| 50 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 51 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 52 |
+
of this License, Derivative Works shall not include works that remain
|
| 53 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 54 |
+
the Work and Derivative Works thereof. For the avoidance of doubt,
|
| 55 |
+
Derivative Works include any model, weights or adapter (including
|
| 56 |
+
LoRA and similar adapter weights) made by training, fine-tuning,
|
| 57 |
+
merging, quantizing, pruning or distilling the Work or a Derivative
|
| 58 |
+
Work.
|
| 59 |
+
|
| 60 |
+
"Contribution" shall mean any work of authorship, including
|
| 61 |
+
the original version of the Work and any modifications or additions
|
| 62 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 63 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 64 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 65 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 66 |
+
means any form of electronic, verbal, or written communication sent
|
| 67 |
+
to the Licensor or its representatives, including but not limited to
|
| 68 |
+
communication on electronic mailing lists, source code control systems,
|
| 69 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 70 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 71 |
+
excluding communication that is conspicuously marked or otherwise
|
| 72 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 73 |
+
|
| 74 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 75 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 76 |
+
subsequently incorporated within the Work.
|
| 77 |
+
|
| 78 |
+
"Output" shall mean audio, speech, speech tokens, latents and any
|
| 79 |
+
other content generated by running the Work or a Derivative Work.
|
| 80 |
+
|
| 81 |
+
"Commercial Use" shall mean any use of the Work, a Derivative Work or
|
| 82 |
+
Output that is directed toward commercial advantage or monetary
|
| 83 |
+
compensation, including offering the Work or a Derivative Work, or
|
| 84 |
+
access to either, as a product or service, and using the Work, a
|
| 85 |
+
Derivative Work or Output in or to make products, services or
|
| 86 |
+
content that are sold, licensed or otherwise monetized.
|
| 87 |
+
|
| 88 |
+
"Attributable Revenue" shall mean the gross revenue, before
|
| 89 |
+
deductions of any kind, that You receive from (i) the Work or any
|
| 90 |
+
Derivative Work, or access to either (for example through an
|
| 91 |
+
application, an API or a hosted service), and (ii) any product,
|
| 92 |
+
service or content that uses, includes or was made with the Work, a
|
| 93 |
+
Derivative Work or Output, including through sales, subscriptions,
|
| 94 |
+
licensing, advertising and usage fees. Revenue from such a product,
|
| 95 |
+
service or content counts in full and is not apportioned among its
|
| 96 |
+
parts. Where You are a Legal Entity, Attributable Revenue includes
|
| 97 |
+
the revenue of every entity that makes up that Legal Entity.
|
| 98 |
+
|
| 99 |
+
"Threshold" shall mean two million United States dollars
|
| 100 |
+
(US$2,000,000) of Attributable Revenue in any period of twelve (12)
|
| 101 |
+
consecutive months.
|
| 102 |
+
|
| 103 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 104 |
+
this License, including the Commercial Use Limitation in Section 5,
|
| 105 |
+
each Contributor hereby grants to You a perpetual, worldwide,
|
| 106 |
+
non-exclusive, no-charge, royalty-free, irrevocable (except as stated
|
| 107 |
+
in Sections 5 and 12) copyright license to reproduce, prepare
|
| 108 |
+
Derivative Works of, publicly display, publicly perform, sublicense,
|
| 109 |
+
and distribute the Work and such Derivative Works in Source or
|
| 110 |
+
Object form.
|
| 111 |
+
|
| 112 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 113 |
+
this License, including the Commercial Use Limitation in Section 5,
|
| 114 |
+
each Contributor hereby grants to You a perpetual, worldwide,
|
| 115 |
+
non-exclusive, no-charge, royalty-free, irrevocable (except as stated
|
| 116 |
+
in this section and in Sections 5 and 12) patent license to make,
|
| 117 |
+
have made, use, offer to sell, sell, import, and otherwise transfer
|
| 118 |
+
the Work,
|
| 119 |
+
where such license applies only to those patent claims licensable
|
| 120 |
+
by such Contributor that are necessarily infringed by their
|
| 121 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 122 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 123 |
+
institute patent litigation against any entity (including a
|
| 124 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 125 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 126 |
+
or contributory patent infringement, then any patent licenses
|
| 127 |
+
granted to You under this License for that Work shall terminate
|
| 128 |
+
as of the date such litigation is filed.
|
| 129 |
+
|
| 130 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 131 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 132 |
+
modifications, and in Source or Object form, provided that You
|
| 133 |
+
meet the following conditions:
|
| 134 |
+
|
| 135 |
+
(a) You must give any other recipients of the Work or
|
| 136 |
+
Derivative Works a copy of this License; and
|
| 137 |
+
|
| 138 |
+
(b) You must cause any modified files to carry prominent notices
|
| 139 |
+
stating that You changed the files; and
|
| 140 |
+
|
| 141 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 142 |
+
that You distribute, all copyright, patent, trademark, and
|
| 143 |
+
attribution notices from the Source form of the Work,
|
| 144 |
+
excluding those notices that do not pertain to any part of
|
| 145 |
+
the Derivative Works; and
|
| 146 |
+
|
| 147 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 148 |
+
distribution, then any Derivative Works that You distribute must
|
| 149 |
+
include a readable copy of the attribution notices contained
|
| 150 |
+
within such NOTICE file, excluding those notices that do not
|
| 151 |
+
pertain to any part of the Derivative Works, in at least one
|
| 152 |
+
of the following places: within a NOTICE text file distributed
|
| 153 |
+
as part of the Derivative Works; within the Source form or
|
| 154 |
+
documentation, if provided along with the Derivative Works; or,
|
| 155 |
+
within a display generated by the Derivative Works, if and
|
| 156 |
+
wherever such third-party notices normally appear. The contents
|
| 157 |
+
of the NOTICE file are for informational purposes only and
|
| 158 |
+
do not modify the License. You may add Your own attribution
|
| 159 |
+
notices within Derivative Works that You distribute, alongside
|
| 160 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 161 |
+
that such additional attribution notices cannot be construed
|
| 162 |
+
as modifying the License.
|
| 163 |
+
|
| 164 |
+
(e) You must distribute the Work and any Derivative Works under the
|
| 165 |
+
terms of this License, so that every recipient's Commercial Use
|
| 166 |
+
is subject to Section 5.
|
| 167 |
+
|
| 168 |
+
You may add Your own copyright statement to Your modifications and
|
| 169 |
+
may provide additional or different license terms and conditions
|
| 170 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 171 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 172 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 173 |
+
the conditions stated in this License, and provided that no such
|
| 174 |
+
terms remove or limit Section 5 for any recipient.
|
| 175 |
+
|
| 176 |
+
5. Commercial Use Limitation.
|
| 177 |
+
|
| 178 |
+
(a) Below the Threshold. You may make Commercial Use of the Work,
|
| 179 |
+
Derivative Works and Output under this License for as long as
|
| 180 |
+
Your Attributable Revenue has not exceeded the Threshold.
|
| 181 |
+
|
| 182 |
+
(b) Above the Threshold. If Your Attributable Revenue exceeds the
|
| 183 |
+
Threshold, You must tell Fixed Seed in writing within thirty (30)
|
| 184 |
+
days, at support@fixedseed.com or at another address Fixed Seed
|
| 185 |
+
publishes for this purpose, so that You and Fixed Seed can discuss
|
| 186 |
+
a separate commercial license. Your Commercial Use may continue
|
| 187 |
+
under this License for ninety (90) days after Your Attributable
|
| 188 |
+
Revenue first exceeded the Threshold, while You and Fixed Seed
|
| 189 |
+
negotiate in good faith. After that, this License grants You no
|
| 190 |
+
rights for Commercial Use, and Commercial Use requires a separate
|
| 191 |
+
written agreement with Fixed Seed. Fixed Seed may extend that
|
| 192 |
+
period in writing.
|
| 193 |
+
|
| 194 |
+
(c) Other use. Use that is not Commercial Use, such as personal use,
|
| 195 |
+
research, education and evaluation, is not limited by this
|
| 196 |
+
Section, whatever Your revenue.
|
| 197 |
+
|
| 198 |
+
(d) Good faith. If Fixed Seed asks in writing, You will tell Fixed
|
| 199 |
+
Seed in good faith whether Your Attributable Revenue has
|
| 200 |
+
exceeded the Threshold.
|
| 201 |
+
|
| 202 |
+
6. Output. Fixed Seed claims no ownership of Output. You are responsible
|
| 203 |
+
for Output and for how You use it, including for having any rights
|
| 204 |
+
You need in the text, recordings and other material You give the
|
| 205 |
+
Work or a Derivative Work. Commercial Use of Output is subject to
|
| 206 |
+
Section 5.
|
| 207 |
+
|
| 208 |
+
7. Submission of Contributions. Unless You explicitly state otherwise,
|
| 209 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 210 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 211 |
+
this License, without any additional terms or conditions.
|
| 212 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 213 |
+
the terms of any separate license agreement you may have executed
|
| 214 |
+
with Licensor regarding such Contributions.
|
| 215 |
+
|
| 216 |
+
8. Trademarks. This License does not grant permission to use the trade
|
| 217 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 218 |
+
except as required for reasonable and customary use in describing the
|
| 219 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 220 |
+
|
| 221 |
+
9. Disclaimer of Warranty. Unless required by applicable law or
|
| 222 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 223 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 224 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 225 |
+
implied, including, without limitation, any warranties or conditions
|
| 226 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 227 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 228 |
+
appropriateness of using or redistributing the Work and assume any
|
| 229 |
+
risks associated with Your exercise of permissions under this License.
|
| 230 |
+
|
| 231 |
+
10. Limitation of Liability. In no event and under no legal theory,
|
| 232 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 233 |
+
unless required by applicable law (such as deliberate and grossly
|
| 234 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 235 |
+
liable to You for damages, including any direct, indirect, special,
|
| 236 |
+
incidental, or consequential damages of any character arising as a
|
| 237 |
+
result of this License or out of the use or inability to use the
|
| 238 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 239 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 240 |
+
other commercial damages or losses), even if such Contributor
|
| 241 |
+
has been advised of the possibility of such damages.
|
| 242 |
+
|
| 243 |
+
11. Accepting Warranty or Additional Liability. While redistributing
|
| 244 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 245 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 246 |
+
or other liability obligations and/or rights consistent with this
|
| 247 |
+
License. However, in accepting such obligations, You may act only
|
| 248 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 249 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 250 |
+
defend, and hold each Contributor harmless for any liability
|
| 251 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 252 |
+
of your accepting any such warranty or additional liability.
|
| 253 |
+
|
| 254 |
+
12. Termination. If You fail to comply with any term of this License,
|
| 255 |
+
Your rights under it terminate automatically. They are reinstated if
|
| 256 |
+
You cure the failure within thirty (30) days after You first learn of
|
| 257 |
+
it, unless You have failed to comply with this License before.
|
| 258 |
+
Termination does not end the licenses of anyone who received the Work
|
| 259 |
+
or a Derivative Work from You and complies with this License.
|
| 260 |
+
Sections 9, 10, 12 and 13 survive termination.
|
| 261 |
+
|
| 262 |
+
13. Governing Law. This License is governed by the laws of the State of
|
| 263 |
+
California, without regard to its conflict-of-laws rules.
|
| 264 |
+
|
| 265 |
+
END OF TERMS AND CONDITIONS
|
| 266 |
+
|
| 267 |
+
APPENDIX: How to apply this License to your work.
|
| 268 |
+
|
| 269 |
+
Include a copy of this License with the Work, and a NOTICE file that
|
| 270 |
+
names the Work and its copyright owner, for example:
|
| 271 |
+
|
| 272 |
+
Robin
|
| 273 |
+
Copyright 2026 Fixed Seed LLC
|
| 274 |
+
|
| 275 |
+
Licensed under the Fixed Seed Open License, Version 1.0 (the
|
| 276 |
+
"License"); you may not use this file except in compliance with the
|
| 277 |
+
License. You may obtain a copy of the License in the LICENSE file
|
| 278 |
+
distributed with this Work.
|
| 279 |
+
|
| 280 |
+
Unless required by applicable law or agreed to in writing, software
|
| 281 |
+
and models distributed under the License are distributed on an
|
| 282 |
+
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
|
| 283 |
+
express or implied. See the License for the specific language
|
| 284 |
+
governing permissions and limitations under the License.
|
LICENSE-APACHE-2.0
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 180 |
+
|
| 181 |
+
To apply the Apache License to your work, attach the following
|
| 182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 183 |
+
replaced with your own identifying information. (Don't include
|
| 184 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 185 |
+
comment syntax for the file format. We also recommend that a
|
| 186 |
+
file or class name and description of purpose be included on the
|
| 187 |
+
same "printed page" as the copyright notice for easier
|
| 188 |
+
identification within third-party archives.
|
| 189 |
+
|
| 190 |
+
Copyright [yyyy] [name of copyright owner]
|
| 191 |
+
|
| 192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 193 |
+
you may not use this file except in compliance with the License.
|
| 194 |
+
You may obtain a copy of the License at
|
| 195 |
+
|
| 196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 197 |
+
|
| 198 |
+
Unless required by applicable law or agreed to in writing, software
|
| 199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 201 |
+
See the License for the specific language governing permissions and
|
| 202 |
+
limitations under the License.
|
NOTICE
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Robin
|
| 2 |
+
Copyright 2026 Fixed Seed LLC (Fixed Seed Research Laboratory)
|
| 3 |
+
|
| 4 |
+
Licensed under the Fixed Seed Open License, Version 1.0 (see LICENSE).
|
| 5 |
+
|
| 6 |
+
This repository also contains a third-party file that is not covered by
|
| 7 |
+
the Fixed Seed Open License:
|
| 8 |
+
|
| 9 |
+
- speech_tokenizer_v3_25hz.onnx: the speech tokenizer from CosyVoice 3
|
| 10 |
+
(https://github.com/FunAudioLLM/CosyVoice), used under the Apache
|
| 11 |
+
License, Version 2.0 (a copy is in LICENSE-APACHE-2.0).
|
README.md
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: other
|
| 3 |
+
license_name: fixed-seed-open-license
|
| 4 |
+
license_link: LICENSE
|
| 5 |
+
language:
|
| 6 |
+
- en
|
| 7 |
+
- ja
|
| 8 |
+
pipeline_tag: text-to-speech
|
| 9 |
+
tags:
|
| 10 |
+
- text-to-speech
|
| 11 |
+
- lora
|
| 12 |
+
- comfyui
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
<p align="center">
|
| 16 |
+
<img src="https://huggingface.co/FixedSeed/Robin/resolve/main/images/banner.png" alt="Robin. Train any voice. Hear it at 48 kHz. Fixed Seed Research Laboratory." width="100%">
|
| 17 |
+
</p>
|
| 18 |
+
|
| 19 |
+
<p align="center">
|
| 20 |
+
<a href="https://github.com/Fixed-Seed/Robin"><img src="https://huggingface.co/FixedSeed/Robin/resolve/main/images/pill-github.png" alt="GitHub: Fixed-Seed/Robin" height="40"></a>
|
| 21 |
+
<a href="https://audiorobin.io"><img src="https://huggingface.co/FixedSeed/Robin/resolve/main/images/pill-project-page.png" alt="Project page: audiorobin.io" height="40"></a>
|
| 22 |
+
</p>
|
| 23 |
+
|
| 24 |
+
Zero-shot cloning is never good enough for studio work. That's why we trained Robin: an open-weights model built for professionals in the open-source community. It launches with LoRA training scripts included and it renders at 48 kHz, the standard for film and video. Design a voice through text, re-voice your own takes with another voice or train a dedicated adapter model to always produce an exact voice using your own voice data.
|
| 25 |
+
|
| 26 |
+
- English and Japanese, or both in one line
|
| 27 |
+
- 48 kHz audio
|
| 28 |
+
- 3.58 B parameters: a 2.17 B planner writes the speech as tokens, and a 1.41 B flow-matching decoder turns that plan into sound
|
| 29 |
+
- Peak GPU memory in bf16: 8.2 GB to speak, 9.1 GB to change a voice, 9.9 GB to train a voice
|
| 30 |
+
|
| 31 |
+
## Files
|
| 32 |
+
|
| 33 |
+
| File | |
|
| 34 |
+
|---|---|
|
| 35 |
+
| `robin_v1.safetensors`, `robin_vae.safetensors`, `config.json`, `tokenizer.json` | the model |
|
| 36 |
+
| `speech_tokenizer_v3_25hz.onnx` | CosyVoice 3's speech tokenizer, for long text, voice changing and training |
|
| 37 |
+
| `robin_character_lora.safetensors` | Robin's own voice, as a LoRA |
|
| 38 |
+
| `package/` | the `robin` Python package: command line, app and LoRA training |
|
| 39 |
+
| `comfyui-robin/` | the ComfyUI nodes |
|
| 40 |
+
| `comfyui-workflow-examples/` | ComfyUI workflows to start from |
|
| 41 |
+
|
| 42 |
+
## Install
|
| 43 |
+
|
| 44 |
+
```
|
| 45 |
+
hf download FixedSeed/Robin --local-dir robin
|
| 46 |
+
cd robin
|
| 47 |
+
pip install ./package
|
| 48 |
+
pip install "./package[gui]" # for the app
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
## Use
|
| 52 |
+
|
| 53 |
+
```
|
| 54 |
+
python -m robin speak "That went better than expected [laughs]" --model . --voice "a warm, low voice, close to the mic" --out take.flac
|
| 55 |
+
python -m robin speak "Exactly what my take says." --convert my_take.wav --model . --voice "a bright, fast-talking woman" --out revoiced.flac
|
| 56 |
+
python -m robin gui --model .
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
Languages: `--lang en` (default), `--lang ja`, or `--lang mix` for English and Japanese in one line.
|
| 60 |
+
|
| 61 |
+
Inline tags in square brackets, such as `[laughs]`, `[sigh]`, `[crying]` or `[shouting]`.
|
| 62 |
+
|
| 63 |
+
`--convert` performs a recording of up to 45 seconds again in another voice, keeping its words, timing and delivery. The text must be exactly what the recording says.
|
| 64 |
+
|
| 65 |
+
`robin_character_lora.safetensors` is Robin's own voice:
|
| 66 |
+
|
| 67 |
+
```
|
| 68 |
+
python -m robin speak "Hi, I'm Robin." --model . --lora robin_character_lora.safetensors --out robin.flac
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
The app runs in your browser: speak with two takes side by side, change a voice from a description, and train a voice with live progress and a sample at every save.
|
| 72 |
+
|
| 73 |
+
## Train a voice
|
| 74 |
+
|
| 75 |
+
Robin learns a new voice through a LoRA trained on transcribed recordings of it. Each voice is saved as one file, and you set its strength when you use it.
|
| 76 |
+
|
| 77 |
+
A dataset is a folder of clips, each with a `.txt` transcript of the same name, plus an optional `voice.txt` that describes the voice:
|
| 78 |
+
|
| 79 |
+
```
|
| 80 |
+
my_voice/
|
| 81 |
+
├── line_001.txt # what line_001.wav says
|
| 82 |
+
├── line_001.wav
|
| 83 |
+
├── line_002.txt
|
| 84 |
+
├── line_002.wav
|
| 85 |
+
├── …
|
| 86 |
+
└── voice.txt # optional: the voice in plain words
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
```
|
| 90 |
+
python -m robin prep my_voice/
|
| 91 |
+
python -m robin train my_voice/ --model . --out my_voice_lora
|
| 92 |
+
python -m robin speak "This is my voice." --model . --lora my_voice_lora/lora.safetensors --out mine.flac
|
| 93 |
+
```
|
| 94 |
+
|
| 95 |
+
`prep` checks the folder first. It lists the clips it will leave out (no transcript, silent, too short or too long) and notes anything worth fixing: clipping, digits, low sample rates, transcripts that may not match, repeated lines. `train` saves a checkpoint every 200 steps and reads a sample line in the new voice at each save, so you can pick a step by ear. Stop it at any time; running it again continues from the last save.
|
| 96 |
+
|
| 97 |
+
Recommendations:
|
| 98 |
+
|
| 99 |
+
- **How much:** at least 15 minutes of speech. Our test voices averaged 20 minutes, in about 200 clips.
|
| 100 |
+
- **Each clip:** one or two sentences, 3 to 15 seconds. Anything from 1 to 30 seconds is accepted, so split longer takes.
|
| 101 |
+
- **Recording:** one speaker in a quiet, dead-sounding room, with the same mic and distance throughout. No music, effects or other voices. Keep peaks around −6 dBFS.
|
| 102 |
+
- **Format:** WAV or FLAC at 44.1 or 48 kHz. Lower rates train a duller top end, and clips below 16 kHz are left out.
|
| 103 |
+
- **Transcripts:** exactly the words spoken. Write numbers the way they're said ("fifty percent"), and mark sounds and delivery with tags like `[laughs]` or `[sigh]` where they happen. Re-record a stumble instead of transcribing it.
|
| 104 |
+
- **Range:** mix statements, questions and exclamations, short lines and long ones. A calm read trains a calm voice, so record the delivery you want back.
|
| 105 |
+
- **Tip:** write the script first, then record it line by line. The script is the transcript.
|
| 106 |
+
|
| 107 |
+
## ComfyUI
|
| 108 |
+
|
| 109 |
+

|
| 110 |
+
|
| 111 |
+
Copy `comfyui-robin` into `ComfyUI/custom_nodes` and install its requirements into ComfyUI's Python:
|
| 112 |
+
|
| 113 |
+
```
|
| 114 |
+
pip install -r ComfyUI/custom_nodes/comfyui-robin/requirements.txt
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
The first run downloads Robin from this repo: the model into `ComfyUI/models/robin/robin`, and Robin's own voice into `ComfyUI/models/loras`. To place the files yourself, put `robin_v1.safetensors`, `robin_vae.safetensors`, `speech_tokenizer_v3_25hz.onnx`, `config.json` and `tokenizer.json` in `ComfyUI/models/robin/robin`, and `robin_character_lora.safetensors` in `ComfyUI/models/loras`.
|
| 118 |
+
|
| 119 |
+
Two workflows to start from. Drag one onto the ComfyUI canvas:
|
| 120 |
+
|
| 121 |
+
- [`Robin - LoRA Voice Inference Official.json`](comfyui-workflow-examples/Robin%20-%20LoRA%20Voice%20Inference%20Official.json): Robin's own voice reads a line.
|
| 122 |
+
- [`Robin - LoRA Voice Training Official.json`](comfyui-workflow-examples/Robin%20-%20LoRA%20Voice%20Training%20Official.json): checks a folder of clips and trains a voice LoRA on it.
|
| 123 |
+
|
| 124 |
+
| Node | |
|
| 125 |
+
|---|---|
|
| 126 |
+
| **Robin Loader** | Loads Robin, downloading whatever is missing on the first run. Its readout shows what is on disk, what is downloading and when Robin is ready. |
|
| 127 |
+
| **Robin LoRA** | Applies a voice LoRA at any strength from 0 to 2. `robin_character_lora.safetensors` is Robin's own voice; the voices you train are listed under `robin/`. |
|
| 128 |
+
| **Robin Speak** | Reads text in a voice you describe, or in the LoRA's voice. Long text is read in steady pieces, and tags like `[laughs]` can go anywhere. The last take plays on the node, with a download button; connect Save Audio to keep every take. |
|
| 129 |
+
| **Robin Voice Changer** | Performs a recording of up to 45 seconds again in another voice, keeping its words, timing and delivery. Give it exactly what the recording says. |
|
| 130 |
+
| **Robin Load Audio** | The recording for the Voice Changer. **Record** takes a line from your microphone and trims the silence around it; **Choose file**, or dropping a file on the node, adds one from your computer. Both are kept in `ComfyUI/input`. Recording works when ComfyUI is open on localhost or over https. |
|
| 131 |
+
| **Robin Check Dataset** | Checks a folder of clips before training. **Choose folder** uploads one from your computer into `ComfyUI/input/robin_datasets`, or type a path on the machine running ComfyUI. The report lists the clips it will leave out, and why. |
|
| 132 |
+
| **Robin Train LoRA** | Trains a voice LoRA on the checked folder, with live steps, losses and time left. Every save writes a checkpoint and reads the sample line in the new voice, which you can play on the node. Ranks, learning rates and the other settings fold away under **advanced**. Cancel the queue to stop; queue it again to continue from the last save. |
|
| 133 |
+
|
| 134 |
+

|
| 135 |
+
|
| 136 |
+
Trained voices are saved in `ComfyUI/models/loras/robin/<name>`: the finished `lora.safetensors`, and a checkpoint for each save.
|
| 137 |
+
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Fixed Seed Open License
|
| 3 |
+
Version 1.0, November 2026
|
| 4 |
+
|
| 5 |
+
This License is based on the Apache License, Version 2.0. It adds a
|
| 6 |
+
limit on Commercial Use above a revenue threshold (Section 5), a section
|
| 7 |
+
on Output (Section 6), termination (Section 12) and governing law
|
| 8 |
+
(Section 13), and makes the grants in Sections 2 and 3 subject to the
|
| 9 |
+
limit. Fixed Seed may publish new versions of this License; a Work
|
| 10 |
+
stays under the version it was released with.
|
| 11 |
+
|
| 12 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 13 |
+
|
| 14 |
+
1. Definitions.
|
| 15 |
+
|
| 16 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 17 |
+
and distribution as defined by Sections 1 through 13 of this document.
|
| 18 |
+
|
| 19 |
+
"Licensor" shall mean Fixed Seed LLC, a California limited liability
|
| 20 |
+
company doing business as Fixed Seed Research Laboratory ("Fixed
|
| 21 |
+
Seed").
|
| 22 |
+
|
| 23 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 24 |
+
other entities that control, are controlled by, or are under common
|
| 25 |
+
control with that entity. For the purposes of this definition,
|
| 26 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 27 |
+
direction or management of such entity, whether by contract or
|
| 28 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 29 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 30 |
+
|
| 31 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 32 |
+
exercising permissions granted by this License.
|
| 33 |
+
|
| 34 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 35 |
+
including but not limited to model weights and parameters, software
|
| 36 |
+
source code, documentation source, and configuration files.
|
| 37 |
+
|
| 38 |
+
"Object" form shall mean any form resulting from mechanical
|
| 39 |
+
transformation or translation of a Source form, including but
|
| 40 |
+
not limited to compiled object code, generated documentation,
|
| 41 |
+
and conversions to other media types.
|
| 42 |
+
|
| 43 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 44 |
+
Object form, made available under the License, as indicated by a
|
| 45 |
+
copyright notice that is included in or attached to the work
|
| 46 |
+
(an example is provided in the Appendix below).
|
| 47 |
+
|
| 48 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 49 |
+
form, that is based on (or derived from) the Work and for which the
|
| 50 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 51 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 52 |
+
of this License, Derivative Works shall not include works that remain
|
| 53 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 54 |
+
the Work and Derivative Works thereof. For the avoidance of doubt,
|
| 55 |
+
Derivative Works include any model, weights or adapter (including
|
| 56 |
+
LoRA and similar adapter weights) made by training, fine-tuning,
|
| 57 |
+
merging, quantizing, pruning or distilling the Work or a Derivative
|
| 58 |
+
Work.
|
| 59 |
+
|
| 60 |
+
"Contribution" shall mean any work of authorship, including
|
| 61 |
+
the original version of the Work and any modifications or additions
|
| 62 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 63 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 64 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 65 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 66 |
+
means any form of electronic, verbal, or written communication sent
|
| 67 |
+
to the Licensor or its representatives, including but not limited to
|
| 68 |
+
communication on electronic mailing lists, source code control systems,
|
| 69 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 70 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 71 |
+
excluding communication that is conspicuously marked or otherwise
|
| 72 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 73 |
+
|
| 74 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 75 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 76 |
+
subsequently incorporated within the Work.
|
| 77 |
+
|
| 78 |
+
"Output" shall mean audio, speech, speech tokens, latents and any
|
| 79 |
+
other content generated by running the Work or a Derivative Work.
|
| 80 |
+
|
| 81 |
+
"Commercial Use" shall mean any use of the Work, a Derivative Work or
|
| 82 |
+
Output that is directed toward commercial advantage or monetary
|
| 83 |
+
compensation, including offering the Work or a Derivative Work, or
|
| 84 |
+
access to either, as a product or service, and using the Work, a
|
| 85 |
+
Derivative Work or Output in or to make products, services or
|
| 86 |
+
content that are sold, licensed or otherwise monetized.
|
| 87 |
+
|
| 88 |
+
"Attributable Revenue" shall mean the gross revenue, before
|
| 89 |
+
deductions of any kind, that You receive from (i) the Work or any
|
| 90 |
+
Derivative Work, or access to either (for example through an
|
| 91 |
+
application, an API or a hosted service), and (ii) any product,
|
| 92 |
+
service or content that uses, includes or was made with the Work, a
|
| 93 |
+
Derivative Work or Output, including through sales, subscriptions,
|
| 94 |
+
licensing, advertising and usage fees. Revenue from such a product,
|
| 95 |
+
service or content counts in full and is not apportioned among its
|
| 96 |
+
parts. Where You are a Legal Entity, Attributable Revenue includes
|
| 97 |
+
the revenue of every entity that makes up that Legal Entity.
|
| 98 |
+
|
| 99 |
+
"Threshold" shall mean two million United States dollars
|
| 100 |
+
(US$2,000,000) of Attributable Revenue in any period of twelve (12)
|
| 101 |
+
consecutive months.
|
| 102 |
+
|
| 103 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 104 |
+
this License, including the Commercial Use Limitation in Section 5,
|
| 105 |
+
each Contributor hereby grants to You a perpetual, worldwide,
|
| 106 |
+
non-exclusive, no-charge, royalty-free, irrevocable (except as stated
|
| 107 |
+
in Sections 5 and 12) copyright license to reproduce, prepare
|
| 108 |
+
Derivative Works of, publicly display, publicly perform, sublicense,
|
| 109 |
+
and distribute the Work and such Derivative Works in Source or
|
| 110 |
+
Object form.
|
| 111 |
+
|
| 112 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 113 |
+
this License, including the Commercial Use Limitation in Section 5,
|
| 114 |
+
each Contributor hereby grants to You a perpetual, worldwide,
|
| 115 |
+
non-exclusive, no-charge, royalty-free, irrevocable (except as stated
|
| 116 |
+
in this section and in Sections 5 and 12) patent license to make,
|
| 117 |
+
have made, use, offer to sell, sell, import, and otherwise transfer
|
| 118 |
+
the Work,
|
| 119 |
+
where such license applies only to those patent claims licensable
|
| 120 |
+
by such Contributor that are necessarily infringed by their
|
| 121 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 122 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 123 |
+
institute patent litigation against any entity (including a
|
| 124 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 125 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 126 |
+
or contributory patent infringement, then any patent licenses
|
| 127 |
+
granted to You under this License for that Work shall terminate
|
| 128 |
+
as of the date such litigation is filed.
|
| 129 |
+
|
| 130 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 131 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 132 |
+
modifications, and in Source or Object form, provided that You
|
| 133 |
+
meet the following conditions:
|
| 134 |
+
|
| 135 |
+
(a) You must give any other recipients of the Work or
|
| 136 |
+
Derivative Works a copy of this License; and
|
| 137 |
+
|
| 138 |
+
(b) You must cause any modified files to carry prominent notices
|
| 139 |
+
stating that You changed the files; and
|
| 140 |
+
|
| 141 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 142 |
+
that You distribute, all copyright, patent, trademark, and
|
| 143 |
+
attribution notices from the Source form of the Work,
|
| 144 |
+
excluding those notices that do not pertain to any part of
|
| 145 |
+
the Derivative Works; and
|
| 146 |
+
|
| 147 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 148 |
+
distribution, then any Derivative Works that You distribute must
|
| 149 |
+
include a readable copy of the attribution notices contained
|
| 150 |
+
within such NOTICE file, excluding those notices that do not
|
| 151 |
+
pertain to any part of the Derivative Works, in at least one
|
| 152 |
+
of the following places: within a NOTICE text file distributed
|
| 153 |
+
as part of the Derivative Works; within the Source form or
|
| 154 |
+
documentation, if provided along with the Derivative Works; or,
|
| 155 |
+
within a display generated by the Derivative Works, if and
|
| 156 |
+
wherever such third-party notices normally appear. The contents
|
| 157 |
+
of the NOTICE file are for informational purposes only and
|
| 158 |
+
do not modify the License. You may add Your own attribution
|
| 159 |
+
notices within Derivative Works that You distribute, alongside
|
| 160 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 161 |
+
that such additional attribution notices cannot be construed
|
| 162 |
+
as modifying the License.
|
| 163 |
+
|
| 164 |
+
(e) You must distribute the Work and any Derivative Works under the
|
| 165 |
+
terms of this License, so that every recipient's Commercial Use
|
| 166 |
+
is subject to Section 5.
|
| 167 |
+
|
| 168 |
+
You may add Your own copyright statement to Your modifications and
|
| 169 |
+
may provide additional or different license terms and conditions
|
| 170 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 171 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 172 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 173 |
+
the conditions stated in this License, and provided that no such
|
| 174 |
+
terms remove or limit Section 5 for any recipient.
|
| 175 |
+
|
| 176 |
+
5. Commercial Use Limitation.
|
| 177 |
+
|
| 178 |
+
(a) Below the Threshold. You may make Commercial Use of the Work,
|
| 179 |
+
Derivative Works and Output under this License for as long as
|
| 180 |
+
Your Attributable Revenue has not exceeded the Threshold.
|
| 181 |
+
|
| 182 |
+
(b) Above the Threshold. If Your Attributable Revenue exceeds the
|
| 183 |
+
Threshold, You must tell Fixed Seed in writing within thirty (30)
|
| 184 |
+
days, at support@fixedseed.com or at another address Fixed Seed
|
| 185 |
+
publishes for this purpose, so that You and Fixed Seed can discuss
|
| 186 |
+
a separate commercial license. Your Commercial Use may continue
|
| 187 |
+
under this License for ninety (90) days after Your Attributable
|
| 188 |
+
Revenue first exceeded the Threshold, while You and Fixed Seed
|
| 189 |
+
negotiate in good faith. After that, this License grants You no
|
| 190 |
+
rights for Commercial Use, and Commercial Use requires a separate
|
| 191 |
+
written agreement with Fixed Seed. Fixed Seed may extend that
|
| 192 |
+
period in writing.
|
| 193 |
+
|
| 194 |
+
(c) Other use. Use that is not Commercial Use, such as personal use,
|
| 195 |
+
research, education and evaluation, is not limited by this
|
| 196 |
+
Section, whatever Your revenue.
|
| 197 |
+
|
| 198 |
+
(d) Good faith. If Fixed Seed asks in writing, You will tell Fixed
|
| 199 |
+
Seed in good faith whether Your Attributable Revenue has
|
| 200 |
+
exceeded the Threshold.
|
| 201 |
+
|
| 202 |
+
6. Output. Fixed Seed claims no ownership of Output. You are responsible
|
| 203 |
+
for Output and for how You use it, including for having any rights
|
| 204 |
+
You need in the text, recordings and other material You give the
|
| 205 |
+
Work or a Derivative Work. Commercial Use of Output is subject to
|
| 206 |
+
Section 5.
|
| 207 |
+
|
| 208 |
+
7. Submission of Contributions. Unless You explicitly state otherwise,
|
| 209 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 210 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 211 |
+
this License, without any additional terms or conditions.
|
| 212 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 213 |
+
the terms of any separate license agreement you may have executed
|
| 214 |
+
with Licensor regarding such Contributions.
|
| 215 |
+
|
| 216 |
+
8. Trademarks. This License does not grant permission to use the trade
|
| 217 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 218 |
+
except as required for reasonable and customary use in describing the
|
| 219 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 220 |
+
|
| 221 |
+
9. Disclaimer of Warranty. Unless required by applicable law or
|
| 222 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 223 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 224 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 225 |
+
implied, including, without limitation, any warranties or conditions
|
| 226 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 227 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 228 |
+
appropriateness of using or redistributing the Work and assume any
|
| 229 |
+
risks associated with Your exercise of permissions under this License.
|
| 230 |
+
|
| 231 |
+
10. Limitation of Liability. In no event and under no legal theory,
|
| 232 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 233 |
+
unless required by applicable law (such as deliberate and grossly
|
| 234 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 235 |
+
liable to You for damages, including any direct, indirect, special,
|
| 236 |
+
incidental, or consequential damages of any character arising as a
|
| 237 |
+
result of this License or out of the use or inability to use the
|
| 238 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 239 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 240 |
+
other commercial damages or losses), even if such Contributor
|
| 241 |
+
has been advised of the possibility of such damages.
|
| 242 |
+
|
| 243 |
+
11. Accepting Warranty or Additional Liability. While redistributing
|
| 244 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 245 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 246 |
+
or other liability obligations and/or rights consistent with this
|
| 247 |
+
License. However, in accepting such obligations, You may act only
|
| 248 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 249 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 250 |
+
defend, and hold each Contributor harmless for any liability
|
| 251 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 252 |
+
of your accepting any such warranty or additional liability.
|
| 253 |
+
|
| 254 |
+
12. Termination. If You fail to comply with any term of this License,
|
| 255 |
+
Your rights under it terminate automatically. They are reinstated if
|
| 256 |
+
You cure the failure within thirty (30) days after You first learn of
|
| 257 |
+
it, unless You have failed to comply with this License before.
|
| 258 |
+
Termination does not end the licenses of anyone who received the Work
|
| 259 |
+
or a Derivative Work from You and complies with this License.
|
| 260 |
+
Sections 9, 10, 12 and 13 survive termination.
|
| 261 |
+
|
| 262 |
+
13. Governing Law. This License is governed by the laws of the State of
|
| 263 |
+
California, without regard to its conflict-of-laws rules.
|
| 264 |
+
|
| 265 |
+
END OF TERMS AND CONDITIONS
|
| 266 |
+
|
| 267 |
+
APPENDIX: How to apply this License to your work.
|
| 268 |
+
|
| 269 |
+
Include a copy of this License with the Work, and a NOTICE file that
|
| 270 |
+
names the Work and its copyright owner, for example:
|
| 271 |
+
|
| 272 |
+
Robin
|
| 273 |
+
Copyright 2026 Fixed Seed LLC
|
| 274 |
+
|
| 275 |
+
Licensed under the Fixed Seed Open License, Version 1.0 (the
|
| 276 |
+
"License"); you may not use this file except in compliance with the
|
| 277 |
+
License. You may obtain a copy of the License in the LICENSE file
|
| 278 |
+
distributed with this Work.
|
| 279 |
+
|
| 280 |
+
Unless required by applicable law or agreed to in writing, software
|
| 281 |
+
and models distributed under the License are distributed on an
|
| 282 |
+
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
|
| 283 |
+
express or implied. See the License for the specific language
|
| 284 |
+
governing permissions and limitations under the License.
|
comfyui-robin/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
|
| 2 |
+
|
| 3 |
+
WEB_DIRECTORY = './web'
|
| 4 |
+
|
| 5 |
+
__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS', 'WEB_DIRECTORY']
|
comfyui-robin/nodes.py
ADDED
|
@@ -0,0 +1,618 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import hashlib
|
| 3 |
+
import logging
|
| 4 |
+
import math
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
import shutil
|
| 8 |
+
import subprocess
|
| 9 |
+
import sys
|
| 10 |
+
import time
|
| 11 |
+
import uuid
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
import soundfile as sf
|
| 16 |
+
import torch
|
| 17 |
+
from aiohttp import web
|
| 18 |
+
|
| 19 |
+
import comfy.model_management as mm
|
| 20 |
+
import comfy.model_patcher
|
| 21 |
+
import comfy.utils
|
| 22 |
+
import folder_paths
|
| 23 |
+
from server import PromptServer
|
| 24 |
+
|
| 25 |
+
from .robin import Robin, pieces
|
| 26 |
+
from .robin import train as trainer
|
| 27 |
+
from .robin.vae import load_vae
|
| 28 |
+
from .robin.pipeline import SPEECH, VAE, WEIGHTS
|
| 29 |
+
|
| 30 |
+
folder_paths.add_model_folder_path('robin', os.path.join(folder_paths.models_dir, 'robin'))
|
| 31 |
+
|
| 32 |
+
REPO, MODEL, LORA = 'FixedSeed/Robin', 'robin', 'robin_character_lora.safetensors'
|
| 33 |
+
MODEL_FILES = (WEIGHTS, 'config.json', 'tokenizer.json', SPEECH)
|
| 34 |
+
DTYPES = dict(bf16=torch.bfloat16, fp32=torch.float32)
|
| 35 |
+
LANGUAGES = {'English': 'en', 'Japanese': 'ja', 'English + Japanese': 'mix'}
|
| 36 |
+
UPLOADS = 'robin_datasets'
|
| 37 |
+
SOUND_FILES = ('.wav', '.flac', '.mp3', '.ogg', '.opus', '.aiff', '.aif')
|
| 38 |
+
MAX_SOURCE_SECONDS = 45
|
| 39 |
+
WORKING_MEMORY = 2 * 1024 ** 3
|
| 40 |
+
TRAINING_MEMORY = 4 * 1024 ** 3
|
| 41 |
+
NAME = re.compile(r'[A-Za-z0-9][A-Za-z0-9_.-]{0,63}')
|
| 42 |
+
SAVED = re.compile(r'step_\d+')
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def model_folders():
|
| 46 |
+
found = set()
|
| 47 |
+
for base in folder_paths.get_folder_paths('robin'):
|
| 48 |
+
base = Path(base)
|
| 49 |
+
if base.is_dir():
|
| 50 |
+
for config in base.rglob('config.json'):
|
| 51 |
+
if config.parent != base and (config.parent/WEIGHTS).is_file():
|
| 52 |
+
found.add(config.parent.relative_to(base).as_posix())
|
| 53 |
+
return [MODEL] + sorted(found - {MODEL})
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def model_path(name):
|
| 57 |
+
for base in folder_paths.get_folder_paths('robin'):
|
| 58 |
+
path = Path(base)/name
|
| 59 |
+
if (path/'config.json').is_file():
|
| 60 |
+
return path
|
| 61 |
+
return Path(folder_paths.get_folder_paths('robin')[0])/name
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def shown(path):
|
| 65 |
+
try:
|
| 66 |
+
return Path(path).resolve().relative_to(Path(folder_paths.base_path).resolve()).as_posix()
|
| 67 |
+
except ValueError:
|
| 68 |
+
return str(path)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def own_vae(vae):
|
| 72 |
+
return vae == VAE and not folder_paths.get_full_path('vae', VAE)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def model_status(model, vae=VAE):
|
| 76 |
+
path = model_path(model)
|
| 77 |
+
files = MODEL_FILES + ((VAE,) if own_vae(vae) else ())
|
| 78 |
+
present = [path/f for f in files if (path/f).is_file()]
|
| 79 |
+
return dict(model=model, ready=len(present) == len(files), size=sum(f.stat().st_size for f in present),
|
| 80 |
+
voice=bool(folder_paths.get_full_path('loras', LORA)))
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def download(file, folder):
|
| 84 |
+
from huggingface_hub import hf_hub_download
|
| 85 |
+
logging.info(f'Robin: downloading {file} from Hugging Face ({REPO}) into {folder}')
|
| 86 |
+
try:
|
| 87 |
+
hf_hub_download(REPO, file, local_dir=str(folder))
|
| 88 |
+
except Exception as e:
|
| 89 |
+
raise RuntimeError(f'Robin could not download {file} from Hugging Face ({REPO}): {e}') from e
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def lora_path():
|
| 93 |
+
found = folder_paths.get_full_path('loras', LORA)
|
| 94 |
+
if found:
|
| 95 |
+
return found
|
| 96 |
+
folder = Path(folder_paths.get_folder_paths('loras')[0])
|
| 97 |
+
download(LORA, folder)
|
| 98 |
+
return str(folder/LORA)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def loras():
|
| 102 |
+
found = [f for f in folder_paths.get_filename_list('loras') if f.endswith('.safetensors') and '/cache/' not in f.replace(os.sep, '/')]
|
| 103 |
+
return [LORA] + [f for f in found if f != LORA]
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def input_audio():
|
| 107 |
+
folder = Path(folder_paths.get_input_directory())
|
| 108 |
+
return sorted(f.name for f in folder.iterdir() if f.is_file() and f.suffix.lower() in SOUND_FILES) if folder.is_dir() else []
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def dataset_path(folder):
|
| 112 |
+
path = Path(folder.strip()).expanduser()
|
| 113 |
+
return path if path.is_absolute() else Path(folder_paths.get_input_directory())/path
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def folder_signature(folder):
|
| 117 |
+
path = dataset_path(folder)
|
| 118 |
+
if not folder.strip() or not path.is_dir():
|
| 119 |
+
return ''
|
| 120 |
+
files = sorted(f for f in path.rglob('*') if f.is_file())
|
| 121 |
+
return hashlib.sha256('\n'.join(f'{f}:{f.stat().st_size}:{f.stat().st_mtime_ns}' for f in files).encode()).hexdigest()
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def check_folder(folder, language):
|
| 125 |
+
if not folder.strip():
|
| 126 |
+
return None, 'Choose a folder of clips, or type its path.'
|
| 127 |
+
path = dataset_path(folder)
|
| 128 |
+
if not path.is_dir():
|
| 129 |
+
return None, f'There is no folder at {path}.'
|
| 130 |
+
lang = LANGUAGES[language]
|
| 131 |
+
found = trainer.scan(path, lang)
|
| 132 |
+
found['folder'] = shown(path)
|
| 133 |
+
lines = []
|
| 134 |
+
try:
|
| 135 |
+
trainer.describe(found, log=lines.append)
|
| 136 |
+
except SystemExit as e:
|
| 137 |
+
lines.append(str(e))
|
| 138 |
+
return dict(folder=str(path), lang=lang), '\n'.join(lines)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def tell(event, node, **data):
|
| 142 |
+
server = PromptServer.instance
|
| 143 |
+
data = {k: None if isinstance(v, float) and not math.isfinite(v) else v for k, v in data.items()}
|
| 144 |
+
server.send_sync(event, dict(node=node, **data), server.client_id)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def preview(path, subfolder):
|
| 148 |
+
folder = Path(folder_paths.get_temp_directory())/subfolder
|
| 149 |
+
folder.mkdir(parents=True, exist_ok=True)
|
| 150 |
+
shutil.copyfile(path, folder/Path(path).name)
|
| 151 |
+
return dict(filename=Path(path).name, subfolder=subfolder, type='temp')
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def take(audio, seed):
|
| 155 |
+
folder = Path(folder_paths.get_temp_directory())/'robin'
|
| 156 |
+
folder.mkdir(parents=True, exist_ok=True)
|
| 157 |
+
name = f'take_{uuid.uuid4().hex[:12]}.flac'
|
| 158 |
+
sf.write(str(folder/name), np.clip(audio, -1, 1), pieces.RATE, subtype='PCM_24')
|
| 159 |
+
return dict(filename=name, subfolder='robin', type='temp', seconds=round(len(audio) / pieces.RATE, 2), seed=seed)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def trainable(robin):
|
| 163 |
+
for net in (robin.planner, robin.decoder):
|
| 164 |
+
for module in net.modules():
|
| 165 |
+
for key, value in list(module._parameters.items()):
|
| 166 |
+
if value is not None and value.is_inference():
|
| 167 |
+
module._parameters[key] = torch.nn.Parameter(value.clone(), requires_grad=False)
|
| 168 |
+
for key, value in list(module._buffers.items()):
|
| 169 |
+
if value is not None and value.is_inference():
|
| 170 |
+
module._buffers[key] = value.clone()
|
| 171 |
+
for key, value in list(vars(module).items()):
|
| 172 |
+
if isinstance(value, torch.Tensor) and value.is_inference():
|
| 173 |
+
setattr(module, key, value.clone())
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def devices():
|
| 177 |
+
return ['default', 'cpu'] + ([f'cuda:{i}' for i in range(torch.cuda.device_count())] if torch.cuda.device_count() > 1 else [])
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class Core:
|
| 181 |
+
def __init__(self, robin, load_device, offload_device):
|
| 182 |
+
self.robin, self.load_device, self.offload_device = robin, load_device, offload_device
|
| 183 |
+
bundle = torch.nn.ModuleDict(dict(planner=robin.planner, decoder=robin.decoder, vae=robin.vae))
|
| 184 |
+
self.patcher = self.patch(bundle)
|
| 185 |
+
self.speech_patcher = self.lora_patcher = None
|
| 186 |
+
self.lora_file = None
|
| 187 |
+
|
| 188 |
+
def patch(self, module):
|
| 189 |
+
return comfy.model_patcher.ModelPatcher(module, load_device=self.load_device, offload_device=self.offload_device)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
class RobinModel:
|
| 193 |
+
def __init__(self, core, lora=None):
|
| 194 |
+
self.core, self.lora = core, lora
|
| 195 |
+
|
| 196 |
+
def ready(self, speech=False, memory=WORKING_MEMORY):
|
| 197 |
+
core, robin = self.core, self.core.robin
|
| 198 |
+
if self.lora is None:
|
| 199 |
+
if robin.lora is not None:
|
| 200 |
+
robin.remove_lora(); core.lora_patcher = core.lora_file = None
|
| 201 |
+
else:
|
| 202 |
+
path, scale = self.lora
|
| 203 |
+
if core.lora_file != path:
|
| 204 |
+
robin.load_lora(path, scale)
|
| 205 |
+
core.lora_file, core.lora_patcher = path, core.patch(robin.lora)
|
| 206 |
+
robin.set_lora_scale(scale)
|
| 207 |
+
patchers = [core.patcher] + ([core.lora_patcher] if core.lora_patcher else [])
|
| 208 |
+
if speech:
|
| 209 |
+
tokenizer = robin.speech
|
| 210 |
+
if core.speech_patcher is None:
|
| 211 |
+
core.speech_patcher = core.patch(torch.nn.ModuleDict(dict(speech=tokenizer.model)))
|
| 212 |
+
patchers.append(core.speech_patcher)
|
| 213 |
+
mm.load_models_gpu(patchers, memory_required=memory, force_full_load=True)
|
| 214 |
+
return robin
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
class Progress:
|
| 218 |
+
def __init__(self, renders):
|
| 219 |
+
self.bar, self.total, self.done = comfy.utils.ProgressBar(100 * renders), renders, 0
|
| 220 |
+
self.expected, self.plan, self.decode = 1, 0., 0.
|
| 221 |
+
|
| 222 |
+
def start(self, seconds):
|
| 223 |
+
self.expected, self.plan, self.decode = max(1., seconds * 25), 0., 0.
|
| 224 |
+
self.show()
|
| 225 |
+
|
| 226 |
+
def __call__(self, stage, step, total):
|
| 227 |
+
mm.throw_exception_if_processing_interrupted()
|
| 228 |
+
if stage == 'plan':
|
| 229 |
+
self.plan = min(1., step / self.expected)
|
| 230 |
+
if step % 25: return
|
| 231 |
+
else:
|
| 232 |
+
self.plan, self.decode = 1., step / total
|
| 233 |
+
self.show()
|
| 234 |
+
|
| 235 |
+
def finish(self, extra=0):
|
| 236 |
+
self.done += 1; self.total += extra; self.show()
|
| 237 |
+
|
| 238 |
+
def show(self):
|
| 239 |
+
within = .8 * self.plan + .2 * self.decode
|
| 240 |
+
self.bar.update_absolute(int(100 * (self.done + (within if self.done < self.total else 0))), 100 * self.total)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def mono(audio):
|
| 244 |
+
wave = audio['waveform']
|
| 245 |
+
return wave[0].float().mean(0).cpu().numpy(), int(audio['sample_rate'])
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def to_audio(x, rate=pieces.RATE):
|
| 249 |
+
return {'waveform': torch.from_numpy(np.ascontiguousarray(x, dtype=np.float32))[None, None], 'sample_rate': rate}
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
SAMPLING = {
|
| 253 |
+
'seed': ('INT', {'default': 0, 'min': 0, 'max': 0xffffffffffffffff, 'control_after_generate': True}),
|
| 254 |
+
'temperature': ('FLOAT', {'default': .9, 'min': 0., 'max': 2., 'step': .01, 'tooltip': 'Higher is livelier and less predictable; 0 always picks the likeliest sound.'}),
|
| 255 |
+
'top_k': ('INT', {'default': 25, 'min': 0, 'max': 500, 'tooltip': 'Choose among only this many likeliest sounds at each step (0 = no limit).'}),
|
| 256 |
+
'top_p': ('FLOAT', {'default': .8, 'min': .01, 'max': 1., 'step': .01, 'tooltip': 'Choose among only the likeliest sounds that add up to this share.'}),
|
| 257 |
+
}
|
| 258 |
+
RETRIES = ('INT', {'default': 2, 'min': 0, 'max': 6, 'advanced': True,
|
| 259 |
+
'tooltip': 'Tries a piece again with a new seed when it comes out silent or the wrong length.'})
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
class RobinLoader:
|
| 263 |
+
DESCRIPTION = ('Loads Robin from a folder in models/robin. The first run downloads whatever is missing from Hugging Face, '
|
| 264 |
+
f'along with Robin\'s own voice ({LORA}) for the Robin LoRA node.')
|
| 265 |
+
RETURN_TYPES = ('ROBIN_MODEL',)
|
| 266 |
+
RETURN_NAMES = ('robin',)
|
| 267 |
+
FUNCTION = 'load'
|
| 268 |
+
CATEGORY = 'Robin'
|
| 269 |
+
|
| 270 |
+
@classmethod
|
| 271 |
+
def INPUT_TYPES(cls):
|
| 272 |
+
return {
|
| 273 |
+
'required': {
|
| 274 |
+
'model': (model_folders(), {'default': MODEL, 'tooltip': f'A Robin folder in models/robin. "{MODEL}" is downloaded on the first run if it is not there yet.'}),
|
| 275 |
+
'vae': ([VAE] + [f for f in folder_paths.get_filename_list('vae') if f != VAE],
|
| 276 |
+
{'default': VAE, 'tooltip': f'The VAE weights Robin decodes with. {VAE} is downloaded into the Robin folder on the '
|
| 277 |
+
'first run, unless models/vae already has it.'}),
|
| 278 |
+
'device': (devices(), {'default': 'default'}),
|
| 279 |
+
'dtype': (list(DTYPES), {'default': 'bf16', 'tooltip': 'bf16 needs about 8 GB of GPU memory; fp32 about twice that.'}),
|
| 280 |
+
},
|
| 281 |
+
'hidden': {'unique_id': 'UNIQUE_ID'},
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
def load(self, model, vae, device, dtype, unique_id=None):
|
| 285 |
+
path = model_path(model)
|
| 286 |
+
missing = [f for f in MODEL_FILES + ((VAE,) if own_vae(vae) else ()) if not (path/f).is_file()]
|
| 287 |
+
for file in missing:
|
| 288 |
+
tell('robin.loader', unique_id, stage='download', file=file)
|
| 289 |
+
download(file, path)
|
| 290 |
+
if not folder_paths.get_full_path('loras', LORA):
|
| 291 |
+
tell('robin.loader', unique_id, stage='download', file=LORA)
|
| 292 |
+
lora_path()
|
| 293 |
+
tell('robin.loader', unique_id, stage='load')
|
| 294 |
+
load_device = mm.get_torch_device() if device == 'default' else torch.device(device)
|
| 295 |
+
offload_device = load_device if load_device.type == 'cpu' else mm.unet_offload_device()
|
| 296 |
+
vae_file = path/VAE if own_vae(vae) else folder_paths.get_full_path_or_raise('vae', vae)
|
| 297 |
+
try:
|
| 298 |
+
decoder = load_vae(vae_file, offload_device)
|
| 299 |
+
except (RuntimeError, KeyError) as e:
|
| 300 |
+
raise ValueError(f'{vae} is not a VAE Robin can decode with.') from e
|
| 301 |
+
robin = Robin.from_pretrained(str(path), vae=decoder, device=offload_device, dtype=DTYPES[dtype])
|
| 302 |
+
robin.device = load_device
|
| 303 |
+
status = dict(model_status(model, vae), loaded=dtype, downloaded=bool(missing))
|
| 304 |
+
return {'ui': {'robin_status': [status]}, 'result': (RobinModel(Core(robin, load_device, offload_device)),)}
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
class RobinLoRA:
|
| 308 |
+
DESCRIPTION = (f'Applies a voice LoRA trained with Robin. {LORA} is Robin\'s own voice. One LoRA at a time: a second LoRA node '
|
| 309 |
+
'replaces the first.')
|
| 310 |
+
RETURN_TYPES = ('ROBIN_MODEL',)
|
| 311 |
+
RETURN_NAMES = ('robin',)
|
| 312 |
+
FUNCTION = 'apply'
|
| 313 |
+
CATEGORY = 'Robin'
|
| 314 |
+
|
| 315 |
+
@classmethod
|
| 316 |
+
def INPUT_TYPES(cls):
|
| 317 |
+
return {
|
| 318 |
+
'required': {
|
| 319 |
+
'robin': ('ROBIN_MODEL',),
|
| 320 |
+
'lora': (loras(), {'default': LORA}),
|
| 321 |
+
'strength': ('FLOAT', {'default': 1., 'min': 0., 'max': 2., 'step': .05, 'tooltip': '1 is the voice as trained, 0 is Robin without the LoRA.'}),
|
| 322 |
+
},
|
| 323 |
+
}
|
| 324 |
+
|
| 325 |
+
def apply(self, robin, lora, strength):
|
| 326 |
+
path = lora_path() if lora == LORA else folder_paths.get_full_path_or_raise('loras', lora)
|
| 327 |
+
from safetensors import safe_open
|
| 328 |
+
with safe_open(path, framework='pt', device='cpu') as f:
|
| 329 |
+
if 'robin_lora' not in (f.metadata() or {}):
|
| 330 |
+
raise ValueError(f'{lora} is not a Robin LoRA.')
|
| 331 |
+
return (RobinModel(robin.core, (path, strength)),)
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
class RobinSpeak:
|
| 335 |
+
DESCRIPTION = ('Reads text aloud in a voice you describe. Long text is read in pieces that carry the voice from one to the next. '
|
| 336 |
+
'[laughs] and [coughs] can go anywhere in the text. The last take plays on the node; connect Save Audio to keep '
|
| 337 |
+
'every take in the output folder.')
|
| 338 |
+
RETURN_TYPES = ('AUDIO',)
|
| 339 |
+
RETURN_NAMES = ('audio',)
|
| 340 |
+
FUNCTION = 'speak'
|
| 341 |
+
OUTPUT_NODE = True
|
| 342 |
+
CATEGORY = 'Robin'
|
| 343 |
+
|
| 344 |
+
@classmethod
|
| 345 |
+
def INPUT_TYPES(cls):
|
| 346 |
+
return {
|
| 347 |
+
'required': {
|
| 348 |
+
'robin': ('ROBIN_MODEL',),
|
| 349 |
+
'text': ('STRING', {'multiline': True, 'default': 'Hello there! [laughs] It is so good to finally hear my own voice.',
|
| 350 |
+
'tooltip': 'What to say. [laughs] and [coughs] can go anywhere in it.'}),
|
| 351 |
+
'voice': ('STRING', {'multiline': True, 'default': 'A warm, low voice, unhurried and close to the mic.',
|
| 352 |
+
'tooltip': 'The voice in plain words: age, pitch, pace, mood, how close to the mic. Leave it empty to let Robin choose.'}),
|
| 353 |
+
**SAMPLING,
|
| 354 |
+
'cfg': ('FLOAT', {'default': 1., 'min': 1., 'max': 10., 'step': .1,
|
| 355 |
+
'tooltip': 'Above 1 follows the voice description more closely (try 3).'}),
|
| 356 |
+
},
|
| 357 |
+
'optional': {
|
| 358 |
+
'retries': RETRIES,
|
| 359 |
+
'max_words': ('INT', {'default': 35, 'min': 8, 'max': 60, 'advanced': True, 'tooltip': 'Long text is read in pieces of about this many words.'}),
|
| 360 |
+
'language': (list(LANGUAGES), {'default': 'English', 'tooltip': 'The language of the text. English + Japanese is for lines that mix the two.'}),
|
| 361 |
+
},
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
def speak(self, robin, text, voice, seed, temperature, top_k, top_p, cfg, retries=2, max_words=35, language='English'):
|
| 365 |
+
lang = LANGUAGES[language]
|
| 366 |
+
chunks = pieces.split(text, max_words, lang)
|
| 367 |
+
if not chunks:
|
| 368 |
+
raise ValueError('There is no text to read.')
|
| 369 |
+
model = robin.ready(speech=len(chunks) > 1)
|
| 370 |
+
audio = pieces.read(model, text, voice, seed=seed, cfg=cfg, retries=retries, max_words=max_words, lang=lang,
|
| 371 |
+
progress=Progress(len(chunks)), temperature=temperature, top_k=top_k, top_p=top_p)
|
| 372 |
+
return {'ui': {'robin_take': [take(audio, seed)]}, 'result': (to_audio(audio),)}
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
class RobinVoiceChanger:
|
| 376 |
+
DESCRIPTION = ('Performs a recording again in another voice: the same words, timing and delivery. The new voice comes from the '
|
| 377 |
+
'description, and from a Robin LoRA when one is connected. The last take plays on the node; connect Save Audio to '
|
| 378 |
+
'keep every take in the output folder.')
|
| 379 |
+
RETURN_TYPES = ('AUDIO',)
|
| 380 |
+
RETURN_NAMES = ('audio',)
|
| 381 |
+
FUNCTION = 'change'
|
| 382 |
+
OUTPUT_NODE = True
|
| 383 |
+
CATEGORY = 'Robin'
|
| 384 |
+
|
| 385 |
+
@classmethod
|
| 386 |
+
def INPUT_TYPES(cls):
|
| 387 |
+
return {
|
| 388 |
+
'required': {
|
| 389 |
+
'robin': ('ROBIN_MODEL',),
|
| 390 |
+
'source_audio': ('AUDIO', {'tooltip': f'The performance to keep, up to {MAX_SOURCE_SECONDS} seconds.'}),
|
| 391 |
+
'source_text': ('STRING', {'multiline': True, 'default': '', 'tooltip': 'Exactly what the source clip says.'}),
|
| 392 |
+
'voice': ('STRING', {'multiline': True, 'default': '',
|
| 393 |
+
'tooltip': 'The new voice in plain words. It can stay empty when a Robin LoRA is connected.'}),
|
| 394 |
+
**SAMPLING,
|
| 395 |
+
},
|
| 396 |
+
'optional': {
|
| 397 |
+
'retries': RETRIES,
|
| 398 |
+
'language': (list(LANGUAGES), {'default': 'English', 'tooltip': 'The language of the recording. English + Japanese is for lines that mix the two.'}),
|
| 399 |
+
},
|
| 400 |
+
}
|
| 401 |
+
|
| 402 |
+
def change(self, robin, source_audio, source_text, voice, seed, temperature, top_k, top_p, retries=2, language='English'):
|
| 403 |
+
if not source_text.strip():
|
| 404 |
+
raise ValueError('Fill in source_text with exactly what the source clip says.')
|
| 405 |
+
if not voice.strip() and robin.lora is None:
|
| 406 |
+
raise ValueError('Describe the new voice, or connect a Robin LoRA.')
|
| 407 |
+
source, source_rate = mono(source_audio)
|
| 408 |
+
seconds = len(source) / source_rate
|
| 409 |
+
if seconds > MAX_SOURCE_SECONDS:
|
| 410 |
+
raise ValueError(f'The source clip is {seconds:.0f} s long; the Voice Changer takes up to {MAX_SOURCE_SECONDS} s at a time.')
|
| 411 |
+
model = robin.ready(speech=True)
|
| 412 |
+
audio = pieces.change(model, source, source_rate, source_text, voice=voice, seed=seed, retries=retries, lang=LANGUAGES[language],
|
| 413 |
+
progress=Progress(2), temperature=temperature, top_k=top_k, top_p=top_p)
|
| 414 |
+
return {'ui': {'robin_take': [take(audio, seed)]}, 'result': (to_audio(audio),)}
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
class RobinLoadAudio:
|
| 418 |
+
DESCRIPTION = ('A recording for the Voice Changer: record one with your microphone, or choose an audio file. Recordings are '
|
| 419 |
+
'trimmed to the line and kept in ComfyUI\'s input folder.')
|
| 420 |
+
RETURN_TYPES = ('AUDIO',)
|
| 421 |
+
RETURN_NAMES = ('audio',)
|
| 422 |
+
FUNCTION = 'load'
|
| 423 |
+
CATEGORY = 'Robin'
|
| 424 |
+
|
| 425 |
+
@classmethod
|
| 426 |
+
def INPUT_TYPES(cls):
|
| 427 |
+
return {
|
| 428 |
+
'required': {
|
| 429 |
+
'audio': (input_audio(), {'tooltip': 'A recording in ComfyUI\'s input folder. Record and Choose file add new ones.'}),
|
| 430 |
+
},
|
| 431 |
+
}
|
| 432 |
+
|
| 433 |
+
@classmethod
|
| 434 |
+
def IS_CHANGED(cls, audio):
|
| 435 |
+
path = Path(folder_paths.get_annotated_filepath(audio))
|
| 436 |
+
return hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else ''
|
| 437 |
+
|
| 438 |
+
@classmethod
|
| 439 |
+
def VALIDATE_INPUTS(cls, audio):
|
| 440 |
+
if not audio or not folder_paths.exists_annotated_filepath(audio):
|
| 441 |
+
return 'Record a line or choose an audio file first.' if not audio else f'There is no {audio} in ComfyUI\'s input folder.'
|
| 442 |
+
return True
|
| 443 |
+
|
| 444 |
+
def load(self, audio):
|
| 445 |
+
x, rate = sf.read(folder_paths.get_annotated_filepath(audio), dtype='float32', always_2d=True)
|
| 446 |
+
return ({'waveform': torch.from_numpy(np.ascontiguousarray(x.T))[None], 'sample_rate': int(rate)},)
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
class RobinCheckDataset:
|
| 450 |
+
DESCRIPTION = ('Checks a folder of clips for training a voice: each audio file needs a .txt transcript with the same name, and a '
|
| 451 |
+
'voice.txt can describe the voice. Lists the clips it will leave out and anything worth fixing, in plain words. '
|
| 452 |
+
f'Choose folder uploads a folder from your computer into input/{UPLOADS}.')
|
| 453 |
+
RETURN_TYPES = ('ROBIN_DATASET', 'STRING')
|
| 454 |
+
RETURN_NAMES = ('dataset', 'report')
|
| 455 |
+
FUNCTION = 'check'
|
| 456 |
+
OUTPUT_NODE = True
|
| 457 |
+
CATEGORY = 'Robin'
|
| 458 |
+
|
| 459 |
+
@classmethod
|
| 460 |
+
def INPUT_TYPES(cls):
|
| 461 |
+
return {
|
| 462 |
+
'required': {
|
| 463 |
+
'folder': ('STRING', {'default': '', 'tooltip': 'The folder of clips: audio files, each with a .txt transcript of the same name. '
|
| 464 |
+
'A relative path is inside ComfyUI\'s input folder.'}),
|
| 465 |
+
'language': (list(LANGUAGES), {'default': 'English', 'tooltip': 'The language of the recordings.'}),
|
| 466 |
+
},
|
| 467 |
+
}
|
| 468 |
+
|
| 469 |
+
@classmethod
|
| 470 |
+
def IS_CHANGED(cls, folder, language):
|
| 471 |
+
return folder_signature(folder) + language
|
| 472 |
+
|
| 473 |
+
def check(self, folder, language):
|
| 474 |
+
dataset, report = check_folder(folder, language)
|
| 475 |
+
if dataset is None:
|
| 476 |
+
raise ValueError(report)
|
| 477 |
+
return {'ui': {'text': [report]}, 'result': (dataset, report)}
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
class RobinTrainLoRA:
|
| 481 |
+
DESCRIPTION = ('Trains a voice LoRA on a checked dataset, with the same recipe as the Robin app. Every save writes a checkpoint and '
|
| 482 |
+
'reads the sample line in the new voice, into models/loras/robin/<name>. Cancel the queue to stop; running it again '
|
| 483 |
+
'continues from the last save.')
|
| 484 |
+
RETURN_TYPES = ('ROBIN_MODEL', 'STRING')
|
| 485 |
+
RETURN_NAMES = ('robin', 'lora_name')
|
| 486 |
+
FUNCTION = 'train'
|
| 487 |
+
OUTPUT_NODE = True
|
| 488 |
+
CATEGORY = 'Robin'
|
| 489 |
+
|
| 490 |
+
@classmethod
|
| 491 |
+
def INPUT_TYPES(cls):
|
| 492 |
+
return {
|
| 493 |
+
'required': {
|
| 494 |
+
'robin': ('ROBIN_MODEL',),
|
| 495 |
+
'dataset': ('ROBIN_DATASET',),
|
| 496 |
+
'name': ('STRING', {'default': 'my_voice', 'tooltip': 'The LoRA is saved as models/loras/robin/<name>/lora.safetensors.'}),
|
| 497 |
+
'steps': ('INT', {'default': 1000, 'min': 10, 'max': 20000, 'step': 10}),
|
| 498 |
+
'save_every': ('INT', {'default': 200, 'min': 10, 'max': 5000, 'step': 10, 'tooltip': 'How often to save a checkpoint and read the sample line.'}),
|
| 499 |
+
'sample_text': ('STRING', {'multiline': True, 'default': trainer.SAMPLE_TEXT['en'],
|
| 500 |
+
'tooltip': 'Read in the new voice at every save, so you can pick a step by ear.'}),
|
| 501 |
+
'restart': ('BOOLEAN', {'default': False, 'tooltip': 'Start over instead of continuing an unfinished run with this name.'}),
|
| 502 |
+
},
|
| 503 |
+
'optional': {
|
| 504 |
+
'rank_planner': ('INT', {'default': 32, 'min': 0, 'max': 256, 'step': 8, 'advanced': True}),
|
| 505 |
+
'rank_decoder': ('INT', {'default': 64, 'min': 0, 'max': 256, 'step': 8, 'advanced': True}),
|
| 506 |
+
'lr_planner': ('FLOAT', {'default': 5e-5, 'min': 1e-6, 'max': 1e-2, 'step': 1e-6, 'round': False, 'advanced': True}),
|
| 507 |
+
'lr_decoder': ('FLOAT', {'default': 2e-4, 'min': 1e-6, 'max': 1e-2, 'step': 1e-6, 'round': False, 'advanced': True}),
|
| 508 |
+
'clips_per_step': ('INT', {'default': 8, 'min': 1, 'max': 64, 'advanced': True}),
|
| 509 |
+
'seed': ('INT', {'default': 0, 'min': 0, 'max': 2 ** 31 - 1, 'control_after_generate': False, 'advanced': True}),
|
| 510 |
+
},
|
| 511 |
+
'hidden': {'unique_id': 'UNIQUE_ID'},
|
| 512 |
+
}
|
| 513 |
+
|
| 514 |
+
def train(self, robin, dataset, name, steps, save_every, sample_text, restart, rank_planner=32, rank_decoder=64, lr_planner=5e-5,
|
| 515 |
+
lr_decoder=2e-4, clips_per_step=8, seed=0, unique_id=None):
|
| 516 |
+
name = name.strip()
|
| 517 |
+
if not NAME.fullmatch(name):
|
| 518 |
+
raise ValueError('Name the LoRA with letters, digits, dashes, dots or underscores.')
|
| 519 |
+
base = Path(folder_paths.get_folder_paths('loras')[0])
|
| 520 |
+
out = base/'robin'/name
|
| 521 |
+
bar = comfy.utils.ProgressBar(steps)
|
| 522 |
+
listen, samples = f'robin/{name}_{uuid.uuid4().hex[:8]}', []
|
| 523 |
+
|
| 524 |
+
def progress(stage, step, total, path=None, **info):
|
| 525 |
+
if stage == 'sample':
|
| 526 |
+
samples.append(dict(preview(path, listen), step=step))
|
| 527 |
+
info = dict(sample=samples[-1])
|
| 528 |
+
else:
|
| 529 |
+
bar.update_absolute(step, total)
|
| 530 |
+
tell('robin.train', unique_id, stage=stage, step=step, total=total, **info)
|
| 531 |
+
|
| 532 |
+
tell('robin.train', unique_id, stage='start', step=0, total=steps, save_every=save_every)
|
| 533 |
+
if not restart:
|
| 534 |
+
for f in sorted((out/'samples').glob('*.wav')):
|
| 535 |
+
if f.stem == 'base' or SAVED.fullmatch(f.stem):
|
| 536 |
+
progress('sample', 0 if f.stem == 'base' else int(f.stem[5:]), steps, path=f)
|
| 537 |
+
model = RobinModel(robin.core).ready(speech=True, memory=TRAINING_MEMORY)
|
| 538 |
+
started = time.time()
|
| 539 |
+
with torch.inference_mode(False), torch.enable_grad():
|
| 540 |
+
trainable(model)
|
| 541 |
+
try:
|
| 542 |
+
path = trainer.train(model, dataset['folder'], out, lang=dataset['lang'], restart=restart, log=lambda m: logging.info(f'Robin: {m}'),
|
| 543 |
+
stop=mm.processing_interrupted, progress=progress, steps=steps, save_every=save_every,
|
| 544 |
+
rank_planner=rank_planner, rank_decoder=rank_decoder, lr_planner=lr_planner, lr_decoder=lr_decoder,
|
| 545 |
+
accum=clips_per_step, sample_text=sample_text.strip() or None, seed=seed)
|
| 546 |
+
except SystemExit as e:
|
| 547 |
+
tell('robin.train', unique_id, stage='stopped' if mm.processing_interrupted() else 'failed')
|
| 548 |
+
mm.throw_exception_if_processing_interrupted()
|
| 549 |
+
raise ValueError(str(e)) from None
|
| 550 |
+
if path is None or mm.processing_interrupted():
|
| 551 |
+
tell('robin.train', unique_id, stage='stopped')
|
| 552 |
+
mm.throw_exception_if_processing_interrupted()
|
| 553 |
+
raise ValueError('Training stopped before it finished.')
|
| 554 |
+
done = dict(stage='done', step=steps, total=steps, minutes=(time.time() - started) / 60, samples=samples)
|
| 555 |
+
tell('robin.train', unique_id, **done)
|
| 556 |
+
return {'ui': {'robin_train': [done]}, 'result': (RobinModel(robin.core, (str(path), 1.)), Path(path).relative_to(base).as_posix())}
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
routes = PromptServer.instance.routes
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
@routes.get('/robin/status')
|
| 563 |
+
async def status_route(request):
|
| 564 |
+
model = request.query.get('model', MODEL)
|
| 565 |
+
return web.json_response(model_status(model if model in model_folders() else MODEL, request.query.get('vae', VAE)))
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
@routes.get('/robin/uploaded')
|
| 569 |
+
async def uploaded_route(request):
|
| 570 |
+
base = (Path(folder_paths.get_input_directory())/UPLOADS).resolve()
|
| 571 |
+
folder = (base/request.query.get('name', '')).resolve()
|
| 572 |
+
if folder.parent != base:
|
| 573 |
+
return web.Response(status=400)
|
| 574 |
+
files = {f.relative_to(folder).as_posix(): f.stat().st_size for f in folder.rglob('*') if f.is_file()} if folder.is_dir() else {}
|
| 575 |
+
return web.json_response(dict(files=files))
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
@routes.post('/robin/open_recordings')
|
| 579 |
+
async def open_recordings_route(request):
|
| 580 |
+
folder = folder_paths.get_input_directory()
|
| 581 |
+
here = request.remote in ('127.0.0.1', '::1', '::ffff:127.0.0.1') and request.host.rsplit(':', 1)[-1] == str(PromptServer.instance.port)
|
| 582 |
+
desktop = sys.platform in ('darwin', 'win32') or os.environ.get('DISPLAY') or os.environ.get('WAYLAND_DISPLAY')
|
| 583 |
+
if not (here and desktop):
|
| 584 |
+
return web.json_response(dict(opened=False, folder=folder))
|
| 585 |
+
if sys.platform == 'win32':
|
| 586 |
+
os.startfile(folder)
|
| 587 |
+
else:
|
| 588 |
+
subprocess.Popen(['open' if sys.platform == 'darwin' else 'xdg-open', folder], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
| 589 |
+
start_new_session=True)
|
| 590 |
+
return web.json_response(dict(opened=True, folder=folder))
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
@routes.post('/robin/check')
|
| 594 |
+
async def check_route(request):
|
| 595 |
+
body = await request.json()
|
| 596 |
+
language = body.get('language') if body.get('language') in LANGUAGES else 'English'
|
| 597 |
+
_, report = await asyncio.to_thread(check_folder, str(body.get('folder', '')), language)
|
| 598 |
+
return web.json_response(dict(report=report))
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
NODE_CLASS_MAPPINGS = {
|
| 602 |
+
'RobinLoader': RobinLoader,
|
| 603 |
+
'RobinLoRA': RobinLoRA,
|
| 604 |
+
'RobinSpeak': RobinSpeak,
|
| 605 |
+
'RobinVoiceChanger': RobinVoiceChanger,
|
| 606 |
+
'RobinLoadAudio': RobinLoadAudio,
|
| 607 |
+
'RobinCheckDataset': RobinCheckDataset,
|
| 608 |
+
'RobinTrainLoRA': RobinTrainLoRA,
|
| 609 |
+
}
|
| 610 |
+
NODE_DISPLAY_NAME_MAPPINGS = {
|
| 611 |
+
'RobinLoader': 'Robin Loader',
|
| 612 |
+
'RobinLoRA': 'Robin LoRA',
|
| 613 |
+
'RobinSpeak': 'Robin Speak',
|
| 614 |
+
'RobinVoiceChanger': 'Robin Voice Changer',
|
| 615 |
+
'RobinLoadAudio': 'Robin Load Audio',
|
| 616 |
+
'RobinCheckDataset': 'Robin Check Dataset',
|
| 617 |
+
'RobinTrainLoRA': 'Robin Train LoRA',
|
| 618 |
+
}
|
comfyui-robin/pyproject.toml
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[project]
|
| 2 |
+
name = "comfyui-robin"
|
| 3 |
+
description = "Robin text to speech in ComfyUI: voices from a description, long text, voice changing and voice LoRAs."
|
| 4 |
+
version = "0.1.0"
|
| 5 |
+
license = { file = "LICENSE" }
|
| 6 |
+
requires-python = ">=3.10"
|
| 7 |
+
dependencies = ["safetensors", "tokenizers", "huggingface_hub", "numpy", "soundfile", "torchaudio", "s3tokenizer>=0.3.0"]
|
| 8 |
+
|
| 9 |
+
[tool.comfy]
|
| 10 |
+
DisplayName = "Robin"
|
| 11 |
+
includes = []
|
comfyui-robin/requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
safetensors
|
| 2 |
+
tokenizers
|
| 3 |
+
huggingface_hub
|
| 4 |
+
numpy
|
| 5 |
+
soundfile
|
| 6 |
+
torchaudio
|
| 7 |
+
s3tokenizer>=0.3.0
|
comfyui-robin/robin/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .pipeline import Cancelled, Robin
|
| 2 |
+
|
| 3 |
+
__all__ = ['Cancelled', 'Robin']
|
comfyui-robin/robin/__main__.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def model_args(p, required=True):
|
| 6 |
+
p.add_argument('--model', required=required, help='a weights folder or Hugging Face repo')
|
| 7 |
+
p.add_argument('--vae', help='the VAE weights (.safetensors); by default the robin_vae.safetensors in the --model folder')
|
| 8 |
+
p.add_argument('--device', default='cuda')
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def main():
|
| 12 |
+
p = argparse.ArgumentParser(prog='python -m robin')
|
| 13 |
+
sub = p.add_subparsers(dest='command', required=True)
|
| 14 |
+
|
| 15 |
+
s = sub.add_parser('speak', help='text to speech, and voice changing')
|
| 16 |
+
s.add_argument('text', help='what to say, any length; [laughs] and [coughs] can go inline')
|
| 17 |
+
s.add_argument('--voice', help='the voice in words, e.g. "a warm, low voice, unhurried and close to the mic"')
|
| 18 |
+
s.add_argument('--convert', help='a recording (up to 45 s) to perform again in the --voice (or --lora) voice; the text must be exactly '
|
| 19 |
+
'what it says')
|
| 20 |
+
s.add_argument('--lora', help='a LoRA file trained with "python -m robin train"')
|
| 21 |
+
s.add_argument('--lora-scale', type=float, default=1., help='how strongly the LoRA applies (1 = as trained)')
|
| 22 |
+
s.add_argument('--lang', default='en', choices=('en', 'ja', 'mix'))
|
| 23 |
+
s.add_argument('--as-written', action='store_true', help='read English exactly as typed, without spelling out numbers, symbols and '
|
| 24 |
+
'abbreviations first')
|
| 25 |
+
s.add_argument('--seed', type=int, default=0)
|
| 26 |
+
s.add_argument('--temperature', type=float); s.add_argument('--top-k', type=int); s.add_argument('--top-p', type=float)
|
| 27 |
+
s.add_argument('--cfg', type=float, default=1., help='above 1 follows --voice more closely (try 3)')
|
| 28 |
+
s.add_argument('--steps', type=int); s.add_argument('--sampler', choices=('dpm_2', 'dpmpp_2m'))
|
| 29 |
+
s.add_argument('--out', default='robin.flac')
|
| 30 |
+
model_args(s)
|
| 31 |
+
|
| 32 |
+
g = sub.add_parser('gui', help='Robin in your browser: speak, change voices and train voices')
|
| 33 |
+
g.add_argument('--out', default='robin_studio', help='where saved takes and trained voices go')
|
| 34 |
+
g.add_argument('--host', default='127.0.0.1'); g.add_argument('--port', type=int, default=7860)
|
| 35 |
+
model_args(g)
|
| 36 |
+
|
| 37 |
+
def data_args(q):
|
| 38 |
+
q.add_argument('data', help='a folder of audio clips, each with a .txt transcript of the same name, plus an optional voice.txt '
|
| 39 |
+
'describing the voice')
|
| 40 |
+
q.add_argument('--lang', default='en', choices=('en', 'ja', 'mix'))
|
| 41 |
+
q.add_argument('--min-seconds', type=float, default=1., help='shorter clips are left out')
|
| 42 |
+
q.add_argument('--max-seconds', type=float, default=30., help='longer clips are left out (split them first)')
|
| 43 |
+
|
| 44 |
+
q = sub.add_parser('prep', help='check a LoRA dataset; with --out, also prepare it for training')
|
| 45 |
+
data_args(q)
|
| 46 |
+
q.add_argument('--out', help='the LoRA folder to prepare (the same --out you will give train)')
|
| 47 |
+
model_args(q, required=False)
|
| 48 |
+
|
| 49 |
+
t = sub.add_parser('train', help='train a LoRA on a voice')
|
| 50 |
+
data_args(t)
|
| 51 |
+
t.add_argument('--out', required=True, help='a folder for the LoRA, its checkpoints and samples')
|
| 52 |
+
t.add_argument('--steps', type=int, default=1000)
|
| 53 |
+
t.add_argument('--save-every', type=int, default=200)
|
| 54 |
+
t.add_argument('--rank-planner', type=int, default=32); t.add_argument('--rank-decoder', type=int, default=64)
|
| 55 |
+
t.add_argument('--lr-planner', type=float, default=5e-5); t.add_argument('--lr-decoder', type=float, default=2e-4)
|
| 56 |
+
t.add_argument('--accum', type=int, default=8, help='clips per step')
|
| 57 |
+
t.add_argument('--sample-text', help='the line rendered at every save, so you can pick a checkpoint by ear')
|
| 58 |
+
t.add_argument('--seed', type=int, default=0)
|
| 59 |
+
t.add_argument('--restart', action='store_true', help='start over instead of continuing an unfinished run')
|
| 60 |
+
model_args(t)
|
| 61 |
+
|
| 62 |
+
a = p.parse_args()
|
| 63 |
+
from .pipeline import Robin
|
| 64 |
+
|
| 65 |
+
if a.command == 'gui':
|
| 66 |
+
try:
|
| 67 |
+
from . import gui
|
| 68 |
+
except ModuleNotFoundError as e:
|
| 69 |
+
if e.name != 'gradio': raise
|
| 70 |
+
raise SystemExit("The GUI needs Gradio: pip install 'robin[gui]'")
|
| 71 |
+
gui.launch(Robin.from_pretrained(a.model, a.vae, device=a.device), a.out, a.host, a.port)
|
| 72 |
+
return
|
| 73 |
+
|
| 74 |
+
if a.command == 'speak':
|
| 75 |
+
import soundfile as sf
|
| 76 |
+
from . import pieces
|
| 77 |
+
tts = Robin.from_pretrained(a.model, a.vae, device=a.device, lora=a.lora, lora_scale=a.lora_scale)
|
| 78 |
+
sampling = dict(temperature=a.temperature, top_k=a.top_k, top_p=a.top_p, steps=a.steps, sampler=a.sampler)
|
| 79 |
+
if a.convert:
|
| 80 |
+
if not (a.voice or a.lora): s.error('--convert needs --voice (a description of the new voice) or --lora')
|
| 81 |
+
x, rate = sf.read(a.convert, dtype='float32', always_2d=True)
|
| 82 |
+
if len(x) / rate > 45: s.error(f'{a.convert} is {len(x) / rate:.0f} s long; convert up to 45 s at a time')
|
| 83 |
+
wav = pieces.change(tts, x.mean(1), rate, a.text, voice=a.voice, lang=a.lang, seed=a.seed, **sampling)
|
| 84 |
+
else:
|
| 85 |
+
wav = pieces.read(tts, a.text, a.voice, lang=a.lang, seed=a.seed, cfg=a.cfg, as_written=a.as_written, **sampling)
|
| 86 |
+
sf.write(a.out, wav, pieces.RATE, subtype='PCM_24')
|
| 87 |
+
print(f'wrote {a.out}: {len(wav) / pieces.RATE:.1f} s')
|
| 88 |
+
return
|
| 89 |
+
|
| 90 |
+
from . import train as tr
|
| 91 |
+
if a.command == 'prep':
|
| 92 |
+
found = tr.scan(a.data, a.lang, a.min_seconds, a.max_seconds); tr.describe(found)
|
| 93 |
+
if a.out:
|
| 94 |
+
if not a.model: q.error('--out needs --model')
|
| 95 |
+
from pathlib import Path
|
| 96 |
+
clips = tr.encode(Robin.from_pretrained(a.model, a.vae, device=a.device), found, Path(a.out)/'cache')
|
| 97 |
+
print(f'{len(clips)} clips prepared in {Path(a.out)/"cache"}')
|
| 98 |
+
return
|
| 99 |
+
|
| 100 |
+
robin = Robin.from_pretrained(a.model, a.vae, device=a.device)
|
| 101 |
+
tr.train(robin, a.data, a.out, lang=a.lang, min_seconds=a.min_seconds, max_seconds=a.max_seconds, restart=a.restart,
|
| 102 |
+
steps=a.steps, save_every=a.save_every, rank_planner=a.rank_planner, rank_decoder=a.rank_decoder, lr_planner=a.lr_planner,
|
| 103 |
+
lr_decoder=a.lr_decoder, accum=a.accum, sample_text=a.sample_text, seed=a.seed)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
if __name__ == '__main__':
|
| 107 |
+
sys.exit(main())
|
comfyui-robin/robin/gui.py
ADDED
|
@@ -0,0 +1,508 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 6 |
+
from datetime import datetime
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import gradio as gr
|
| 10 |
+
import numpy as np
|
| 11 |
+
import soundfile as sf
|
| 12 |
+
import torch
|
| 13 |
+
|
| 14 |
+
from . import pieces
|
| 15 |
+
from . import train as tr
|
| 16 |
+
from .pipeline import Cancelled
|
| 17 |
+
|
| 18 |
+
LANGUAGES = {'English': 'en', 'Japanese': 'ja', 'English + Japanese': 'mix'}
|
| 19 |
+
MAX_SOURCE_SECONDS = 45
|
| 20 |
+
GROUND, PANEL, LINE, CREAM, RED, RED_FILL, RED_TEXT = '#121212', '#1b1b1c', '#2c2c2d', '#F2EEE6', '#D9302A', '#BF2A24', '#F0564F'
|
| 21 |
+
STEP_LINE = re.compile(r'^step (\d+)/(\d+) .*?\| ([\d.]+) s/step \| (\d+) min left(?: \| GPU ([\d.]+) GB)?')
|
| 22 |
+
NONE = ''
|
| 23 |
+
|
| 24 |
+
CSS = f"""
|
| 25 |
+
.gradio-container {{ max-width: 1200px !important; margin: 0 auto !important; }}
|
| 26 |
+
#robin-head {{ align-items: baseline; border-bottom: 2px solid {RED}; padding: 2px 2px 10px; margin-bottom: 2px; }}
|
| 27 |
+
#robin-head h1 {{ margin: 0; font-size: 34px; line-height: 1; letter-spacing: .32em; font-weight: 800; color: {RED_TEXT}; }}
|
| 28 |
+
#robin-head p {{ margin: 0; color: {CREAM}; opacity: .7; }}
|
| 29 |
+
#adapter {{ border: 1px solid {LINE}; border-radius: 12px; padding: 4px 8px; background: {PANEL}; }}
|
| 30 |
+
.take {{ border: 1px solid {RED}88 !important; border-radius: 12px !important; background: {PANEL} !important; }}
|
| 31 |
+
.kept {{ outline: 2px solid {RED}; }}
|
| 32 |
+
.bar {{ height: 10px; border-radius: 6px; background: {RED}2a; overflow: hidden; }}
|
| 33 |
+
.bar i {{ display: block; height: 100%; background: {RED}; }}
|
| 34 |
+
.summary table {{ width: 100%; }}
|
| 35 |
+
.summary td, .summary th {{ text-align: center !important; }}
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def theme():
|
| 40 |
+
red = gr.themes.Color(c50='#fdf0ef', c100='#fadcd9', c200='#f4b6b1', c300='#ec8a82', c400=RED_TEXT, c500=RED, c600=RED_FILL,
|
| 41 |
+
c700='#9a1f1a', c800='#771814', c900='#55110e', c950='#3a0b09', name='robin')
|
| 42 |
+
look = dict(body_background_fill=GROUND, background_fill_primary=GROUND, background_fill_secondary=PANEL, block_background_fill=PANEL,
|
| 43 |
+
panel_background_fill=PANEL, block_border_color=LINE, border_color_primary=LINE, body_text_color=CREAM,
|
| 44 |
+
body_text_color_subdued='#b8b2a9', block_label_text_color=CREAM, block_title_text_color=CREAM, block_info_text_color='#b8b2a9',
|
| 45 |
+
block_label_background_fill=PANEL, input_background_fill=GROUND, input_border_color='#3a3a3b', input_placeholder_color='#7d7872',
|
| 46 |
+
button_primary_background_fill=RED_FILL, button_primary_background_fill_hover=RED, button_primary_text_color=CREAM,
|
| 47 |
+
button_secondary_background_fill=CREAM, button_secondary_background_fill_hover='#ffffff', button_secondary_text_color=GROUND,
|
| 48 |
+
slider_color=RED, color_accent=RED, color_accent_soft=f'{RED}33', link_text_color=RED_TEXT, checkbox_background_color=GROUND,
|
| 49 |
+
checkbox_background_color_selected=RED_FILL, checkbox_border_color='#3a3a3b')
|
| 50 |
+
base = gr.themes.Base(primary_hue=red, neutral_hue=gr.themes.colors.stone, font=['ui-sans-serif', 'system-ui', 'sans-serif'],
|
| 51 |
+
font_mono=['ui-monospace', 'monospace'])
|
| 52 |
+
return base.set(**look, **{f'{k}_dark': v for k, v in look.items() if hasattr(base, f'{k}_dark')})
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
GUIDE = """
|
| 56 |
+
### The voice learns what's in the folder.
|
| 57 |
+
|
| 58 |
+
You bring the recordings and the transcripts. Clean, consistent audio with exact transcripts makes the biggest difference to how a
|
| 59 |
+
trained voice sounds.
|
| 60 |
+
|
| 61 |
+
```
|
| 62 |
+
my_voice/
|
| 63 |
+
voice.txt (optional: the voice in words)
|
| 64 |
+
line_001.wav
|
| 65 |
+
line_001.txt (what line_001.wav says)
|
| 66 |
+
...
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
The surest way to exact transcripts: write the script first, then record it line by line. The script is the transcript.
|
| 70 |
+
|
| 71 |
+
- **How much:** 20 minutes of speech or more. Our test voice used 23 minutes across 227 clips.
|
| 72 |
+
- **Each clip:** one or two sentences, 3 to 15 seconds. Anything from 1 to 30 seconds is accepted, so split longer takes.
|
| 73 |
+
- **Recording:** one speaker in a quiet, dead-sounding room, with the same mic and distance throughout. No music, effects or other
|
| 74 |
+
voices. Keep peaks around −6 dBFS.
|
| 75 |
+
- **Format:** WAV or FLAC at 44.1 or 48 kHz. Lower rates train a duller top end, and clips below 16 kHz are left out.
|
| 76 |
+
- **Transcripts:** exactly the words spoken. Write numbers the way they're said ("fifty percent"), and put [laughs] or [coughs] where
|
| 77 |
+
they happen. Re-record a stumble instead of transcribing it.
|
| 78 |
+
- **Range:** mix statements, questions and exclamations, short lines and long ones. A calm read trains a calm voice, so record the
|
| 79 |
+
delivery you want back.
|
| 80 |
+
|
| 81 |
+
**What Check data does**
|
| 82 |
+
|
| 83 |
+
- **Leaves out:** no transcript or an empty one, an unreadable file or a format it can't read, below 16 kHz, almost silent, under 1 s
|
| 84 |
+
or over 30 s, a transcript far too long or short for its audio.
|
| 85 |
+
- **Keeps, with a note:** below 44.1 kHz, clipped peaks, digits in a transcript, a transcript that may not match, the same line twice.
|
| 86 |
+
It also points out transcripts that have no audio file.
|
| 87 |
+
|
| 88 |
+
Train on voices you have the rights to use.
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
def read_mono(path):
|
| 92 |
+
x, rate = sf.read(str(path), dtype='float32', always_2d=True)
|
| 93 |
+
return np.ascontiguousarray(x.mean(1)), rate
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def slug(text, n=40):
|
| 97 |
+
return re.sub(r'[^a-z0-9]+', '-', text.lower())[:n].strip('-')
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def new_seed():
|
| 101 |
+
return random.randrange(2 ** 31)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class Meter:
|
| 105 |
+
def __init__(self, progress, renders, halt, label):
|
| 106 |
+
self.progress, self.total, self.done, self.halt, self.label = progress, max(1, renders), 0, halt, label
|
| 107 |
+
self.expected, self.frac = 1., 0.
|
| 108 |
+
|
| 109 |
+
def start(self, seconds):
|
| 110 |
+
self.expected, self.frac = max(1., seconds * 25), 0.
|
| 111 |
+
self.show()
|
| 112 |
+
|
| 113 |
+
def finish(self, extra=0):
|
| 114 |
+
self.done += 1; self.total += extra; self.frac = 0.
|
| 115 |
+
self.show()
|
| 116 |
+
|
| 117 |
+
def __call__(self, stage, step, total):
|
| 118 |
+
if self.halt.is_set(): return False
|
| 119 |
+
self.frac = .8 * min(1., step / self.expected) if stage == 'plan' else .8 + .2 * step / total
|
| 120 |
+
if stage == 'decode' or step % 10 == 0: self.show()
|
| 121 |
+
|
| 122 |
+
def show(self):
|
| 123 |
+
self.progress(min(1., (self.done + self.frac) / self.total), desc=self.label)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class Studio:
|
| 127 |
+
def __init__(self, robin, out):
|
| 128 |
+
self.robin, self.out = robin, Path(out).expanduser().resolve()
|
| 129 |
+
for d in ('saved', 'voices', '.listen'): (self.out/d).mkdir(parents=True, exist_ok=True)
|
| 130 |
+
self.lock, self.halt = threading.Lock(), threading.Event()
|
| 131 |
+
self.job, self.adapter = None, None
|
| 132 |
+
|
| 133 |
+
def training(self):
|
| 134 |
+
return self.job is not None and self.job['thread'].is_alive()
|
| 135 |
+
|
| 136 |
+
def claim(self):
|
| 137 |
+
if self.training(): raise gr.Error('A voice is training. Robin speaks again when the training finishes or you stop it.')
|
| 138 |
+
if not self.lock.acquire(blocking=False): raise gr.Error('Robin is busy with another request. Try again in a moment.')
|
| 139 |
+
self.halt.clear()
|
| 140 |
+
|
| 141 |
+
def stop(self):
|
| 142 |
+
self.halt.set()
|
| 143 |
+
|
| 144 |
+
def saved(self):
|
| 145 |
+
return [str(p) for p in sorted((self.out/'saved').glob('*.flac'), key=lambda p: p.stat().st_mtime, reverse=True)[:60]]
|
| 146 |
+
|
| 147 |
+
def listen(self, x):
|
| 148 |
+
d = self.out/'.listen'
|
| 149 |
+
for old in sorted(d.glob('*.flac'), key=lambda p: p.stat().st_mtime)[:-40]: old.unlink(missing_ok=True)
|
| 150 |
+
f = d/f'{datetime.now():%Y%m%d-%H%M%S-%f}.flac'
|
| 151 |
+
sf.write(str(f), np.clip(x, -1, 1), pieces.RATE, subtype='PCM_24')
|
| 152 |
+
return str(f)
|
| 153 |
+
|
| 154 |
+
def save(self, take):
|
| 155 |
+
if not take: raise gr.Error('There is no take to save yet.')
|
| 156 |
+
name = f"{datetime.now():%Y%m%d-%H%M%S}_{slug(take['text']) or 'take'}_seed{take['seed']}.flac"
|
| 157 |
+
sf.write(str(self.out/'saved'/name), take['audio'], pieces.RATE, subtype='PCM_24')
|
| 158 |
+
gr.Info(f'Saved {name}')
|
| 159 |
+
return self.saved()
|
| 160 |
+
|
| 161 |
+
def label(self, path):
|
| 162 |
+
path = Path(path)
|
| 163 |
+
try:
|
| 164 |
+
run = path.parent.parent if path.parent.name == 'checkpoints' else path.parent
|
| 165 |
+
name = run.relative_to(self.out/'voices').as_posix()
|
| 166 |
+
return f"{name} · {'final' if path.name == 'lora.safetensors' else 'step ' + str(int(path.stem.split('_')[1]))}"
|
| 167 |
+
except (ValueError, IndexError):
|
| 168 |
+
return path.name
|
| 169 |
+
|
| 170 |
+
def adapters(self):
|
| 171 |
+
found = []
|
| 172 |
+
for run in sorted(p for p in (self.out/'voices').iterdir() if p.is_dir()):
|
| 173 |
+
if (run/'lora.safetensors').exists(): found.append(run/'lora.safetensors')
|
| 174 |
+
found += sorted((run/'checkpoints').glob('step_*.safetensors'), reverse=True)
|
| 175 |
+
return [('None: Robin as it comes', NONE)] + [(self.label(p), str(p)) for p in found]
|
| 176 |
+
|
| 177 |
+
def adapter_status(self):
|
| 178 |
+
if self.adapter is None: return 'No voice adapter: Robin as it comes.'
|
| 179 |
+
path, scale = self.adapter
|
| 180 |
+
return f'Using **{self.label(path)}** at strength {scale:g}, in every tab.'
|
| 181 |
+
|
| 182 |
+
def apply(self, choice, scale):
|
| 183 |
+
choice = str(choice or '').strip()
|
| 184 |
+
self.claim()
|
| 185 |
+
try:
|
| 186 |
+
if choice == NONE:
|
| 187 |
+
self.robin.remove_lora(); self.adapter = None
|
| 188 |
+
else:
|
| 189 |
+
path = Path(choice).expanduser()
|
| 190 |
+
if not path.is_file(): raise gr.Error(f'No voice adapter file at {path}')
|
| 191 |
+
try:
|
| 192 |
+
self.robin.load_lora(path, scale)
|
| 193 |
+
except ValueError as e:
|
| 194 |
+
raise gr.Error(str(e))
|
| 195 |
+
self.adapter = (str(path), scale)
|
| 196 |
+
finally:
|
| 197 |
+
self.lock.release()
|
| 198 |
+
return self.adapter_status()
|
| 199 |
+
|
| 200 |
+
def strength(self, scale):
|
| 201 |
+
if self.adapter is not None:
|
| 202 |
+
self.robin.set_lora_scale(scale); self.adapter = (self.adapter[0], scale)
|
| 203 |
+
return self.adapter_status()
|
| 204 |
+
|
| 205 |
+
def takes(self, which, text, voice, seed, cfg, temperature, top_k, top_p, language, state, progress):
|
| 206 |
+
lang = LANGUAGES.get(language, 'en')
|
| 207 |
+
text = (text or '').strip()
|
| 208 |
+
if not text: raise gr.Error('Type something for Robin to say.')
|
| 209 |
+
state = dict(state or {}); kept = state.get('kept', set())
|
| 210 |
+
if which == 'both':
|
| 211 |
+
roll = [k for k in 'AB' if k not in kept]
|
| 212 |
+
if not roll: raise gr.Error('Both takes are kept. Un-keep one to roll it again.')
|
| 213 |
+
seeds = {k: int(seed) + i for i, k in enumerate(roll)}
|
| 214 |
+
else:
|
| 215 |
+
seeds = {which: new_seed()}
|
| 216 |
+
meter = Meter(progress, len(pieces.split(text, 35, lang)) * len(seeds), self.halt, 'Robin is speaking')
|
| 217 |
+
self.claim()
|
| 218 |
+
try:
|
| 219 |
+
for k, s in seeds.items():
|
| 220 |
+
audio = pieces.read(self.robin, text, voice, seed=s, cfg=cfg, lang=lang, progress=meter, temperature=temperature, top_k=top_k,
|
| 221 |
+
top_p=top_p)
|
| 222 |
+
state[k] = dict(seed=s, audio=audio, text=text)
|
| 223 |
+
except Cancelled:
|
| 224 |
+
raise gr.Error('Stopped.')
|
| 225 |
+
finally:
|
| 226 |
+
self.lock.release()
|
| 227 |
+
out = []
|
| 228 |
+
for k in 'AB':
|
| 229 |
+
if k in seeds: out += [self.listen(state[k]['audio']), f"seed {state[k]['seed']} · {len(state[k]['audio']) / pieces.RATE:.1f} s"]
|
| 230 |
+
else: out += [gr.skip(), gr.skip()]
|
| 231 |
+
return out + [state]
|
| 232 |
+
|
| 233 |
+
def keep(self, which, state):
|
| 234 |
+
state = dict(state or {}); kept = set(state.get('kept', set()))
|
| 235 |
+
if which not in state: raise gr.Error(f'There is no take {which} yet.')
|
| 236 |
+
kept ^= {which}; state['kept'] = kept
|
| 237 |
+
on = which in kept
|
| 238 |
+
return gr.update(value=f'Kept {which}' if on else f'Keep {which}', variant='primary' if on else 'secondary'), state
|
| 239 |
+
|
| 240 |
+
def change(self, source, source_text, voice, seed, temperature, top_k, top_p, language, progress):
|
| 241 |
+
if source is None: raise gr.Error('Add the recording to change.')
|
| 242 |
+
if not (source_text or '').strip(): raise gr.Error('Type exactly what the recording says.')
|
| 243 |
+
if not (voice or '').strip() and self.adapter is None: raise gr.Error('Describe the new voice, or use a voice adapter.')
|
| 244 |
+
x, rate = read_mono(source)
|
| 245 |
+
if len(x) / rate > MAX_SOURCE_SECONDS:
|
| 246 |
+
raise gr.Error(f'The recording is {len(x) / rate:.0f} s long; the voice changer takes up to {MAX_SOURCE_SECONDS} s at a time.')
|
| 247 |
+
meter = Meter(progress, 2, self.halt, 'Robin is changing the voice')
|
| 248 |
+
self.claim()
|
| 249 |
+
try:
|
| 250 |
+
audio = pieces.change(self.robin, x, rate, source_text, voice=voice, seed=int(seed), lang=LANGUAGES.get(language, 'en'), progress=meter,
|
| 251 |
+
temperature=temperature, top_k=top_k, top_p=top_p)
|
| 252 |
+
except Cancelled:
|
| 253 |
+
raise gr.Error('Stopped.')
|
| 254 |
+
finally:
|
| 255 |
+
self.lock.release()
|
| 256 |
+
return self.listen(audio), f'seed {int(seed)} · {len(audio) / pieces.RATE:.1f} s', dict(seed=int(seed), audio=audio, text=source_text)
|
| 257 |
+
|
| 258 |
+
def check(self, data, language):
|
| 259 |
+
data = Path(str(data or '').strip()).expanduser()
|
| 260 |
+
if not str(data).strip() or not data.is_dir(): raise gr.Error(f'{data} is not a folder.')
|
| 261 |
+
found = tr.scan(data, LANGUAGES.get(language, 'en'))
|
| 262 |
+
lines = []
|
| 263 |
+
try:
|
| 264 |
+
tr.describe(found, lines.append)
|
| 265 |
+
except SystemExit as e:
|
| 266 |
+
lines.append(str(e))
|
| 267 |
+
left = sum(len(v) for v in found['problems'].values())
|
| 268 |
+
notes = sum(len(v) for v in found['warnings'].values())
|
| 269 |
+
minutes = sum(c['seconds'] for c in found['clips']) / 60
|
| 270 |
+
table = ('| Ready clips | Minutes of speech | Left out | Notes |\n|---|---|---|---|\n'
|
| 271 |
+
f"| {len(found['clips'])} | {minutes:.1f} | {left} | {notes} |")
|
| 272 |
+
return table, '\n'.join(lines[1:]), slug(data.name) or 'my-voice'
|
| 273 |
+
|
| 274 |
+
def where(self, name):
|
| 275 |
+
name = slug(str(name or ''))
|
| 276 |
+
return f'Saves to `{self.out/"voices"/name}`' if name else 'Give the voice a name.'
|
| 277 |
+
|
| 278 |
+
def start(self, data, name, steps, save_every, sample_text, restart, language):
|
| 279 |
+
data, name = Path(str(data or '').strip()).expanduser(), slug(str(name or ''))
|
| 280 |
+
if not data.is_dir(): raise gr.Error(f'{data} is not a folder.')
|
| 281 |
+
if not name: raise gr.Error('Give the voice a name.')
|
| 282 |
+
if self.training(): raise gr.Error('A voice is already training.')
|
| 283 |
+
if self.lock.locked(): raise gr.Error('Robin is busy with another request. Try again in a moment.')
|
| 284 |
+
job = dict(data=data, out=self.out/'voices'/name, steps=int(steps), save_every=int(save_every),
|
| 285 |
+
sample_text=(sample_text or '').strip() or None, restart=bool(restart), lang=LANGUAGES.get(language, 'en'),
|
| 286 |
+
stop=threading.Event(), log=[], result=None,
|
| 287 |
+
error=None, ended=None)
|
| 288 |
+
job['thread'] = threading.Thread(target=self._train, args=(job,), daemon=True)
|
| 289 |
+
self.job = job; job['thread'].start()
|
| 290 |
+
gr.Info('Training started.')
|
| 291 |
+
|
| 292 |
+
def _train(self, job):
|
| 293 |
+
log = job['log'].append
|
| 294 |
+
try:
|
| 295 |
+
with self.lock:
|
| 296 |
+
if self.robin.lora is not None:
|
| 297 |
+
self.robin.remove_lora(); self.adapter = None
|
| 298 |
+
log('The voice adapter in use was taken off for training.')
|
| 299 |
+
job['result'] = tr.train(self.robin, job['data'], job['out'], lang=job['lang'], restart=job['restart'], log=log, stop=job['stop'].is_set,
|
| 300 |
+
steps=job['steps'], save_every=job['save_every'], sample_text=job['sample_text'])
|
| 301 |
+
except SystemExit as e:
|
| 302 |
+
log(str(e))
|
| 303 |
+
except Exception as e:
|
| 304 |
+
job['error'] = f'{type(e).__name__}: {e}'
|
| 305 |
+
log(f"Training stopped with an error: {job['error']}"); log(traceback.format_exc(limit=4))
|
| 306 |
+
finally:
|
| 307 |
+
job['ended'] = time.time()
|
| 308 |
+
if torch.cuda.is_available(): torch.cuda.empty_cache()
|
| 309 |
+
|
| 310 |
+
def stop_training(self):
|
| 311 |
+
if not self.training(): raise gr.Error('Nothing is training.')
|
| 312 |
+
self.job['stop'].set()
|
| 313 |
+
gr.Info('Stopping after the current step...')
|
| 314 |
+
|
| 315 |
+
def saves(self, out):
|
| 316 |
+
rows = []
|
| 317 |
+
if (out/'samples'/'base.wav').exists(): rows.append(('before training', str(out/'samples'/'base.wav')))
|
| 318 |
+
rows += [(f"step {int(p.stem.split('_')[1])}", str(p)) for p in sorted((out/'samples').glob('step_*.wav'))]
|
| 319 |
+
return rows
|
| 320 |
+
|
| 321 |
+
def poll(self, name, shown):
|
| 322 |
+
job = self.job
|
| 323 |
+
out = job['out'] if job else self.out/'voices'/(slug(str(name or '')) or '_')
|
| 324 |
+
if job is None:
|
| 325 |
+
status, bar, log = 'Nothing is training.', '', ''
|
| 326 |
+
else:
|
| 327 |
+
m = next((STEP_LINE.match(l) for l in reversed(job['log']) if STEP_LINE.match(l)), None)
|
| 328 |
+
alive = job['thread'].is_alive()
|
| 329 |
+
if alive and m:
|
| 330 |
+
step, total, pace, left, gb = m.groups()
|
| 331 |
+
status = (f"Training **{out.name}**: step {step} of {total} · {float(pace):.1f} s/step · about {left} min left"
|
| 332 |
+
+ (f' · {gb} GB of GPU memory' if gb else ''))
|
| 333 |
+
elif alive: status = f'Training **{out.name}**: preparing the clips...'
|
| 334 |
+
elif job['error']: status = f"Training stopped with an error: {job['error']}"
|
| 335 |
+
elif job['result']: status = f"Finished **{out.name}**. Pick a step below and use it."
|
| 336 |
+
else: status = 'Stopped. Start again with the same name to continue where it left off.'
|
| 337 |
+
if alive and job['stop'].is_set(): status += ' (stopping after this step)'
|
| 338 |
+
pct = 100 * int(m.group(1)) / int(m.group(2)) if m else 0
|
| 339 |
+
bar = f'<div class="bar"><i style="width:{pct:.1f}%"></i></div>' if m else ''
|
| 340 |
+
log = '\n'.join(job['log'][-300:])
|
| 341 |
+
rows = self.saves(out)
|
| 342 |
+
paths = [r[1] for r in rows]
|
| 343 |
+
choices = gr.update(choices=rows, value=paths[-1] if paths else None) if paths != (shown or []) else gr.skip()
|
| 344 |
+
return status, bar, log, choices, paths
|
| 345 |
+
|
| 346 |
+
def use(self, sample, scale):
|
| 347 |
+
if not sample: raise gr.Error('Pick a saved step first.')
|
| 348 |
+
p = Path(sample)
|
| 349 |
+
if p.stem == 'base': raise gr.Error('That is Robin before training. Pick a saved step.')
|
| 350 |
+
lora = p.parent.parent/'checkpoints'/f'{p.stem}.safetensors'
|
| 351 |
+
if not lora.exists(): raise gr.Error(f'No voice adapter was saved for {p.stem}.')
|
| 352 |
+
status = self.apply(str(lora), scale)
|
| 353 |
+
gr.Info(f'Using {self.label(lora)}')
|
| 354 |
+
return status, gr.update(choices=self.adapters(), value=str(lora))
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def knobs(cfg=True):
|
| 358 |
+
with gr.Row():
|
| 359 |
+
g = gr.Slider(1, 10, 1, step=.1, label='Guidance', info='Above 1 follows the voice description more closely; try 3.', visible=cfg)
|
| 360 |
+
temperature = gr.Slider(0, 2, .9, step=.01, label='Temperature', info='Higher is livelier and less predictable.')
|
| 361 |
+
top_k = gr.Slider(0, 500, 25, step=1, label='Top-k', info='Choose among only this many likeliest sounds (0 = no limit).')
|
| 362 |
+
top_p = gr.Slider(.01, 1, .8, step=.01, label='Top-p', info='Choose among the likeliest sounds that add up to this share.')
|
| 363 |
+
with gr.Row():
|
| 364 |
+
seed = gr.Number(0, label='Seed', precision=0, minimum=0, scale=3)
|
| 365 |
+
reseed = gr.Button('New seed', scale=1)
|
| 366 |
+
reseed.click(new_seed, None, seed)
|
| 367 |
+
return g, temperature, top_k, top_p, seed
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def speak_tab(studio, language):
|
| 371 |
+
with gr.Row():
|
| 372 |
+
with gr.Column(scale=3):
|
| 373 |
+
text = gr.Textbox(label='What to say', lines=6, info='Any length. [laughs] and [coughs] can go anywhere in the text.',
|
| 374 |
+
value="Okay, okay, [laughs] I really didn't think you'd do it! [coughs] Sorry. Anyway, that was brilliant.")
|
| 375 |
+
with gr.Row():
|
| 376 |
+
laugh = gr.Button('+ [laughs]', size='sm')
|
| 377 |
+
cough = gr.Button('+ [coughs]', size='sm')
|
| 378 |
+
voice = gr.Textbox(label='The voice', lines=8, scale=2,
|
| 379 |
+
info='Describe it in plain words: age, pitch, pace, mood, how close to the mic. Leave it empty to let Robin choose.',
|
| 380 |
+
value='A cheerful woman in her thirties with a clear, medium-pitched voice, chatting casually with a friend.')
|
| 381 |
+
cfg, temperature, top_k, top_p, seed = knobs()
|
| 382 |
+
with gr.Row():
|
| 383 |
+
go = gr.Button('Speak: two takes', variant='primary', scale=4)
|
| 384 |
+
stop = gr.Button('Stop', scale=1)
|
| 385 |
+
takes, state = {}, gr.State({})
|
| 386 |
+
with gr.Row(equal_height=True):
|
| 387 |
+
for k in 'AB':
|
| 388 |
+
with gr.Column(elem_classes='take'):
|
| 389 |
+
audio = gr.Audio(label=f'Take {k}', type='numpy', interactive=False, buttons=['download'])
|
| 390 |
+
info = gr.Markdown('')
|
| 391 |
+
with gr.Row():
|
| 392 |
+
keep = gr.Button(f'Keep {k}', size='sm')
|
| 393 |
+
redo = gr.Button(f'Redo {k}', size='sm')
|
| 394 |
+
save = gr.Button(f'Save {k}', size='sm')
|
| 395 |
+
takes[k] = (audio, info, keep, redo, save)
|
| 396 |
+
saved = gr.Files(label='Saved takes', value=studio.saved, interactive=False)
|
| 397 |
+
inputs = [text, voice, seed, cfg, temperature, top_k, top_p, language, state]
|
| 398 |
+
outputs = [takes['A'][0], takes['A'][1], takes['B'][0], takes['B'][1], state]
|
| 399 |
+
go.click(lambda *a, progress=gr.Progress(): studio.takes('both', *a, progress), inputs, outputs)
|
| 400 |
+
for k in 'AB':
|
| 401 |
+
takes[k][2].click(lambda st, k=k: studio.keep(k, st), state, [takes[k][2], state])
|
| 402 |
+
takes[k][3].click(lambda *a, k=k, progress=gr.Progress(): studio.takes(k, *a, progress), inputs, outputs)
|
| 403 |
+
takes[k][4].click(lambda st, k=k: studio.save(st.get(k)), state, saved)
|
| 404 |
+
laugh.click(lambda t: (t or '').rstrip() + ' [laughs] ', text, text)
|
| 405 |
+
cough.click(lambda t: (t or '').rstrip() + ' [coughs] ', text, text)
|
| 406 |
+
stop.click(studio.stop)
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def changer_tab(studio, language):
|
| 410 |
+
gr.Markdown(f'Performs a recording again in another voice: the same words, timing and delivery, up to {MAX_SOURCE_SECONDS} seconds at '
|
| 411 |
+
'a time. The new voice comes from the description, and from the voice adapter when one is in use.')
|
| 412 |
+
with gr.Row():
|
| 413 |
+
with gr.Column():
|
| 414 |
+
source = gr.Audio(sources=['upload', 'microphone'], type='filepath', label='The recording to change')
|
| 415 |
+
source_text = gr.Textbox(label='Exactly what it says', lines=3)
|
| 416 |
+
voice = gr.Textbox(label='The new voice', lines=6, info='Describe it in plain words. It can stay empty when a voice adapter is in use.',
|
| 417 |
+
value='A soft-spoken young man with a calm, low voice.')
|
| 418 |
+
_, temperature, top_k, top_p, seed = knobs(cfg=False)
|
| 419 |
+
with gr.Row():
|
| 420 |
+
go = gr.Button('Change the voice', variant='primary', scale=4)
|
| 421 |
+
stop = gr.Button('Stop', scale=1)
|
| 422 |
+
with gr.Column(elem_classes='take'):
|
| 423 |
+
result = gr.Audio(label='Changed', type='numpy', interactive=False, buttons=['download'])
|
| 424 |
+
info = gr.Markdown('')
|
| 425 |
+
save = gr.Button('Save', size='sm')
|
| 426 |
+
take = gr.State(None)
|
| 427 |
+
saved = gr.Files(label='Saved takes', value=studio.saved, interactive=False)
|
| 428 |
+
go.click(lambda *a, progress=gr.Progress(): studio.change(*a, progress), [source, source_text, voice, seed, temperature, top_k, top_p, language],
|
| 429 |
+
[result, info, take])
|
| 430 |
+
save.click(studio.save, take, saved)
|
| 431 |
+
stop.click(studio.stop)
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
def train_tab(studio, adapter, strength, status_line, language):
|
| 435 |
+
gr.Markdown('Teach Robin a voice from recordings: a folder of clips, each with a `.txt` file of the same name holding exactly what it '
|
| 436 |
+
'says. Every few hundred steps it saves the voice with a sample, so you can pick a step by ear.')
|
| 437 |
+
with gr.Accordion('Dataset guide', open=False):
|
| 438 |
+
gr.Markdown(GUIDE)
|
| 439 |
+
with gr.Row():
|
| 440 |
+
data = gr.Textbox(label='Folder of clips', scale=4)
|
| 441 |
+
check = gr.Button('Check data', scale=1)
|
| 442 |
+
summary = gr.Markdown('', elem_classes='summary')
|
| 443 |
+
notes = gr.Textbox(label='Notes', lines=6, interactive=False)
|
| 444 |
+
with gr.Row():
|
| 445 |
+
name = gr.Textbox(label='Name', scale=2)
|
| 446 |
+
steps = gr.Number(1000, label='Steps', precision=0, minimum=10)
|
| 447 |
+
save_every = gr.Number(200, label='Save every', precision=0, minimum=10)
|
| 448 |
+
where = gr.Markdown('')
|
| 449 |
+
with gr.Row():
|
| 450 |
+
sample_text = gr.Textbox(tr.SAMPLE_TEXT['en'], label='Sample line read at every save', scale=4)
|
| 451 |
+
restart = gr.Checkbox(False, label='Start over (replaces an earlier run with this name)')
|
| 452 |
+
with gr.Row():
|
| 453 |
+
start = gr.Button('Start', variant='primary', scale=4)
|
| 454 |
+
halt = gr.Button('Stop', scale=1)
|
| 455 |
+
status = gr.Markdown('Nothing is training.')
|
| 456 |
+
bar = gr.HTML('')
|
| 457 |
+
with gr.Accordion('Training log', open=False):
|
| 458 |
+
log = gr.Textbox(show_label=False, lines=12, max_lines=12, interactive=False, autoscroll=True)
|
| 459 |
+
with gr.Row(equal_height=True):
|
| 460 |
+
sample = gr.Dropdown([], label='Saves', scale=2)
|
| 461 |
+
player = gr.Audio(label='Sample', type='filepath', interactive=False, scale=3)
|
| 462 |
+
use = gr.Button('Use this step', variant='primary', scale=1)
|
| 463 |
+
shown = gr.State([])
|
| 464 |
+
check.click(studio.check, [data, language], [summary, notes, name]).then(studio.where, name, where)
|
| 465 |
+
name.change(studio.where, name, where)
|
| 466 |
+
start.click(studio.start, [data, name, steps, save_every, sample_text, restart, language])
|
| 467 |
+
language.change(lambda l: tr.SAMPLE_TEXT[LANGUAGES.get(l, 'en')], language, sample_text)
|
| 468 |
+
halt.click(studio.stop_training)
|
| 469 |
+
sample.change(lambda p: p or None, sample, player)
|
| 470 |
+
use.click(studio.use, [sample, strength], [status_line, adapter])
|
| 471 |
+
gr.Timer(2).tick(studio.poll, [name, shown], [status, bar, log, sample, shown])
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def build(studio):
|
| 475 |
+
with gr.Blocks(title='Robin', analytics_enabled=False) as demo:
|
| 476 |
+
with gr.Row(elem_id='robin-head'):
|
| 477 |
+
gr.HTML('<h1>ROBIN</h1>')
|
| 478 |
+
gr.HTML('<p>Speak, change voices, train voices.</p>')
|
| 479 |
+
with gr.Row(elem_id='adapter', equal_height=True):
|
| 480 |
+
adapter = gr.Dropdown(studio.adapters(), value=NONE, label='Voice adapter', allow_custom_value=True, scale=3,
|
| 481 |
+
info='A voice trained in "Train a voice", or the path to one.')
|
| 482 |
+
strength = gr.Slider(0, 2, 1, step=.05, label='Strength', info='1 is the voice as trained.', scale=2)
|
| 483 |
+
language = gr.Dropdown(list(LANGUAGES), value='English', label='Language', scale=1,
|
| 484 |
+
info='The language Robin speaks, on every tab.')
|
| 485 |
+
with gr.Column(scale=1, min_width=120):
|
| 486 |
+
apply = gr.Button('Use', variant='primary', size='sm')
|
| 487 |
+
refresh = gr.Button('Refresh list', size='sm')
|
| 488 |
+
status_line = gr.Markdown(studio.adapter_status)
|
| 489 |
+
demo.load(lambda: (gr.update(choices=studio.adapters(), value=studio.adapter[0] if studio.adapter else NONE),
|
| 490 |
+
studio.adapter[1] if studio.adapter else 1, studio.adapter_status()), None, [adapter, strength, status_line])
|
| 491 |
+
apply.click(studio.apply, [adapter, strength], status_line)
|
| 492 |
+
refresh.click(lambda: gr.update(choices=studio.adapters()), None, adapter)
|
| 493 |
+
strength.change(studio.strength, strength, status_line)
|
| 494 |
+
with gr.Tabs():
|
| 495 |
+
with gr.Tab('Speak'):
|
| 496 |
+
speak_tab(studio, language)
|
| 497 |
+
with gr.Tab('Voice changer'):
|
| 498 |
+
changer_tab(studio, language)
|
| 499 |
+
with gr.Tab('Train a voice'):
|
| 500 |
+
train_tab(studio, adapter, strength, status_line, language)
|
| 501 |
+
return demo
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
def launch(robin, out='robin_studio', host='127.0.0.1', port=7860):
|
| 505 |
+
studio = Studio(robin, out)
|
| 506 |
+
demo = build(studio)
|
| 507 |
+
demo.queue(default_concurrency_limit=1)
|
| 508 |
+
demo.launch(server_name=host, server_port=port, theme=theme(), css=CSS, allowed_paths=[str(studio.out)], show_error=True)
|
comfyui-robin/robin/lora.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import hashlib
|
| 2 |
+
import json
|
| 3 |
+
import math
|
| 4 |
+
import os
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from safetensors import safe_open
|
| 9 |
+
from safetensors.torch import save_file
|
| 10 |
+
from torch import nn
|
| 11 |
+
|
| 12 |
+
TARGETS = ('self_attn.qkv_proj', 'self_attn.o_proj', 'mlp.gate_up_proj')
|
| 13 |
+
FORMAT = 'robin-lora-1'
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def file_sha256(path):
|
| 17 |
+
path = Path(path).resolve(); st = path.stat()
|
| 18 |
+
key = f'{path}:{st.st_size}:{st.st_mtime_ns}'
|
| 19 |
+
cache = Path(os.environ.get('ROBIN_CACHE', Path.home()/'.cache'/'robin'))/'sha256.json'
|
| 20 |
+
known = {}
|
| 21 |
+
try: known = json.loads(cache.read_text())
|
| 22 |
+
except (OSError, ValueError): pass
|
| 23 |
+
if key not in known:
|
| 24 |
+
h = hashlib.sha256()
|
| 25 |
+
with path.open('rb') as f:
|
| 26 |
+
for chunk in iter(lambda: f.read(1 << 24), b''): h.update(chunk)
|
| 27 |
+
known[key] = h.hexdigest()
|
| 28 |
+
try:
|
| 29 |
+
cache.parent.mkdir(parents=True, exist_ok=True); cache.write_text(json.dumps(known))
|
| 30 |
+
except OSError: pass
|
| 31 |
+
return known[key]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class LoRA(nn.Module):
|
| 35 |
+
def __init__(self, nets, ranks, alphas=None, targets=TARGETS, seed=0):
|
| 36 |
+
super().__init__()
|
| 37 |
+
self.ranks, self.alphas, self.targets = dict(ranks), dict(alphas or ranks), tuple(targets)
|
| 38 |
+
self.scale, self.names, self._mods, self._factor, self._handles = 1.0, [], [], [], []
|
| 39 |
+
self.A, self.B = nn.ParameterList(), nn.ParameterList()
|
| 40 |
+
g = torch.Generator().manual_seed(seed)
|
| 41 |
+
for net, layers in nets.items():
|
| 42 |
+
r = self.ranks[net]
|
| 43 |
+
for i, layer in enumerate(layers):
|
| 44 |
+
for t in self.targets:
|
| 45 |
+
m = layer.get_submodule(t)
|
| 46 |
+
a = torch.randn(r, m.in_features, generator=g) / math.sqrt(m.in_features)
|
| 47 |
+
self.A.append(nn.Parameter(a.to(m.weight.device)))
|
| 48 |
+
self.B.append(nn.Parameter(torch.zeros(m.out_features, r, device=m.weight.device)))
|
| 49 |
+
self.names.append(f'{net}.layers.{i}.{t}'); self._mods.append(m); self._factor.append(self.alphas[net] / r)
|
| 50 |
+
|
| 51 |
+
def attach(self):
|
| 52 |
+
if not self._handles:
|
| 53 |
+
self._handles = [m.register_forward_hook(self._hook(i)) for i, m in enumerate(self._mods)]
|
| 54 |
+
return self
|
| 55 |
+
|
| 56 |
+
def detach(self):
|
| 57 |
+
for h in self._handles: h.remove()
|
| 58 |
+
self._handles = []
|
| 59 |
+
|
| 60 |
+
def _hook(self, i):
|
| 61 |
+
def hook(_module, args, out):
|
| 62 |
+
if self.scale == 0: return out
|
| 63 |
+
delta = (args[0].float() @ self.A[i].T) @ self.B[i].T
|
| 64 |
+
return out + (delta * (self._factor[i] * self.scale)).to(out.dtype)
|
| 65 |
+
return hook
|
| 66 |
+
|
| 67 |
+
def config(self, base_sha256=None):
|
| 68 |
+
return dict(format=FORMAT, ranks=self.ranks, alphas=self.alphas, targets=list(self.targets), base_sha256=base_sha256)
|
| 69 |
+
|
| 70 |
+
def save(self, path, base_sha256=None, dtype=torch.bfloat16):
|
| 71 |
+
path = Path(path); tmp = path.with_name(path.name + '.tmp')
|
| 72 |
+
state = {}
|
| 73 |
+
for name, a, b in zip(self.names, self.A, self.B):
|
| 74 |
+
state[f'{name}.lora_A'] = a.detach().to(dtype).cpu().contiguous(); state[f'{name}.lora_B'] = b.detach().to(dtype).cpu().contiguous()
|
| 75 |
+
save_file(state, str(tmp), metadata=dict(robin_lora=json.dumps(self.config(base_sha256))))
|
| 76 |
+
os.replace(tmp, path)
|
| 77 |
+
|
| 78 |
+
@classmethod
|
| 79 |
+
def load(cls, path, nets, device='cuda'):
|
| 80 |
+
with safe_open(str(path), framework='pt', device='cpu') as f:
|
| 81 |
+
meta = f.metadata() or {}
|
| 82 |
+
if 'robin_lora' not in meta:
|
| 83 |
+
raise ValueError(f'{path} is not a Robin LoRA')
|
| 84 |
+
config = json.loads(meta['robin_lora'])
|
| 85 |
+
lora = cls({k: v for k, v in nets.items() if k in config['ranks']}, config['ranks'], config['alphas'], config['targets'])
|
| 86 |
+
keys = set(f.keys())
|
| 87 |
+
for i, name in enumerate(lora.names):
|
| 88 |
+
for which, params in (('lora_A', lora.A), ('lora_B', lora.B)):
|
| 89 |
+
k = f'{name}.{which}'
|
| 90 |
+
if k not in keys: raise ValueError(f'{path} is missing {k}')
|
| 91 |
+
t = f.get_tensor(k)
|
| 92 |
+
if t.shape != params[i].shape: raise ValueError(f'{path}: {k} has shape {tuple(t.shape)}, expected {tuple(params[i].shape)}')
|
| 93 |
+
params[i].data.copy_(t)
|
| 94 |
+
return lora.to(device).requires_grad_(False), config
|
comfyui-robin/robin/model.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from torch import nn
|
| 7 |
+
from torch.utils.checkpoint import checkpoint
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@dataclass
|
| 11 |
+
class Config:
|
| 12 |
+
vocab_size: int = 184704
|
| 13 |
+
hidden_size: int = 2048
|
| 14 |
+
intermediate_size: int = 6144
|
| 15 |
+
num_hidden_layers: int = 28
|
| 16 |
+
num_attention_heads: int = 16
|
| 17 |
+
num_key_value_heads: int = 8
|
| 18 |
+
head_dim: int = 128
|
| 19 |
+
rope_theta: float = 1_000_000.0
|
| 20 |
+
rms_norm_eps: float = 1e-6
|
| 21 |
+
max_position_embeddings: int = 24576
|
| 22 |
+
latent_dim: int = 64
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class RMSNorm(nn.Module):
|
| 26 |
+
def __init__(self, dim, eps):
|
| 27 |
+
super().__init__()
|
| 28 |
+
self.weight = nn.Parameter(torch.ones(dim)); self.eps = eps
|
| 29 |
+
|
| 30 |
+
def forward(self, x):
|
| 31 |
+
return F.rms_norm(x, self.weight.shape, self.weight.to(x.dtype), self.eps)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def rope(positions, head_dim, theta, device):
|
| 35 |
+
inv = 1.0 / (theta ** (torch.arange(0, head_dim, 2, dtype=torch.float32, device=device) / head_dim))
|
| 36 |
+
ang = positions.float().to(device)[:, None] * inv[None]
|
| 37 |
+
return ang.cos(), ang.sin()
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def apply_rope(x, cos, sin):
|
| 41 |
+
f = x.float(); h = f.shape[-1] // 2
|
| 42 |
+
lo, hi = f[..., :h], f[..., h:]
|
| 43 |
+
return torch.cat([lo * cos - hi * sin, hi * cos + lo * sin], dim=-1).to(x.dtype)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class Attention(nn.Module):
|
| 47 |
+
def __init__(self, c):
|
| 48 |
+
super().__init__()
|
| 49 |
+
self.h, self.kv, self.d = c.num_attention_heads, c.num_key_value_heads, c.head_dim
|
| 50 |
+
self.qkv_proj = nn.Linear(c.hidden_size, (self.h + 2 * self.kv) * self.d, bias=False)
|
| 51 |
+
self.o_proj = nn.Linear(self.h * self.d, c.hidden_size, bias=False)
|
| 52 |
+
self.q_norm, self.k_norm = RMSNorm(self.d, c.rms_norm_eps), RMSNorm(self.d, c.rms_norm_eps)
|
| 53 |
+
|
| 54 |
+
def qkv(self, x, cos, sin):
|
| 55 |
+
B, T, _ = x.shape
|
| 56 |
+
q, k, v = self.qkv_proj(x).split((self.h * self.d, self.kv * self.d, self.kv * self.d), dim=-1)
|
| 57 |
+
q = self.q_norm(q.view(B, T, self.h, self.d)).transpose(1, 2)
|
| 58 |
+
k = self.k_norm(k.view(B, T, self.kv, self.d)).transpose(1, 2)
|
| 59 |
+
v = v.view(B, T, self.kv, self.d).transpose(1, 2)
|
| 60 |
+
return apply_rope(q, cos, sin), apply_rope(k, cos, sin), v
|
| 61 |
+
|
| 62 |
+
def attend(self, q, k, v, mask=None):
|
| 63 |
+
o = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, enable_gqa=self.h != self.kv)
|
| 64 |
+
return self.o_proj(o.transpose(1, 2).reshape(q.shape[0], q.shape[2], -1))
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class MLP(nn.Module):
|
| 68 |
+
def __init__(self, c):
|
| 69 |
+
super().__init__()
|
| 70 |
+
self.gate_up_proj = nn.Linear(c.hidden_size, 2 * c.intermediate_size, bias=False)
|
| 71 |
+
self.down_proj = nn.Linear(c.intermediate_size, c.hidden_size, bias=False)
|
| 72 |
+
|
| 73 |
+
def forward(self, x):
|
| 74 |
+
g, u = self.gate_up_proj(x).chunk(2, dim=-1)
|
| 75 |
+
return self.down_proj(F.silu(g) * u)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class Block(nn.Module):
|
| 79 |
+
def __init__(self, c):
|
| 80 |
+
super().__init__()
|
| 81 |
+
self.input_layernorm = RMSNorm(c.hidden_size, c.rms_norm_eps)
|
| 82 |
+
self.self_attn = Attention(c)
|
| 83 |
+
self.post_attention_layernorm = RMSNorm(c.hidden_size, c.rms_norm_eps)
|
| 84 |
+
self.mlp = MLP(c)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def planner_block(layer, x, cos, sin, mask):
|
| 88 |
+
q, k, v = layer.self_attn.qkv(layer.input_layernorm(x), cos, sin)
|
| 89 |
+
x = x + layer.self_attn.attend(q, k, v, mask)
|
| 90 |
+
return x + layer.mlp(layer.post_attention_layernorm(x))
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def decoder_block(layer, s, cos, sin, prefix_k, prefix_v):
|
| 94 |
+
q, k, v = layer.self_attn.qkv(layer.input_layernorm(s), cos, sin)
|
| 95 |
+
k = torch.cat((prefix_k.to(k.dtype), k), dim=2); v = torch.cat((prefix_v.to(v.dtype), v), dim=2)
|
| 96 |
+
s = s + layer.self_attn.attend(q, k, v)
|
| 97 |
+
return s + layer.mlp(layer.post_attention_layernorm(s))
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class Planner(nn.Module):
|
| 101 |
+
def __init__(self, c: Config):
|
| 102 |
+
super().__init__()
|
| 103 |
+
self.c = c
|
| 104 |
+
self.embed_tokens = nn.Embedding(c.vocab_size, c.hidden_size)
|
| 105 |
+
self.layers = nn.ModuleList(Block(c) for _ in range(c.num_hidden_layers))
|
| 106 |
+
self.norm = RMSNorm(c.hidden_size, c.rms_norm_eps)
|
| 107 |
+
self.lm_head = nn.Linear(c.hidden_size, c.vocab_size, bias=False)
|
| 108 |
+
|
| 109 |
+
def forward(self, ids, mask):
|
| 110 |
+
x = self.embed_tokens(ids)
|
| 111 |
+
cos, sin = rope(torch.arange(ids.shape[1]), self.c.head_dim, self.c.rope_theta, x.device)
|
| 112 |
+
mask = mask.to(x.dtype)
|
| 113 |
+
for layer in self.layers:
|
| 114 |
+
x = checkpoint(planner_block, layer, x, cos, sin, mask, use_reentrant=False)
|
| 115 |
+
return self.norm(x)
|
| 116 |
+
|
| 117 |
+
@torch.no_grad()
|
| 118 |
+
def prefill(self, ids, mask):
|
| 119 |
+
x = self.embed_tokens(ids[None]); T = ids.shape[0]
|
| 120 |
+
cos, sin = rope(torch.arange(T), self.c.head_dim, self.c.rope_theta, x.device)
|
| 121 |
+
ks, vs = [], []
|
| 122 |
+
for layer in self.layers:
|
| 123 |
+
q, k, v = layer.self_attn.qkv(layer.input_layernorm(x), cos, sin)
|
| 124 |
+
x = x + layer.self_attn.attend(q, k, v, mask.to(x.dtype))
|
| 125 |
+
x = x + layer.mlp(layer.post_attention_layernorm(x))
|
| 126 |
+
ks.append(k); vs.append(v)
|
| 127 |
+
return ks, vs, self.norm(x)
|
| 128 |
+
|
| 129 |
+
@torch.no_grad()
|
| 130 |
+
def step(self, token, pos, kbuf, vbuf):
|
| 131 |
+
x = self.embed_tokens(torch.tensor([[token]], device=self.lm_head.weight.device))
|
| 132 |
+
cos, sin = rope(torch.tensor([pos]), self.c.head_dim, self.c.rope_theta, x.device)
|
| 133 |
+
for i, layer in enumerate(self.layers):
|
| 134 |
+
q, k, v = layer.self_attn.qkv(layer.input_layernorm(x), cos, sin)
|
| 135 |
+
kbuf[i][:, :, pos] = k[:, :, 0]; vbuf[i][:, :, pos] = v[:, :, 0]
|
| 136 |
+
x = x + layer.self_attn.attend(q, kbuf[i][:, :, :pos + 1], vbuf[i][:, :, :pos + 1])
|
| 137 |
+
x = x + layer.mlp(layer.post_attention_layernorm(x))
|
| 138 |
+
return self.lm_head(self.norm(x)[:, -1]).float()[0]
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
class TimestepEmbedder(nn.Module):
|
| 142 |
+
def __init__(self, hidden):
|
| 143 |
+
super().__init__()
|
| 144 |
+
self.mlp = nn.Sequential(nn.Linear(256, hidden), nn.SiLU(), nn.Linear(hidden, hidden))
|
| 145 |
+
|
| 146 |
+
def forward(self, t):
|
| 147 |
+
half = 128
|
| 148 |
+
freqs = torch.exp(-math.log(10000) * torch.arange(half, dtype=torch.float32, device=t.device) / half)
|
| 149 |
+
a = t.float()[:, None] * freqs[None]
|
| 150 |
+
return self.mlp(torch.cat([a.cos(), a.sin()], dim=-1).to(self.mlp[0].weight.dtype))
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def positions(n, dim, device):
|
| 154 |
+
pos = torch.arange(n, dtype=torch.float32, device=device)[:, None]
|
| 155 |
+
ang = pos * torch.exp(torch.arange(0, dim, 2, dtype=torch.float32, device=device) * (-math.log(10000.0) / dim))
|
| 156 |
+
pe = torch.zeros(n, dim, device=device)
|
| 157 |
+
pe[:, 0::2], pe[:, 1::2] = ang.sin(), ang.cos()
|
| 158 |
+
return pe
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class _Stack(nn.Module):
|
| 162 |
+
def __init__(self, c):
|
| 163 |
+
super().__init__()
|
| 164 |
+
self.layers = nn.ModuleList(Block(c) for _ in range(c.num_hidden_layers))
|
| 165 |
+
self.norm = RMSNorm(c.hidden_size, c.rms_norm_eps)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class Decoder(nn.Module):
|
| 169 |
+
def __init__(self, c: Config):
|
| 170 |
+
super().__init__()
|
| 171 |
+
self.c = c
|
| 172 |
+
self.model = _Stack(c)
|
| 173 |
+
self.vae2llm = nn.Linear(c.latent_dim, c.hidden_size)
|
| 174 |
+
self.llm2vae = nn.Linear(c.hidden_size, c.latent_dim)
|
| 175 |
+
self.time_embedder = TimestepEmbedder(c.hidden_size)
|
| 176 |
+
self._pe = None
|
| 177 |
+
|
| 178 |
+
@torch.no_grad()
|
| 179 |
+
def velocity(self, x, sigma, prefix_k, prefix_v):
|
| 180 |
+
return self(x, sigma, prefix_k, prefix_v)
|
| 181 |
+
|
| 182 |
+
def forward(self, x, sigma, prefix_k, prefix_v, checkpointing=False):
|
| 183 |
+
dt = self.vae2llm.weight.dtype
|
| 184 |
+
A = prefix_k[0].shape[2]; n = x.shape[1] + 2
|
| 185 |
+
s = F.pad(x.to(dt), (0, 0, 1, 1))
|
| 186 |
+
if self._pe is None or self._pe.shape[0] < n or self._pe.device != x.device:
|
| 187 |
+
self._pe = positions(max(n, 1024), self.c.hidden_size, x.device).to(dt)
|
| 188 |
+
s = self.vae2llm(s) + self.time_embedder(sigma.to(dt))[:, None] + self._pe[:n][None]
|
| 189 |
+
cos, sin = rope(torch.arange(A, A + n), self.c.head_dim, self.c.rope_theta, x.device)
|
| 190 |
+
for i, layer in enumerate(self.model.layers):
|
| 191 |
+
if checkpointing:
|
| 192 |
+
s = checkpoint(decoder_block, layer, s, cos, sin, prefix_k[i], prefix_v[i], use_reentrant=False)
|
| 193 |
+
else:
|
| 194 |
+
s = decoder_block(layer, s, cos, sin, prefix_k[i], prefix_v[i])
|
| 195 |
+
return self.llm2vae(self.model.norm(s))[:, 1:-1].float()
|
comfyui-robin/robin/pieces.py
ADDED
|
@@ -0,0 +1,181 @@
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
from .text import speakable
|
| 6 |
+
|
| 7 |
+
RATE = 48000
|
| 8 |
+
SAMPLE_LINE = 'Here is a short sample of my voice, read clearly and at an easy pace.'
|
| 9 |
+
SAMPLE_LINES = dict(en=SAMPLE_LINE, ja='これは私の声の短いサンプルです。はっきりと、ゆっくり読んでいます。', mix=SAMPLE_LINE)
|
| 10 |
+
TAG = re.compile(r'\[[^\]]*\]')
|
| 11 |
+
ENDS = re.compile(r'(?<=[.!?])\s+|(?<=[.!?]")\s+|(?<=[。!?])\s*')
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def size(text, lang='en'):
|
| 15 |
+
text = TAG.sub(' ', text)
|
| 16 |
+
if lang == 'en':
|
| 17 |
+
return len(re.findall(r"[A-Za-z0-9']+", text))
|
| 18 |
+
return len(re.sub(r'[\s\W]', '', text)) / 2.8
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def sentences(text):
|
| 22 |
+
out, cur = [], ''
|
| 23 |
+
for part in ENDS.split(text.strip()):
|
| 24 |
+
if not part: continue
|
| 25 |
+
cur = f'{cur} {part}'.strip() if cur else part
|
| 26 |
+
if cur.count('"') % 2 == 0: out.append(cur); cur = ''
|
| 27 |
+
return out + ([cur] if cur else [])
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def clauses(s, limit, lang):
|
| 31 |
+
if size(s, lang) <= limit: return [s]
|
| 32 |
+
best = None
|
| 33 |
+
for m in re.finditer(r'[,;:、,]\s*', s):
|
| 34 |
+
i = m.end()
|
| 35 |
+
if s[:i].count('"') % 2 or i >= len(s): continue
|
| 36 |
+
d = abs(size(s[:i], lang) - size(s, lang) / 2)
|
| 37 |
+
if best is None or d < best[0]: best = (d, i)
|
| 38 |
+
if best is None: return [s]
|
| 39 |
+
return clauses(s[:best[1]].strip(), limit, lang) + clauses(s[best[1]:].strip(), limit, lang)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def glue(parts, lang):
|
| 43 |
+
if lang == 'en': return ' '.join(parts)
|
| 44 |
+
out = ''
|
| 45 |
+
for p in parts:
|
| 46 |
+
out += (' ' if lang == 'mix' and out and (out[-1].isascii() or p[0].isascii()) else '') + p
|
| 47 |
+
return out
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def split(text, max_words=35, lang='en', as_written=False):
|
| 51 |
+
if lang == 'en' and not as_written: text = speakable(text)
|
| 52 |
+
parts = [c for s in sentences(text) for c in clauses(s, max_words, lang)]
|
| 53 |
+
chunks, cur = [], []
|
| 54 |
+
for p in parts:
|
| 55 |
+
if cur and size(glue(cur + [p], lang), lang) > max_words:
|
| 56 |
+
chunks.append(glue(cur, lang)); cur = []
|
| 57 |
+
cur.append(p)
|
| 58 |
+
return chunks + ([glue(cur, lang)] if cur else [])
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def frames_on(x, rate=RATE):
|
| 62 |
+
f = rate // 20; n = len(x) // f
|
| 63 |
+
return 20 * np.log10(np.sqrt((x[:n * f].reshape(n, f) ** 2).mean(1)) + 1e-9) > -45
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def stats(x, rate=RATE):
|
| 67 |
+
on = frames_on(x, rate); idx = np.flatnonzero(on); dur = len(on) / 20
|
| 68 |
+
if not len(idx): return dict(sound=0., lead=dur, gap=0., tail=0.)
|
| 69 |
+
gap = run = 0
|
| 70 |
+
for v in on[idx[0]:idx[-1] + 1]:
|
| 71 |
+
run = 0 if v else run + 1; gap = max(gap, run)
|
| 72 |
+
return dict(sound=on.sum() / 20, lead=idx[0] / 20, gap=gap / 20, tail=dur - (idx[-1] + 1) / 20)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def expected_seconds(text, lang='en'):
|
| 76 |
+
per_second = 2.7 if lang == 'en' else 2.5
|
| 77 |
+
return max(1., size(text, lang) / per_second + .8 * len(TAG.findall(text)))
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def check(x, text, lang='en', capped=False):
|
| 81 |
+
st = stats(x); ratio = st['sound'] / expected_seconds(text, lang); problems = []
|
| 82 |
+
if st['sound'] < .3: problems.append('no sound')
|
| 83 |
+
if st['lead'] > 1.: problems.append('starts late')
|
| 84 |
+
if st['gap'] > 2.5: problems.append('goes quiet')
|
| 85 |
+
if ratio < .45: problems.append('too short')
|
| 86 |
+
if ratio > 1.8: problems.append('too long')
|
| 87 |
+
if capped and st['tail'] < .5: problems.append('still talking at the length limit')
|
| 88 |
+
return (10 * len(problems) + abs(np.log(max(ratio, 1e-3)))), problems
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def trim(x):
|
| 92 |
+
f = RATE // 20; idx = np.flatnonzero(frames_on(x))
|
| 93 |
+
if not len(idx): return x[:0]
|
| 94 |
+
y = x[max(0, idx[0] * f - RATE // 20):min(len(x), (idx[-1] + 1) * f + int(.12 * RATE))].copy()
|
| 95 |
+
f = min(len(y) // 2, RATE // 100)
|
| 96 |
+
y[:f] *= np.linspace(0, 1, f); y[len(y) - f:] *= np.linspace(1, 0, f)
|
| 97 |
+
return y
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def loudness(x):
|
| 101 |
+
f = RATE // 20; n = len(x) // f
|
| 102 |
+
e = (x[:n * f].reshape(n, f) ** 2).mean(1); on = 10 * np.log10(e + 1e-12) > -45
|
| 103 |
+
return float(np.sqrt(e[on].mean())) if on.any() else 0.
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def join(pieces, texts):
|
| 107 |
+
ref = loudness(pieces[0]) or 1.; out = []
|
| 108 |
+
for i, (y, t) in enumerate(zip(pieces, texts)):
|
| 109 |
+
level = loudness(y)
|
| 110 |
+
out.append(y * (min(2., max(.5, ref / level)) if level else 1.))
|
| 111 |
+
if i < len(pieces) - 1:
|
| 112 |
+
pause = .35 if re.search(r'[.!?。!?]["\]]?\s*$', t) else .2
|
| 113 |
+
out.append(np.zeros(int(pause * RATE), dtype=np.float32))
|
| 114 |
+
return np.concatenate(out).astype(np.float32)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class Quiet:
|
| 118 |
+
def start(self, seconds): pass
|
| 119 |
+
|
| 120 |
+
def finish(self, extra=0): pass
|
| 121 |
+
|
| 122 |
+
def __call__(self, stage, step, total): pass
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def _best_take(robin, text, voice, lang, seed, retries, progress, **kwargs):
|
| 126 |
+
best = None
|
| 127 |
+
for k in range(retries + 1):
|
| 128 |
+
progress.start(expected_seconds(text, lang))
|
| 129 |
+
audio, _, info = robin.speak(text, voice, lang=lang, seed=seed + 7919 * k, callback=progress, **kwargs)
|
| 130 |
+
score, problems = check(audio, text, lang, info['capped'])
|
| 131 |
+
if best is None or score < best[0]: best = (score, problems, audio)
|
| 132 |
+
if not problems or k == retries:
|
| 133 |
+
progress.finish(); break
|
| 134 |
+
progress.finish(extra=1)
|
| 135 |
+
return best[2], best[1]
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def read(robin, text, voice=None, *, reference=None, reference_rate=None, reference_text=None, seed=0, cfg=1., retries=2, max_words=35,
|
| 139 |
+
lang='en', as_written=False, progress=None, **sampling):
|
| 140 |
+
progress = progress or Quiet()
|
| 141 |
+
chunks = split(text, max_words, lang, as_written)
|
| 142 |
+
if not chunks: raise ValueError('There is no text to read.')
|
| 143 |
+
voice = (voice or '').strip() or None
|
| 144 |
+
ref = None if reference is None else (reference, reference_rate, (reference_text or '').strip() or None)
|
| 145 |
+
kept = []
|
| 146 |
+
for i, chunk in enumerate(chunks):
|
| 147 |
+
audio, problems = _best_take(robin, chunk, voice, lang, seed + 1000 * i, retries, progress, cfg=cfg,
|
| 148 |
+
reference=ref[0] if ref else None, reference_rate=ref[1] if ref else None,
|
| 149 |
+
reference_text=ref[2] if ref else None, **sampling)
|
| 150 |
+
take = trim(audio)
|
| 151 |
+
kept.append(take)
|
| 152 |
+
if not problems and len(chunks) > 1 and len(take):
|
| 153 |
+
ref = (take, RATE, chunk)
|
| 154 |
+
return join(kept, chunks)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def change(robin, source, source_rate, source_text, *, reference=None, reference_rate=None, reference_text=None, voice=None, seed=0,
|
| 158 |
+
retries=2, lang='en', progress=None, **sampling):
|
| 159 |
+
progress = progress or Quiet()
|
| 160 |
+
voice = (voice or '').strip() or None
|
| 161 |
+
if not (source_text or '').strip(): raise ValueError('The source text must say exactly what the source clip says.')
|
| 162 |
+
if reference is None:
|
| 163 |
+
line = SAMPLE_LINES.get(lang, SAMPLE_LINE)
|
| 164 |
+
audio, _ = _best_take(robin, line, voice, lang, seed, retries, progress, **sampling)
|
| 165 |
+
reference, reference_rate, reference_text = trim(audio), RATE, line
|
| 166 |
+
seconds = len(source) / source_rate
|
| 167 |
+
target = stats(source, source_rate)['sound'] or seconds
|
| 168 |
+
best = None
|
| 169 |
+
for k in range(retries + 1):
|
| 170 |
+
progress.start(seconds)
|
| 171 |
+
audio, _, info = robin.convert(source, source_text.strip(), reference, reference_text=(reference_text or '').strip() or None,
|
| 172 |
+
source_rate=source_rate, reference_rate=reference_rate, description=voice, lang=lang,
|
| 173 |
+
seed=seed + 7919 * k, callback=progress, **sampling)
|
| 174 |
+
st = stats(audio); ratio = st['sound'] / max(target, .1)
|
| 175 |
+
problems = st['sound'] < .3 or not .5 <= ratio <= 2. or (info['capped'] and st['tail'] < .5)
|
| 176 |
+
score = 10 * problems + abs(np.log(max(ratio, 1e-3)))
|
| 177 |
+
if best is None or score < best[0]: best = (score, audio)
|
| 178 |
+
if not problems or k == retries:
|
| 179 |
+
progress.finish(); break
|
| 180 |
+
progress.finish(extra=1)
|
| 181 |
+
return best[1]
|
comfyui-robin/robin/pipeline.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import warnings
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
from safetensors.torch import load_file
|
| 8 |
+
from tokenizers import Tokenizer
|
| 9 |
+
|
| 10 |
+
from .model import Config, Planner, Decoder
|
| 11 |
+
|
| 12 |
+
LANGS = dict(en='English', ja='Japanese', mix='English and Japanese')
|
| 13 |
+
WEIGHTS = 'robin_v1.safetensors'
|
| 14 |
+
VAE = 'robin_vae.safetensors'
|
| 15 |
+
SPEECH = 'speech_tokenizer_v3_25hz.onnx'
|
| 16 |
+
APOSTROPHES = str.maketrans(dict.fromkeys('\u2019\u2018\u201b\u02bc\uff07\u2032\u00b4`', "'"))
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def plain(s):
|
| 20 |
+
return s.translate(APOSTROPHES) if s else s
|
| 21 |
+
FRAME_RATE, SAMPLE_RATE = 25, 48000
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class Cancelled(Exception):
|
| 25 |
+
pass
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def prefix_mask(n, ss, device):
|
| 29 |
+
m = torch.full((n, n), float('-inf'), device=device).triu_(1)
|
| 30 |
+
m[:ss, :ss] = 0
|
| 31 |
+
return m
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class Robin:
|
| 35 |
+
def __init__(self, planner, decoder, vae, tokenizer, config, device):
|
| 36 |
+
self.planner, self.decoder, self.vae, self.tok, self.device = planner, decoder, vae, tokenizer, device
|
| 37 |
+
t = config['tokens']
|
| 38 |
+
self.eod, self.score_start, self.score_end = t['eod'], t['score_start'], t['score_end']
|
| 39 |
+
self.audio_start, self.audio_end, self.offset, self.codes = t['audio_start'], t['audio_end'], t['audio_offset'], t['audio_codes']
|
| 40 |
+
self.instruction, self.defaults = config['instruction'], config['sampling']
|
| 41 |
+
self._speech, self.lora, self.weights_file, self.vae_file = None, None, None, None
|
| 42 |
+
|
| 43 |
+
@classmethod
|
| 44 |
+
def from_pretrained(cls, path, vae=None, device='cuda', dtype=torch.bfloat16, lora=None, lora_scale=1.0):
|
| 45 |
+
path = Path(path)
|
| 46 |
+
if not path.exists():
|
| 47 |
+
from huggingface_hub import snapshot_download
|
| 48 |
+
path = Path(snapshot_download(str(path)))
|
| 49 |
+
if vae is None:
|
| 50 |
+
vae = path/VAE
|
| 51 |
+
if not vae.is_file():
|
| 52 |
+
raise ValueError(f'VAE weights are required: put {VAE} in {path}, or pass vae=<path to the .safetensors file>')
|
| 53 |
+
config = json.loads((path/'config.json').read_text())
|
| 54 |
+
c = Config(**config['model'])
|
| 55 |
+
with torch.device('meta'):
|
| 56 |
+
planner, decoder = Planner(c), Decoder(c)
|
| 57 |
+
sd = load_file(str(path/WEIGHTS), device=str(torch.device(device)))
|
| 58 |
+
for net, prefix in ((planner, 'robin.planner.'), (decoder, 'robin.decoder.')):
|
| 59 |
+
net.load_state_dict({k[len(prefix):]: sd.pop(k) for k in [k for k in sd if k.startswith(prefix)]}, strict=True, assign=True)
|
| 60 |
+
if sd: raise ValueError(f'unexpected weights in {path/WEIGHTS}: {", ".join(list(sd)[:5])}')
|
| 61 |
+
del sd
|
| 62 |
+
vae_file = None
|
| 63 |
+
if not isinstance(vae, torch.nn.Module):
|
| 64 |
+
from .vae import load_vae
|
| 65 |
+
vae_file, vae = Path(vae), load_vae(vae, device)
|
| 66 |
+
planner = planner.to(device, dtype).eval().requires_grad_(False); decoder = decoder.to(device, dtype).eval().requires_grad_(False)
|
| 67 |
+
robin = cls(planner, decoder, vae, Tokenizer.from_file(str(path/'tokenizer.json')), config, device)
|
| 68 |
+
robin.weights_file, robin.vae_file = path/WEIGHTS, vae_file
|
| 69 |
+
if lora is not None:
|
| 70 |
+
robin.load_lora(lora, lora_scale)
|
| 71 |
+
return robin
|
| 72 |
+
|
| 73 |
+
def base_sha256(self):
|
| 74 |
+
from .lora import file_sha256
|
| 75 |
+
return file_sha256(self.weights_file) if self.weights_file else None
|
| 76 |
+
|
| 77 |
+
def load_lora(self, path, scale=1.0):
|
| 78 |
+
from .lora import LoRA
|
| 79 |
+
self.remove_lora()
|
| 80 |
+
lora, config = LoRA.load(path, dict(planner=self.planner.layers, decoder=self.decoder.model.layers), self.device)
|
| 81 |
+
base = config.get('base_sha256')
|
| 82 |
+
if base and self.weights_file and base != self.base_sha256():
|
| 83 |
+
warnings.warn(f'{Path(path).name} was trained on different Robin weights; it may not sound right')
|
| 84 |
+
lora.scale = scale
|
| 85 |
+
self.lora = lora.attach()
|
| 86 |
+
return self
|
| 87 |
+
|
| 88 |
+
def set_lora_scale(self, scale):
|
| 89 |
+
if self.lora is None: raise ValueError('no LoRA is loaded')
|
| 90 |
+
self.lora.scale = scale
|
| 91 |
+
|
| 92 |
+
def remove_lora(self):
|
| 93 |
+
if self.lora is not None:
|
| 94 |
+
self.lora.detach(); self.lora = None
|
| 95 |
+
|
| 96 |
+
@property
|
| 97 |
+
def speech(self):
|
| 98 |
+
if self._speech is None:
|
| 99 |
+
from .speech import SpeechTokenizer
|
| 100 |
+
self._speech = SpeechTokenizer(self.weights_file.parent/SPEECH, self.device)
|
| 101 |
+
return self._speech
|
| 102 |
+
|
| 103 |
+
def tags(self, description=None, lang='en'):
|
| 104 |
+
base = f"speech, spoken word, {LANGS.get(lang, lang)}"
|
| 105 |
+
return f"{base}. {description.strip()}" if description and description.strip() else base
|
| 106 |
+
|
| 107 |
+
def _block(self, label, tokens, text=None):
|
| 108 |
+
head = f'[{label}]\n' + (f'{text}\n' if text else '')
|
| 109 |
+
return self.tok.encode(head).ids + [self.audio_start] + [int(t) + self.offset for t in tokens] + [self.audio_end] + self.tok.encode('\n').ids
|
| 110 |
+
|
| 111 |
+
def prompt(self, text, description=None, lang='en', reference=None, reference_text=None, source=None):
|
| 112 |
+
text, description, reference_text = plain(text), plain(description), plain(reference_text)
|
| 113 |
+
ids = [self.eod] + self.tok.encode(f"{self.instruction}\n[Tags]\n{self.tags(description, lang)}\n[Lyrics]\n{text}\n").ids
|
| 114 |
+
if reference is not None:
|
| 115 |
+
ids += self._block('Reference voice', reference, reference_text)
|
| 116 |
+
if source is not None:
|
| 117 |
+
ids += self._block('Source performance', source)
|
| 118 |
+
return ids + [self.score_start, self.score_end, self.audio_start]
|
| 119 |
+
|
| 120 |
+
def reference_tokens(self, audio, text=None, sample_rate=None, max_frames=400, excerpt_frames=375):
|
| 121 |
+
tokens = self.speech(audio, sample_rate)
|
| 122 |
+
if len(tokens) <= max_frames:
|
| 123 |
+
return tokens, text
|
| 124 |
+
s = (len(tokens) - excerpt_frames) // 2
|
| 125 |
+
return tokens[s:s + excerpt_frames], None
|
| 126 |
+
|
| 127 |
+
def _branch(self, ids, budget):
|
| 128 |
+
ks, vs, h = self.planner.prefill(torch.tensor(ids, device=self.device), prefix_mask(len(ids), len(ids), self.device))
|
| 129 |
+
cap = len(ids) + budget + 1
|
| 130 |
+
kb, vb = [], []
|
| 131 |
+
for k, v in zip(ks, vs):
|
| 132 |
+
kbuf = torch.zeros(1, k.shape[1], cap, k.shape[3], dtype=k.dtype, device=self.device); kbuf[:, :, :len(ids)] = k
|
| 133 |
+
vbuf = torch.zeros_like(kbuf); vbuf[:, :, :len(ids)] = v
|
| 134 |
+
kb.append(kbuf); vb.append(vbuf)
|
| 135 |
+
return dict(k=kb, v=vb, pos=len(ids), logits=self.planner.lm_head(h[:, -1]).float()[0])
|
| 136 |
+
|
| 137 |
+
@torch.no_grad()
|
| 138 |
+
def plan(self, ids, budget, *, seed=0, temperature=None, top_k=None, top_p=None, min_tokens=25, negative=None, cfg=1.,
|
| 139 |
+
pause_guard=None, guard_distinct=None, callback=None):
|
| 140 |
+
d = self.defaults
|
| 141 |
+
temperature = d['temperature'] if temperature is None else temperature
|
| 142 |
+
top_k = d['top_k'] if top_k is None else top_k
|
| 143 |
+
top_p = d['top_p'] if top_p is None else top_p
|
| 144 |
+
pause_guard = d['pause_guard'] if pause_guard is None else pause_guard
|
| 145 |
+
guard_distinct = d['guard_distinct'] if guard_distinct is None else guard_distinct
|
| 146 |
+
g = torch.Generator(device=self.device).manual_seed(int(seed) % 2 ** 64)
|
| 147 |
+
branches = [self._branch(ids, budget)] + ([self._branch(negative, budget)] if negative is not None and cfg != 1. else [])
|
| 148 |
+
allowed = torch.full_like(branches[0]['logits'], float('-inf'))
|
| 149 |
+
allowed[self.offset:self.offset + self.codes] = 0; allowed[self.audio_end] = 0
|
| 150 |
+
out = []
|
| 151 |
+
for step in range(budget):
|
| 152 |
+
lg = branches[0]['logits'] if len(branches) == 1 else branches[1]['logits'] + cfg * (branches[0]['logits'] - branches[1]['logits'])
|
| 153 |
+
s = lg + allowed
|
| 154 |
+
if step < min_tokens: s[self.audio_end] = float('-inf')
|
| 155 |
+
if pause_guard and len(out) >= pause_guard:
|
| 156 |
+
recent = set(out[-pause_guard:])
|
| 157 |
+
if len(recent) <= guard_distinct: s[torch.tensor(sorted(recent), device=self.device)] = float('-inf')
|
| 158 |
+
if temperature == 0:
|
| 159 |
+
tok = int(s.argmax())
|
| 160 |
+
else:
|
| 161 |
+
s = s / temperature
|
| 162 |
+
if top_k: s = s.masked_fill(s < s.topk(min(top_k, s.numel())).values[-1], float('-inf'))
|
| 163 |
+
if top_p < 1:
|
| 164 |
+
v, ix = s.sort(descending=True); cp = v.softmax(-1).cumsum(-1)
|
| 165 |
+
drop = cp - v.softmax(-1) > top_p; s = s.masked_fill(torch.zeros_like(s, dtype=torch.bool).scatter(0, ix, drop), float('-inf'))
|
| 166 |
+
tok = int(torch.multinomial(s.softmax(-1), 1, generator=g))
|
| 167 |
+
if tok == self.audio_end: return out, False
|
| 168 |
+
out.append(tok)
|
| 169 |
+
if callback is not None and callback('plan', step + 1, budget) is False: raise Cancelled()
|
| 170 |
+
for b in branches:
|
| 171 |
+
b['logits'] = self.planner.step(tok, b['pos'], b['k'], b['v']); b['pos'] += 1
|
| 172 |
+
return out, True
|
| 173 |
+
|
| 174 |
+
@torch.no_grad()
|
| 175 |
+
def latents(self, ids, tokens, *, seed=0, steps=None, sampler=None, callback=None):
|
| 176 |
+
steps = self.defaults['decoder_steps'] if steps is None else steps
|
| 177 |
+
sampler = self.defaults['decoder_sampler'] if sampler is None else sampler
|
| 178 |
+
full = list(ids) + list(tokens) + [self.audio_end]
|
| 179 |
+
ks, vs, _ = self.planner.prefill(torch.tensor(full, device=self.device), prefix_mask(len(full), len(ids), self.device))
|
| 180 |
+
T = len(tokens)
|
| 181 |
+
x = torch.randn((1, 64, T), generator=torch.Generator().manual_seed(int(seed) % 2 ** 64)).to(self.device).transpose(1, 2)
|
| 182 |
+
sig = torch.cat([torch.linspace(1.0, 0.001, steps + 1)[:-1], torch.zeros(1)]).to(self.device)
|
| 183 |
+
|
| 184 |
+
def denoised(x_, s_):
|
| 185 |
+
return x_ - self.decoder.velocity(x_, s_.reshape(1), ks, vs) * s_
|
| 186 |
+
|
| 187 |
+
if sampler == 'dpm_2':
|
| 188 |
+
for i in range(steps):
|
| 189 |
+
s0, s1 = sig[i], sig[i + 1]
|
| 190 |
+
d = (x - denoised(x, s0)) / s0
|
| 191 |
+
if s1 == 0:
|
| 192 |
+
x = x + d * (s1 - s0)
|
| 193 |
+
else:
|
| 194 |
+
sm = s0.log().lerp(s1.log(), 0.5).exp()
|
| 195 |
+
x2 = x + d * (sm - s0)
|
| 196 |
+
x = x + (x2 - denoised(x2, sm)) / sm * (s1 - s0)
|
| 197 |
+
if callback is not None and callback('decode', i + 1, steps) is False: raise Cancelled()
|
| 198 |
+
elif sampler == 'dpmpp_2m':
|
| 199 |
+
old = None
|
| 200 |
+
for i in range(steps):
|
| 201 |
+
s0, s1 = sig[i], sig[i + 1]
|
| 202 |
+
den = denoised(x, s0)
|
| 203 |
+
t, tn = -s0.log(), -s1.log()
|
| 204 |
+
h = tn - t
|
| 205 |
+
if old is None or s1 == 0:
|
| 206 |
+
x = (s1 / s0) * x - (-h).expm1() * den
|
| 207 |
+
else:
|
| 208 |
+
r = (t + sig[i - 1].log()) / h
|
| 209 |
+
x = (s1 / s0) * x - (-h).expm1() * ((1 + 1 / (2 * r)) * den - (1 / (2 * r)) * old)
|
| 210 |
+
old = den
|
| 211 |
+
if callback is not None and callback('decode', i + 1, steps) is False: raise Cancelled()
|
| 212 |
+
else:
|
| 213 |
+
raise ValueError(f'unknown sampler {sampler}')
|
| 214 |
+
return x.transpose(1, 2).float()
|
| 215 |
+
|
| 216 |
+
@torch.no_grad()
|
| 217 |
+
def decode(self, latents):
|
| 218 |
+
return self.vae.decode(latents.to(self.device, torch.float32))[0].float().mean(0).cpu().numpy()
|
| 219 |
+
|
| 220 |
+
def _budget(self, text, lang, max_seconds):
|
| 221 |
+
if lang == 'mix': frames = sum(5.0 if ord(c) > 127 else 2.2 for c in text)
|
| 222 |
+
else: frames = len(text) * (5.0 if lang == 'ja' else 2.2)
|
| 223 |
+
return int(min(max_seconds * FRAME_RATE, frames + 100))
|
| 224 |
+
|
| 225 |
+
def _render(self, ids, budget, seed, negative=None, cfg=1., steps=None, sampler=None, callback=None, **sampling):
|
| 226 |
+
tokens, capped = self.plan(ids, budget, seed=seed, negative=negative, cfg=cfg, callback=callback, **sampling)
|
| 227 |
+
if not tokens: raise RuntimeError('nothing was generated')
|
| 228 |
+
lat = self.latents(ids, tokens, seed=seed, steps=steps, sampler=sampler, callback=callback)
|
| 229 |
+
return self.decode(lat), SAMPLE_RATE, dict(frames=len(tokens), seconds=len(tokens) / FRAME_RATE, capped=capped,
|
| 230 |
+
tokens=[t - self.offset for t in tokens])
|
| 231 |
+
|
| 232 |
+
@torch.no_grad()
|
| 233 |
+
def speak(self, text, description=None, *, reference=None, reference_text=None, reference_rate=None, lang='en', seed=0, cfg=1.,
|
| 234 |
+
max_seconds=45, steps=None, sampler=None, callback=None, **sampling):
|
| 235 |
+
ref = None
|
| 236 |
+
if reference is not None:
|
| 237 |
+
ref, reference_text = self.reference_tokens(reference, reference_text, reference_rate)
|
| 238 |
+
ids = self.prompt(text, description, lang, ref, reference_text)
|
| 239 |
+
negative = self.prompt(text, None, lang) if description and cfg != 1. and ref is None else None
|
| 240 |
+
return self._render(ids, self._budget(text, lang, max_seconds), seed, negative, cfg, steps, sampler, callback, **sampling)
|
| 241 |
+
|
| 242 |
+
@torch.no_grad()
|
| 243 |
+
def convert(self, source, text, reference, *, reference_text=None, source_rate=None, reference_rate=None, description=None,
|
| 244 |
+
lang='en', seed=0, steps=None, sampler=None, callback=None, **sampling):
|
| 245 |
+
src = self.speech(source, source_rate)
|
| 246 |
+
ref, reference_text = self.reference_tokens(reference, reference_text, reference_rate)
|
| 247 |
+
ids = self.prompt(text, description, lang, ref, reference_text, src)
|
| 248 |
+
return self._render(ids, int(len(src) * 1.6) + 50, seed, None, 1., steps, sampler, callback, **sampling)
|
comfyui-robin/robin/speech.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import soundfile as sf
|
| 5 |
+
import torch
|
| 6 |
+
from torchaudio.functional import resample
|
| 7 |
+
|
| 8 |
+
HOP = 640
|
| 9 |
+
CORE, CTX = 700, 25
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def load_audio(audio, sample_rate=None):
|
| 13 |
+
if isinstance(audio, (str, bytes)) or hasattr(audio, '__fspath__'):
|
| 14 |
+
x, sample_rate = sf.read(str(audio), dtype='float32', always_2d=True)
|
| 15 |
+
return torch.from_numpy(x.mean(1)), sample_rate
|
| 16 |
+
if sample_rate is None:
|
| 17 |
+
raise ValueError('pass sample_rate with an array')
|
| 18 |
+
x = torch.as_tensor(np.asarray(audio, dtype=np.float32))
|
| 19 |
+
return (x.mean(1) if x.ndim == 2 else x), sample_rate
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class SpeechTokenizer:
|
| 23 |
+
def __init__(self, path, device='cuda'):
|
| 24 |
+
import s3tokenizer
|
| 25 |
+
path = Path(path)
|
| 26 |
+
if not path.is_file():
|
| 27 |
+
raise ValueError(f'The speech tokenizer is missing: put {path.name} in {path.parent}. It comes with Robin on Hugging Face.')
|
| 28 |
+
self.s3, self.device = s3tokenizer, device
|
| 29 |
+
self.model = s3tokenizer.load_model(str(path)).to(device).eval()
|
| 30 |
+
|
| 31 |
+
@torch.no_grad()
|
| 32 |
+
def _codes(self, wav16):
|
| 33 |
+
m, lens = self.s3.padding([self.s3.log_mel_spectrogram(wav16, n_mels=128)])
|
| 34 |
+
codes, clens = self.model.quantize(m.to(self.device), lens.to(self.device))
|
| 35 |
+
return codes[0, :clens[0]].cpu().numpy()
|
| 36 |
+
|
| 37 |
+
def __call__(self, audio, sample_rate=None):
|
| 38 |
+
x, rate = load_audio(audio, sample_rate)
|
| 39 |
+
wav16 = resample(x, rate, 16000)
|
| 40 |
+
total = int(round(len(wav16) / HOP))
|
| 41 |
+
if total <= CORE:
|
| 42 |
+
return self._codes(wav16).astype(np.int64)
|
| 43 |
+
out = []
|
| 44 |
+
for s in range(0, total, CORE):
|
| 45 |
+
a = max(0, s - CTX); b = min(total, s + CORE + CTX)
|
| 46 |
+
c = self._codes(wav16[a * HOP:b * HOP])
|
| 47 |
+
keep = min(CORE, total - s); piece = c[s - a:s - a + keep]
|
| 48 |
+
if len(piece) < keep: piece = np.concatenate([piece, np.repeat(c[-1:], keep - len(piece))])
|
| 49 |
+
out.append(piece)
|
| 50 |
+
return np.concatenate(out).astype(np.int64)
|
comfyui-robin/robin/text.py
ADDED
|
@@ -0,0 +1,699 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
ONES = ('zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen '
|
| 4 |
+
'nineteen').split()
|
| 5 |
+
TENS = ('', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety')
|
| 6 |
+
SCALES = ('', ' thousand', ' million', ' billion', ' trillion')
|
| 7 |
+
IRREGULAR = dict(one='first', two='second', three='third', five='fifth', eight='eighth', nine='ninth', twelve='twelfth')
|
| 8 |
+
MONTHS = ('January February March April May June July August September October November December').split()
|
| 9 |
+
MONTH = re.compile(r'(Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?|July?|Aug(?:ust)?|Sept?(?:ember)?|Oct(?:ober)?|'
|
| 10 |
+
r'Nov(?:ember)?|Dec(?:ember)?)')
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def number(n):
|
| 14 |
+
if n < 0: return 'minus ' + number(-n)
|
| 15 |
+
if n < 20: return ONES[n]
|
| 16 |
+
if n < 100: return TENS[n // 10] + ('-' + ONES[n % 10] if n % 10 else '')
|
| 17 |
+
if n < 1000: return ONES[n // 100] + ' hundred' + (' ' + number(n % 100) if n % 100 else '')
|
| 18 |
+
if n >= 10 ** 15: return digits(str(n))
|
| 19 |
+
out, i = [], 0
|
| 20 |
+
while n:
|
| 21 |
+
n, r = divmod(n, 1000)
|
| 22 |
+
if r: out.append(number(r) + SCALES[i])
|
| 23 |
+
i += 1
|
| 24 |
+
return ' '.join(reversed(out))
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def digits(s, zero='zero'):
|
| 28 |
+
return ' '.join(zero if c == '0' else ONES[int(c)] for c in s if c.isdigit())
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def ordinal(n):
|
| 32 |
+
head, last = re.match(r'(.*?)([a-z]+)$', number(n)).groups()
|
| 33 |
+
return head + (IRREGULAR.get(last) or (last[:-1] + 'ieth' if last.endswith('y') else last + 'th'))
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def year(n):
|
| 37 |
+
if not 1000 <= n <= 9999 or n % 1000 == 0 or 2000 < n < 2010: return number(n)
|
| 38 |
+
hi, lo = divmod(n, 100)
|
| 39 |
+
return number(hi) + (' hundred' if lo == 0 else ' oh ' + ONES[lo] if lo < 10 else ' ' + number(lo))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def pairs(s):
|
| 43 |
+
if len(s) > 1 and s[0] == '0' or len(s) > 4: return digits(s)
|
| 44 |
+
n = int(s)
|
| 45 |
+
if len(s) == 4: return year(n)
|
| 46 |
+
if len(s) < 3 or n % 100 == 0: return number(n)
|
| 47 |
+
return ONES[n // 100] + (' oh ' + ONES[n % 100] if n % 100 < 10 else ' ' + number(n % 100))
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def cardinal(s):
|
| 51 |
+
s = s.replace(',', '')
|
| 52 |
+
return digits(s) if len(s) > 1 and s[0] == '0' or len(s) > 15 else number(int(s))
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def decimal(s):
|
| 56 |
+
whole, _, frac = s.replace(',', '').partition('.')
|
| 57 |
+
words = cardinal(whole) if whole else ''
|
| 58 |
+
return (words + ' point ' if words else 'point ') + digits(frac) if frac else words
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def plural(words):
|
| 62 |
+
return words[:-1] + 'ies' if words.endswith('y') else words + ('es' if words.endswith(('x', 's')) else 's')
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def fraction(n, d, of_unit=None):
|
| 66 |
+
name = {2: 'half', 4: 'quarter'}.get(d) or ordinal(d)
|
| 67 |
+
if of_unit:
|
| 68 |
+
if n == 1: return f'half a {of_unit}' if d == 2 else ('an ' if name[0] in 'aeiou' else 'a ') + f'{name} {of_unit}'
|
| 69 |
+
return f'{number(n)} {"halves" if d == 2 else name + "s"} of a {of_unit}'
|
| 70 |
+
return f'{number(n)} ' + (name if n == 1 else 'halves' if d == 2 else name + 's')
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
UNITS = {
|
| 74 |
+
'mm': 'millimeter', 'cm': 'centimeter', 'km': 'kilometer', 'm': 'meter', 'nm': 'nanometer', 'µm': 'micrometer',
|
| 75 |
+
'mi': 'mile', 'ft': ('foot', 'feet'), 'yd': 'yard', 'in.': ('inch', 'inches'), 'ly': 'light-year',
|
| 76 |
+
'mg': 'milligram', 'mcg': 'microgram', 'µg': 'microgram', 'g': 'gram', 'kg': 'kilogram', 'lb': 'pound', 'lbs': 'pound',
|
| 77 |
+
'oz': 'ounce', 'fl oz': 'fluid ounce', 'ml': 'milliliter', 'mL': 'milliliter', 'L': 'liter', 'dL': 'deciliter', 'dl': 'deciliter',
|
| 78 |
+
'tsp': 'teaspoon', 'tbsp': 'tablespoon', 'Tbsp': 'tablespoon', 'TBSP': 'tablespoon', 'qt': 'quart', 'gal': 'gallon',
|
| 79 |
+
'ms': 'millisecond', 'sec': 'second', 'secs': 'second', 'min': 'minute', 'mins': 'minute', 'hr': 'hour', 'hrs': 'hour',
|
| 80 |
+
'yr': 'year', 'yrs': 'year', 'wk': 'week', 'wks': 'week',
|
| 81 |
+
'Hz': ('hertz', 'hertz'), 'kHz': ('kilohertz', 'kilohertz'), 'MHz': ('megahertz', 'megahertz'), 'GHz': ('gigahertz', 'gigahertz'),
|
| 82 |
+
'KB': 'kilobyte', 'kB': 'kilobyte', 'MB': 'megabyte', 'GB': 'gigabyte', 'TB': 'terabyte', 'PB': 'petabyte',
|
| 83 |
+
'Kb': 'kilobit', 'kb': 'kilobit', 'Mb': 'megabit', 'Gb': 'gigabit',
|
| 84 |
+
'kbps': ('kilobit per second', 'kilobits per second'), 'Kbps': ('kilobit per second', 'kilobits per second'),
|
| 85 |
+
'Mbps': ('megabit per second', 'megabits per second'), 'Gbps': ('gigabit per second', 'gigabits per second'),
|
| 86 |
+
'MB/s': ('megabyte per second', 'megabytes per second'), 'GB/s': ('gigabyte per second', 'gigabytes per second'),
|
| 87 |
+
'W': 'watt', 'kW': 'kilowatt', 'MW': 'megawatt', 'GW': 'gigawatt', 'Wh': 'watt-hour', 'kWh': 'kilowatt-hour',
|
| 88 |
+
'MWh': 'megawatt-hour', 'GWh': 'gigawatt-hour', 'mAh': 'milliamp-hour', 'V': 'volt', 'mV': 'millivolt', 'kV': 'kilovolt',
|
| 89 |
+
'mA': 'milliamp', 'kcal': 'kilocalorie', 'cal': 'calorie', 'kJ': 'kilojoule',
|
| 90 |
+
'Pa': 'pascal', 'kPa': 'kilopascal', 'hPa': 'hectopascal', 'psi': ('P S I', 'P S I'), 'mmHg': ('millimeter of mercury',
|
| 91 |
+
'millimeters of mercury'),
|
| 92 |
+
'mph': ('mile per hour', 'miles per hour'), 'kph': ('kilometer per hour', 'kilometers per hour'),
|
| 93 |
+
'km/h': ('kilometer per hour', 'kilometers per hour'), 'm/s': ('meter per second', 'meters per second'),
|
| 94 |
+
'mg/dL': ('milligram per deciliter', 'milligrams per deciliter'), 'mmol/L': ('millimole per liter', 'millimoles per liter'),
|
| 95 |
+
'rpm': ('R P M', 'R P M'), 'RPM': ('R P M', 'R P M'), 'bpm': ('B P M', 'B P M'), 'BPM': ('B P M', 'B P M'),
|
| 96 |
+
'fps': ('F P S', 'F P S'), 'FPS': ('F P S', 'F P S'), 'dB': 'decibel', 'dpi': ('D P I', 'D P I'), 'DPI': ('D P I', 'D P I'),
|
| 97 |
+
'ppi': ('P P I', 'P P I'), 'px': 'pixel', 'IU': ('I U', 'I U'), 'N·m': ('newton-meter', 'newton-meters'), 'Nm': ('newton-meter', 'newton-meters'),
|
| 98 |
+
'lb-ft': ('pound-foot', 'pound-feet'), 'lb·ft': ('pound-foot', 'pound-feet'),
|
| 99 |
+
}
|
| 100 |
+
POWERS = {'²': 'square', '³': 'cubic', '^2': 'square', '^3': 'cubic'}
|
| 101 |
+
CURRENCIES = {
|
| 102 |
+
'$': ('dollar', 'dollars', 'cent', 'cents'), 'US$': ('dollar', 'dollars', 'cent', 'cents'),
|
| 103 |
+
'A$': ('Australian dollar', 'Australian dollars', 'cent', 'cents'), 'AU$': ('Australian dollar', 'Australian dollars', 'cent', 'cents'),
|
| 104 |
+
'C$': ('Canadian dollar', 'Canadian dollars', 'cent', 'cents'), 'CA$': ('Canadian dollar', 'Canadian dollars', 'cent', 'cents'),
|
| 105 |
+
'NZ$': ('New Zealand dollar', 'New Zealand dollars', 'cent', 'cents'), 'HK$': ('Hong Kong dollar', 'Hong Kong dollars', 'cent', 'cents'),
|
| 106 |
+
'S$': ('Singapore dollar', 'Singapore dollars', 'cent', 'cents'), 'R$': ('real', 'reais', 'centavo', 'centavos'),
|
| 107 |
+
'MX$': ('peso', 'pesos', 'centavo', 'centavos'), '€': ('euro', 'euros', 'cent', 'cents'), '£': ('pound', 'pounds', 'penny', 'pence'),
|
| 108 |
+
'¥': ('yen', 'yen', None, None), '₹': ('rupee', 'rupees', 'paisa', 'paise'), '₩': ('won', 'won', None, None),
|
| 109 |
+
'₽': ('ruble', 'rubles', 'kopek', 'kopeks'), '₱': ('peso', 'pesos', 'centavo', 'centavos'), '₺': ('lira', 'lira', 'kurus', 'kurus'),
|
| 110 |
+
}
|
| 111 |
+
CODES = {'USD': ('U S dollar', 'U S dollars'), 'EUR': ('euro', 'euros'), 'GBP': ('pound', 'pounds'), 'JPY': ('yen', 'yen'),
|
| 112 |
+
'CHF': ('Swiss franc', 'Swiss francs'), 'CAD': ('Canadian dollar', 'Canadian dollars'), 'AUD': ('Australian dollar',
|
| 113 |
+
'Australian dollars'), 'NZD': ('New Zealand dollar', 'New Zealand dollars'), 'INR': ('rupee', 'rupees'), 'CNY': ('yuan', 'yuan'),
|
| 114 |
+
'MXN': ('peso', 'pesos'), 'BRL': ('real', 'reais'), 'KRW': ('won', 'won'), 'SEK': ('krona', 'kronor'), 'NOK': ('krone', 'kroner'),
|
| 115 |
+
'DKK': ('krone', 'kroner'), 'BTC': ('bitcoin', 'bitcoin'), 'ETH': ('ether', 'ether'), 'HKD': ('Hong Kong dollar', 'Hong Kong dollars'),
|
| 116 |
+
'SGD': ('Singapore dollar', 'Singapore dollars'), 'ZAR': ('rand', 'rand'), 'TRY': ('lira', 'lira'), 'PLN': ('zloty', 'zlotys')}
|
| 117 |
+
SCALE_WORDS = {'k': 'thousand', 'K': 'thousand', 'm': 'million', 'M': 'million', 'mm': 'million', 'mn': 'million', 'MM': 'million',
|
| 118 |
+
'b': 'billion', 'B': 'billion', 'bn': 'billion', 'Bn': 'billion', 't': 'trillion', 'T': 'trillion', 'tn': 'trillion'}
|
| 119 |
+
AS_WORDS = {
|
| 120 |
+
'NASA': 'NASA', 'NATO': 'NATO', 'UNESCO': 'UNESCO', 'UNICEF': 'UNICEF', 'FIFA': 'FIFA', 'FEMA': 'FEMA', 'OPEC': 'OPEC',
|
| 121 |
+
'NAFTA': 'NAFTA', 'POTUS': 'POTUS', 'SCOTUS': 'SCOTUS', 'SWAT': 'SWAT', 'AIDS': 'AIDS', 'COVID': 'COVID', 'SARS': 'SARS',
|
| 122 |
+
'SCUBA': 'scuba', 'LASER': 'laser', 'RADAR': 'radar', 'SONAR': 'sonar', 'CAPTCHA': 'captcha', 'YOLO': 'yolo', 'FOMO': 'fomo',
|
| 123 |
+
'ROM': 'rom', 'RAM': 'ram', 'PIN': 'pin', 'ZIP': 'zip', 'SIM': 'sim', 'GIF': 'gif', 'JPEG': 'jay-peg', 'JSON': 'jay-son',
|
| 124 |
+
'GUI': 'gooey', 'ASCII': 'ask-ee', 'IKEA': 'Ikea', 'LEGO': 'Lego', 'OK': 'OK', 'TBD': 'T B D', 'WWII': 'World War Two',
|
| 125 |
+
'WWI': 'World War One', 'ASAP': 'A S A P', 'NIMBY': 'nimby', 'IMAX': 'IMAX', 'AWOL': 'AWOL', 'MASH': 'MASH', 'GOAT': 'GOAT',
|
| 126 |
+
'UCLA': 'U C L A', 'ACLU': 'A C L U', 'AARP': 'A A R P', 'IEEE': 'I triple E', 'NAACP': 'N double A C P', 'USAF': 'U S A F',
|
| 127 |
+
'OLED': 'O L E D', 'SQL': 'S Q L', 'AMOLED': 'A M O L E D', 'URL': 'U R L', 'UI': 'U I', 'API': 'A P I',
|
| 128 |
+
'DOS': 'doss', 'LAN': 'lan', 'VLAN': 'vee-lan', 'NAS': 'nass', 'SCSI': 'scuzzy', 'NGINX': 'engine-ex', 'WYSIWYG': 'wizzy-wig',
|
| 129 |
+
'CMOS': 'see-moss', 'BIOS': 'bye-oss', 'SATA': 'say-tuh', 'RAID': 'raid', 'VRAM': 'vee-ram', 'DRAM': 'dee-ram', 'SRAM': 'ess-ram',
|
| 130 |
+
'SDRAM': 'ess-dee-ram', 'IMAP': 'eye-map', 'YAML': 'yamel', 'POP': 'pop', 'WAV': 'wave', 'OGG': 'ogg', 'FLAC': 'flack',
|
| 131 |
+
'MPEG': 'em-peg', 'MIDI': 'middy', 'LUFS': 'luffs', 'LUT': 'lut', 'SMPTE': 'simp-tee', 'PAL': 'pal', 'HUD': 'hud', 'LARP': 'larp',
|
| 132 |
+
'MOBA': 'moba', 'LIDAR': 'lidar', 'PAC': 'pack', 'TED': 'Ted', 'HIPAA': 'hippa',
|
| 133 |
+
}
|
| 134 |
+
ONSETS = set('BL BR CH CL CR DR DW FL FR GL GN GR KL KN KR KW PH PL PR PS QU SC SH SK SL SM SN SP ST SW TH TR TW WH WR SCH SCR SHR SPL '
|
| 135 |
+
'SPR STR THR'.split())
|
| 136 |
+
CODAS = set('CH CK CT FT GH LB LD LF LK LL LM LP LT MB MP ND NG NK NS NT PH PT RB RC RD RF RG RK RL RM RN RP RS RT SH SK SP SS ST TH TS '
|
| 137 |
+
'TZ XT'.split())
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def pronounceable(w):
|
| 141 |
+
if not re.search('[AEIOUY]', w): return False
|
| 142 |
+
if len(w) >= 6: return True
|
| 143 |
+
w = re.sub(r'(?<=[AEIOU])[HWY]', 'E', w)
|
| 144 |
+
for run in re.findall(r'[^AEIOUY]+', w):
|
| 145 |
+
if len(run) > 3: return False
|
| 146 |
+
m = re.match(r'[^AEIOUY]+', w)
|
| 147 |
+
if m and len(m.group(0)) > 1 and m.group(0) not in ONSETS: return False
|
| 148 |
+
m = re.search(r'[^AEIOUY]+$', w)
|
| 149 |
+
if m and len(m.group(0)) > 1 and m.group(0) not in CODAS: return False
|
| 150 |
+
return all(len(r) < 2 or r in ONSETS or r in CODAS or r[:-1] in CODAS and r[-1:] + 'R' in ONSETS | {r[-1:] + 'R'}
|
| 151 |
+
for r in re.findall(r'(?<=[AEIOUY])[^AEIOUY]{2,}(?=[AEIOUY])', w)) or len(w) >= 6
|
| 152 |
+
RESPELLING_CUES = re.compile(r'\b(?:pronounced?|pronouncing|pronunciation|rhymes?|stress(?:ed)?|syllables?|spelled|accent on)\b', re.I)
|
| 153 |
+
RESPELLING = re.compile(r'\b[A-Za-z]+(?:-[A-Za-z]+)+\b')
|
| 154 |
+
RESPELL = {'codec': 'koh-deck', 'codecs': 'koh-decks', 'bitrate': 'bit rate', 'bitrates': 'bit rates', 'iOS': 'eye O S',
|
| 155 |
+
'MySQL': 'my S Q L', 'NoSQL': 'no S Q L', 'PhD': 'P H D', 'PhDs': 'P H Ds',
|
| 156 |
+
'macOS': 'mac O S', 'iPadOS': 'eye-pad O S', 'tvOS': 'T V O S', 'watchOS': 'watch O S'}
|
| 157 |
+
COMMON = set('''a about after again all also always an and any are as at away back bad be because been before being best better big
|
| 158 |
+
both but by call came can come could day did do does done down each even ever every far few find first for from get give go goes going
|
| 159 |
+
gone good got great had has have he her here him his how i if in into is its just keep kind know last least left less let like
|
| 160 |
+
little long look lot love made make man many may me might mine more most much must my need never new next nice no none nor not
|
| 161 |
+
nothing now of off oh old on once one only or our out over own please put real really right run said same saw say see seen she
|
| 162 |
+
should show since so some still stop such sure take tell than thank thanks that the their them then there these they thing think
|
| 163 |
+
this those though through time to too took true try turn two under until up upon use very wait want was watch way we well went
|
| 164 |
+
were what when where which while who whole why will wish with without wow yeah yes yet you your yours hey help hello go stay run
|
| 165 |
+
listen look out right left never ever again done over here there love hate fire free gold big huge boom bang ugh omg wait'''.split())
|
| 166 |
+
REGNAL = set('''Henry Louis Elizabeth George Charles Edward William James Richard John Mary Victoria Anne Philip Felipe Juan Carlos
|
| 167 |
+
Frederick Friedrich Wilhelm Napoleon Peter Catherine Ivan Nicholas Alexander Alfonso Ferdinand Leopold Rudolf Francis Franz Pius
|
| 168 |
+
Benedict Gregory Leo Innocent Clement Boniface Urban Paul Ramesses Ramses Thutmose Amenhotep Ptolemy Constantine Justinian Otto
|
| 169 |
+
Gustav Gustavus Christian Olaf Haakon Harald Pedro Manuel Afonso Henri Ludwig Maximilian Selim Suleiman Mehmed Murad Ahmed Rama
|
| 170 |
+
David Robert Kamehameha Willem Carl Gustaf Harold Edmund Stephen Matilda Sancho Wenceslaus Sigismund Casimir Boleslaw Vladimir
|
| 171 |
+
Basil Michael Andronikos Theodore Sixtus Julius Martin Nicolas Augustus Antiochus Seleucus Darius Xerxes Cyrus Artaxerxes'''.split())
|
| 172 |
+
ROMAN_AFTER = set('''War Part Chapter Act Book Volume Vol Phase Episode Season Level Stage Type Class Gen Generation Mark Bowl Rocky
|
| 173 |
+
Fantasy Edition Round Wave Tier Grade Section Article Title Division Appendix Psalm Canto Scene Movement Symphony Op Opus Unit Year
|
| 174 |
+
Form Saga Quest Wars Kombat Rising Revelations Legacy Origins Collection Chronicles Trilogy Remastered Zero Force Command'''.split())
|
| 175 |
+
STATES = set('AL AK AZ AR CA CO CT DE FL GA HI ID IL IN IA KS KY LA ME MD MA MI MN MS MO MT NE NV NH NJ NM NY NC ND OH OK OR PA RI SC SD '
|
| 176 |
+
'TN TX UT VT VA WA WV WI WY DC'.split())
|
| 177 |
+
TLD_WORDS = set('com net org edu gov mil int info biz shop store blog news art design games site online tech app dev co me so to page '
|
| 178 |
+
'live media cloud space world club life today zone'.split())
|
| 179 |
+
TLDS = TLD_WORDS | set('io ai uk us tv gg ly fm ca de jp fr au nz in xyz eu es it nl se no ch be at dk fi pl ru br mx cn kr'.split())
|
| 180 |
+
EXTENSIONS = {'jpg': 'J P G', 'jpeg': 'jay-peg', 'png': 'P N G', 'gif': 'gif', 'webp': 'web P', 'heic': 'H E I C', 'svg': 'S V G',
|
| 181 |
+
'pdf': 'P D F', 'doc': 'doc', 'docx': 'doc X', 'xls': 'X L S', 'xlsx': 'X L S X', 'ppt': 'P P T', 'pptx': 'P P T X',
|
| 182 |
+
'txt': 'T X T', 'csv': 'C S V', 'md': 'M D', 'json': 'jay-son', 'xml': 'X M L', 'yaml': 'yaml', 'yml': 'Y M L',
|
| 183 |
+
'html': 'H T M L', 'htm': 'H T M', 'css': 'C S S', 'js': 'J S', 'ts': 'T S', 'py': 'P Y', 'rb': 'R B', 'go': 'go',
|
| 184 |
+
'rs': 'R S', 'java': 'java', 'cpp': 'C P P', 'sh': 'S H', 'exe': 'E X E', 'dmg': 'D M G', 'apk': 'A P K',
|
| 185 |
+
'zip': 'zip', 'rar': 'rar', 'tar': 'tar', 'gz': 'G Z', 'iso': 'I S O', 'mp3': 'M P three', 'mp4': 'M P four',
|
| 186 |
+
'm4a': 'M four A', 'wav': 'wave', 'flac': 'flack', 'ogg': 'ogg', 'mov': 'mov', 'avi': 'A V I', 'mkv': 'M K V',
|
| 187 |
+
'webm': 'web M', 'srt': 'S R T', 'epub': 'E pub', 'ttf': 'T T F', 'otf': 'O T F', 'psd': 'P S D', 'raw': 'raw',
|
| 188 |
+
'arw': 'A R W', 'cr2': 'C R two', 'cr3': 'C R three', 'nef': 'N E F', 'dng': 'D N G', 'tif': 'tiff', 'tiff': 'tiff',
|
| 189 |
+
'bmp': 'B M P', 'log': 'log', 'ini': 'I N I', 'cfg': 'C F G', 'sql': 'S Q L', 'db': 'D B', 'bak': 'back',
|
| 190 |
+
'pages': 'pages', 'key': 'key', 'numbers': 'numbers', 'ipynb': 'I P Y N B', 'kt': 'K T', 'swift': 'swift',
|
| 191 |
+
'odt': 'O D T', 'ods': 'O D S', 'odp': 'O D P', 'rtf': 'R T F'}
|
| 192 |
+
ABBREVIATIONS = {
|
| 193 |
+
'Mr.': 'Mister', 'Mrs.': 'Missus', 'Ms.': 'Miz', 'Prof.': 'Professor', 'Lt.': 'Lieutenant', 'Sgt.': 'Sergeant',
|
| 194 |
+
'Capt.': 'Captain', 'Col.': 'Colonel', 'Gen.': 'General', 'Gov.': 'Governor', 'Sen.': 'Senator', 'Rep.': 'Representative',
|
| 195 |
+
'Pres.': 'President', 'Rev.': 'Reverend', 'Hon.': 'Honorable', 'Supt.': 'Superintendent', 'Cmdr.': 'Commander',
|
| 196 |
+
'vs.': 'versus', 'vs': 'versus', 'etc.': 'et cetera', 'e.g.': 'for example', 'i.e.': 'that is', 'approx.': 'approximately',
|
| 197 |
+
'dept.': 'department', 'Dept.': 'Department', 'est.': 'established', 'Est.': 'Established', 'misc.': 'miscellaneous',
|
| 198 |
+
'govt.': 'government', 'Govt.': 'Government', 'Inc.': 'Incorporated', 'Ltd.': 'Limited', 'Corp.': 'Corporation',
|
| 199 |
+
'Bros.': 'Brothers', 'Assn.': 'Association', 'Univ.': 'University', 'Intl.': 'International', 'Natl.': 'National',
|
| 200 |
+
'Ave.': 'Avenue', 'Blvd.': 'Boulevard', 'Rd.': 'Road', 'Ln.': 'Lane', 'Hwy.': 'Highway', 'Rte.': 'Route', 'Pkwy.': 'Parkway',
|
| 201 |
+
'Apt.': 'Apartment', 'Ste.': 'Suite', 'Mt.': 'Mount', 'Ft.': 'Fort', 'Jr.': 'Junior', 'Sr.': 'Senior', 'Ph.D.': 'P H D',
|
| 202 |
+
'Fig.': 'Figure', 'fig.': 'figure', 'Vol.': 'Volume', 'vol.': 'volume', 'Ch.': 'Chapter', 'ch.': 'chapter', 'pp.': 'pages',
|
| 203 |
+
'pg.': 'page', 'max.': 'maximum', 'min.': 'minimum', 'avg.': 'average', 'temp.': 'temperature', 'ext.': 'extension',
|
| 204 |
+
'Mon.': 'Monday', 'Tue.': 'Tuesday', 'Tues.': 'Tuesday', 'Wed.': 'Wednesday', 'Thu.': 'Thursday', 'Thur.': 'Thursday',
|
| 205 |
+
'Thurs.': 'Thursday', 'Fri.': 'Friday', 'Sat.': 'Saturday', 'Sun.': 'Sunday',
|
| 206 |
+
'w/': 'with', 'w/o': 'without', 'b/c': 'because', 'c/o': 'care of', 'N/A': 'not applicable', 'n/a': 'not applicable',
|
| 207 |
+
'a/c': 'A C', 'A/C': 'A C', 'P/E': 'P E', 'TL;DR': 'T L D R', 'tl;dr': 'T L D R',
|
| 208 |
+
}
|
| 209 |
+
TITLES = {'Mr.', 'Mrs.', 'Ms.', 'Prof.', 'Lt.', 'Sgt.', 'Capt.', 'Col.', 'Gen.', 'Gov.', 'Sen.', 'Rep.', 'Pres.', 'Rev.', 'Hon.', 'Supt.',
|
| 210 |
+
'Cmdr.', 'Mt.', 'Ft.'}
|
| 211 |
+
ENDS_SENTENCE = {'etc.', 'Inc.', 'Ltd.', 'Corp.', 'Bros.', 'Jr.', 'Sr.', 'Ave.', 'Blvd.', 'Rd.', 'Ln.', 'Hwy.', 'Pkwy.', 'Ph.D.',
|
| 212 |
+
'approx.', 'misc.', 'Assn.', 'Univ.'}
|
| 213 |
+
NETSPEAK = {'rn': 'right now', 'gtg': 'got to go', 'brb': 'be right back', 'idk': "I don't know", 'tbh': 'to be honest',
|
| 214 |
+
'imo': 'in my opinion', 'imho': 'in my humble opinion', 'btw': 'by the way', 'irl': 'in real life', 'np': 'no problem',
|
| 215 |
+
'thx': 'thanks', 'ty': 'thank you', 'pls': 'please', 'plz': 'please', 'ngl': 'not gonna lie', 'jk': 'just kidding',
|
| 216 |
+
'nvm': 'never mind', 'ikr': 'I know, right', 'afaik': 'as far as I know', 'smh': 'S M H', 'lol': 'L O L', 'lmao': 'L M A O',
|
| 217 |
+
'omg': 'O M G', 'wtf': 'W T F', 'fyi': 'F Y I', 'dm': 'D M', 'dms': 'D Ms', 'gg': 'G G', 'afk': 'A F K', 'ftw': 'for the win',
|
| 218 |
+
'ngmi': 'N G M I', 'wagmi': 'wag me', 'bc': 'because', 'atm': 'at the moment', 'iirc': 'if I recall correctly',
|
| 219 |
+
'ootd': 'outfit of the day', 'ianal': 'I A N A L', 'npc': 'N P C', 'npcs': 'N P Cs', 'eli5': 'E L I five', 'iykyk': 'I Y K Y K',
|
| 220 |
+
'qotd': 'Q O T D', 'tfw': 'T F W', 'mfw': 'M F W', 'pov': 'P O V', 'pfp': 'P F P', 'ofc': 'of course', 'nsfw': 'N S F W',
|
| 221 |
+
'omw': 'on my way', 'hmu': 'hit me up', 'wyd': 'what are you doing', 'hbu': 'how about you', 'ily': 'I love you',
|
| 222 |
+
'idc': "I don't care", 'tmi': 'T M I', 'lmk': 'let me know', 'ttyl': 'talk to you later', 'nbd': 'no big deal',
|
| 223 |
+
'wfh': 'work from home', 'lfg': 'L F G', 'icymi': 'in case you missed it', 'tbt': 'T B T', 'fwiw': "for what it's worth",
|
| 224 |
+
'tbf': 'to be fair', 'tysm': 'thank you so much', 'pvp': 'P V P', 'pve': 'P V E', 'mmo': 'M M O', 'rpg': 'R P G',
|
| 225 |
+
'fr': 'for real', 'ymmv': 'Y M M V', 'fyp': 'F Y P', 'istg': 'I swear to God', 'tl;dr': 'T L D R'}
|
| 226 |
+
KEYS = {'Cmd': 'Command', 'Ctrl': 'Control', 'Alt': 'Alt', 'Opt': 'Option', 'Option': 'Option', 'Shift': 'Shift', 'Win': 'Windows',
|
| 227 |
+
'Fn': 'Function', 'Esc': 'Escape', 'Del': 'Delete', 'Tab': 'Tab', 'Enter': 'Enter', 'Return': 'Return', 'Space': 'Space',
|
| 228 |
+
'Super': 'Super', 'Meta': 'Meta', 'Backspace': 'Backspace', 'PgUp': 'Page Up', 'PgDn': 'Page Down', 'Home': 'Home', 'End': 'End'}
|
| 229 |
+
YEAR_CUES = set('in since from by until till til circa c. ca. during before after around of year years spring summer fall autumn winter '
|
| 230 |
+
'early late mid the and to through between class vintage born died founded built released'.split())
|
| 231 |
+
FRACTION_DENOMS = {2, 3, 4, 5, 6, 8, 10, 12, 16, 32, 64, 100}
|
| 232 |
+
CODE_WORDS = set('zip code pin id ext extension account acct order confirmation ticket serial reference ref tracking postcode passcode'.split())
|
| 233 |
+
STREET = r'(?:St|Street|Ave|Avenue|Rd|Road|Blvd|Boulevard|Dr|Drive|Ln|Lane|Way|Ct|Court|Pl|Place|Pkwy|Parkway|Hwy|Highway|Ter|Terrace|Cir|Circle|Trail)\b'
|
| 234 |
+
QUANTITY_NOUNS = set('people men women children kids staff crew personnel feet foot money cash fish sheep deer'.split())
|
| 235 |
+
NOT_PLURAL = set('''was is has does gives goes makes takes sees says gets comes means seems marks changes brings starts ends begins
|
| 236 |
+
sits stands looks feels works runs plays shows its this his hers as us yes plus minus versus whereas always perhaps unless besides
|
| 237 |
+
thus across less series news '''.split())
|
| 238 |
+
NUM = r'\d{1,3}(?:,\d{3})+|\d+'
|
| 239 |
+
DEC = rf'(?:{NUM})(?:\.\d+)?|\.\d+'
|
| 240 |
+
BEFORE = r'(?<![\w.,/$€£¥₹#@-])'
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def _unit(u):
|
| 244 |
+
v = UNITS[u]
|
| 245 |
+
return v if isinstance(v, tuple) else (v, v + 's')
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def letters(s):
|
| 249 |
+
return ' '.join(s.upper())
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def ident(s):
|
| 253 |
+
out = []
|
| 254 |
+
for part in re.split(r'([_.\-])', s):
|
| 255 |
+
if part in ('_', '.', '-'): out.append({'_': 'underscore', '.': 'dot', '-': 'dash'}[part]); continue
|
| 256 |
+
for run in re.findall(r'[A-Za-z]+|\d+', part):
|
| 257 |
+
if run.isdigit(): out.append(year(int(run)) if len(run) == 4 and 1900 <= int(run) <= 2099 else
|
| 258 |
+
cardinal(run) if len(run) <= 2 else digits(run))
|
| 259 |
+
elif run.isupper() and len(run) > 1 and run not in AS_WORDS: out.append(letters(run))
|
| 260 |
+
else: out.append(AS_WORDS.get(run, run))
|
| 261 |
+
return ' '.join(out)
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def alnum(s):
|
| 265 |
+
out = []
|
| 266 |
+
chem = re.fullmatch(r'(?:[A-Z][a-z]?\d*){2,}', s) and re.search(r'\d', s) and not re.search(r'[a-z]{2}', s)
|
| 267 |
+
for part in s.split('-'):
|
| 268 |
+
for run in re.findall(r'[A-Za-z]+|\d+\.\d+|\d+', part):
|
| 269 |
+
if run[0].isdigit(): out.append(decimal(run) if '.' in run else pairs(run))
|
| 270 |
+
elif chem or len(run) == 1 or run.isupper() and run not in AS_WORDS or len(run) <= 3 and not re.search(r'[aeiouyAEIOUY]', run):
|
| 271 |
+
out.append(letters(run))
|
| 272 |
+
else: out.append(AS_WORDS.get(run, run))
|
| 273 |
+
return ' '.join(out)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def roman(s):
|
| 277 |
+
vals = dict(I=1, V=5, X=10, L=50, C=100)
|
| 278 |
+
total = 0
|
| 279 |
+
for a, b in zip(s, s[1:] + ' '):
|
| 280 |
+
total += -vals[a] if vals.get(b, 0) > vals[a] else vals[a]
|
| 281 |
+
return total if 0 < total < 400 and re.fullmatch(r'C{0,3}(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})', s) else None
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def _sub(pattern, fn, s, flags=0):
|
| 285 |
+
return re.sub(pattern, fn, s, flags=flags)
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def _money(m):
|
| 289 |
+
neg, cur, a, sa, b, sb = m.group('neg'), m.group('cur'), m.group('a'), m.group('sa'), m.group('b'), m.group('sb')
|
| 290 |
+
one, many, sub1, subs = CURRENCIES[cur]
|
| 291 |
+
|
| 292 |
+
def amount(x, scale):
|
| 293 |
+
if scale:
|
| 294 |
+
return f'{decimal(x)} {SCALE_WORDS.get(scale, scale.lower())}', True
|
| 295 |
+
whole, _, frac = x.replace(',', '').partition('.')
|
| 296 |
+
if not sub1 or not frac: return decimal(x), (x.replace(',', '') != '1')
|
| 297 |
+
cents = int((frac + '0')[:2])
|
| 298 |
+
w = int(whole or 0)
|
| 299 |
+
if not w: return f'{number(cents)} {sub1 if cents == 1 else subs}', None
|
| 300 |
+
return f'{number(w)} {one if w == 1 else many}' + (f' and {number(cents)} {sub1 if cents == 1 else subs}' if cents else ''), None
|
| 301 |
+
|
| 302 |
+
first, plural_a = amount(a, sa)
|
| 303 |
+
out = ('minus ' if neg else '')
|
| 304 |
+
if b:
|
| 305 |
+
second, plural_b = amount(b, sb or sa)
|
| 306 |
+
if plural_a is not None and plural_b is not None: return out + f'{first} to {second} {many}'
|
| 307 |
+
if plural_a is not None: first += f' {many if plural_a else one}'
|
| 308 |
+
if plural_b is not None: second += f' {many if plural_b else one}'
|
| 309 |
+
return out + f'{first} to {second}'
|
| 310 |
+
return out + (first if plural_a is None else f'{first} {many if plural_a else one}')
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def _time(m):
|
| 314 |
+
h, mm, ap = int(m.group(1)), int(m.group(2)), m.group(3)
|
| 315 |
+
hw = number(h % 12 or 12) if ap else number(h)
|
| 316 |
+
if mm == 0: words = hw if ap else (f'{hw} hundred' if h >= 13 or h == 0 else f"{hw} o'clock")
|
| 317 |
+
else: words = f'{hw} oh {ONES[mm]}' if mm < 10 else f'{hw} {number(mm)}'
|
| 318 |
+
return words + (f' {ap[0].upper()} M' if ap else '')
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def _duration(m):
|
| 322 |
+
h, mi, se = int(m.group(1)), int(m.group(2)), int(m.group(3))
|
| 323 |
+
parts = [f'{number(v)} {u}{"" if v == 1 else "s"}' for v, u in ((h, 'hour'), (mi, 'minute'), (se, 'second')) if v]
|
| 324 |
+
return ', '.join(parts[:-1]) + (' and ' if len(parts) > 1 else '') + parts[-1] if parts else 'zero seconds'
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def _date_words(mo, d, y=None, order='us'):
|
| 328 |
+
month = MONTHS[mo - 1]
|
| 329 |
+
out = f'{month} {ordinal(d)}' if order == 'us' else f'the {ordinal(d)} of {month}'
|
| 330 |
+
if y is not None: out += ', ' + (year(y) if len(str(y)) == 4 else short_year(str(y).zfill(2)))
|
| 331 |
+
return out
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def short_year(yy):
|
| 335 |
+
return 'oh ' + ONES[int(yy[1])] if yy[0] == '0' else number(int(yy))
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def _month_index(name):
|
| 339 |
+
return [m[:3] for m in MONTHS].index(name[:3].title()) + 1
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def _unit_amount(m):
|
| 343 |
+
a, b, u, pw = m.group('a'), m.group('b'), m.group('u'), m.group('pw')
|
| 344 |
+
one, many = _unit(u)
|
| 345 |
+
if pw:
|
| 346 |
+
p = POWERS[pw]; one, many = f'{p} {one}', f'{p} {many}'
|
| 347 |
+
first = decimal(a)
|
| 348 |
+
if b: return f'{first} to {decimal(b)} {many}'
|
| 349 |
+
return f'{first} {one if a == "1" else many}'
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def _number_in_context(m):
|
| 353 |
+
raw, s = m.group(0), m.string
|
| 354 |
+
if len(raw) > 1 and raw[0] == '0': return digits(raw)
|
| 355 |
+
before, after = s[:m.start()], s[m.end():]
|
| 356 |
+
pm = re.search(r"([A-Za-z][\w.']*)\s+$", before)
|
| 357 |
+
prev = pm.group(1) if pm else ''
|
| 358 |
+
starts = not pm or re.search(r'(^|[.!?:;]\s+|["(]\s*)$', before[:pm.start()]) is not None
|
| 359 |
+
nm = re.match(r'\s+([a-z]+)', after); nxt = nm.group(1) if nm else ''
|
| 360 |
+
v = int(raw)
|
| 361 |
+
counted = nxt in QUANTITY_NOUNS or nxt.endswith('s') and nxt not in NOT_PLURAL
|
| 362 |
+
if prev.lower().rstrip('.') in CODE_WORDS and len(raw) >= 4 and not counted: return digits(raw)
|
| 363 |
+
if 3 <= len(raw) <= 5 and re.match(r'\s+(?:[A-Z][\w]*\.?\s+){1,3}' + STREET, after): return pairs(raw)
|
| 364 |
+
if len(raw) == 4:
|
| 365 |
+
if prev.lower() in YEAR_CUES or not counted: return year(v)
|
| 366 |
+
return number(v // 100) + ' hundred' if v % 100 == 0 and v % 1000 else number(v)
|
| 367 |
+
if len(raw) == 3 and prev and (prev.isupper() and len(prev) > 1 or prev[0].isupper() and not starts):
|
| 368 |
+
return pairs(raw)
|
| 369 |
+
return number(v)
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def _words(s):
|
| 373 |
+
s = re.sub(r'(^|[.!?]["\')\]]?\s+)(?=[-$€£¥₹#~+]?\d)', _opener, s)
|
| 374 |
+
s = _rules(s)
|
| 375 |
+
return re.sub('\x01(.)', lambda m: m.group(1).upper(), s).replace('\x01', '')
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
SHORT_ABBR = re.compile(r'\b(?:[A-Z][a-z]{0,3}|no|vol|pp|pg|ch|fig|sec|art|ca|vs|ex|est|ed|p|c)\.$')
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def _opener(m):
|
| 382 |
+
lead = m.group(1)
|
| 383 |
+
return lead if lead.startswith('.') and SHORT_ABBR.search(m.string[:m.start() + 1]) else lead + '\x01'
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def _rules(s):
|
| 387 |
+
s = s.replace(' ', ' ').replace(' ', ' ').replace(' ', ' ').replace('‑', '-').replace('−', '-')
|
| 388 |
+
s = s.translate(str.maketrans('₀₁₂₃₄₅₆₇₈₉′″', "0123456789'\""))
|
| 389 |
+
for f, (n, d) in {'½': (1, 2), '⅓': (1, 3), '⅔': (2, 3), '¼': (1, 4), '¾': (3, 4), '⅕': (1, 5), '⅛': (1, 8), '⅜': (3, 8),
|
| 390 |
+
'⅝': (5, 8), '⅞': (7, 8)}.items():
|
| 391 |
+
s = re.sub(rf'(\d)\s?{f}', rf'\1 {n}/{d}', s).replace(f, f'{n}/{d}')
|
| 392 |
+
|
| 393 |
+
s = _sub(r'\b([\w.+-]+)@([\w-]+(?:\.[\w-]+)+)\b',
|
| 394 |
+
lambda m: f'{ident(m.group(1))} at {_domain(m.group(2))}', s)
|
| 395 |
+
s = _sub(r'\b(?:(https?)://)?((?:www\.)?(?:[A-Za-z0-9-]+\.)+(?:' + '|'.join(sorted(TLDS, key=len, reverse=True)) + r'))\b(/[^\s,;!?)"]*[^\s,;!?)".])?',
|
| 396 |
+
lambda m: _url(m), s)
|
| 397 |
+
s = _sub(r'(?<![\w@/])([ur])/([A-Za-z0-9_]{2,})', lambda m: f'{m.group(1)} slash {ident(m.group(2))}', s)
|
| 398 |
+
s = _sub(r'(?<![\w@])@([A-Za-z0-9_]{2,})', lambda m: f'at {ident(m.group(1))}', s)
|
| 399 |
+
s = _sub(r'(?<![\w&#])#\s?(\d+)\b', lambda m: f'number {cardinal(m.group(1)) if len(m.group(1)) <= 4 else digits(m.group(1))}', s)
|
| 400 |
+
s = _sub(r'(?<![\w&#])#([A-Za-z]\w*)', lambda m: f'hashtag {m.group(1)}', s)
|
| 401 |
+
ext = '|'.join(sorted(EXTENSIONS, key=len, reverse=True))
|
| 402 |
+
s = _sub(rf'\b([\w-]+)((?:\.(?:{ext}))+)\b', lambda m: ident(m.group(1)) + ''.join(
|
| 403 |
+
f' dot {EXTENSIONS[e.lower()]}' for e in m.group(2).split('.')[1:]), s, flags=re.I)
|
| 404 |
+
s = _sub(r'\b(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\b', lambda m: ' dot '.join(pairs(g) if len(g) == 3 else cardinal(g)
|
| 405 |
+
for g in m.groups()), s)
|
| 406 |
+
|
| 407 |
+
s = _sub(r'\b(' + '|'.join(NETSPEAK) + r')\b', lambda m: NETSPEAK[m.group(1)], s)
|
| 408 |
+
|
| 409 |
+
s = _sub(r'\b(?:' + '|'.join(KEYS) + r')(?:\s?\+\s?(?:' + '|'.join(KEYS) + r'|F\d{1,2}|[A-Za-z0-9]))+\b',
|
| 410 |
+
lambda m: ' '.join(KEYS.get(k, alnum(k) if re.search(r'\d', k) else k) for k in re.split(r'\s?\+\s?', m.group(0))), s)
|
| 411 |
+
s = _sub(r'\b([A-Z]{2,})/(?=\d)', r'\1 ', s)
|
| 412 |
+
s = _sub(r'(?<![\w+])(\+\d{1,3}[\s.-]?)?(\(\d{3}\)\s?|\b\d{3}[.-])(\d{3})[.-](\d{4})\b',
|
| 413 |
+
lambda m: (f'plus {digits(m.group(1), "oh")}, ' if m.group(1) else '') +
|
| 414 |
+
', '.join(digits(g, 'oh') for g in (m.group(2), m.group(3), m.group(4))), s)
|
| 415 |
+
s = _sub(r'(?<![\w+])\+(\d{1,3})((?:[\s.-]\(?\d{1,4}\)?){2,5})(?![\d.,]\d)',
|
| 416 |
+
lambda m: f'plus {digits(m.group(1), "oh")}, ' + ', '.join(digits(g, 'oh') for g in re.findall(r'\d+', m.group(2))), s)
|
| 417 |
+
s = _sub(r'(?<![\w.])[vV](\d+(?:\.\d+)*)\b', lambda m: 'version ' + ' point '.join(cardinal(p) for p in m.group(1).split('.')), s)
|
| 418 |
+
s = _sub(r'(?<![\w.])(\d+)\.(\d+)\.(\d+)(?:\.(\d+))?(?![\w.])', lambda m: ' point '.join(cardinal(p) for p in m.groups() if p), s)
|
| 419 |
+
s = _sub(r'\b(\d{5})-(\d{4})\b', lambda m: f'{digits(m.group(1))}, {digits(m.group(2))}', s)
|
| 420 |
+
s = _sub(r'(?<![\w$.-])(\d{3})-(\d{4})\b', lambda m: m.group(0) if int(m.group(1)) % 100 == 0 and int(m.group(2)) % 100 == 0
|
| 421 |
+
else f'{digits(m.group(1), "oh")}, {digits(m.group(2), "oh")}', s)
|
| 422 |
+
s = _sub(r'\b([A-Z]{2})\s+(\d{5})\b', lambda m: f'{m.group(1)} {digits(m.group(2))}' if m.group(1) in STATES else m.group(0), s)
|
| 423 |
+
|
| 424 |
+
s = _sub(r'(\d+(?:\.\d+)?)\s?°\s?(?:(\d+(?:\.\d+)?)\s?\'\s?)?(?:(\d+(?:\.\d+)?)\s?"\s?)?([NSEW])\b',
|
| 425 |
+
lambda m: f'{decimal(m.group(1))} degrees' + (f' {decimal(m.group(2))} minutes' if m.group(2) else '') +
|
| 426 |
+
(f' {decimal(m.group(3))} seconds' if m.group(3) else '') + ' ' + dict(N='north', S='south', E='east', W='west')[m.group(4)], s)
|
| 427 |
+
s = _sub(BEFORE + r'(-?)(\d+(?:\.\d+)?)\s?°\s?([FCK])\b', lambda m: ('minus ' if m.group(1) else '') + f'{decimal(m.group(2))} degrees ' +
|
| 428 |
+
dict(F='Fahrenheit', C='Celsius', K='Kelvin')[m.group(3)], s)
|
| 429 |
+
s = _sub(BEFORE + r'(-?)(\d+(?:\.\d+)?)\s?°', lambda m: ('minus ' if m.group(1) else '') + f'{decimal(m.group(2))} degrees', s)
|
| 430 |
+
s = _sub(r"\b(\d+)'\s?(\d{1,2})(?:\"|'')", lambda m: f'{number(int(m.group(1)))} foot {number(int(m.group(2)))}', s)
|
| 431 |
+
s = _sub(r"\b(\d+)'(?=[\s,.;!?]|$)", lambda m: f'{number(int(m.group(1)))} feet', s)
|
| 432 |
+
|
| 433 |
+
s = _sub(r'\b(\d{1,2}):([0-5]\d):([0-5]\d)\b', _duration, s)
|
| 434 |
+
s = _sub(r'\b([01]?\d|2[0-3]):([0-5]\d)(?:\s?([AaPp])\.?\s?[Mm]\.?(?![\w]))?(?![\w:])', _time, s)
|
| 435 |
+
s = _sub(r'\b(\d{1,2})\s?([AaPp])\.?\s?[Mm]\.?(?![\w])', lambda m: f'{number(int(m.group(1)))} {m.group(2).upper()} M', s)
|
| 436 |
+
s = _sub(r'\b(\d+)\s?h(?:rs?)?\s?(\d+)\s?m(?:ins?)?(?:\s?(\d+)\s?s(?:ecs?)?)?\b',
|
| 437 |
+
lambda m: ' '.join(f'{number(int(v))} {u}{"" if v == "1" else "s"}' for v, u in
|
| 438 |
+
((m.group(1), 'hour'), (m.group(2), 'minute'), (m.group(3), 'second')) if v), s)
|
| 439 |
+
s = _sub(r'\b(\d+)\s?m(?:ins?)?\s?(\d+)\s?s(?:ecs?)?\b',
|
| 440 |
+
lambda m: f'{number(int(m.group(1)))} minute{"" if m.group(1) == "1" else "s"} {number(int(m.group(2)))} second'
|
| 441 |
+
f'{"" if m.group(2) == "1" else "s"}', s)
|
| 442 |
+
s = _sub(r'\b(\d+)h\b', lambda m: f'{number(int(m.group(1)))} hour{"" if m.group(1) == "1" else "s"}', s)
|
| 443 |
+
|
| 444 |
+
s = _sub(r'\b' + MONTH.pattern + r'\.?\s+(\d{1,2})(?:st|nd|rd|th)?\b(?:,?\s+(\d{4})\b)?(?!:)',
|
| 445 |
+
lambda m: _date_words(_month_index(m.group(1)), int(m.group(2)), int(m.group(3)) if m.group(3) else None)
|
| 446 |
+
if 1 <= int(m.group(2)) <= 31 else m.group(0), s)
|
| 447 |
+
s = _sub(r'\b' + MONTH.pattern + r"\.?\s+'(\d{2})\b", lambda m: f'{MONTHS[_month_index(m.group(1)) - 1]} {short_year(m.group(2))}', s)
|
| 448 |
+
s = _sub(r'\b(\d{1,2})(?:st|nd|rd|th)?\s+' + MONTH.pattern + r'\b\.?(?:,?\s+(\d{4})\b)?',
|
| 449 |
+
lambda m: _date_words(_month_index(m.group(2)), int(m.group(1)), int(m.group(3)) if m.group(3) else None, 'uk')
|
| 450 |
+
if 1 <= int(m.group(1)) <= 31 else m.group(0), s)
|
| 451 |
+
s = _sub(r'\b(\d{4})-(\d{2})-(\d{2})\b', lambda m: _date_words(int(m.group(2)), int(m.group(3)), int(m.group(1)))
|
| 452 |
+
if 1 <= int(m.group(2)) <= 12 and 1 <= int(m.group(3)) <= 31 else m.group(0), s)
|
| 453 |
+
s = _sub(r'(?<![\w/.])(\d{1,2})/(\d{1,2})/(\d{4}|\d{2})(?![\w/])', _numeric_date, s)
|
| 454 |
+
s = _sub(r'\b(Jan|Feb|Mar|Apr|Jun|Jul|Aug|Sep|Sept|Oct|Nov|Dec)\.(?=\s|$)',
|
| 455 |
+
lambda m: MONTHS[_month_index(m.group(1)) - 1] + ('.' if _ends(m) else ''), s)
|
| 456 |
+
|
| 457 |
+
s = _sub(r'\b(\d{3})\(([a-z])\)', lambda m: f'{pairs(m.group(1))} {m.group(2).upper()}', s)
|
| 458 |
+
s = _sub(rf'{BEFORE}(\d+)\^(-?\d+)\b', lambda m: f'{number(int(m.group(1)))} to the ' +
|
| 459 |
+
('minus ' if m.group(2)[0] == '-' else '') + ordinal(abs(int(m.group(2)))), s)
|
| 460 |
+
s = _sub(r'\b(ft|in|yd|m|cm|km|mi|mm)\.(?=[²³])', r'\1', s)
|
| 461 |
+
s = _sub(r'\${2,4}', lambda m: f'{number(len(m.group(0)))} dollar signs', s)
|
| 462 |
+
codes = '|'.join(CODES)
|
| 463 |
+
s = _sub(rf'\b({codes})\s?({DEC})\b', lambda m: f'{decimal(m.group(2))} {CODES[m.group(1)][m.group(2) != "1"]}', s)
|
| 464 |
+
s = _sub(rf'{BEFORE}({DEC})\s?({codes})\b', lambda m: f'{decimal(m.group(1))} {CODES[m.group(2)][m.group(1) != "1"]}', s)
|
| 465 |
+
cur = '|'.join(re.escape(c) for c in sorted(CURRENCIES, key=len, reverse=True))
|
| 466 |
+
scale = r'(?:k|K|mm|MM|mn|m|M|bn|Bn|b|B|tn|t|T|thousand|million|billion|trillion)\b'
|
| 467 |
+
s = _sub(rf'(?<![\w$])(?P<neg>-)?(?P<cur>{cur})\s?(?P<a>{DEC})(?:\s?(?P<sa>{scale}))?'
|
| 468 |
+
rf'(?:\s?(?:-|–|to)\s?(?:{cur})?\s?(?P<b>{DEC})(?:\s?(?P<sb>{scale}))?)?', _money, s)
|
| 469 |
+
s = _sub(r'\b3M\b', 'three M', s)
|
| 470 |
+
s = _sub(rf'{BEFORE}({DEC})\s?(M|MM|mn|B|bn|Bn|T|tn)(?=[\s,.;:!?)]|$)', lambda m: f'{decimal(m.group(1))} {SCALE_WORDS[m.group(2)]}', s)
|
| 471 |
+
s = _sub(rf'{BEFORE}(\d+)\s?¢', lambda m: f'{number(int(m.group(1)))} cent{"" if m.group(1) == "1" else "s"}', s)
|
| 472 |
+
s = _sub(rf'{BEFORE}(-?)({DEC})(?:\s?(?:-|–|to)\s?({DEC}))?\s?%',
|
| 473 |
+
lambda m: ('minus ' if m.group(1) else '') + decimal(m.group(2)) + (f' to {decimal(m.group(3))}' if m.group(3) else '') + ' percent', s)
|
| 474 |
+
units = '|'.join(re.escape(u) for u in sorted(UNITS, key=len, reverse=True))
|
| 475 |
+
s = _sub(rf'{BEFORE}(?P<a>{DEC})(?:\s?(?:-|–|to)\s?(?P<b>{DEC}))?\s?(?P<u>{units})(?P<pw>²|³|\^2|\^3)?(?![\w/])', _unit_amount, s)
|
| 476 |
+
s = _sub(rf'{BEFORE}(\d+)\s(\d)/(\d+)\s?(?P<u>{units})(?![\w/])',
|
| 477 |
+
lambda m: f'{number(int(m.group(1)))} and {fraction(int(m.group(2)), int(m.group(3)))} {_unit(m.group("u"))[1]}', s)
|
| 478 |
+
s = _sub(rf'{BEFORE}(\d)/(\d+)\s?(?P<u>{units})(?![\w/])',
|
| 479 |
+
lambda m: fraction(int(m.group(1)), int(m.group(2)), _unit(m.group('u'))[0]), s)
|
| 480 |
+
s = _sub(rf'{BEFORE}({DEC})\s?×\s?({DEC})', lambda m: f'{decimal(m.group(1))} by {decimal(m.group(2))}', s)
|
| 481 |
+
s = _sub(rf'{BEFORE}({DEC})\s?[x×](?=\s|$|[,.;!?])', lambda m: f'{decimal(m.group(1))} times', s)
|
| 482 |
+
s = _sub(r'(?<![\w])[x×](\d+(?:\.\d+)?)\b', lambda m: f'times {decimal(m.group(1))}', s)
|
| 483 |
+
s = _sub(r'\b(\d+)v(\d+)\b', lambda m: f'{number(int(m.group(1)))} versus {number(int(m.group(2)))}', s)
|
| 484 |
+
s = _sub(r'\b(\d{3,4})p\b', lambda m: f'{pairs(m.group(1))} p', s)
|
| 485 |
+
|
| 486 |
+
s = _sub(r'\b24/7\b', 'twenty-four seven', s)
|
| 487 |
+
s = _sub(r'\b9[-/]11\b', 'nine eleven', s)
|
| 488 |
+
s = _sub(rf'{BEFORE}(\d+)\s(\d)/(\d+)(?![\w/])', lambda m: f'{number(int(m.group(1)))} and ' +
|
| 489 |
+
('a half' if m.group(2) + m.group(3) == '12' else fraction(int(m.group(2)), int(m.group(3)))), s)
|
| 490 |
+
s = _sub(rf'{BEFORE}(\d{{1,3}})/(\d{{1,3}})(?![\w/])', _slash_numbers, s)
|
| 491 |
+
s = _sub(r'\b(\d+):(\d+)\b', lambda m: f'{cardinal(m.group(1))} to {cardinal(m.group(2))}', s)
|
| 492 |
+
s = _sub(r'\b(\d+)(?:-(\d+)){2,}\b', lambda m: ' '.join(cardinal(g) for g in m.group(0).split('-')), s)
|
| 493 |
+
s = _sub(r'\b(\d{4})s\b|\b(\d{4})\'s\b', lambda m: plural(year(int(m.group(1) or m.group(2)))), s)
|
| 494 |
+
s = _sub(r"(?<![\w'])'(\d)0s\b", lambda m: plural(TENS[int(m.group(1))]), s)
|
| 495 |
+
s = _sub(r'\b([2-9])0s\b', lambda m: plural(TENS[int(m.group(1))]), s)
|
| 496 |
+
s = _sub(r"(?<![\w'])'(\d{2})\b(?!')", lambda m: short_year(m.group(1)), s)
|
| 497 |
+
s = _sub(rf'{BEFORE}(\d{{4}})\s?[–-]\s?(\d{{2}}|\d{{4}})(?![\w-])', _year_range, s)
|
| 498 |
+
s = _sub(rf'{BEFORE}(-?{DEC})\s?(?:–|-)\s?(-?{DEC})(?![\w-])', lambda m: f'{decimal_signed(m.group(1))} to {decimal_signed(m.group(2))}', s)
|
| 499 |
+
s = _sub(r'\b(\d+)(st|nd|rd|th|ST|ND|RD|TH)\b', lambda m: ordinal(int(m.group(1))), s)
|
| 500 |
+
s = _sub(r'\b(\d+)s\b', lambda m: {'1': 'ones', '0': 'zeros'}.get(m.group(1)) or f'{number(int(m.group(1)))} seconds', s)
|
| 501 |
+
|
| 502 |
+
s = _sub(rf'{BEFORE}(\d{{1,3}}(?:,\d{{3}})+(?:\.\d+)?|\d+\.\d+)-(?=[A-Za-z])', lambda m: decimal(m.group(1)) + ' ', s)
|
| 503 |
+
s = _sub(r'\b(\d+)[x×](\d+)\b', lambda m: f'{cardinal(m.group(1)) if len(m.group(1)) < 4 else pairs(m.group(1))} by '
|
| 504 |
+
f'{cardinal(m.group(2)) if len(m.group(2)) < 4 else pairs(m.group(2))}', s)
|
| 505 |
+
s = _sub(r'\b(?=[A-Za-z0-9.-]*\d)(?=[A-Za-z0-9.-]*[A-Za-z])[A-Za-z0-9]+(?:\.\d+)?(?:-[A-Za-z0-9]+(?:\.\d+)?)*\b',
|
| 506 |
+
lambda m: alnum(m.group(0)), s)
|
| 507 |
+
s = _sub(r'\b([A-Z][a-z]+(?:\s[A-Z][a-z]+)?)\s(I|[IVXLC]{2,8})\b(?!\.\w)', _roman, s)
|
| 508 |
+
|
| 509 |
+
s = _sub(rf'(?<![\w.,-])-(?={DEC})', 'minus ', s)
|
| 510 |
+
s = _sub(r'(?<![\w.,])(\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d*\.\d+)(?![\w,]|\.\d)', lambda m: decimal(m.group(1)), s)
|
| 511 |
+
s = re.sub(r'(?<![\w.,])\d+(?![\w])', _number_in_context, s)
|
| 512 |
+
s = re.sub(r'\d+', lambda m: cardinal(m.group(0)), s)
|
| 513 |
+
|
| 514 |
+
s = _sub(r'\b([A-Za-z])\+\+', r'\1 plus plus', s)
|
| 515 |
+
s = _sub(r'\b([A-Z]{1,4})&([A-Z]{1,4})(s?)\b', lambda m: f'{letters(m.group(1))} and {letters(m.group(2))}{m.group(3)}', s)
|
| 516 |
+
s = _sub(r'\s?&\s?', ' and ', s)
|
| 517 |
+
s = _sub(r'\s@\s', ' at ', s)
|
| 518 |
+
s = _sub(r'(?<!\w)#(?=\s)', 'number', s)
|
| 519 |
+
s = _sub(r'(?<=\w)\+(?=\w)|\s\+\s', ' plus ', s)
|
| 520 |
+
s = _sub(r'(?<=\w)\+(?=[\s,.;!?)]|$)', ' plus', s)
|
| 521 |
+
s = _sub(r'(?<![\w])\+(?=\w)', 'plus ', s)
|
| 522 |
+
s = _sub(r'\s?=\s?', ' equals ', s)
|
| 523 |
+
s = _sub(r'~\s?', 'about ', s)
|
| 524 |
+
s = _sub(r'≈\s?', 'approximately ', s)
|
| 525 |
+
s = _sub(r'\s?±\s?', ' plus or minus ', s)
|
| 526 |
+
s = _sub(r'\s?÷\s?', ' divided by ', s)
|
| 527 |
+
s = _sub(r'\s?×\s?', ' times ', s)
|
| 528 |
+
s = _sub(r'\s?≥\s?', ' greater than or equal to ', s)
|
| 529 |
+
s = _sub(r'\s?≤\s?', ' less than or equal to ', s)
|
| 530 |
+
s = _sub(r'\s?≠\s?', ' not equal to ', s)
|
| 531 |
+
s = _sub(r'(\w)\^2\b|(\w)²', lambda m: (m.group(1) or m.group(2)) + ' squared', s)
|
| 532 |
+
s = _sub(r'(\w)\^3\b|(\w)³', lambda m: (m.group(1) or m.group(2)) + ' cubed', s)
|
| 533 |
+
s = _sub(r'√\s?', 'square root of ', s)
|
| 534 |
+
s = _sub(r'%', ' percent', s)
|
| 535 |
+
s = _sub(r'°', ' degrees', s)
|
| 536 |
+
s = _sub(r'©\s?', 'copyright ', s)
|
| 537 |
+
s = _sub(r'[™®]', '', s)
|
| 538 |
+
s = _sub(r'§\s?', 'section ', s)
|
| 539 |
+
s = _sub(r'(?<=[A-Za-z])_(?=[A-Za-z0-9])', ' underscore ', s)
|
| 540 |
+
s = _sub(r'\$(?=[A-Z]{1,5}\b)', '', s)
|
| 541 |
+
|
| 542 |
+
for k, v in ABBREVIATIONS.items():
|
| 543 |
+
tail = r'(?=\s+[A-Z])' if k in TITLES else r'(?=[\s,;:!?)"]|$)' if k.endswith(('.', '/')) else r'\b'
|
| 544 |
+
s = re.sub(r'(?<![\w.])' + re.escape(k) + tail, lambda m, k=k, v=v: v + ('.' if k in ENDS_SENTENCE and _ends(m) else ''), s)
|
| 545 |
+
s = _sub(r'(?<![\w.])(Dr|St)\.(?=\s|$)', _dr_st, s)
|
| 546 |
+
s = _sub(r'\b(Street|Avenue|Road|Boulevard|Drive|Lane|Highway|Parkway|Way|Court|Place)\.?\s(NW|NE|SW|SE)\b',
|
| 547 |
+
lambda m: f'{m.group(1)} ' + dict(NW='Northwest', NE='Northeast', SW='Southwest', SE='Southeast')[m.group(2)], s)
|
| 548 |
+
s = _sub(r'(?<![\w.])([Nn]o)\.\s?(?=\d|[a-z]+\b)', lambda m: ('Number' if m.group(1) == 'No' else 'number') + ' ', s)
|
| 549 |
+
s = _sub(r'(?<![\w.])p\.\s?(?=\d)', 'page ', s)
|
| 550 |
+
s = _sub(r'\b([A-Z]{1,6}\d*)/([A-Z0-9]{1,6})\b', lambda m: f'{m.group(1)} slash {m.group(2)}', s)
|
| 551 |
+
s = _sub(r'\bd([a-z])/d([a-z])\b', r'd \1 d \2', s)
|
| 552 |
+
s = _sub(r'\b([a-z]+)/([a-z]+)\b', r'\1 \2', s)
|
| 553 |
+
s = _sub(r'(?<=\w)/(?=\w)', ' ', s)
|
| 554 |
+
s = _sub(r'(?<![\w.])((?:[A-Za-z]\.){2,})(?=[\s,;:!?)"]|$)', lambda m: letters(m.group(1).replace('.', '')) + ('.' if _ends(m) else ''), s)
|
| 555 |
+
s = _acronyms(s)
|
| 556 |
+
s = _sub(r'\b(' + '|'.join(re.escape(k) for k in RESPELL) + r')\b', lambda m: RESPELL[m.group(1)], s)
|
| 557 |
+
s = _sub(r'\b(' + '|'.join(re.escape(k) for k in RESPELL if k.islower()) + r')\b',
|
| 558 |
+
lambda m: RESPELL[m.group(1).lower()].capitalize() if m.group(1)[0].isupper() else m.group(0), s, flags=re.I)
|
| 559 |
+
s = _sub(r'\*+', '', s)
|
| 560 |
+
s = _sub(r'[ \t]{2,}', ' ', s)
|
| 561 |
+
s = _sub(r' +([,.;:!?])', r'\1', s)
|
| 562 |
+
return s
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
def _ends(m):
|
| 566 |
+
rest = m.string[m.end():]
|
| 567 |
+
return not rest.strip() or bool(re.match(r'\s+["\']?[A-Z](?![A-Z])', rest))
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
def _dr_st(m):
|
| 571 |
+
before, after = m.string[:m.start()], m.string[m.end():]
|
| 572 |
+
pm = re.search(r'([A-Z][\w]*|\w*\d\w*)\s+$', before)
|
| 573 |
+
named = pm is not None and re.search(r'(^|[.!?:;]\s+|["(]\s*)$', before[:pm.start()]) is None
|
| 574 |
+
if not named and re.match(r'\s+[A-Z]', after): return 'Doctor' if m.group(1) == 'Dr' else 'Saint'
|
| 575 |
+
return ('Drive' if m.group(1) == 'Dr' else 'Street') + ('.' if _ends(m) else '')
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
def _domain(d):
|
| 579 |
+
labels = d.split('.')
|
| 580 |
+
tld = labels[-1].lower()
|
| 581 |
+
out = [ident(x) for x in labels[:-1]] + [tld if tld in TLD_WORDS else letters(tld)]
|
| 582 |
+
return ' dot '.join(out)
|
| 583 |
+
|
| 584 |
+
|
| 585 |
+
def _url(m):
|
| 586 |
+
host, path = m.group(2), m.group(3) or ''
|
| 587 |
+
words = []
|
| 588 |
+
if host.lower().startswith('www.'): words.append('w w w dot'); host = host[4:]
|
| 589 |
+
words.append(_domain(host))
|
| 590 |
+
for p in [p for p in path.split('/') if p][:6]:
|
| 591 |
+
words.append('slash ' + ident(p))
|
| 592 |
+
return ' '.join(words)
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
def _numeric_date(m):
|
| 596 |
+
a, b, y = int(m.group(1)), int(m.group(2)), m.group(3)
|
| 597 |
+
yv = int(y)
|
| 598 |
+
if 1 <= a <= 12 and 1 <= b <= 31: return _date_words(a, b, yv if len(y) == 4 else y)
|
| 599 |
+
if 1 <= b <= 12 and 1 <= a <= 31: return _date_words(b, a, yv if len(y) == 4 else y, 'uk')
|
| 600 |
+
return m.group(0)
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
def _slash_numbers(m):
|
| 604 |
+
n, d = int(m.group(1)), int(m.group(2))
|
| 605 |
+
special = {'9/11': 'nine eleven', '50/50': 'fifty fifty', '20/20': 'twenty twenty', '9/10': 'nine out of ten'}
|
| 606 |
+
if m.group(0) in special: return special[m.group(0)]
|
| 607 |
+
if d in (5, 10, 100) and n <= d: return f'{number(n)} out of {number(d)}'
|
| 608 |
+
if d in FRACTION_DENOMS and 0 < n < d: return fraction(n, d)
|
| 609 |
+
if 1 <= n <= 12 and 1 <= d <= 31: return f'{MONTHS[n - 1]} {ordinal(d)}'
|
| 610 |
+
return f'{number(n)} {"out of" if n <= d else "over"} {number(d)}'
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
def _year_range(m):
|
| 614 |
+
a, b = m.group(1), m.group(2)
|
| 615 |
+
if not 1000 <= int(a) <= 2099: return m.group(0)
|
| 616 |
+
if len(b) == 2: return f'{year(int(a))} to {short_year(b) if b[0] == "0" else number(int(b))}'
|
| 617 |
+
return f'{year(int(a))} to {year(int(b))}' if 1000 <= int(b) <= 2099 else m.group(0)
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
def decimal_signed(x):
|
| 621 |
+
return 'minus ' + decimal(x[1:]) if x.startswith('-') else decimal(x)
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
def _roman(m):
|
| 625 |
+
name, num = m.group(1), m.group(2)
|
| 626 |
+
v = roman(num)
|
| 627 |
+
last = name.split()[-1]
|
| 628 |
+
if v is None or num in ('XL', 'XXL', 'XXXL', 'LV', 'CV', 'CI', 'LI', 'XC', 'CC', 'CL') or num == 'I' and last not in REGNAL:
|
| 629 |
+
return m.group(0)
|
| 630 |
+
if last in REGNAL: return f'{name} the {ordinal(v).capitalize()}'
|
| 631 |
+
if last in ROMAN_AFTER or len(num) >= 2: return f'{name} {number(v)}'
|
| 632 |
+
return m.group(0)
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
def _respelling(w):
|
| 636 |
+
parts = w.split('-'); low = [p for p in parts if p.islower()]
|
| 637 |
+
return any(p.isupper() for p in parts) and low and all(len(p) <= 5 for p in low) and (len(parts) >= 3 or any(len(p) <= 3 for p in low))
|
| 638 |
+
|
| 639 |
+
|
| 640 |
+
def _acronyms(s):
|
| 641 |
+
out = []
|
| 642 |
+
for sent in re.split(r'(?<=[.!?])(\s+)', s):
|
| 643 |
+
words = re.findall(r'[A-Za-z]{2,}', sent)
|
| 644 |
+
caps = [w for w in words if w.isupper()]
|
| 645 |
+
shouting = len(caps) >= 3 and len(caps) >= .6 * len(words)
|
| 646 |
+
respelled = [w for w in RESPELLING.findall(sent) if _respelling(w)]
|
| 647 |
+
if shouting or RESPELLING_CUES.search(sent): out.append(sent); continue
|
| 648 |
+
if respelled:
|
| 649 |
+
keep = {}
|
| 650 |
+
for i, w in enumerate(respelled):
|
| 651 |
+
keep[f'\x00{i}\x00'] = w; sent = sent.replace(w, f'\x00{i}\x00', 1)
|
| 652 |
+
sent = _acronym_words(sent)
|
| 653 |
+
for k, w in keep.items(): sent = sent.replace(k, w)
|
| 654 |
+
out.append(sent); continue
|
| 655 |
+
out.append(_acronym_words(sent))
|
| 656 |
+
return ''.join(out)
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def _acronym_words(sent):
|
| 660 |
+
sent = re.sub(r'\b([A-Z]{2,6})-(?=[A-Z]{2,6}\b)', r'\1 ', sent)
|
| 661 |
+
sent = re.sub(r'\b(?![A-Z]{2,}s\b)(?=[A-Za-z]*[a-z])(?=[A-Za-z]*[A-Z][a-z]?[A-Z])(?:[A-Z]+[a-z]?)+\b', _mixed_caps, sent)
|
| 662 |
+
return re.sub(r"\b([A-Z]{2,8})(s|'s)?\b", _acronym, sent)
|
| 663 |
+
|
| 664 |
+
|
| 665 |
+
def _mixed_caps(m):
|
| 666 |
+
w = m.group(0)
|
| 667 |
+
if w in RESPELL or len(w) > 6 or sum(c.isupper() for c in w) <= sum(c.islower() for c in w): return w
|
| 668 |
+
return letters(w)
|
| 669 |
+
|
| 670 |
+
|
| 671 |
+
def _acronym(m):
|
| 672 |
+
w, suffix = m.group(1), m.group(2) or ''
|
| 673 |
+
if w in AS_WORDS: return AS_WORDS[w] + suffix
|
| 674 |
+
if w.lower() in COMMON and not suffix: return w
|
| 675 |
+
if len(w) >= 4 and pronounceable(w): return w + suffix
|
| 676 |
+
return letters(w) + ("'s" if suffix else '')
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
LETTER_NAMES = dict(A='ay', B='bee', C='see', D='dee', E='ee', F='ef', G='jee', H='aitch', I='eye', J='jay', K='kay', L='el', M='em',
|
| 680 |
+
N='en', O='oh', P='pee', Q='cue', R='ar', S='ess', T='tee', U='you', V='vee', W='double-you', X='ex', Y='why', Z='zee')
|
| 681 |
+
LETTER_RUN = re.compile(r"(?<![\w'-])[A-Z](?:'s|s)?(?: [A-Z](?:'s|s)?)+(?![\w'-])")
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
def _names(said, written):
|
| 685 |
+
said = re.sub(r'(?<=\b[A-Z] [A-Z])-(?=\w)|(?<=\w)-(?=[A-Z] [A-Z]\b)', ' ', said)
|
| 686 |
+
said = re.sub(r'\b([A-Z])-([A-Z])\b', r'\1 \2', said)
|
| 687 |
+
|
| 688 |
+
def run(m):
|
| 689 |
+
letters = m.group(0).split(' ')
|
| 690 |
+
keep = letters[0] in ('A', 'I') and re.search(rf"\b{letters[0]} {re.escape(''.join(t[0] for t in letters[1:]))}", written)
|
| 691 |
+
named = [LETTER_NAMES[t[0]] + t[1:] for t in letters[1 if keep else 0:]]
|
| 692 |
+
return ' '.join(([letters[0]] if keep else []) + named) if len(named) > 1 or not keep else m.group(0)
|
| 693 |
+
return LETTER_RUN.sub(run, said)
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
def speakable(text):
|
| 697 |
+
if not text or re.search(r'[\u3040-\u30ff\u3400-\u9fff\uac00-\ud7af]', text): return text
|
| 698 |
+
parts = re.split(r'(\[[^\]]*\])', text)
|
| 699 |
+
return ''.join(p if i % 2 else _names(_words(p), p) for i, p in enumerate(parts))
|
comfyui-robin/robin/train.py
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import hashlib
|
| 2 |
+
import json
|
| 3 |
+
import math
|
| 4 |
+
import os
|
| 5 |
+
import random
|
| 6 |
+
import re
|
| 7 |
+
import time
|
| 8 |
+
from collections import defaultdict
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import soundfile as sf
|
| 13 |
+
import torch
|
| 14 |
+
import torch.nn.functional as F
|
| 15 |
+
from torch.utils.checkpoint import checkpoint
|
| 16 |
+
|
| 17 |
+
from .lora import LoRA, file_sha256
|
| 18 |
+
from .pipeline import plain, prefix_mask
|
| 19 |
+
|
| 20 |
+
AUDIO = ('.wav', '.flac', '.mp3', '.ogg', '.opus', '.aiff', '.aif')
|
| 21 |
+
OTHER_AUDIO = ('.m4a', '.aac', '.wma', '.mp4', '.webm', '.mov')
|
| 22 |
+
SPEECH_TOKENS = 'speech_tokenizer_v3_25hz'
|
| 23 |
+
REF_WHOLE, REF_EXCERPT = 400, 375
|
| 24 |
+
SAMPLE_TEXT = dict(en='Hello there! This is a quick test of my new voice. How does it sound to you?',
|
| 25 |
+
ja='こんにちは。これは新しい声のテストです。どう聞こえますか?',
|
| 26 |
+
mix='Hello! これは新しい声のテストです。How does it sound?')
|
| 27 |
+
CHARS_PER_SECOND = dict(en=((2.5, 35), (6, 24)), ja=((1, 25), (3, 15)), mix=((1, 35), (3, 24)))
|
| 28 |
+
|
| 29 |
+
PROBLEMS = {
|
| 30 |
+
'no_text': 'no transcript (add a .txt file with the same name)',
|
| 31 |
+
'empty_text': 'the transcript is empty',
|
| 32 |
+
'unreadable': "the audio can't be read",
|
| 33 |
+
'other_format': "this audio format can't be read (convert it to .wav or .flac)",
|
| 34 |
+
'low_rate': 'recorded below 16 kHz (too low to learn a voice from)',
|
| 35 |
+
'silent': 'almost silent',
|
| 36 |
+
'short': 'too short',
|
| 37 |
+
'long': 'too long (split it into shorter clips)',
|
| 38 |
+
'mismatch': "the transcript doesn't fit the length of the audio (check the .txt)",
|
| 39 |
+
'tokens': "the audio couldn't be processed",
|
| 40 |
+
}
|
| 41 |
+
WARNINGS = {
|
| 42 |
+
'rate': 'recorded below 44.1 kHz: the voice will learn a duller top end',
|
| 43 |
+
'clipped': 'clipped (distorted peaks)',
|
| 44 |
+
'digits': 'digits in the transcript: write numbers out as words, the way they are spoken',
|
| 45 |
+
'pace': 'the transcript may not fit the audio (unusually fast or slow speech for its length)',
|
| 46 |
+
'duplicate': 'the same transcript appears more than once',
|
| 47 |
+
'orphan': 'a transcript with no audio file of the same name',
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def frames_db(x, rate):
|
| 52 |
+
n = max(1, rate // 100); k = len(x) // n
|
| 53 |
+
if k == 0: return np.full(1, -120.)
|
| 54 |
+
return 20 * np.log10(np.sqrt((x[:k * n].reshape(k, n) ** 2).mean(1)) + 1e-9)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def trim(x, rate):
|
| 58 |
+
db = frames_db(x, rate); loud = float(db.max())
|
| 59 |
+
on = np.where(db > max(min(-45., loud - 30), -60.))[0]
|
| 60 |
+
if len(on) == 0: return x[:0], loud
|
| 61 |
+
n = rate // 100
|
| 62 |
+
return x[max(0, on[0] * n - int(.15 * rate)):min(len(x), (on[-1] + 1) * n + int(.25 * rate))], loud
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def read_mono(path):
|
| 66 |
+
x, rate = sf.read(str(path), dtype='float32', always_2d=True)
|
| 67 |
+
return x.mean(1), rate
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def scan(folder, lang='en', min_seconds=1., max_seconds=30.):
|
| 71 |
+
folder = Path(folder)
|
| 72 |
+
if not folder.is_dir(): raise SystemExit(f'{folder} is not a folder')
|
| 73 |
+
desc_file = folder/'voice.txt'
|
| 74 |
+
description = plain(' '.join(desc_file.read_text(encoding='utf-8').split())) if desc_file.exists() else None
|
| 75 |
+
problems, warnings, clips, seen = defaultdict(list), defaultdict(list), [], defaultdict(list)
|
| 76 |
+
files = sorted(p for p in folder.rglob('*') if p.is_file() and not any(part.startswith('.') for part in p.relative_to(folder).parts))
|
| 77 |
+
hard, soft = CHARS_PER_SECOND.get(lang, CHARS_PER_SECOND['en'])
|
| 78 |
+
for p in files:
|
| 79 |
+
rel = p.relative_to(folder).as_posix(); ext = p.suffix.lower()
|
| 80 |
+
if ext in OTHER_AUDIO: problems['other_format'].append(rel); continue
|
| 81 |
+
if ext not in AUDIO: continue
|
| 82 |
+
txt = p.with_suffix('.txt')
|
| 83 |
+
if not txt.exists(): problems['no_text'].append(rel); continue
|
| 84 |
+
text = plain(' '.join(txt.read_text(encoding='utf-8', errors='replace').split()))
|
| 85 |
+
if not text: problems['empty_text'].append(rel); continue
|
| 86 |
+
try:
|
| 87 |
+
x, rate = read_mono(p)
|
| 88 |
+
except Exception:
|
| 89 |
+
problems['unreadable'].append(rel); continue
|
| 90 |
+
if rate < 16000: problems['low_rate'].append(rel); continue
|
| 91 |
+
y, loud = trim(x, rate); seconds = len(y) / rate
|
| 92 |
+
if loud < -40 or seconds == 0: problems['silent'].append(rel); continue
|
| 93 |
+
if seconds < min_seconds: problems['short'].append(f'{rel} ({seconds:.1f} s)'); continue
|
| 94 |
+
if seconds > max_seconds: problems['long'].append(f'{rel} ({seconds:.0f} s)'); continue
|
| 95 |
+
cps = len(re.sub(r'\[[^\]]*\]|[\W_]', '', text)) / seconds
|
| 96 |
+
if not hard[0] <= cps <= hard[1]: problems['mismatch'].append(rel); continue
|
| 97 |
+
if not soft[0] <= cps <= soft[1]: warnings['pace'].append(rel)
|
| 98 |
+
if rate < 44100: warnings['rate'].append(rel)
|
| 99 |
+
if (np.abs(x) >= .999).mean() > 1e-3: warnings['clipped'].append(rel)
|
| 100 |
+
if re.search(r'\d', re.sub(r'\[[^\]]*\]', '', text)): warnings['digits'].append(rel)
|
| 101 |
+
seen[text.lower()].append(rel)
|
| 102 |
+
st = p.stat()
|
| 103 |
+
key = hashlib.sha1(f'{rel}|{st.st_size}|{st.st_mtime_ns}|{text}|{min_seconds}|{max_seconds}'.encode()).hexdigest()[:20]
|
| 104 |
+
clips.append(dict(file=rel, text=text, seconds=round(seconds, 2), rate=rate, key=key))
|
| 105 |
+
for rels in seen.values():
|
| 106 |
+
if len(rels) > 1: warnings['duplicate'] += rels
|
| 107 |
+
audio = {p.with_suffix('') for p in files if p.suffix.lower() in AUDIO + OTHER_AUDIO}
|
| 108 |
+
warnings['orphan'] += [p.relative_to(folder).as_posix() for p in files
|
| 109 |
+
if p.suffix.lower() == '.txt' and p != desc_file and p.with_suffix('') not in audio]
|
| 110 |
+
if not warnings['orphan']: del warnings['orphan']
|
| 111 |
+
return dict(clips=clips, problems=problems, warnings=warnings, description=description, folder=folder)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def describe(found, log=print):
|
| 115 |
+
clips, problems, warnings = found['clips'], found['problems'], found['warnings']
|
| 116 |
+
left = sum(len(v) for v in problems.values())
|
| 117 |
+
minutes = sum(c['seconds'] for c in clips) / 60
|
| 118 |
+
log(f"Checked {len(clips) + left} clips in {found['folder']}")
|
| 119 |
+
log(f' ready: {len(clips)} clips, {minutes:.1f} minutes of speech')
|
| 120 |
+
if left:
|
| 121 |
+
log(f' left out: {left} clips')
|
| 122 |
+
for kind, rels in problems.items():
|
| 123 |
+
log(f' {PROBLEMS[kind]}: {len(rels)}')
|
| 124 |
+
for r in rels[:8]: log(f' {r}')
|
| 125 |
+
if len(rels) > 8: log(f' ... and {len(rels) - 8} more')
|
| 126 |
+
for kind, rels in warnings.items():
|
| 127 |
+
log(f' note, {WARNINGS[kind]}: {len(rels)}' + (f' ({", ".join(rels[:3])}{"..." if len(rels) > 3 else ""})' if len(rels) < len(clips) else ''))
|
| 128 |
+
log(f' voice description (voice.txt): {found["description"]!r}' if found['description'] else
|
| 129 |
+
' voice description: none (optional: describe the voice in a voice.txt file in the folder)')
|
| 130 |
+
if minutes < 2:
|
| 131 |
+
raise SystemExit(f'Only {minutes:.1f} minutes of usable speech. A LoRA needs at least 2 minutes; 20 to 60 minutes works best.')
|
| 132 |
+
if minutes < 10:
|
| 133 |
+
log(' note: under 10 minutes of speech. It can work, but 20 to 60 minutes gives a much closer voice.')
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
@torch.no_grad()
|
| 137 |
+
def encode(robin, found, cache, log=print, stop=None, progress=None):
|
| 138 |
+
from torchaudio.functional import resample
|
| 139 |
+
cache = Path(cache); cache.mkdir(parents=True, exist_ok=True)
|
| 140 |
+
vae_id = file_sha256(robin.vae_file) if getattr(robin, 'vae_file', None) else 'module'
|
| 141 |
+
meta_file = cache/'meta.json'; meta = dict(vae=vae_id, speech_tokens=SPEECH_TOKENS)
|
| 142 |
+
if meta_file.exists() and json.loads(meta_file.read_text()) != meta:
|
| 143 |
+
for f in cache.glob('*.npz'): f.unlink()
|
| 144 |
+
meta_file.write_text(json.dumps(meta))
|
| 145 |
+
out, bad, t0, done = [], [], time.time(), 0
|
| 146 |
+
todo = sum(not (cache/f"{c['key']}.npz").exists() for c in found['clips'])
|
| 147 |
+
if todo: log(f'Preparing {todo} clips...')
|
| 148 |
+
for c in found['clips']:
|
| 149 |
+
f = cache/f"{c['key']}.npz"
|
| 150 |
+
if not f.exists():
|
| 151 |
+
if stop is not None and stop():
|
| 152 |
+
raise SystemExit(f'Stopped while preparing clips ({done} of {todo} done; they are kept for next time).')
|
| 153 |
+
try:
|
| 154 |
+
x, rate = read_mono(found['folder']/c['file'])
|
| 155 |
+
y = torch.from_numpy(trim(x, rate)[0])
|
| 156 |
+
tokens = robin.speech(y.numpy(), rate)
|
| 157 |
+
z = robin.vae.encode(resample(y, rate, 48000)[None].repeat(2, 1)[None].to(robin.device))[0].T.float().cpu().numpy()
|
| 158 |
+
if abs(len(tokens) - len(z)) > 2: raise ValueError('length mismatch')
|
| 159 |
+
k = min(len(tokens), len(z))
|
| 160 |
+
np.savez(f, tokens=tokens[:k].astype(np.int16), latents=z[:k].astype(np.float16))
|
| 161 |
+
except Exception:
|
| 162 |
+
bad.append(c['file']); continue
|
| 163 |
+
done += 1
|
| 164 |
+
if progress is not None: progress('prepare', done, todo)
|
| 165 |
+
if done % 25 == 0 or done == todo: log(f' {done}/{todo} prepared ({time.time() - t0:.0f} s)')
|
| 166 |
+
d = np.load(f)
|
| 167 |
+
out.append(dict(c, tokens=d['tokens'].astype(np.int64), latents=d['latents']))
|
| 168 |
+
if bad:
|
| 169 |
+
found['problems']['tokens'] += bad
|
| 170 |
+
log(f" left out {len(bad)} clips: {PROBLEMS['tokens']}: {', '.join(bad[:5])}{'...' if len(bad) > 5 else ''}")
|
| 171 |
+
return out
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
class Trainer:
|
| 175 |
+
def __init__(self, robin, clips, description, out, *, lang='en', steps=1000, rank_planner=32, rank_decoder=64, lr_planner=5e-5,
|
| 176 |
+
lr_decoder=2e-4, accum=8, warmup=100, lr_floor=.2, p_reference=.4, save_every=200, sample_text=None, seed=0, log=print, stop=None,
|
| 177 |
+
progress=None):
|
| 178 |
+
self.robin, self.description, self.out, self.lang, self.log, self.stop = robin, description, Path(out), lang, log, stop
|
| 179 |
+
self.progress = progress
|
| 180 |
+
self.hp = dict(steps=steps, rank_planner=rank_planner, rank_decoder=rank_decoder, lr_planner=lr_planner, lr_decoder=lr_decoder,
|
| 181 |
+
accum=accum, warmup=min(warmup, max(1, steps // 10)), lr_floor=lr_floor, p_reference=p_reference, save_every=save_every,
|
| 182 |
+
lang=lang, seed=seed)
|
| 183 |
+
self.sample_text = sample_text or SAMPLE_TEXT.get(lang, SAMPLE_TEXT['en'])
|
| 184 |
+
rng = random.Random(seed); order = list(range(len(clips))); rng.shuffle(order); torch.manual_seed(seed)
|
| 185 |
+
hold = min(10, len(clips) // 20) if len(clips) >= 40 else 0
|
| 186 |
+
self.holdout = [clips[i] for i in order[:hold]]; self.clips = [clips[i] for i in order[hold:]]
|
| 187 |
+
self.short = [c for c in self.clips if len(c['tokens']) <= REF_WHOLE]
|
| 188 |
+
ranks = {k: r for k, r in (('planner', rank_planner), ('decoder', rank_decoder)) if r > 0}
|
| 189 |
+
nets = dict(planner=robin.planner.layers, decoder=robin.decoder.model.layers)
|
| 190 |
+
self.lora = LoRA({k: nets[k] for k in ranks}, ranks, seed=seed).attach()
|
| 191 |
+
groups = [dict(params=[p for n, p in zip(self.lora.names, getattr(self.lora, which)) if n.startswith(net + '.')],
|
| 192 |
+
lr=dict(planner=lr_planner, decoder=lr_decoder)[net]) for net in ranks for which in ('A', 'B')]
|
| 193 |
+
for g in groups: g['base_lr'] = g['lr']
|
| 194 |
+
self.optimizer = torch.optim.AdamW(groups, betas=(.9, .95), weight_decay=0., eps=1e-8)
|
| 195 |
+
self.rng, self.step, self.norms = rng, 0, []
|
| 196 |
+
self.sel = torch.cat((torch.arange(robin.offset, robin.offset + 32768), torch.tensor([robin.audio_end]))).to(robin.device)
|
| 197 |
+
self.base_sha = robin.base_sha256()
|
| 198 |
+
|
| 199 |
+
def lr_scale(self, step):
|
| 200 |
+
hp = self.hp
|
| 201 |
+
if step <= hp['warmup']: return step / hp['warmup']
|
| 202 |
+
f = min(1., (step - hp['warmup']) / max(1, hp['steps'] - hp['warmup']))
|
| 203 |
+
return hp['lr_floor'] + (1 - hp['lr_floor']) * .5 * (1 + math.cos(math.pi * f))
|
| 204 |
+
|
| 205 |
+
def example(self, clip, rng):
|
| 206 |
+
mode = 'reference' if len(self.clips) > 1 and rng.random() < self.hp['p_reference'] else 'tts'
|
| 207 |
+
desc = self.description if mode == 'tts' or rng.random() < .5 else None
|
| 208 |
+
if mode == 'tts' and rng.random() < .1: desc = None
|
| 209 |
+
ref = ref_text = None
|
| 210 |
+
if mode == 'reference':
|
| 211 |
+
pool = [c for c in (self.short or self.clips) if c is not clip] or [c for c in self.clips if c is not clip]
|
| 212 |
+
other = rng.choice(pool); tok = other['tokens']
|
| 213 |
+
if len(tok) <= REF_WHOLE:
|
| 214 |
+
ref, ref_text = tok, other['text']
|
| 215 |
+
else:
|
| 216 |
+
s = rng.randrange(len(tok) - REF_EXCERPT + 1); ref = tok[s:s + REF_EXCERPT]
|
| 217 |
+
return self.robin.prompt(clip['text'], desc, self.lang, ref, ref_text)
|
| 218 |
+
|
| 219 |
+
def losses(self, ids, clip, train=True, gen=None, sigmas=None):
|
| 220 |
+
r = self.robin; dev = r.device
|
| 221 |
+
seq = torch.tensor(list(ids) + [int(t) + r.offset for t in clip['tokens']] + [r.audio_end], device=dev)
|
| 222 |
+
ss, n = len(ids), len(seq)
|
| 223 |
+
mask = prefix_mask(n, ss, dev)
|
| 224 |
+
h = r.planner(seq[None], mask)[0][ss - 1:-1]
|
| 225 |
+
targets = seq[ss:]
|
| 226 |
+
targets = torch.where(targets == r.audio_end, torch.full_like(targets, 32768), targets - r.offset)
|
| 227 |
+
W = r.planner.lm_head.weight[self.sel]
|
| 228 |
+
ce = h.new_zeros((), dtype=torch.float32)
|
| 229 |
+
for s in range(0, len(targets), 256):
|
| 230 |
+
ce = ce + checkpoint(lambda hs, ys: F.cross_entropy(F.linear(hs, W).float(), ys, reduction='sum'),
|
| 231 |
+
h[s:s + 256], targets[s:s + 256], use_reentrant=False)
|
| 232 |
+
ce = ce / len(targets)
|
| 233 |
+
if train: (ce / self.hp['accum']).backward()
|
| 234 |
+
del h
|
| 235 |
+
with torch.no_grad():
|
| 236 |
+
ks, vs, _ = r.planner.prefill(seq, mask)
|
| 237 |
+
clean = torch.from_numpy(clip['latents'].astype(np.float32)).to(dev)
|
| 238 |
+
flows, sigmas = [], sigmas or [min(.98, max(.02, self.rng.betavariate(2, 2))) for _ in range(2)]
|
| 239 |
+
for sigma in sigmas:
|
| 240 |
+
noise = torch.randn(clean.shape, device=dev, generator=gen)
|
| 241 |
+
xt = sigma * noise + (1 - sigma) * clean
|
| 242 |
+
v = r.decoder(xt[None], torch.tensor([sigma], device=dev), ks, vs, checkpointing=train)[0]
|
| 243 |
+
fl = F.mse_loss(v, noise - clean)
|
| 244 |
+
if train: (fl / (len(sigmas) * self.hp['accum'])).backward()
|
| 245 |
+
flows.append(float(fl.detach()))
|
| 246 |
+
return float(ce.detach()), sum(flows) / len(flows)
|
| 247 |
+
|
| 248 |
+
@torch.no_grad()
|
| 249 |
+
def evaluate(self):
|
| 250 |
+
if not self.holdout: return None
|
| 251 |
+
gen = torch.Generator(device=self.robin.device).manual_seed(1)
|
| 252 |
+
rows = [self.losses(self.robin.prompt(c['text'], self.description, self.lang), c, train=False, gen=gen, sigmas=(.25, .5, .75))
|
| 253 |
+
for c in self.holdout]
|
| 254 |
+
return dict(planner=round(sum(r[0] for r in rows) / len(rows), 4), decoder=round(sum(r[1] for r in rows) / len(rows), 4))
|
| 255 |
+
|
| 256 |
+
@torch.no_grad()
|
| 257 |
+
def sample(self, name):
|
| 258 |
+
if self.robin.vae is None: return
|
| 259 |
+
try:
|
| 260 |
+
wav, sr, _ = self.robin.speak(self.sample_text, self.description, lang=self.lang, seed=0)
|
| 261 |
+
(self.out/'samples').mkdir(exist_ok=True)
|
| 262 |
+
path = self.out/'samples'/f'{name}.wav'
|
| 263 |
+
sf.write(str(path), wav, sr, subtype='PCM_16')
|
| 264 |
+
except Exception as e:
|
| 265 |
+
self.log(f' (could not render a sample: {e})')
|
| 266 |
+
return
|
| 267 |
+
if self.progress is not None: self.progress('sample', self.step, self.hp['steps'], path=path)
|
| 268 |
+
|
| 269 |
+
def save(self, final=False, light=False):
|
| 270 |
+
(self.out/'checkpoints').mkdir(exist_ok=True)
|
| 271 |
+
path = self.out/'checkpoints'/f'step_{self.step:05d}.safetensors'
|
| 272 |
+
self.lora.save(path, self.base_sha)
|
| 273 |
+
if final: self.lora.save(self.out/'lora.safetensors', self.base_sha)
|
| 274 |
+
state = dict(step=self.step, hp=self.hp, lora=self.lora.state_dict(), optimizer=self.optimizer.state_dict(), rng=self.rng.getstate(),
|
| 275 |
+
torch_rng=torch.get_rng_state(), cuda_rng=torch.cuda.get_rng_state() if torch.cuda.is_available() else None, norms=self.norms)
|
| 276 |
+
tmp = self.out/'resume.pt.tmp'; torch.save(state, tmp); os.replace(tmp, self.out/'resume.pt')
|
| 277 |
+
ev = None if light else self.evaluate()
|
| 278 |
+
if not light: self.sample(f'step_{self.step:05d}')
|
| 279 |
+
self.log(f' saved {path.relative_to(self.out)}' + (f' | held-out loss: planner {ev["planner"]:.3f}, decoder {ev["decoder"]:.4f}' if ev else ''))
|
| 280 |
+
with (self.out/'log.jsonl').open('a') as f: f.write(json.dumps(dict(step=self.step, saved=path.name, heldout=ev)) + '\n')
|
| 281 |
+
|
| 282 |
+
def resume(self):
|
| 283 |
+
state = torch.load(self.out/'resume.pt', map_location='cpu', weights_only=False)
|
| 284 |
+
keep = ('rank_planner', 'rank_decoder', 'lang')
|
| 285 |
+
if any(state['hp'][k] != self.hp[k] for k in keep):
|
| 286 |
+
raise SystemExit(f'{self.out} holds a run with different settings ({", ".join(f"{k}={state["hp"][k]}" for k in keep)}). '
|
| 287 |
+
'Use the same settings, a new output folder, or start over (--restart).')
|
| 288 |
+
self.lora.load_state_dict(state['lora']); self.optimizer.load_state_dict(state['optimizer'])
|
| 289 |
+
self.rng.setstate(state['rng']); torch.set_rng_state(state['torch_rng'])
|
| 290 |
+
if state.get('cuda_rng') is not None and torch.cuda.is_available(): torch.cuda.set_rng_state(state['cuda_rng'])
|
| 291 |
+
self.step, self.norms = state['step'], state.get('norms', [])
|
| 292 |
+
|
| 293 |
+
def run(self):
|
| 294 |
+
hp, r = self.hp, self.robin
|
| 295 |
+
self.out.mkdir(parents=True, exist_ok=True)
|
| 296 |
+
(self.out/'train_config.json').write_text(json.dumps(dict(hp, clips=len(self.clips), held_out=len(self.holdout),
|
| 297 |
+
description=bool(self.description)), indent=1))
|
| 298 |
+
if self.step == 0:
|
| 299 |
+
self.lora.scale = 0; self.sample('base'); self.lora.scale = 1
|
| 300 |
+
params = [p for p in self.lora.parameters()]
|
| 301 |
+
n_params = sum(p.numel() for p in params)
|
| 302 |
+
self.log(f'Training a LoRA ({n_params / 1e6:.0f}M parameters) on {len(self.clips)} clips'
|
| 303 |
+
+ (f', {len(self.holdout)} held out for checking' if self.holdout else '') + f', {hp["steps"]} steps.')
|
| 304 |
+
if torch.cuda.is_available(): torch.cuda.reset_peak_memory_stats()
|
| 305 |
+
t_start, step_times, run_loss = time.time(), [], []
|
| 306 |
+
while self.step < hp['steps']:
|
| 307 |
+
t0 = time.time(); self.step += 1
|
| 308 |
+
ces, flows = [], []
|
| 309 |
+
for _ in range(hp['accum']):
|
| 310 |
+
for _attempt in range(4):
|
| 311 |
+
clip = self.rng.choice(self.clips)
|
| 312 |
+
try:
|
| 313 |
+
ce, fl = self.losses(self.example(clip, self.rng), clip)
|
| 314 |
+
ces.append(ce); flows.append(fl); break
|
| 315 |
+
except torch.cuda.OutOfMemoryError:
|
| 316 |
+
self.optimizer.zero_grad(set_to_none=True); torch.cuda.empty_cache(); ces, flows = [], []
|
| 317 |
+
self.log(f" ran out of GPU memory on {clip['file']} ({clip['seconds']:.0f} s), leaving it out. "
|
| 318 |
+
'If this keeps happening, use a smaller --max-seconds.')
|
| 319 |
+
except Exception as e:
|
| 320 |
+
self.optimizer.zero_grad(set_to_none=True); ces, flows = [], []
|
| 321 |
+
self.log(f" couldn't train on {clip['file']} ({type(e).__name__}: {e}), leaving it out.")
|
| 322 |
+
self.clips = [c for c in self.clips if c is not clip]
|
| 323 |
+
self.short = [c for c in self.short if c is not clip]
|
| 324 |
+
if not self.clips: raise SystemExit('No clips left to train on.')
|
| 325 |
+
for g in self.optimizer.param_groups: g['lr'] = g['base_lr'] * self.lr_scale(self.step)
|
| 326 |
+
norm = float(torch.nn.utils.clip_grad_norm_(params, 1.0))
|
| 327 |
+
med = sorted(self.norms)[len(self.norms) // 2] if len(self.norms) >= 50 else None
|
| 328 |
+
if not ces or not math.isfinite(norm) or (med is not None and norm > 20 * med):
|
| 329 |
+
self.optimizer.zero_grad(set_to_none=True)
|
| 330 |
+
if ces: self.log(f' step {self.step}: an unusual update (gradient {norm:.2f}) was skipped')
|
| 331 |
+
else:
|
| 332 |
+
self.norms = (self.norms + [norm])[-200:]
|
| 333 |
+
self.optimizer.step(); self.optimizer.zero_grad(set_to_none=True)
|
| 334 |
+
step_times.append(time.time() - t0); run_loss.append((np.mean(ces) if ces else float('nan'), np.mean(flows) if flows else float('nan')))
|
| 335 |
+
with (self.out/'log.jsonl').open('a') as f:
|
| 336 |
+
f.write(json.dumps(dict(step=self.step, planner=round(float(run_loss[-1][0]), 4), decoder=round(float(run_loss[-1][1]), 5),
|
| 337 |
+
grad=round(norm, 4), seconds=round(step_times[-1], 2))) + '\n')
|
| 338 |
+
pace = float(np.mean(step_times[-20:])); left = (hp['steps'] - self.step) * pace
|
| 339 |
+
pl, dl = np.nanmean([x[0] for x in run_loss[-10:]]), np.nanmean([x[1] for x in run_loss[-10:]])
|
| 340 |
+
if self.progress is not None:
|
| 341 |
+
self.progress('train', self.step, hp['steps'], planner=float(pl), decoder=float(dl), pace=pace, left=left)
|
| 342 |
+
if self.step % 10 == 0 or self.step <= 3 or self.step == hp['steps']:
|
| 343 |
+
mem = f' | GPU {torch.cuda.max_memory_allocated() / 2 ** 30:.1f} GB' if torch.cuda.is_available() else ''
|
| 344 |
+
self.log(f"step {self.step}/{hp['steps']} | planner loss {pl:.3f} | decoder loss {dl:.4f} | {pace:.1f} s/step | "
|
| 345 |
+
f"{left / 60:.0f} min left{mem}")
|
| 346 |
+
if self.step % hp['save_every'] == 0 or self.step == hp['steps']:
|
| 347 |
+
self.save(final=self.step == hp['steps'])
|
| 348 |
+
elif self.stop is not None and self.stop():
|
| 349 |
+
self.save(light=True)
|
| 350 |
+
if self.stop is not None and self.stop() and self.step < hp['steps']:
|
| 351 |
+
self.log(f'Stopped at step {self.step}. Train again with the same folder to continue from here.')
|
| 352 |
+
return None
|
| 353 |
+
self.log(f"Done in {(time.time() - t_start) / 60:.0f} min. The LoRA is {self.out/'lora.safetensors'}; every saved step is in "
|
| 354 |
+
f"{self.out/'checkpoints'} with a sample of each in {self.out/'samples'}.")
|
| 355 |
+
return self.out/'lora.safetensors'
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def train(robin, data, out, *, lang='en', min_seconds=1., max_seconds=30., restart=False, log=print, stop=None, progress=None, **settings):
|
| 359 |
+
out = Path(out)
|
| 360 |
+
if restart:
|
| 361 |
+
old = [out/f for f in ('resume.pt', 'lora.safetensors', 'log.jsonl')] + list(out.glob('checkpoints/step_*.safetensors')) + list(out.glob('samples/*.wav'))
|
| 362 |
+
for f in old:
|
| 363 |
+
if f.exists(): f.unlink()
|
| 364 |
+
elif (out/'lora.safetensors').exists() and not (out/'resume.pt').exists():
|
| 365 |
+
raise SystemExit(f'{out} already holds a finished LoRA. Use a new output folder, or start over (--restart) to train again.')
|
| 366 |
+
found = scan(data, lang, min_seconds, max_seconds); describe(found, log)
|
| 367 |
+
clips = encode(robin, found, out/'cache', log, stop, progress)
|
| 368 |
+
robin._speech = None
|
| 369 |
+
if torch.cuda.is_available(): torch.cuda.empty_cache()
|
| 370 |
+
trainer = Trainer(robin, clips, found['description'], out, lang=lang, log=log, stop=stop, progress=progress, **settings)
|
| 371 |
+
try:
|
| 372 |
+
if (out/'resume.pt').exists():
|
| 373 |
+
trainer.resume()
|
| 374 |
+
if trainer.step >= trainer.hp['steps']:
|
| 375 |
+
if not (out/'lora.safetensors').exists(): trainer.lora.save(out/'lora.safetensors', trainer.base_sha)
|
| 376 |
+
log(f'This run already finished ({trainer.step} steps). Start over (--restart) to train again, or give more steps (--steps) to keep going.')
|
| 377 |
+
return out/'lora.safetensors'
|
| 378 |
+
log(f'Continuing the unfinished run from step {trainer.step}.')
|
| 379 |
+
return trainer.run()
|
| 380 |
+
finally:
|
| 381 |
+
trainer.lora.detach()
|
comfyui-robin/robin/vae.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from safetensors.torch import load_file
|
| 3 |
+
from torch import nn
|
| 4 |
+
|
| 5 |
+
WIDTH, LATENT, AUDIO_CHANNELS = 64, 64, 2
|
| 6 |
+
MULTS = (1, 1, 2, 4, 8, 16, 32)
|
| 7 |
+
STRIDES = (2, 2, 4, 4, 5, 6)
|
| 8 |
+
NORMED = (('weight_g', 'weight_v'), ('parametrizations.weight.original0', 'parametrizations.weight.original1'))
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Snake(nn.Module):
|
| 12 |
+
def __init__(self, ch):
|
| 13 |
+
super().__init__()
|
| 14 |
+
self.alpha = nn.Parameter(torch.zeros(ch)); self.beta = nn.Parameter(torch.zeros(ch))
|
| 15 |
+
|
| 16 |
+
def forward(self, x):
|
| 17 |
+
freq, amp = self.alpha.exp().view(1, -1, 1), self.beta.exp().view(1, -1, 1)
|
| 18 |
+
return x + torch.sin(freq * x).square() / (amp + 1e-9)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class Stack(nn.Module):
|
| 22 |
+
def __init__(self, *layers):
|
| 23 |
+
super().__init__()
|
| 24 |
+
self.layers = nn.Sequential(*layers)
|
| 25 |
+
|
| 26 |
+
def forward(self, x):
|
| 27 |
+
return self.layers(x)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class Residual(Stack):
|
| 31 |
+
def __init__(self, ch, dilation):
|
| 32 |
+
super().__init__(Snake(ch), nn.Conv1d(ch, ch, 7, padding=3 * dilation, dilation=dilation), Snake(ch), nn.Conv1d(ch, ch, 1))
|
| 33 |
+
|
| 34 |
+
def forward(self, x):
|
| 35 |
+
return x + self.layers(x)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def down(cin, cout, s):
|
| 39 |
+
return Stack(Residual(cin, 1), Residual(cin, 3), Residual(cin, 9), Snake(cin), nn.Conv1d(cin, cout, 2 * s, s, (s + 1) // 2))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def up(cin, cout, s):
|
| 43 |
+
return Stack(Snake(cin), nn.ConvTranspose1d(cin, cout, 2 * s, s, (s + 1) // 2, output_padding=s % 2),
|
| 44 |
+
Residual(cout, 1), Residual(cout, 3), Residual(cout, 9))
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class VAE(nn.Module):
|
| 48 |
+
def __init__(self):
|
| 49 |
+
super().__init__()
|
| 50 |
+
ch = [WIDTH * m for m in MULTS]
|
| 51 |
+
n = len(STRIDES)
|
| 52 |
+
self.encoder = Stack(nn.Conv1d(AUDIO_CHANNELS, ch[0], 7, padding=3), *[down(ch[i], ch[i + 1], STRIDES[i]) for i in range(n)],
|
| 53 |
+
Snake(ch[-1]), nn.Conv1d(ch[-1], 2 * LATENT, 3, padding=1))
|
| 54 |
+
self.decoder = Stack(nn.Conv1d(LATENT, ch[-1], 7, padding=3), *[up(ch[i + 1], ch[i], STRIDES[i]) for i in reversed(range(n))],
|
| 55 |
+
Snake(ch[0]), nn.Conv1d(ch[0], AUDIO_CHANNELS, 7, padding=3, bias=False))
|
| 56 |
+
|
| 57 |
+
@torch.no_grad()
|
| 58 |
+
def encode(self, audio):
|
| 59 |
+
return self.encoder(audio)[:, :LATENT]
|
| 60 |
+
|
| 61 |
+
@torch.no_grad()
|
| 62 |
+
def decode(self, latents):
|
| 63 |
+
return self.decoder(latents)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def plain_weights(state):
|
| 67 |
+
state = {k.removeprefix('vae.'): v.float() for k, v in state.items()}
|
| 68 |
+
out = {}
|
| 69 |
+
for k, v in state.items():
|
| 70 |
+
mag = next((m for m, d in NORMED if k.endswith(m)), None)
|
| 71 |
+
if mag:
|
| 72 |
+
stem = k[:-len(mag)]; direction = state[stem + dict(NORMED)[mag]]
|
| 73 |
+
out[stem + 'weight'] = direction * (v / direction.flatten(1).norm(dim=1).view(-1, *[1] * (direction.dim() - 1)))
|
| 74 |
+
elif not any(k.endswith(d) for _, d in NORMED):
|
| 75 |
+
out[k] = v
|
| 76 |
+
return out
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def load_vae(path, device='cuda'):
|
| 80 |
+
vae = VAE(); vae.load_state_dict(plain_weights(load_file(str(path))), strict=True)
|
| 81 |
+
return vae.to(device, torch.float32).eval()
|
comfyui-robin/web/fonts/FamiljenGrotesk.woff2
ADDED
|
Binary file (18.9 kB). View file
|
|
|
comfyui-robin/web/fonts/IBMPlexMono-Medium.woff2
ADDED
|
Binary file (10.1 kB). View file
|
|
|
comfyui-robin/web/fonts/IBMPlexMono-Regular.woff2
ADDED
|
Binary file (10.1 kB). View file
|
|
|
comfyui-robin/web/fonts/OFL-FamiljenGrotesk.txt
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright 2021 The Familjen Grotesk Project Authors (https://github.com/Familjen-Sthlm/Familjen-Grotesk)
|
| 2 |
+
|
| 3 |
+
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
| 4 |
+
This license is copied below, and is also available with a FAQ at:
|
| 5 |
+
http://scripts.sil.org/OFL
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
-----------------------------------------------------------
|
| 9 |
+
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
| 10 |
+
-----------------------------------------------------------
|
| 11 |
+
|
| 12 |
+
PREAMBLE
|
| 13 |
+
The goals of the Open Font License (OFL) are to stimulate worldwide
|
| 14 |
+
development of collaborative font projects, to support the font creation
|
| 15 |
+
efforts of academic and linguistic communities, and to provide a free and
|
| 16 |
+
open framework in which fonts may be shared and improved in partnership
|
| 17 |
+
with others.
|
| 18 |
+
|
| 19 |
+
The OFL allows the licensed fonts to be used, studied, modified and
|
| 20 |
+
redistributed freely as long as they are not sold by themselves. The
|
| 21 |
+
fonts, including any derivative works, can be bundled, embedded,
|
| 22 |
+
redistributed and/or sold with any software provided that any reserved
|
| 23 |
+
names are not used by derivative works. The fonts and derivatives,
|
| 24 |
+
however, cannot be released under any other type of license. The
|
| 25 |
+
requirement for fonts to remain under this license does not apply
|
| 26 |
+
to any document created using the fonts or their derivatives.
|
| 27 |
+
|
| 28 |
+
DEFINITIONS
|
| 29 |
+
"Font Software" refers to the set of files released by the Copyright
|
| 30 |
+
Holder(s) under this license and clearly marked as such. This may
|
| 31 |
+
include source files, build scripts and documentation.
|
| 32 |
+
|
| 33 |
+
"Reserved Font Name" refers to any names specified as such after the
|
| 34 |
+
copyright statement(s).
|
| 35 |
+
|
| 36 |
+
"Original Version" refers to the collection of Font Software components as
|
| 37 |
+
distributed by the Copyright Holder(s).
|
| 38 |
+
|
| 39 |
+
"Modified Version" refers to any derivative made by adding to, deleting,
|
| 40 |
+
or substituting -- in part or in whole -- any of the components of the
|
| 41 |
+
Original Version, by changing formats or by porting the Font Software to a
|
| 42 |
+
new environment.
|
| 43 |
+
|
| 44 |
+
"Author" refers to any designer, engineer, programmer, technical
|
| 45 |
+
writer or other person who contributed to the Font Software.
|
| 46 |
+
|
| 47 |
+
PERMISSION & CONDITIONS
|
| 48 |
+
Permission is hereby granted, free of charge, to any person obtaining
|
| 49 |
+
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
| 50 |
+
redistribute, and sell modified and unmodified copies of the Font
|
| 51 |
+
Software, subject to the following conditions:
|
| 52 |
+
|
| 53 |
+
1) Neither the Font Software nor any of its individual components,
|
| 54 |
+
in Original or Modified Versions, may be sold by itself.
|
| 55 |
+
|
| 56 |
+
2) Original or Modified Versions of the Font Software may be bundled,
|
| 57 |
+
redistributed and/or sold with any software, provided that each copy
|
| 58 |
+
contains the above copyright notice and this license. These can be
|
| 59 |
+
included either as stand-alone text files, human-readable headers or
|
| 60 |
+
in the appropriate machine-readable metadata fields within text or
|
| 61 |
+
binary files as long as those fields can be easily viewed by the user.
|
| 62 |
+
|
| 63 |
+
3) No Modified Version of the Font Software may use the Reserved Font
|
| 64 |
+
Name(s) unless explicit written permission is granted by the corresponding
|
| 65 |
+
Copyright Holder. This restriction only applies to the primary font name as
|
| 66 |
+
presented to the users.
|
| 67 |
+
|
| 68 |
+
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
| 69 |
+
Software shall not be used to promote, endorse or advertise any
|
| 70 |
+
Modified Version, except to acknowledge the contribution(s) of the
|
| 71 |
+
Copyright Holder(s) and the Author(s) or with their explicit written
|
| 72 |
+
permission.
|
| 73 |
+
|
| 74 |
+
5) The Font Software, modified or unmodified, in part or in whole,
|
| 75 |
+
must be distributed entirely under this license, and must not be
|
| 76 |
+
distributed under any other license. The requirement for fonts to
|
| 77 |
+
remain under this license does not apply to any document created
|
| 78 |
+
using the Font Software.
|
| 79 |
+
|
| 80 |
+
TERMINATION
|
| 81 |
+
This license becomes null and void if any of the above conditions are
|
| 82 |
+
not met.
|
| 83 |
+
|
| 84 |
+
DISCLAIMER
|
| 85 |
+
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
| 86 |
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
| 87 |
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
| 88 |
+
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
| 89 |
+
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
| 90 |
+
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
| 91 |
+
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
| 92 |
+
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
| 93 |
+
OTHER DEALINGS IN THE FONT SOFTWARE.
|
comfyui-robin/web/fonts/OFL-IBMPlexMono.txt
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright © 2017 IBM Corp. with Reserved Font Name "Plex"
|
| 2 |
+
|
| 3 |
+
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
| 4 |
+
|
| 5 |
+
This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
-----------------------------------------------------------
|
| 9 |
+
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
| 10 |
+
-----------------------------------------------------------
|
| 11 |
+
|
| 12 |
+
PREAMBLE
|
| 13 |
+
The goals of the Open Font License (OFL) are to stimulate worldwide
|
| 14 |
+
development of collaborative font projects, to support the font creation
|
| 15 |
+
efforts of academic and linguistic communities, and to provide a free and
|
| 16 |
+
open framework in which fonts may be shared and improved in partnership
|
| 17 |
+
with others.
|
| 18 |
+
|
| 19 |
+
The OFL allows the licensed fonts to be used, studied, modified and
|
| 20 |
+
redistributed freely as long as they are not sold by themselves. The
|
| 21 |
+
fonts, including any derivative works, can be bundled, embedded,
|
| 22 |
+
redistributed and/or sold with any software provided that any reserved
|
| 23 |
+
names are not used by derivative works. The fonts and derivatives,
|
| 24 |
+
however, cannot be released under any other type of license. The
|
| 25 |
+
requirement for fonts to remain under this license does not apply
|
| 26 |
+
to any document created using the fonts or their derivatives.
|
| 27 |
+
|
| 28 |
+
DEFINITIONS
|
| 29 |
+
"Font Software" refers to the set of files released by the Copyright
|
| 30 |
+
Holder(s) under this license and clearly marked as such. This may
|
| 31 |
+
include source files, build scripts and documentation.
|
| 32 |
+
|
| 33 |
+
"Reserved Font Name" refers to any names specified as such after the
|
| 34 |
+
copyright statement(s).
|
| 35 |
+
|
| 36 |
+
"Original Version" refers to the collection of Font Software components as
|
| 37 |
+
distributed by the Copyright Holder(s).
|
| 38 |
+
|
| 39 |
+
"Modified Version" refers to any derivative made by adding to, deleting,
|
| 40 |
+
or substituting -- in part or in whole -- any of the components of the
|
| 41 |
+
Original Version, by changing formats or by porting the Font Software to a
|
| 42 |
+
new environment.
|
| 43 |
+
|
| 44 |
+
"Author" refers to any designer, engineer, programmer, technical
|
| 45 |
+
writer or other person who contributed to the Font Software.
|
| 46 |
+
|
| 47 |
+
PERMISSION & CONDITIONS
|
| 48 |
+
Permission is hereby granted, free of charge, to any person obtaining
|
| 49 |
+
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
| 50 |
+
redistribute, and sell modified and unmodified copies of the Font
|
| 51 |
+
Software, subject to the following conditions:
|
| 52 |
+
|
| 53 |
+
1) Neither the Font Software nor any of its individual components,
|
| 54 |
+
in Original or Modified Versions, may be sold by itself.
|
| 55 |
+
|
| 56 |
+
2) Original or Modified Versions of the Font Software may be bundled,
|
| 57 |
+
redistributed and/or sold with any software, provided that each copy
|
| 58 |
+
contains the above copyright notice and this license. These can be
|
| 59 |
+
included either as stand-alone text files, human-readable headers or
|
| 60 |
+
in the appropriate machine-readable metadata fields within text or
|
| 61 |
+
binary files as long as those fields can be easily viewed by the user.
|
| 62 |
+
|
| 63 |
+
3) No Modified Version of the Font Software may use the Reserved Font
|
| 64 |
+
Name(s) unless explicit written permission is granted by the corresponding
|
| 65 |
+
Copyright Holder. This restriction only applies to the primary font name as
|
| 66 |
+
presented to the users.
|
| 67 |
+
|
| 68 |
+
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
| 69 |
+
Software shall not be used to promote, endorse or advertise any
|
| 70 |
+
Modified Version, except to acknowledge the contribution(s) of the
|
| 71 |
+
Copyright Holder(s) and the Author(s) or with their explicit written
|
| 72 |
+
permission.
|
| 73 |
+
|
| 74 |
+
5) The Font Software, modified or unmodified, in part or in whole,
|
| 75 |
+
must be distributed entirely under this license, and must not be
|
| 76 |
+
distributed under any other license. The requirement for fonts to
|
| 77 |
+
remain under this license does not apply to any document created
|
| 78 |
+
using the Font Software.
|
| 79 |
+
|
| 80 |
+
TERMINATION
|
| 81 |
+
This license becomes null and void if any of the above conditions are
|
| 82 |
+
not met.
|
| 83 |
+
|
| 84 |
+
DISCLAIMER
|
| 85 |
+
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
| 86 |
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
| 87 |
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
| 88 |
+
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
| 89 |
+
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
| 90 |
+
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
| 91 |
+
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
| 92 |
+
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
| 93 |
+
OTHER DEALINGS IN THE FONT SOFTWARE.
|
comfyui-robin/web/robin.css
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@font-face { font-family: 'Familjen Grotesk'; src: url(fonts/FamiljenGrotesk.woff2) format('woff2'); font-weight: 400 700; font-display: swap; }
|
| 2 |
+
@font-face { font-family: 'IBM Plex Mono'; src: url(fonts/IBMPlexMono-Regular.woff2) format('woff2'); font-weight: 400; font-display: swap; }
|
| 3 |
+
@font-face { font-family: 'IBM Plex Mono'; src: url(fonts/IBMPlexMono-Medium.woff2) format('woff2'); font-weight: 500; font-display: swap; }
|
| 4 |
+
|
| 5 |
+
.robin-panel { box-sizing: border-box; width: 100%; height: 100%; display: flex; flex-direction: column; gap: 8px;
|
| 6 |
+
font-family: 'IBM Plex Mono', ui-monospace, Menlo, monospace; color: #F2EEE6; }
|
| 7 |
+
.robin-panel * { box-sizing: border-box; }
|
| 8 |
+
.robin-panel button { margin: 0; font-family: inherit; }
|
| 9 |
+
.robin-panel :focus-visible { outline: 2px solid #F2EEE6; outline-offset: 2px; }
|
| 10 |
+
|
| 11 |
+
/* The readouts on the Loader and Train LoRA nodes */
|
| 12 |
+
.robin-lcd { flex: none; display: flex; flex-direction: column; gap: 4px; padding: 8px 11px; border-radius: 6px; background: #0c0c0c;
|
| 13 |
+
border: 1px solid #2e2e30; box-shadow: inset 0 0 0 2px #090909; font-size: 11px; line-height: 16px; letter-spacing: .08em;
|
| 14 |
+
text-transform: uppercase; color: #D9302A; pointer-events: none; }
|
| 15 |
+
.robin-lcd .row { display: flex; justify-content: space-between; gap: 14px; white-space: nowrap; }
|
| 16 |
+
.robin-lcd .row > :first-child { flex: none; color: #8a2a25; }
|
| 17 |
+
.robin-lcd .row > :last-child { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
| 18 |
+
.robin-lcd .meter { margin-top: 4px; height: 6px; border-radius: 3px; background: #241312; overflow: hidden; }
|
| 19 |
+
.robin-lcd .meter > i { display: block; width: 0; height: 100%; background: #D9302A; transition: width .4s ease; }
|
| 20 |
+
|
| 21 |
+
/* Badge buttons: the cream face, dark ring and red bands of the Robin badge */
|
| 22 |
+
.robin-badge { flex: none; display: inline-flex; align-items: center; gap: 7px; height: 30px; padding: 0 10px 3px 8px; border-radius: 7px;
|
| 23 |
+
border: 2px solid #F2EEE6; box-shadow: inset 0 0 0 2px #111111;
|
| 24 |
+
background: linear-gradient(to top, transparent 0 2px, #D9302A 2px 4px, transparent 4px), linear-gradient(180deg, #FFFDF9, #F0D3C8);
|
| 25 |
+
font-size: 11px; font-weight: 500; line-height: 1; color: #111111; white-space: nowrap; cursor: pointer; }
|
| 26 |
+
.robin-badge.on { background: linear-gradient(to top, transparent 0 2px, #D9302A 2px 4px, transparent 4px), #111111; color: #F2EEE6; }
|
| 27 |
+
.robin-badge:disabled { cursor: default; opacity: .5; }
|
| 28 |
+
.robin-badge svg { flex: none; }
|
| 29 |
+
.robin-play { flex: none; display: grid; place-items: center; width: 40px; height: 40px; padding: 0 0 6px; border-radius: 8px;
|
| 30 |
+
border: 2px solid #F2EEE6; box-shadow: inset 0 0 0 2px #111111; cursor: pointer;
|
| 31 |
+
background: linear-gradient(to top, transparent 0 2px, #D9302A 2px 4px, transparent 4px 6px, #D9302A 6px 8px, transparent 8px),
|
| 32 |
+
linear-gradient(180deg, #FFFDF9, #F0D3C8); }
|
| 33 |
+
.robin-play.on { background: linear-gradient(to top, transparent 0 2px, #D9302A 2px 4px, transparent 4px 6px, #D9302A 6px 8px, transparent 8px), #111111; }
|
| 34 |
+
.robin-play:disabled { cursor: default; opacity: .4; }
|
| 35 |
+
|
| 36 |
+
/* Speak and Voice Changer: the last take */
|
| 37 |
+
.robin-take { flex: none; display: flex; align-items: center; gap: 10px; height: 58px; padding: 8px 10px 8px 8px; border-radius: 8px;
|
| 38 |
+
background: #0c0c0c; border: 1px solid #2c2c2f; }
|
| 39 |
+
.robin-wave { flex: 1; min-width: 0; height: 32px; display: flex; align-items: center; justify-content: space-between; gap: 2px; cursor: pointer; }
|
| 40 |
+
.robin-wave > i { flex: 0 1 3px; min-width: 1px; border-radius: 2px; background: #4a4a4c; }
|
| 41 |
+
.robin-wave > i.on { background: #D9302A; }
|
| 42 |
+
.robin-wave.empty { cursor: default; }
|
| 43 |
+
.robin-wave.empty::before { content: ''; flex: 1; height: 1px; background: #2e2e30; }
|
| 44 |
+
.robin-time { flex: none; font-size: 11.5px; color: #a6a49e; white-space: nowrap; }
|
| 45 |
+
.robin-save { flex: none; display: grid; place-items: center; width: 28px; height: 28px; border-radius: 6px; color: #F2EEE6; }
|
| 46 |
+
.robin-save:hover { background: #232325; }
|
| 47 |
+
.robin-save[hidden] { display: none; }
|
| 48 |
+
|
| 49 |
+
/* Check Dataset: the folder picker and the report */
|
| 50 |
+
.robin-pick { flex: none; display: flex; align-items: center; gap: 10px; min-width: 0; }
|
| 51 |
+
.robin-pick > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 10.5px; letter-spacing: .04em; color: #a6a49e; }
|
| 52 |
+
.robin-hint { flex: none; height: 16px; font-size: 10.5px; line-height: 16px; letter-spacing: .04em; color: #a6a49e; white-space: nowrap;
|
| 53 |
+
overflow: hidden; text-overflow: ellipsis; }
|
| 54 |
+
.robin-term { flex: 1; min-height: 0; display: flex; flex-direction: column; border-radius: 8px; background: #000000; border: 1px solid #2c2c2e; overflow: hidden; }
|
| 55 |
+
.robin-term > header { flex: none; display: flex; align-items: center; gap: 7px; padding: 7px 10px; background: #161617; border-bottom: 1px solid #262628; }
|
| 56 |
+
.robin-term > header > i { width: 9px; height: 9px; border-radius: 50%; background: #333335; }
|
| 57 |
+
.robin-term > header > i:first-child { background: #D9302A; }
|
| 58 |
+
.robin-term > header > span { margin-left: 6px; font-size: 10px; letter-spacing: .1em; color: #a6a49e; }
|
| 59 |
+
.robin-term > pre { flex: 1; min-height: 0; margin: 0; padding: 10px 12px 12px; overflow: auto; font: 11.5px/1.7 'IBM Plex Mono', ui-monospace, Menlo, monospace;
|
| 60 |
+
color: #F2EEE6; white-space: pre-wrap; overflow-wrap: anywhere; user-select: text; }
|
| 61 |
+
.robin-term .ok { color: #9fcf8f; }
|
| 62 |
+
.robin-term .bad { color: #e8766f; }
|
| 63 |
+
.robin-term .note { color: #d9b36b; }
|
| 64 |
+
.robin-term .dim { color: #a6a49e; }
|
| 65 |
+
|
| 66 |
+
/* Train LoRA: advanced settings, the readout and the saved steps */
|
| 67 |
+
.robin-more { flex: none; display: flex; align-items: center; gap: 8px; height: 26px; padding: 0 12px; border-radius: 13px; background: transparent;
|
| 68 |
+
border: 1px dashed #3a3a3d; font-size: 11px; letter-spacing: .04em; color: #a6a49e; white-space: nowrap; overflow: hidden; cursor: pointer; }
|
| 69 |
+
.robin-more:hover { border-color: #5a5a5e; color: #F2EEE6; }
|
| 70 |
+
.robin-more svg { flex: none; transition: transform .15s ease; }
|
| 71 |
+
.robin-more.open svg { transform: rotate(90deg); }
|
| 72 |
+
.robin-saved { flex: none; display: flex; align-items: center; gap: 8px; height: 30px; overflow-x: auto; scrollbar-width: none; }
|
| 73 |
+
.robin-saved::-webkit-scrollbar { display: none; }
|
| 74 |
+
.robin-saved > b { flex: none; margin-right: 2px; font-size: 10px; font-weight: 400; letter-spacing: .12em; color: #a6a49e; }
|
| 75 |
+
.robin-wait { flex: none; display: flex; align-items: center; height: 30px; padding: 0 10px; border-radius: 7px; border: 1px dashed #3a3a3d;
|
| 76 |
+
font-size: 11px; color: #5e5d59; }
|
| 77 |
+
|
| 78 |
+
/* Robin's text boxes */
|
| 79 |
+
textarea.robin-text { background: #111113 !important; border: 1px solid #2c2c2f !important; border-radius: 6px !important; color: #F2EEE6 !important;
|
| 80 |
+
font: 12px/1.55 'I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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { app } from '../../scripts/app.js';
|
| 2 |
+
import { api } from '../../scripts/api.js';
|
| 3 |
+
|
| 4 |
+
const RED = '#D9302A';
|
| 5 |
+
const INK = '#1B1B1C';
|
| 6 |
+
const CREAM = '#F2EEE6';
|
| 7 |
+
const AUDIO_LINK = 'rgba(242,238,230,0.75)';
|
| 8 |
+
const HERE = new URL('.', import.meta.url).href;
|
| 9 |
+
const TITLE_FONT = '600 14px "Familjen Grotesk", Inter, system-ui, sans-serif';
|
| 10 |
+
const TAG_FONT = '9px "IBM Plex Mono", ui-monospace, Menlo, monospace';
|
| 11 |
+
const UPLOADS = 'robin_datasets';
|
| 12 |
+
const MAX_TAKE = 45; // the Voice Changer's limit, in seconds
|
| 13 |
+
const SOUND_FILES = /\.(wav|flac|mp3|ogg|opus|aiff?)$/i; // what Robin reads as is; other audio becomes WAV in the browser first
|
| 14 |
+
const CLIP_FILES = /\.(wav|flac|mp3|ogg|opus|aiff?|m4a|aac|wma|mp4|webm|mov|txt)$/i;
|
| 15 |
+
const EMPTY_REPORT = 'Choose a folder of clips, or type its path in folder.';
|
| 16 |
+
const DASH = '—';
|
| 17 |
+
// A new node's width, and the extra height its text boxes get.
|
| 18 |
+
const SIZES = { RobinLoader: [330, 0], RobinLoRA: [330, 0], RobinSpeak: [430, 110], RobinVoiceChanger: [430, 90], RobinCheckDataset: [440, 90],
|
| 19 |
+
RobinTrainLoRA: [460, 30], RobinLoadAudio: [380, 0] };
|
| 20 |
+
const ICONS = {
|
| 21 |
+
play: '<svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><path d="M4 2.5v11l9-5.5z" fill="#D9302A" stroke="#D9302A" stroke-width="1.5" stroke-linejoin="round"/></svg>',
|
| 22 |
+
pause: '<svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><path d="M4 3h3v10H4zM9 3h3v10H9z" fill="#D9302A"/></svg>',
|
| 23 |
+
save: '<svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 2.5v8M4.5 7.5 8 11l3.5-3.5M3 13.5h10"/></svg>',
|
| 24 |
+
folder: '<svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><path d="M1.5 4a1 1 0 0 1 1-1h3.7l1.5 1.6h5.8a1 1 0 0 1 1 1V12a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1z" fill="#D9302A"/></svg>',
|
| 25 |
+
record: '<svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><circle cx="8" cy="8" r="5" fill="#D9302A"/></svg>',
|
| 26 |
+
stop: '<svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><rect x="3.5" y="3.5" width="9" height="9" rx="1.5" fill="#D9302A"/></svg>',
|
| 27 |
+
open: '<svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><path d="M9 2.5h4.5V7M13.5 2.5 7.5 8.5M12 9.5v3a1 1 0 0 1-1 1H3.5a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h3" fill="none" stroke="#D9302A" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></svg>',
|
| 28 |
+
more: '<svg width="10" height="10" viewBox="0 0 10 10" aria-hidden="true"><path d="M3 1.5 7 5 3 8.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
|
| 29 |
+
};
|
| 30 |
+
|
| 31 |
+
const sheet = Object.assign(document.createElement('link'), { rel: 'stylesheet', href: HERE + 'robin.css' });
|
| 32 |
+
sheet.addEventListener('load', () => Promise.all([TITLE_FONT, TAG_FONT].map((font) => document.fonts.load(font))).then(redraw));
|
| 33 |
+
document.head.append(sheet);
|
| 34 |
+
|
| 35 |
+
const badge = document.createElement('canvas');
|
| 36 |
+
const art = new Image();
|
| 37 |
+
art.addEventListener('load', () => {
|
| 38 |
+
badge.width = badge.height = 96;
|
| 39 |
+
badge.getContext('2d').drawImage(art, 0, 0, 96, 96);
|
| 40 |
+
badge.ready = true;
|
| 41 |
+
redraw();
|
| 42 |
+
});
|
| 43 |
+
art.src = HERE + 'robin_badge.svg';
|
| 44 |
+
|
| 45 |
+
function redraw() {
|
| 46 |
+
app.canvas?.setDirty(true, true);
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
function h(tag, attrs = {}, ...children) {
|
| 50 |
+
const el = document.createElement(tag);
|
| 51 |
+
for (const [key, value] of Object.entries(attrs)) {
|
| 52 |
+
if (key === 'class') el.className = value;
|
| 53 |
+
else if (key === 'html') el.innerHTML = value;
|
| 54 |
+
else if (key.startsWith('on')) el.addEventListener(key.slice(2), value);
|
| 55 |
+
else if (value === true) el.setAttribute(key, '');
|
| 56 |
+
else if (value != null && value !== false) el.setAttribute(key, value);
|
| 57 |
+
}
|
| 58 |
+
el.append(...children);
|
| 59 |
+
return el;
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
function icon(name, size = 14) {
|
| 63 |
+
return h('span', { html: ICONS[name].replace(/width="\d+" height="\d+"/, `width="${size}" height="${size}"`) }).firstChild;
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
function chain(proto, name, fn) {
|
| 67 |
+
const original = proto[name];
|
| 68 |
+
proto[name] = function () {
|
| 69 |
+
const result = original?.apply(this, arguments);
|
| 70 |
+
fn.apply(this, arguments);
|
| 71 |
+
return result;
|
| 72 |
+
};
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
function widget(node, name) {
|
| 76 |
+
return node.widgets?.find((w) => w.name === name);
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
function value(node, name) {
|
| 80 |
+
return widget(node, name)?.value;
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
function watch(node, names, fn) {
|
| 84 |
+
for (const name of names) {
|
| 85 |
+
const w = widget(node, name);
|
| 86 |
+
if (w) {
|
| 87 |
+
const callback = w.callback;
|
| 88 |
+
w.callback = function () {
|
| 89 |
+
const result = callback?.apply(this, arguments);
|
| 90 |
+
fn();
|
| 91 |
+
return result;
|
| 92 |
+
};
|
| 93 |
+
}
|
| 94 |
+
}
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
function addPanel(node, name, element, height, grow = false) {
|
| 98 |
+
const options = { serialize: false, getMinHeight: () => height + 20 };
|
| 99 |
+
if (!grow) options.getMaxHeight = () => height + 20;
|
| 100 |
+
const w = node.addDOMWidget(name, 'robin', element, options);
|
| 101 |
+
w.serialize = false;
|
| 102 |
+
return w;
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
function findNode(id) {
|
| 106 |
+
let graph = app.rootGraph ?? app.graph;
|
| 107 |
+
let node;
|
| 108 |
+
for (const part of String(id ?? '').split(':')) {
|
| 109 |
+
node = graph?.getNodeById(part);
|
| 110 |
+
graph = node?.subgraph;
|
| 111 |
+
}
|
| 112 |
+
return node;
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
function viewUrl(file) {
|
| 116 |
+
return api.apiURL(`/view?${new URLSearchParams({ filename: file.filename, subfolder: file.subfolder ?? '', type: file.type ?? 'temp' })}`);
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
function clock(seconds) {
|
| 120 |
+
const s = Math.max(0, Math.floor(seconds || 0));
|
| 121 |
+
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
function span(seconds) {
|
| 125 |
+
const minutes = Math.round(seconds / 60);
|
| 126 |
+
if (minutes < 1) return 'under a minute';
|
| 127 |
+
return minutes < 90 ? `${minutes} min` : `${Math.floor(minutes / 60)} h ${minutes % 60} min`;
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
function gigabytes(bytes) {
|
| 131 |
+
return `${(bytes / 1e9).toFixed(1)} GB`;
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
// One sound at a time across every Robin node: starting a take or a sample stops the one playing.
|
| 135 |
+
let playing = null;
|
| 136 |
+
|
| 137 |
+
function stopPlaying() {
|
| 138 |
+
if (!playing) return;
|
| 139 |
+
const { audio, changed } = playing;
|
| 140 |
+
playing = null;
|
| 141 |
+
audio.pause();
|
| 142 |
+
changed(false);
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
function toggle(audio, changed) {
|
| 146 |
+
if (playing?.audio === audio) return stopPlaying();
|
| 147 |
+
stopPlaying();
|
| 148 |
+
playing = { audio, changed };
|
| 149 |
+
audio.onended = () => playing?.audio === audio && stopPlaying();
|
| 150 |
+
changed(true);
|
| 151 |
+
audio.play().catch(() => playing?.audio === audio && stopPlaying());
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
// -> the sound as mono samples at 48 kHz, from a URL or a file.
|
| 155 |
+
async function sound(source) {
|
| 156 |
+
const data = source instanceof Blob ? await source.arrayBuffer() : await (await fetch(source)).arrayBuffer();
|
| 157 |
+
const decoded = await new OfflineAudioContext(1, 1, 48000).decodeAudioData(data);
|
| 158 |
+
const mono = new Float32Array(decoded.length);
|
| 159 |
+
for (let c = 0; c < decoded.numberOfChannels; c++) decoded.getChannelData(c).forEach((v, i) => (mono[i] += v / decoded.numberOfChannels));
|
| 160 |
+
return mono;
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
function peaks(samples, count) {
|
| 164 |
+
const size = Math.max(1, Math.floor(samples.length / count));
|
| 165 |
+
const found = Array.from({ length: count }, (_, i) => {
|
| 166 |
+
let peak = 0;
|
| 167 |
+
for (let j = i * size, end = Math.min(samples.length, j + size); j < end; j++) peak = Math.max(peak, Math.abs(samples[j]));
|
| 168 |
+
return peak;
|
| 169 |
+
});
|
| 170 |
+
const top = Math.max(...found, 1e-6);
|
| 171 |
+
return found.map((peak) => Math.sqrt(peak / top));
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
// Title bar: the badge, the name in Familjen Grotesk and a ROBIN tag, on scarlet.
|
| 175 |
+
function drawTitleBar(ctx, height, size) {
|
| 176 |
+
const width = size[0];
|
| 177 |
+
ctx.save();
|
| 178 |
+
ctx.beginPath();
|
| 179 |
+
ctx.roundRect(0, -height, width, height, this.flags?.collapsed ? [8] : [8, 8, 0, 0]);
|
| 180 |
+
ctx.fillStyle = RED;
|
| 181 |
+
ctx.fill();
|
| 182 |
+
ctx.clip();
|
| 183 |
+
ctx.fillStyle = 'rgba(255,255,255,0.22)';
|
| 184 |
+
ctx.fillRect(0, -height, width, 1);
|
| 185 |
+
ctx.fillStyle = 'rgba(0,0,0,0.25)';
|
| 186 |
+
ctx.fillRect(0, -1, width, 1);
|
| 187 |
+
ctx.restore();
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
function drawTitleBox(ctx, height) {
|
| 191 |
+
if (badge.ready) ctx.drawImage(badge, 7, -height + (height - 20) / 2, 20, 20);
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
function fit(ctx, text, room) {
|
| 195 |
+
if (ctx.measureText(text).width <= room) return text;
|
| 196 |
+
while (text.length > 1 && ctx.measureText(text + '…').width > room) text = text.slice(0, -1);
|
| 197 |
+
return text + '…';
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
function drawTitleText(ctx, height, size, scale, font, selected) {
|
| 201 |
+
if (app.canvas?.low_quality) return;
|
| 202 |
+
const width = size[0];
|
| 203 |
+
const y = -height / 2 + 1;
|
| 204 |
+
let room = width - 44;
|
| 205 |
+
ctx.save();
|
| 206 |
+
ctx.textBaseline = 'middle';
|
| 207 |
+
if (!this.flags?.collapsed) {
|
| 208 |
+
ctx.font = TAG_FONT;
|
| 209 |
+
ctx.letterSpacing = '1.3px';
|
| 210 |
+
ctx.textAlign = 'right';
|
| 211 |
+
ctx.fillStyle = 'rgba(242,238,230,0.78)';
|
| 212 |
+
ctx.fillText('ROBIN', width - 11, y);
|
| 213 |
+
room -= ctx.measureText('ROBIN').width + 14;
|
| 214 |
+
ctx.letterSpacing = '0px';
|
| 215 |
+
}
|
| 216 |
+
ctx.font = TITLE_FONT;
|
| 217 |
+
ctx.textAlign = 'left';
|
| 218 |
+
ctx.fillStyle = selected ? '#FFFFFF' : CREAM;
|
| 219 |
+
ctx.fillText(fit(ctx, String(this.getTitle?.() ?? this.title), room), 34, y);
|
| 220 |
+
ctx.restore();
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
// The two red bands across the bottom of the badge close every Robin node; Robin's own slots get a cream ring.
|
| 224 |
+
function drawBands(ctx) {
|
| 225 |
+
if (this.flags?.collapsed) return;
|
| 226 |
+
const [width, height] = this.size;
|
| 227 |
+
ctx.save();
|
| 228 |
+
ctx.beginPath();
|
| 229 |
+
ctx.roundRect(0, 0, width, height, [0, 0, 8, 8]);
|
| 230 |
+
ctx.clip();
|
| 231 |
+
ctx.fillStyle = RED;
|
| 232 |
+
ctx.fillRect(0, height - 10, width, 3);
|
| 233 |
+
ctx.fillRect(0, height - 5, width, 3);
|
| 234 |
+
ctx.restore();
|
| 235 |
+
if (app.canvas?.low_quality) return;
|
| 236 |
+
ctx.save();
|
| 237 |
+
ctx.lineWidth = 2;
|
| 238 |
+
ctx.strokeStyle = CREAM;
|
| 239 |
+
const ring = (slots, at) => slots?.forEach((slot, i) => {
|
| 240 |
+
if (slot.type !== 'ROBIN_MODEL' && slot.type !== 'ROBIN_DATASET') return;
|
| 241 |
+
const [x, y] = at.call(this, i);
|
| 242 |
+
ctx.beginPath();
|
| 243 |
+
ctx.arc(x - this.pos[0], y - this.pos[1], 5.5, 0, Math.PI * 2);
|
| 244 |
+
ctx.stroke();
|
| 245 |
+
});
|
| 246 |
+
ring(this.inputs, this.getInputPos);
|
| 247 |
+
ring(this.outputs, this.getOutputPos);
|
| 248 |
+
ctx.restore();
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
function loaderPanel(node) {
|
| 252 |
+
const rows = {};
|
| 253 |
+
const row = (key) => h('div', { class: 'row' }, h('span', {}, key), (rows[key] = h('span', {}, DASH)));
|
| 254 |
+
addPanel(node, 'robin_status', h('div', { class: 'robin-panel' }, h('div', { class: 'robin-lcd' }, row('model'), row('voice'), row('from'))), 74);
|
| 255 |
+
const name = () => (value(node, 'model') === 'robin' ? 'robin_v1' : value(node, 'model'));
|
| 256 |
+
const show = (model, voice, from) => Object.entries({ model, voice, from }).forEach(([key, text]) => (rows[key].textContent = text));
|
| 257 |
+
|
| 258 |
+
async function refresh() {
|
| 259 |
+
const res = await api.fetchApi(`/robin/status?${new URLSearchParams({ model: value(node, 'model') ?? 'robin', vae: value(node, 'vae') ?? '' })}`);
|
| 260 |
+
if (!res.ok) return;
|
| 261 |
+
const status = await res.json();
|
| 262 |
+
show(`${name()} · ${status.ready ? 'on disk' : 'to download'}`, `robin · ${status.voice ? 'on disk' : 'to download'}`,
|
| 263 |
+
status.ready ? `models/robin · ${gigabytes(status.size)}` : 'hugging face');
|
| 264 |
+
}
|
| 265 |
+
watch(node, ['model', 'vae'], refresh);
|
| 266 |
+
setTimeout(() => refresh().catch(() => {}));
|
| 267 |
+
|
| 268 |
+
return {
|
| 269 |
+
loader(detail) {
|
| 270 |
+
if (detail.stage === 'load') {
|
| 271 |
+
rows.model.textContent = `${name()} · loading`;
|
| 272 |
+
return;
|
| 273 |
+
}
|
| 274 |
+
const voice = detail.file.startsWith('robin_character_lora');
|
| 275 |
+
if (voice) rows.voice.textContent = 'robin · downloading';
|
| 276 |
+
else rows.model.textContent = `${name()} · downloading`;
|
| 277 |
+
rows.from.textContent = voice ? 'hugging face' : `hugging face · ${detail.file.replace(/\.[^.]+$/, '')}`;
|
| 278 |
+
},
|
| 279 |
+
executed(message) {
|
| 280 |
+
const status = message?.robin_status?.[0];
|
| 281 |
+
if (status) show(`${name()} · ready · ${status.loaded}`, 'robin · on disk',
|
| 282 |
+
`${status.downloaded ? 'hugging face' : 'models/robin'} · ${gigabytes(status.size)}`);
|
| 283 |
+
},
|
| 284 |
+
};
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
// The player on Speak, Voice Changer and Load Audio: the badge play button, a waveform to click and seek, the time, and for takes a
|
| 288 |
+
// download button.
|
| 289 |
+
function makePlayer(what, { download = false } = {}) {
|
| 290 |
+
const play = h('button', { class: 'robin-play', type: 'button', 'aria-label': `Play ${what}`, disabled: true }, icon('play'));
|
| 291 |
+
const wave = h('div', { class: 'robin-wave empty' });
|
| 292 |
+
const time = h('span', { class: 'robin-time' });
|
| 293 |
+
const save = h('a', { class: 'robin-save', 'aria-label': `Download ${what}`, title: `Download ${what}`, hidden: true }, icon('save', 16));
|
| 294 |
+
const row = h('div', { class: 'robin-take' }, play, wave, time, ...(download ? [save] : []));
|
| 295 |
+
let audio = null;
|
| 296 |
+
let seconds = 0;
|
| 297 |
+
let bars = [];
|
| 298 |
+
let frame = 0;
|
| 299 |
+
|
| 300 |
+
const paint = () => {
|
| 301 |
+
const at = audio?.duration ? audio.currentTime / audio.duration : 0;
|
| 302 |
+
bars.forEach((bar, i) => bar.classList.toggle('on', i < Math.round(at * bars.length)));
|
| 303 |
+
time.textContent = `${clock(audio?.currentTime)} / ${clock(audio?.duration || seconds)}`;
|
| 304 |
+
};
|
| 305 |
+
const changed = (on) => {
|
| 306 |
+
play.classList.toggle('on', on);
|
| 307 |
+
play.replaceChildren(icon(on ? 'pause' : 'play'));
|
| 308 |
+
play.setAttribute('aria-label', `${on ? 'Pause' : 'Play'} ${what}`);
|
| 309 |
+
cancelAnimationFrame(frame);
|
| 310 |
+
const tick = () => {
|
| 311 |
+
paint();
|
| 312 |
+
frame = requestAnimationFrame(tick);
|
| 313 |
+
};
|
| 314 |
+
if (on) tick();
|
| 315 |
+
else paint();
|
| 316 |
+
};
|
| 317 |
+
const draw = (heights, lit) => {
|
| 318 |
+
if (bars.length !== heights.length) {
|
| 319 |
+
bars = heights.map(() => h('i'));
|
| 320 |
+
wave.replaceChildren(...bars);
|
| 321 |
+
}
|
| 322 |
+
wave.classList.remove('empty');
|
| 323 |
+
heights.forEach((height, i) => {
|
| 324 |
+
bars[i].style.height = `${Math.max(3, Math.round(height * 32))}px`;
|
| 325 |
+
bars[i].classList.toggle('on', lit);
|
| 326 |
+
});
|
| 327 |
+
};
|
| 328 |
+
play.addEventListener('click', () => audio && toggle(audio, changed));
|
| 329 |
+
wave.addEventListener('click', (event) => {
|
| 330 |
+
if (!audio?.duration) return;
|
| 331 |
+
const box = wave.getBoundingClientRect();
|
| 332 |
+
audio.currentTime = Math.min(1, Math.max(0, (event.clientX - box.left) / box.width)) * audio.duration;
|
| 333 |
+
paint();
|
| 334 |
+
});
|
| 335 |
+
|
| 336 |
+
const player = {
|
| 337 |
+
row,
|
| 338 |
+
// -> the length in seconds, or null when the file can't be played or a newer one replaced it.
|
| 339 |
+
async load(url, { length = 0, name = null, missing = "can't play this one" } = {}) {
|
| 340 |
+
player.stop();
|
| 341 |
+
audio = new Audio(url);
|
| 342 |
+
seconds = length;
|
| 343 |
+
play.disabled = false;
|
| 344 |
+
Object.assign(save, { hidden: !name, href: url, download: name ?? '' });
|
| 345 |
+
paint();
|
| 346 |
+
const samples = await sound(url).catch(() => null);
|
| 347 |
+
if (audio?.src !== new URL(url, location.href).href) return null;
|
| 348 |
+
if (!samples) {
|
| 349 |
+
player.clear(missing);
|
| 350 |
+
return null;
|
| 351 |
+
}
|
| 352 |
+
seconds = samples.length / 48000;
|
| 353 |
+
draw(peaks(samples, 64), false);
|
| 354 |
+
paint();
|
| 355 |
+
return seconds;
|
| 356 |
+
},
|
| 357 |
+
clear(text) {
|
| 358 |
+
player.stop();
|
| 359 |
+
audio = null;
|
| 360 |
+
bars = [];
|
| 361 |
+
play.disabled = true;
|
| 362 |
+
save.hidden = true;
|
| 363 |
+
wave.className = 'robin-wave empty';
|
| 364 |
+
wave.replaceChildren();
|
| 365 |
+
time.textContent = text;
|
| 366 |
+
},
|
| 367 |
+
live(levels, at) {
|
| 368 |
+
player.stop();
|
| 369 |
+
audio = null;
|
| 370 |
+
play.disabled = true;
|
| 371 |
+
draw(levels, true);
|
| 372 |
+
time.textContent = `${clock(at)} / ${clock(MAX_TAKE)}`;
|
| 373 |
+
},
|
| 374 |
+
stop() {
|
| 375 |
+
if (audio && playing?.audio === audio) stopPlaying();
|
| 376 |
+
},
|
| 377 |
+
};
|
| 378 |
+
return player;
|
| 379 |
+
}
|
| 380 |
+
|
| 381 |
+
function takePanel(node) {
|
| 382 |
+
const player = makePlayer('the last take', { download: true });
|
| 383 |
+
player.clear('no take yet');
|
| 384 |
+
addPanel(node, 'robin_take', h('div', { class: 'robin-panel' }, player.row), 58);
|
| 385 |
+
return {
|
| 386 |
+
executed(message) {
|
| 387 |
+
const take = message?.robin_take?.[0];
|
| 388 |
+
if (take) player.load(viewUrl(take), { length: take.seconds, name: `robin_take_seed${take.seed}.flac` });
|
| 389 |
+
},
|
| 390 |
+
stop: player.stop,
|
| 391 |
+
};
|
| 392 |
+
}
|
| 393 |
+
|
| 394 |
+
// -> the name ComfyUI stored the file under, in its input folder.
|
| 395 |
+
async function toInput(blob, filename, fields = {}) {
|
| 396 |
+
const body = new FormData();
|
| 397 |
+
body.append('image', blob, filename);
|
| 398 |
+
body.append('type', 'input');
|
| 399 |
+
for (const [key, value] of Object.entries(fields)) body.append(key, value);
|
| 400 |
+
const res = await api.fetchApi('/upload/image', { method: 'POST', body });
|
| 401 |
+
if (!res.ok) throw new Error(res.status === 413 ? 'too large to upload' : `upload failed, ${res.status}`);
|
| 402 |
+
return (await res.json()).name;
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
function wav(samples, rate) {
|
| 406 |
+
const view = new DataView(new ArrayBuffer(44 + samples.length * 2));
|
| 407 |
+
const text = (at, s) => [...s].forEach((c, i) => view.setUint8(at + i, c.charCodeAt(0)));
|
| 408 |
+
text(0, 'RIFF');
|
| 409 |
+
view.setUint32(4, 36 + samples.length * 2, true);
|
| 410 |
+
text(8, 'WAVEfmt ');
|
| 411 |
+
view.setUint32(16, 16, true);
|
| 412 |
+
view.setUint16(20, 1, true);
|
| 413 |
+
view.setUint16(22, 1, true);
|
| 414 |
+
view.setUint32(24, rate, true);
|
| 415 |
+
view.setUint32(28, rate * 2, true);
|
| 416 |
+
view.setUint16(32, 2, true);
|
| 417 |
+
view.setUint16(34, 16, true);
|
| 418 |
+
text(36, 'data');
|
| 419 |
+
view.setUint32(40, samples.length * 2, true);
|
| 420 |
+
samples.forEach((s, i) => view.setInt16(44 + 2 * i, Math.max(-1, Math.min(1, s)) * 0x7fff, true));
|
| 421 |
+
return new Blob([view], { type: 'audio/wav' });
|
| 422 |
+
}
|
| 423 |
+
|
| 424 |
+
// Keeps the line: from 0.15 s before the first sound to 0.25 s after the last, as the trainer trims clips. -> null when nothing was heard.
|
| 425 |
+
function trimSilence(x, rate) {
|
| 426 |
+
const n = rate / 100;
|
| 427 |
+
const db = Array.from({ length: Math.floor(x.length / n) }, (_, k) => {
|
| 428 |
+
let sum = 0;
|
| 429 |
+
for (let i = k * n; i < (k + 1) * n; i++) sum += x[i] * x[i];
|
| 430 |
+
return 10 * Math.log10(sum / n + 1e-18);
|
| 431 |
+
});
|
| 432 |
+
const loud = Math.max(-120, ...db);
|
| 433 |
+
if (loud < -55) return null;
|
| 434 |
+
const floor = Math.max(Math.min(-45, loud - 30), -60);
|
| 435 |
+
const first = db.findIndex((d) => d > floor);
|
| 436 |
+
const last = db.findLastIndex((d) => d > floor);
|
| 437 |
+
return x.subarray(Math.max(0, first * n - Math.round(0.15 * rate)), Math.min(x.length, (last + 1) * n + Math.round(0.25 * rate)));
|
| 438 |
+
}
|
| 439 |
+
|
| 440 |
+
function stamp() {
|
| 441 |
+
const d = new Date();
|
| 442 |
+
const two = (v) => String(v).padStart(2, '0');
|
| 443 |
+
return `${d.getFullYear()}${two(d.getMonth() + 1)}${two(d.getDate())}_${two(d.getHours())}${two(d.getMinutes())}${two(d.getSeconds())}`;
|
| 444 |
+
}
|
| 445 |
+
|
| 446 |
+
// Robin Load Audio: record a line with the microphone, or choose a file; either way it lands in ComfyUI's input folder.
|
| 447 |
+
function audioPanel(node) {
|
| 448 |
+
const player = makePlayer('the recording');
|
| 449 |
+
const record = h('button', { class: 'robin-badge', type: 'button' });
|
| 450 |
+
const choose = h('button', { class: 'robin-badge', type: 'button' }, icon('folder'), 'Choose file');
|
| 451 |
+
const reveal = h('button', { class: 'robin-badge', type: 'button', title: 'Open the folder your recordings are saved in' }, icon('open'), 'Open Save Dir');
|
| 452 |
+
const note = h('div', { class: 'robin-hint' });
|
| 453 |
+
const input = h('input', { type: 'file', accept: 'audio/*,video/*', hidden: true });
|
| 454 |
+
addPanel(node, 'robin_audio', h('div', { class: 'robin-panel' }, player.row, h('div', { class: 'robin-pick' }, record, choose, reveal, input), note), 120);
|
| 455 |
+
const list = widget(node, 'audio');
|
| 456 |
+
let session = null;
|
| 457 |
+
const say = (text, full = text) => {
|
| 458 |
+
note.textContent = text;
|
| 459 |
+
note.title = full;
|
| 460 |
+
};
|
| 461 |
+
const idle = () => say(`up to ${MAX_TAKE} s`, `Recordings and files up to ${MAX_TAKE} s, the Voice Changer's limit`);
|
| 462 |
+
|
| 463 |
+
const label = (on) => {
|
| 464 |
+
record.classList.toggle('on', on);
|
| 465 |
+
record.replaceChildren(icon(on ? 'stop' : 'record'), on ? 'Stop' : 'Record');
|
| 466 |
+
};
|
| 467 |
+
const busy = (on) => {
|
| 468 |
+
record.disabled = choose.disabled = on;
|
| 469 |
+
};
|
| 470 |
+
|
| 471 |
+
async function show() {
|
| 472 |
+
const name = list?.value;
|
| 473 |
+
if (!name) return player.clear('no recording yet');
|
| 474 |
+
const seconds = await player.load(viewUrl({ filename: name, subfolder: '', type: 'input' }), { missing: `can't find ${name}` });
|
| 475 |
+
if (seconds > MAX_TAKE) say(`${clock(seconds)}: over ${MAX_TAKE} s`, `The Voice Changer takes up to ${MAX_TAKE} s: trim this one first.`);
|
| 476 |
+
}
|
| 477 |
+
function use(name) {
|
| 478 |
+
if (!list.options.values.includes(name)) list.options.values.push(name);
|
| 479 |
+
list.value = name;
|
| 480 |
+
idle();
|
| 481 |
+
node.setDirtyCanvas(true, true);
|
| 482 |
+
show();
|
| 483 |
+
}
|
| 484 |
+
|
| 485 |
+
async function add(file) {
|
| 486 |
+
busy(true);
|
| 487 |
+
say('adding');
|
| 488 |
+
try {
|
| 489 |
+
const plain = SOUND_FILES.test(file.name);
|
| 490 |
+
use(await toInput(plain ? file : wav(await sound(file), 48000), plain ? file.name : `${file.name.replace(/\.[^.]+$/, '')}.wav`));
|
| 491 |
+
} catch (e) {
|
| 492 |
+
say("couldn't add it", `${file.name}: ${e.message}`);
|
| 493 |
+
} finally {
|
| 494 |
+
busy(false);
|
| 495 |
+
}
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
async function finish(chunks, type) {
|
| 499 |
+
try {
|
| 500 |
+
const line = trimSilence(await sound(new Blob(chunks, { type })), 48000);
|
| 501 |
+
if (line) use(await toInput(wav(line, 48000), `recording_${stamp()}.wav`));
|
| 502 |
+
else {
|
| 503 |
+
say('no sound came in', 'Nothing came through the microphone. Check which input the browser is using.');
|
| 504 |
+
show();
|
| 505 |
+
}
|
| 506 |
+
} catch (e) {
|
| 507 |
+
say("didn't save", `The recording didn't save: ${e.message}`);
|
| 508 |
+
show();
|
| 509 |
+
} finally {
|
| 510 |
+
busy(false);
|
| 511 |
+
}
|
| 512 |
+
}
|
| 513 |
+
|
| 514 |
+
async function start() {
|
| 515 |
+
if (!navigator.mediaDevices?.getUserMedia || !window.MediaRecorder) {
|
| 516 |
+
say('needs localhost or https', 'Browsers only allow recording on localhost or https. Open ComfyUI that way to record.');
|
| 517 |
+
return;
|
| 518 |
+
}
|
| 519 |
+
let stream;
|
| 520 |
+
try {
|
| 521 |
+
stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: false, noiseSuppression: false, autoGainControl: false } });
|
| 522 |
+
} catch (e) {
|
| 523 |
+
if (e.name === 'NotAllowedError') say('microphone blocked', 'The browser blocked the microphone. Allow it for this page and try again.');
|
| 524 |
+
else say('no microphone', e.message);
|
| 525 |
+
return;
|
| 526 |
+
}
|
| 527 |
+
stopPlaying();
|
| 528 |
+
const recorder = new MediaRecorder(stream, { audioBitsPerSecond: 256000 });
|
| 529 |
+
const chunks = [];
|
| 530 |
+
const context = new AudioContext();
|
| 531 |
+
const meter = context.createAnalyser();
|
| 532 |
+
meter.fftSize = 2048;
|
| 533 |
+
context.createMediaStreamSource(stream).connect(meter);
|
| 534 |
+
const frame = new Float32Array(meter.fftSize);
|
| 535 |
+
const levels = new Array(64).fill(0);
|
| 536 |
+
const began = performance.now();
|
| 537 |
+
let tick = 0;
|
| 538 |
+
let last = 0;
|
| 539 |
+
const draw = (now) => {
|
| 540 |
+
const at = (now - began) / 1000;
|
| 541 |
+
if (now - last >= 70) {
|
| 542 |
+
meter.getFloatTimeDomainData(frame);
|
| 543 |
+
let sum = 0;
|
| 544 |
+
for (const v of frame) sum += v * v;
|
| 545 |
+
levels.shift();
|
| 546 |
+
levels.push(Math.min(1, Math.sqrt(4 * Math.sqrt(sum / frame.length))));
|
| 547 |
+
last = now;
|
| 548 |
+
}
|
| 549 |
+
player.live(levels, at);
|
| 550 |
+
if (at >= MAX_TAKE) session?.stop();
|
| 551 |
+
else tick = requestAnimationFrame(draw);
|
| 552 |
+
};
|
| 553 |
+
const release = () => {
|
| 554 |
+
cancelAnimationFrame(tick);
|
| 555 |
+
stream.getTracks().forEach((track) => track.stop());
|
| 556 |
+
context.close();
|
| 557 |
+
session = null;
|
| 558 |
+
label(false);
|
| 559 |
+
};
|
| 560 |
+
recorder.ondataavailable = (event) => event.data.size && chunks.push(event.data);
|
| 561 |
+
recorder.onstop = () => finish(chunks, recorder.mimeType);
|
| 562 |
+
session = {
|
| 563 |
+
stop() {
|
| 564 |
+
release();
|
| 565 |
+
busy(true);
|
| 566 |
+
say('saving');
|
| 567 |
+
recorder.stop();
|
| 568 |
+
},
|
| 569 |
+
cancel() {
|
| 570 |
+
recorder.onstop = null;
|
| 571 |
+
release();
|
| 572 |
+
recorder.stop();
|
| 573 |
+
},
|
| 574 |
+
};
|
| 575 |
+
recorder.start(250);
|
| 576 |
+
label(true);
|
| 577 |
+
choose.disabled = true;
|
| 578 |
+
say('say the line');
|
| 579 |
+
tick = requestAnimationFrame(draw);
|
| 580 |
+
}
|
| 581 |
+
|
| 582 |
+
// A page can't open the file manager itself: ComfyUI opens its input folder when it runs on this computer, and otherwise says where it is.
|
| 583 |
+
reveal.addEventListener('click', async () => {
|
| 584 |
+
try {
|
| 585 |
+
const res = await api.fetchApi('/robin/open_recordings', { method: 'POST' });
|
| 586 |
+
const { opened, folder } = await res.json();
|
| 587 |
+
if (opened) return say('opened the save folder', folder);
|
| 588 |
+
const copied = await navigator.clipboard?.writeText(folder).then(() => true, () => false);
|
| 589 |
+
say(`saved on the ComfyUI computer${copied ? ', path copied' : ''}`, `Recordings are saved in ${folder} on the computer running ComfyUI.`);
|
| 590 |
+
} catch (e) {
|
| 591 |
+
say("couldn't open it", e.message);
|
| 592 |
+
}
|
| 593 |
+
});
|
| 594 |
+
record.addEventListener('click', () => (session ? session.stop() : start()));
|
| 595 |
+
choose.addEventListener('click', () => input.click());
|
| 596 |
+
input.addEventListener('change', () => {
|
| 597 |
+
const file = input.files[0];
|
| 598 |
+
input.value = '';
|
| 599 |
+
if (file) add(file);
|
| 600 |
+
});
|
| 601 |
+
node.onDragOver = (event) => !!event?.dataTransfer?.types?.includes?.('Files');
|
| 602 |
+
node.onDragDrop = (event) => {
|
| 603 |
+
const file = event?.dataTransfer?.files?.[0];
|
| 604 |
+
if (file) add(file);
|
| 605 |
+
return !!file;
|
| 606 |
+
};
|
| 607 |
+
watch(node, ['audio'], () => {
|
| 608 |
+
idle();
|
| 609 |
+
show();
|
| 610 |
+
});
|
| 611 |
+
label(false);
|
| 612 |
+
idle();
|
| 613 |
+
setTimeout(show);
|
| 614 |
+
|
| 615 |
+
return {
|
| 616 |
+
stop() {
|
| 617 |
+
session?.cancel();
|
| 618 |
+
player.stop();
|
| 619 |
+
},
|
| 620 |
+
};
|
| 621 |
+
}
|
| 622 |
+
|
| 623 |
+
function inside(file) {
|
| 624 |
+
return file.webkitRelativePath.split('/').slice(1).join('/');
|
| 625 |
+
}
|
| 626 |
+
|
| 627 |
+
function fingerprint(files) {
|
| 628 |
+
const text = files.map((f) => `${inside(f)}|${f.size}|${f.lastModified}`).sort().join('\n');
|
| 629 |
+
let hash = 0x811c9dc5;
|
| 630 |
+
for (let i = 0; i < text.length; i++) hash = Math.imul(hash ^ text.charCodeAt(i), 0x01000193);
|
| 631 |
+
return (hash >>> 0).toString(16).padStart(8, '0');
|
| 632 |
+
}
|
| 633 |
+
|
| 634 |
+
async function send(file, name) {
|
| 635 |
+
const path = inside(file);
|
| 636 |
+
const subfolder = [UPLOADS, name, path.slice(0, Math.max(0, path.lastIndexOf('/')))].filter(Boolean).join('/');
|
| 637 |
+
await toInput(file, file.name, { subfolder, overwrite: 'true' });
|
| 638 |
+
}
|
| 639 |
+
|
| 640 |
+
// A picked folder goes to input/robin_datasets/<folder name>-<fingerprint of its files>: picking it again sends only what is missing,
|
| 641 |
+
// and a different folder with the same name never mixes with it.
|
| 642 |
+
async function upload(files, progress) {
|
| 643 |
+
const root = files[0].webkitRelativePath.split('/')[0];
|
| 644 |
+
const name = `${root.replace(/[^A-Za-z0-9_.-]+/g, '_').replace(/^[._-]+/, '').slice(0, 48) || 'clips'}-${fingerprint(files)}`;
|
| 645 |
+
const res = await api.fetchApi(`/robin/uploaded?${new URLSearchParams({ name })}`);
|
| 646 |
+
const have = res.ok ? (await res.json()).files : {};
|
| 647 |
+
const todo = files.filter((f) => have[inside(f)] !== f.size);
|
| 648 |
+
const sending = todo.length;
|
| 649 |
+
const failed = [];
|
| 650 |
+
let done = files.length - todo.length;
|
| 651 |
+
progress(done);
|
| 652 |
+
const worker = async () => {
|
| 653 |
+
for (let file; (file = todo.shift()); progress(++done)) {
|
| 654 |
+
await send(file, name).catch((e) => failed.push(`${inside(file)} (${e.message})`));
|
| 655 |
+
}
|
| 656 |
+
};
|
| 657 |
+
await Promise.all([worker(), worker(), worker(), worker()]);
|
| 658 |
+
return { folder: `${UPLOADS}/${name}`, sent: sending - failed.length, failed };
|
| 659 |
+
}
|
| 660 |
+
|
| 661 |
+
function datasetPanel(node) {
|
| 662 |
+
const input = h('input', { type: 'file', webkitdirectory: true, multiple: true, hidden: true });
|
| 663 |
+
const pick = h('button', { class: 'robin-badge', type: 'button', onclick: () => input.click() }, icon('folder'), 'Choose folder');
|
| 664 |
+
const note = h('span', {}, 'or type its path in folder');
|
| 665 |
+
const out = h('pre', { 'aria-live': 'polite' });
|
| 666 |
+
const term = h('div', { class: 'robin-term' }, h('header', {}, h('i'), h('i'), h('i'), h('span', {}, 'REPORT')), out);
|
| 667 |
+
addPanel(node, 'robin_dataset', h('div', { class: 'robin-panel' }, h('div', { class: 'robin-pick' }, pick, note, input), term), 178, true);
|
| 668 |
+
out.addEventListener('wheel', (event) => out.scrollHeight > out.clientHeight && event.stopPropagation(), { passive: true });
|
| 669 |
+
|
| 670 |
+
const tone = (line) => (/^\s*ready:/.test(line) ? 'ok' : /^\s*left out:|^There is no folder|^Only .* minutes/.test(line) ? 'bad'
|
| 671 |
+
: /^\s*note/.test(line) ? 'note' : /^\s*voice description|^Choose a folder|^Checking/.test(line) ? 'dim' : '');
|
| 672 |
+
const show = (text) => out.replaceChildren(...String(text).split('\n').map((line) => h('span', { class: tone(line) }, line + '\n')));
|
| 673 |
+
show(EMPTY_REPORT);
|
| 674 |
+
|
| 675 |
+
let asked = 0;
|
| 676 |
+
async function check() {
|
| 677 |
+
const folder = String(value(node, 'folder') ?? '');
|
| 678 |
+
const ask = ++asked;
|
| 679 |
+
if (!folder.trim()) return show(EMPTY_REPORT);
|
| 680 |
+
show('Checking the folder...');
|
| 681 |
+
try {
|
| 682 |
+
const res = await api.fetchApi('/robin/check', {
|
| 683 |
+
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ folder, language: value(node, 'language') }),
|
| 684 |
+
});
|
| 685 |
+
const text = res.ok ? (await res.json()).report : `The check failed (${res.status}).`;
|
| 686 |
+
if (ask === asked) show(text);
|
| 687 |
+
} catch (e) {
|
| 688 |
+
if (ask === asked) show(`The check failed: ${e.message}`);
|
| 689 |
+
}
|
| 690 |
+
}
|
| 691 |
+
watch(node, ['folder', 'language'], check);
|
| 692 |
+
setTimeout(() => value(node, 'folder')?.trim() && check());
|
| 693 |
+
|
| 694 |
+
input.addEventListener('change', async () => {
|
| 695 |
+
const files = [...input.files].filter((f) => CLIP_FILES.test(f.name) && !inside(f).split('/').some((part) => part.startsWith('.')));
|
| 696 |
+
input.value = '';
|
| 697 |
+
if (!files.length) return show('That folder has no audio clips or .txt transcripts.');
|
| 698 |
+
pick.disabled = true;
|
| 699 |
+
try {
|
| 700 |
+
const { folder, sent, failed } = await upload(files, (done) => (note.textContent = `uploading ${done} / ${files.length}`));
|
| 701 |
+
note.textContent = failed.length ? `${failed.length} of ${files.length} files didn't upload` : sent ? `uploaded ${sent} files` : 'already uploaded';
|
| 702 |
+
widget(node, 'folder').value = folder;
|
| 703 |
+
node.setDirtyCanvas(true, true);
|
| 704 |
+
await check();
|
| 705 |
+
if (failed.length) out.append(h('span', { class: 'bad' }, `\nThese files didn't upload:\n${failed.map((f) => ` ${f}`).join('\n')}\n`));
|
| 706 |
+
} catch (e) {
|
| 707 |
+
note.textContent = 'the upload stopped';
|
| 708 |
+
show(`The upload stopped: ${e.message}`);
|
| 709 |
+
} finally {
|
| 710 |
+
pick.disabled = false;
|
| 711 |
+
}
|
| 712 |
+
});
|
| 713 |
+
|
| 714 |
+
return {
|
| 715 |
+
executed(message) {
|
| 716 |
+
if (message?.text) show(message.text.join('\n'));
|
| 717 |
+
},
|
| 718 |
+
};
|
| 719 |
+
}
|
| 720 |
+
|
| 721 |
+
function trainPanel(node) {
|
| 722 |
+
const rows = {};
|
| 723 |
+
const row = (key, label) => h('div', { class: 'row' }, h('span', {}, label), (rows[key] = h('span', {}, DASH)));
|
| 724 |
+
const fill = h('i');
|
| 725 |
+
const more = h('button', { class: 'robin-more', type: 'button' });
|
| 726 |
+
const lcd = h('div', { class: 'robin-lcd' }, row('step', 'step'), row('planner', 'planner loss'), row('decoder', 'decoder loss'), row('pace', 'pace'),
|
| 727 |
+
h('div', { class: 'meter' }, fill));
|
| 728 |
+
const saved = h('div', { class: 'robin-saved' });
|
| 729 |
+
addPanel(node, 'robin_training', h('div', { class: 'robin-panel' }, more, lcd, saved), 180);
|
| 730 |
+
let run = { stage: 'idle', step: 0, samples: new Map() };
|
| 731 |
+
|
| 732 |
+
const steps = () => run.total ?? value(node, 'steps');
|
| 733 |
+
const lr = (name) => Number(value(node, name)).toExponential();
|
| 734 |
+
const pace = () => ({
|
| 735 |
+
idle: DASH,
|
| 736 |
+
start: 'starting',
|
| 737 |
+
prepare: `preparing clips · ${run.done} / ${run.todo}`,
|
| 738 |
+
train: run.pace == null ? DASH : `${run.pace.toFixed(1)} s / step · ${span(run.left)} left`,
|
| 739 |
+
done: `done in ${span(run.minutes * 60)}`,
|
| 740 |
+
stopped: 'stopped · queue again to continue',
|
| 741 |
+
failed: 'stopped · see the error',
|
| 742 |
+
})[run.stage];
|
| 743 |
+
|
| 744 |
+
function readout() {
|
| 745 |
+
rows.step.textContent = `${run.stage === 'idle' ? DASH : run.step} / ${steps()}`;
|
| 746 |
+
rows.planner.textContent = run.planner == null ? DASH : run.planner.toFixed(2);
|
| 747 |
+
rows.decoder.textContent = run.decoder == null ? DASH : run.decoder.toFixed(3);
|
| 748 |
+
rows.pace.textContent = pace();
|
| 749 |
+
const share = run.stage === 'prepare' ? run.done / run.todo : run.stage === 'done' ? 1 : run.step / steps();
|
| 750 |
+
fill.style.width = `${100 * Math.min(1, share || 0)}%`;
|
| 751 |
+
}
|
| 752 |
+
|
| 753 |
+
function mark(entry, on) {
|
| 754 |
+
const label = entry.step ? String(entry.step) : 'base';
|
| 755 |
+
entry.button.classList.toggle('on', on);
|
| 756 |
+
entry.button.replaceChildren(icon(on ? 'pause' : 'play', 10), label);
|
| 757 |
+
entry.button.setAttribute('aria-label', `${on ? 'Pause' : 'Play'} the ${entry.step ? `step ${entry.step}` : 'base'} sample`);
|
| 758 |
+
}
|
| 759 |
+
|
| 760 |
+
function chips() {
|
| 761 |
+
const total = steps();
|
| 762 |
+
const every = run.every ?? value(node, 'save_every');
|
| 763 |
+
const plan = [0];
|
| 764 |
+
for (let step = every; step < total && plan.length < 400; step += every) plan.push(step);
|
| 765 |
+
plan.push(total);
|
| 766 |
+
const waiting = plan.filter((step) => !run.samples.has(step)).slice(0, 12);
|
| 767 |
+
const all = [...new Set([...waiting, ...run.samples.keys()])].sort((a, b) => a - b);
|
| 768 |
+
saved.replaceChildren(h('b', {}, 'SAVED'), ...all.map((step) => {
|
| 769 |
+
const entry = run.samples.get(step);
|
| 770 |
+
if (!entry) return h('span', { class: 'robin-wait' }, step ? String(step) : 'base');
|
| 771 |
+
entry.button = h('button', { class: 'robin-badge', type: 'button', onclick: () => toggle(entry.audio, (on) => mark(entry, on)) });
|
| 772 |
+
mark(entry, playing?.audio === entry.audio);
|
| 773 |
+
return entry.button;
|
| 774 |
+
}));
|
| 775 |
+
}
|
| 776 |
+
|
| 777 |
+
function keep(sample) {
|
| 778 |
+
run.samples.set(sample.step, { step: sample.step, audio: new Audio(viewUrl(sample)) });
|
| 779 |
+
chips();
|
| 780 |
+
const button = run.samples.get(sample.step).button;
|
| 781 |
+
saved.scrollLeft = Math.max(0, button.offsetLeft + button.offsetWidth + 8 - saved.clientWidth);
|
| 782 |
+
}
|
| 783 |
+
|
| 784 |
+
function stop() {
|
| 785 |
+
if ([...run.samples.values()].some((entry) => entry.audio === playing?.audio)) stopPlaying();
|
| 786 |
+
}
|
| 787 |
+
|
| 788 |
+
function label() {
|
| 789 |
+
const open = !!node.showAdvanced;
|
| 790 |
+
more.classList.toggle('open', open);
|
| 791 |
+
more.setAttribute('aria-expanded', String(open));
|
| 792 |
+
more.replaceChildren(icon('more', 10), open ? 'hide advanced'
|
| 793 |
+
: `advanced · ranks ${value(node, 'rank_planner')} / ${value(node, 'rank_decoder')} · lr ${lr('lr_planner')} / ${lr('lr_decoder')}`);
|
| 794 |
+
}
|
| 795 |
+
more.addEventListener('click', () => {
|
| 796 |
+
node.toggleAdvanced();
|
| 797 |
+
if (!node.showAdvanced) node.setSize([node.size[0], node.computeSize()[1]]);
|
| 798 |
+
});
|
| 799 |
+
watch(node, ['steps', 'save_every'], () => run.stage === 'idle' && (readout(), chips()));
|
| 800 |
+
watch(node, ['rank_planner', 'rank_decoder', 'lr_planner', 'lr_decoder'], label);
|
| 801 |
+
setTimeout(() => (label(), readout(), chips()));
|
| 802 |
+
|
| 803 |
+
return {
|
| 804 |
+
event(detail) {
|
| 805 |
+
if (detail.stage === 'start') {
|
| 806 |
+
stop();
|
| 807 |
+
run = { stage: 'start', step: 0, total: detail.total, every: detail.save_every, samples: new Map() };
|
| 808 |
+
chips();
|
| 809 |
+
} else if (detail.stage === 'prepare') Object.assign(run, { stage: 'prepare', done: detail.step, todo: detail.total });
|
| 810 |
+
else if (detail.stage === 'train') {
|
| 811 |
+
const { step, total, planner, decoder, pace, left } = detail;
|
| 812 |
+
Object.assign(run, { stage: 'train', step, total, planner, decoder, pace, left });
|
| 813 |
+
} else if (detail.stage === 'sample') keep(detail.sample);
|
| 814 |
+
else if (detail.stage === 'done') Object.assign(run, { stage: 'done', step: detail.total, minutes: detail.minutes });
|
| 815 |
+
else run.stage = detail.stage;
|
| 816 |
+
readout();
|
| 817 |
+
},
|
| 818 |
+
executed(message) {
|
| 819 |
+
const done = message?.robin_train?.[0];
|
| 820 |
+
if (!done || run.stage === 'done') return;
|
| 821 |
+
stop();
|
| 822 |
+
run = { stage: 'done', step: done.total, total: done.total, minutes: done.minutes, samples: new Map() };
|
| 823 |
+
for (const sample of done.samples) run.samples.set(sample.step, { step: sample.step, audio: new Audio(viewUrl(sample)) });
|
| 824 |
+
readout();
|
| 825 |
+
chips();
|
| 826 |
+
},
|
| 827 |
+
folded: label,
|
| 828 |
+
stop,
|
| 829 |
+
};
|
| 830 |
+
}
|
| 831 |
+
|
| 832 |
+
const PANELS = { RobinLoader: loaderPanel, RobinSpeak: takePanel, RobinVoiceChanger: takePanel, RobinLoadAudio: audioPanel, RobinCheckDataset: datasetPanel,
|
| 833 |
+
RobinTrainLoRA: trainPanel };
|
| 834 |
+
|
| 835 |
+
// ComfyUI marks these inputs advanced but still lays them out; they stay folded away until Show Advanced (or the Train node's toggle).
|
| 836 |
+
function foldAdvanced(node) {
|
| 837 |
+
const folded = (node.widgets ?? []).filter((w) => w.options?.advanced);
|
| 838 |
+
if (!folded.length) return;
|
| 839 |
+
let open = false;
|
| 840 |
+
for (const w of folded) {
|
| 841 |
+
w.advanced = w.hidden = true;
|
| 842 |
+
w.getOutlineColor = () => '#8a2a25';
|
| 843 |
+
}
|
| 844 |
+
Object.defineProperty(node, 'showAdvanced', {
|
| 845 |
+
configurable: true,
|
| 846 |
+
get: () => open,
|
| 847 |
+
set(value) {
|
| 848 |
+
open = !!value;
|
| 849 |
+
for (const w of folded) w.hidden = !open;
|
| 850 |
+
node.robinUI?.folded?.();
|
| 851 |
+
node.setDirtyCanvas(true, true);
|
| 852 |
+
},
|
| 853 |
+
});
|
| 854 |
+
}
|
| 855 |
+
|
| 856 |
+
function colorSlots(node) {
|
| 857 |
+
for (const slot of [...(node.inputs ?? []), ...(node.outputs ?? [])]) {
|
| 858 |
+
if (slot.type === 'AUDIO') slot.color_on = slot.color_off = CREAM;
|
| 859 |
+
}
|
| 860 |
+
}
|
| 861 |
+
|
| 862 |
+
function pin(colors, type, color) {
|
| 863 |
+
Object.defineProperty(colors, type, { get: () => color, set() {}, enumerable: true, configurable: true });
|
| 864 |
+
}
|
| 865 |
+
|
| 866 |
+
app.registerExtension({
|
| 867 |
+
name: 'Robin.Nodes',
|
| 868 |
+
|
| 869 |
+
setup() {
|
| 870 |
+
// Robin's link colors hold through palette changes; dataset links are dashed and audio out of a Robin node is cream.
|
| 871 |
+
const canvas = app.canvas;
|
| 872 |
+
const LGraphCanvas = canvas.constructor;
|
| 873 |
+
pin(LGraphCanvas.link_type_colors, 'ROBIN_MODEL', RED);
|
| 874 |
+
pin(LGraphCanvas.link_type_colors, 'ROBIN_DATASET', AUDIO_LINK);
|
| 875 |
+
pin(canvas.default_connection_color_byType, 'ROBIN_MODEL', RED);
|
| 876 |
+
pin(canvas.default_connection_color_byType, 'ROBIN_DATASET', INK);
|
| 877 |
+
const renderLink = LGraphCanvas.prototype.renderLink;
|
| 878 |
+
LGraphCanvas.prototype.renderLink = function (ctx, a, b, link, skipBorder, flow, color, ...rest) {
|
| 879 |
+
if (color == null && link?.type === 'AUDIO' && this.graph?.getNodeById(link.origin_id)?.type?.startsWith('Robin')) color = AUDIO_LINK;
|
| 880 |
+
if (link?.type !== 'ROBIN_DATASET') return renderLink.call(this, ctx, a, b, link, skipBorder, flow, color, ...rest);
|
| 881 |
+
ctx.save();
|
| 882 |
+
ctx.setLineDash([7, 5]);
|
| 883 |
+
try {
|
| 884 |
+
return renderLink.call(this, ctx, a, b, link, skipBorder, flow, color, ...rest);
|
| 885 |
+
} finally {
|
| 886 |
+
ctx.restore();
|
| 887 |
+
}
|
| 888 |
+
};
|
| 889 |
+
api.addEventListener('robin.loader', ({ detail }) => findNode(detail.node)?.robinUI?.loader?.(detail));
|
| 890 |
+
api.addEventListener('robin.train', ({ detail }) => findNode(detail.node)?.robinUI?.event?.(detail));
|
| 891 |
+
},
|
| 892 |
+
|
| 893 |
+
beforeRegisterNodeDef(nodeType, nodeData) {
|
| 894 |
+
if (!nodeData.name.startsWith('Robin')) return;
|
| 895 |
+
const proto = nodeType.prototype;
|
| 896 |
+
nodeType.title_text_color = CREAM;
|
| 897 |
+
proto.onDrawTitleBar = drawTitleBar;
|
| 898 |
+
proto.onDrawTitleBox = drawTitleBox;
|
| 899 |
+
proto.onDrawTitleText = drawTitleText;
|
| 900 |
+
chain(proto, 'onDrawForeground', drawBands);
|
| 901 |
+
chain(proto, 'onNodeCreated', function () {
|
| 902 |
+
this.color = RED;
|
| 903 |
+
this.bgcolor = INK;
|
| 904 |
+
colorSlots(this);
|
| 905 |
+
for (const w of this.widgets ?? []) {
|
| 906 |
+
if (w.element instanceof HTMLTextAreaElement) w.element.classList.add('robin-text');
|
| 907 |
+
}
|
| 908 |
+
foldAdvanced(this);
|
| 909 |
+
this.robinUI = PANELS[nodeData.name]?.(this);
|
| 910 |
+
const [width, room] = SIZES[nodeData.name] ?? [0, 0];
|
| 911 |
+
this.setSize([Math.max(this.size[0], width), this.computeSize()[1] + room]);
|
| 912 |
+
});
|
| 913 |
+
chain(proto, 'onConfigure', function () {
|
| 914 |
+
colorSlots(this);
|
| 915 |
+
});
|
| 916 |
+
chain(proto, 'onExecuted', function (message) {
|
| 917 |
+
this.robinUI?.executed?.(message);
|
| 918 |
+
});
|
| 919 |
+
chain(proto, 'onRemoved', function () {
|
| 920 |
+
this.robinUI?.stop?.();
|
| 921 |
+
});
|
| 922 |
+
},
|
| 923 |
+
});
|
comfyui-robin/web/robin_badge.svg
ADDED
|
|
comfyui-workflow-examples/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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"id": "86cca837-81dd-4e53-84c1-9ba8bed1996c",
|
| 3 |
+
"revision": 0,
|
| 4 |
+
"last_node_id": 6,
|
| 5 |
+
"last_link_id": 6,
|
| 6 |
+
"nodes": [
|
| 7 |
+
{
|
| 8 |
+
"id": 1,
|
| 9 |
+
"type": "RobinLoader",
|
| 10 |
+
"pos": [
|
| 11 |
+
-392.32904829545515,
|
| 12 |
+
-33.63564275568177
|
| 13 |
+
],
|
| 14 |
+
"size": [
|
| 15 |
+
270,
|
| 16 |
+
228
|
| 17 |
+
],
|
| 18 |
+
"flags": {},
|
| 19 |
+
"order": 0,
|
| 20 |
+
"mode": 0,
|
| 21 |
+
"inputs": [],
|
| 22 |
+
"outputs": [
|
| 23 |
+
{
|
| 24 |
+
"color_off": null,
|
| 25 |
+
"color_on": null,
|
| 26 |
+
"dir": null,
|
| 27 |
+
"label": null,
|
| 28 |
+
"locked": null,
|
| 29 |
+
"name": "robin",
|
| 30 |
+
"nameLocked": null,
|
| 31 |
+
"removable": null,
|
| 32 |
+
"type": "ROBIN_MODEL",
|
| 33 |
+
"pos": null,
|
| 34 |
+
"slot_index": null,
|
| 35 |
+
"links": [
|
| 36 |
+
1
|
| 37 |
+
]
|
| 38 |
+
}
|
| 39 |
+
],
|
| 40 |
+
"properties": {
|
| 41 |
+
"Node name for S&R": "RobinLoader"
|
| 42 |
+
},
|
| 43 |
+
"widgets_values": [
|
| 44 |
+
"robin",
|
| 45 |
+
"robin_vae.safetensors",
|
| 46 |
+
"default",
|
| 47 |
+
"bf16"
|
| 48 |
+
],
|
| 49 |
+
"widgets_values_named": {
|
| 50 |
+
"model": "robin",
|
| 51 |
+
"vae": "robin_vae.safetensors",
|
| 52 |
+
"device": "default",
|
| 53 |
+
"dtype": "bf16"
|
| 54 |
+
},
|
| 55 |
+
"color": "#D9302A",
|
| 56 |
+
"bgcolor": "#1B1B1C"
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"id": 2,
|
| 60 |
+
"type": "RobinLoRA",
|
| 61 |
+
"pos": [
|
| 62 |
+
-104.10679687500026,
|
| 63 |
+
-33.72109375000033
|
| 64 |
+
],
|
| 65 |
+
"size": [
|
| 66 |
+
273.69144531250004,
|
| 67 |
+
95.80156249999999
|
| 68 |
+
],
|
| 69 |
+
"flags": {},
|
| 70 |
+
"order": 1,
|
| 71 |
+
"mode": 0,
|
| 72 |
+
"inputs": [
|
| 73 |
+
{
|
| 74 |
+
"color_off": null,
|
| 75 |
+
"color_on": null,
|
| 76 |
+
"dir": null,
|
| 77 |
+
"label": null,
|
| 78 |
+
"locked": null,
|
| 79 |
+
"name": "robin",
|
| 80 |
+
"nameLocked": null,
|
| 81 |
+
"removable": null,
|
| 82 |
+
"type": "ROBIN_MODEL",
|
| 83 |
+
"pos": null,
|
| 84 |
+
"link": 1
|
| 85 |
+
}
|
| 86 |
+
],
|
| 87 |
+
"outputs": [
|
| 88 |
+
{
|
| 89 |
+
"color_off": null,
|
| 90 |
+
"color_on": null,
|
| 91 |
+
"dir": null,
|
| 92 |
+
"label": null,
|
| 93 |
+
"locked": null,
|
| 94 |
+
"name": "robin",
|
| 95 |
+
"nameLocked": null,
|
| 96 |
+
"removable": null,
|
| 97 |
+
"type": "ROBIN_MODEL",
|
| 98 |
+
"pos": null,
|
| 99 |
+
"slot_index": null,
|
| 100 |
+
"links": [
|
| 101 |
+
2
|
| 102 |
+
]
|
| 103 |
+
}
|
| 104 |
+
],
|
| 105 |
+
"properties": {
|
| 106 |
+
"Node name for S&R": "RobinLoRA"
|
| 107 |
+
},
|
| 108 |
+
"widgets_values": [
|
| 109 |
+
"robin_character_lora.safetensors",
|
| 110 |
+
1
|
| 111 |
+
],
|
| 112 |
+
"widgets_values_named": {
|
| 113 |
+
"lora": "robin_character_lora.safetensors",
|
| 114 |
+
"strength": 1
|
| 115 |
+
},
|
| 116 |
+
"color": "#D9302A",
|
| 117 |
+
"bgcolor": "#1B1B1C"
|
| 118 |
+
},
|
| 119 |
+
{
|
| 120 |
+
"id": 3,
|
| 121 |
+
"type": "RobinSpeak",
|
| 122 |
+
"pos": [
|
| 123 |
+
186.8995703125007,
|
| 124 |
+
-34.50097656249985
|
| 125 |
+
],
|
| 126 |
+
"size": [
|
| 127 |
+
561.74609375,
|
| 128 |
+
456.31640625
|
| 129 |
+
],
|
| 130 |
+
"flags": {},
|
| 131 |
+
"order": 2,
|
| 132 |
+
"mode": 0,
|
| 133 |
+
"showAdvanced": false,
|
| 134 |
+
"inputs": [
|
| 135 |
+
{
|
| 136 |
+
"color_off": null,
|
| 137 |
+
"color_on": null,
|
| 138 |
+
"dir": null,
|
| 139 |
+
"label": null,
|
| 140 |
+
"locked": null,
|
| 141 |
+
"name": "robin",
|
| 142 |
+
"nameLocked": null,
|
| 143 |
+
"removable": null,
|
| 144 |
+
"type": "ROBIN_MODEL",
|
| 145 |
+
"pos": null,
|
| 146 |
+
"link": 2
|
| 147 |
+
}
|
| 148 |
+
],
|
| 149 |
+
"outputs": [
|
| 150 |
+
{
|
| 151 |
+
"color_off": "#F2EEE6",
|
| 152 |
+
"color_on": "#F2EEE6",
|
| 153 |
+
"dir": null,
|
| 154 |
+
"label": null,
|
| 155 |
+
"locked": null,
|
| 156 |
+
"name": "audio",
|
| 157 |
+
"nameLocked": null,
|
| 158 |
+
"removable": null,
|
| 159 |
+
"type": "AUDIO",
|
| 160 |
+
"pos": null,
|
| 161 |
+
"slot_index": null,
|
| 162 |
+
"links": []
|
| 163 |
+
}
|
| 164 |
+
],
|
| 165 |
+
"properties": {
|
| 166 |
+
"Node name for S&R": "RobinSpeak"
|
| 167 |
+
},
|
| 168 |
+
"widgets_values": [
|
| 169 |
+
"[cough] If you are enjoying the Robin audio experience, don't forget to check out Lattice at fixedseed.com. It's the same folks that trained me. They make pretty cool stuff! ",
|
| 170 |
+
"",
|
| 171 |
+
7372229196,
|
| 172 |
+
"fixed",
|
| 173 |
+
0.9,
|
| 174 |
+
25,
|
| 175 |
+
0.8,
|
| 176 |
+
1,
|
| 177 |
+
2,
|
| 178 |
+
35,
|
| 179 |
+
"English"
|
| 180 |
+
],
|
| 181 |
+
"widgets_values_named": {
|
| 182 |
+
"text": "[cough] If you are enjoying the Robin audio experience, don't forget to check out Lattice at fixedseed.com. It's the same folks that trained me. They make pretty cool stuff! ",
|
| 183 |
+
"voice": "",
|
| 184 |
+
"seed": 7372229196,
|
| 185 |
+
"control_after_generate": "fixed",
|
| 186 |
+
"temperature": 0.9,
|
| 187 |
+
"top_k": 25,
|
| 188 |
+
"top_p": 0.8,
|
| 189 |
+
"cfg": 1,
|
| 190 |
+
"retries": 2,
|
| 191 |
+
"max_words": 35,
|
| 192 |
+
"language": "English"
|
| 193 |
+
},
|
| 194 |
+
"color": "#D9302A",
|
| 195 |
+
"bgcolor": "#1B1B1C"
|
| 196 |
+
}
|
| 197 |
+
],
|
| 198 |
+
"links": [
|
| 199 |
+
[
|
| 200 |
+
1,
|
| 201 |
+
1,
|
| 202 |
+
0,
|
| 203 |
+
2,
|
| 204 |
+
0,
|
| 205 |
+
"ROBIN_MODEL"
|
| 206 |
+
],
|
| 207 |
+
[
|
| 208 |
+
2,
|
| 209 |
+
2,
|
| 210 |
+
0,
|
| 211 |
+
3,
|
| 212 |
+
0,
|
| 213 |
+
"ROBIN_MODEL"
|
| 214 |
+
]
|
| 215 |
+
],
|
| 216 |
+
"groups": [],
|
| 217 |
+
"config": {},
|
| 218 |
+
"extra": {
|
| 219 |
+
"ds": {
|
| 220 |
+
"scale": 1.3310000000000004,
|
| 221 |
+
"offset": [
|
| 222 |
+
476.52244566790915,
|
| 223 |
+
185.40094442863185
|
| 224 |
+
]
|
| 225 |
+
},
|
| 226 |
+
"frontendVersion": "1.51.10"
|
| 227 |
+
},
|
| 228 |
+
"version": 0.4
|
| 229 |
+
}
|
comfyui-workflow-examples/Robin - LoRA Voice Training Official.json
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"id": "86cca837-81dd-4e53-84c1-9ba8bed1996c",
|
| 3 |
+
"revision": 0,
|
| 4 |
+
"last_node_id": 8,
|
| 5 |
+
"last_link_id": 9,
|
| 6 |
+
"nodes": [
|
| 7 |
+
{
|
| 8 |
+
"id": 1,
|
| 9 |
+
"type": "RobinLoader",
|
| 10 |
+
"pos": [
|
| 11 |
+
-280.51970880681864,
|
| 12 |
+
-197.51446377840895
|
| 13 |
+
],
|
| 14 |
+
"size": [
|
| 15 |
+
270,
|
| 16 |
+
228
|
| 17 |
+
],
|
| 18 |
+
"flags": {},
|
| 19 |
+
"order": 0,
|
| 20 |
+
"mode": 0,
|
| 21 |
+
"inputs": [],
|
| 22 |
+
"outputs": [
|
| 23 |
+
{
|
| 24 |
+
"color_off": null,
|
| 25 |
+
"color_on": null,
|
| 26 |
+
"dir": null,
|
| 27 |
+
"label": null,
|
| 28 |
+
"locked": null,
|
| 29 |
+
"name": "robin",
|
| 30 |
+
"nameLocked": null,
|
| 31 |
+
"removable": null,
|
| 32 |
+
"type": "ROBIN_MODEL",
|
| 33 |
+
"pos": null,
|
| 34 |
+
"slot_index": null,
|
| 35 |
+
"links": [
|
| 36 |
+
7
|
| 37 |
+
]
|
| 38 |
+
}
|
| 39 |
+
],
|
| 40 |
+
"properties": {
|
| 41 |
+
"Node name for S&R": "RobinLoader"
|
| 42 |
+
},
|
| 43 |
+
"widgets_values": [
|
| 44 |
+
"robin",
|
| 45 |
+
"robin_vae.safetensors",
|
| 46 |
+
"default",
|
| 47 |
+
"bf16"
|
| 48 |
+
],
|
| 49 |
+
"widgets_values_named": {
|
| 50 |
+
"model": "robin",
|
| 51 |
+
"vae": "robin_vae.safetensors",
|
| 52 |
+
"device": "default",
|
| 53 |
+
"dtype": "bf16"
|
| 54 |
+
},
|
| 55 |
+
"color": "#D9302A",
|
| 56 |
+
"bgcolor": "#1B1B1C"
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"id": 8,
|
| 60 |
+
"type": "RobinCheckDataset",
|
| 61 |
+
"pos": [
|
| 62 |
+
-451.8397117624823,
|
| 63 |
+
70.40017913917423
|
| 64 |
+
],
|
| 65 |
+
"size": [
|
| 66 |
+
440,
|
| 67 |
+
394
|
| 68 |
+
],
|
| 69 |
+
"flags": {},
|
| 70 |
+
"order": 1,
|
| 71 |
+
"mode": 0,
|
| 72 |
+
"inputs": [],
|
| 73 |
+
"outputs": [
|
| 74 |
+
{
|
| 75 |
+
"name": "dataset",
|
| 76 |
+
"type": "ROBIN_DATASET",
|
| 77 |
+
"links": [
|
| 78 |
+
9
|
| 79 |
+
]
|
| 80 |
+
},
|
| 81 |
+
{
|
| 82 |
+
"name": "report",
|
| 83 |
+
"type": "STRING",
|
| 84 |
+
"links": null
|
| 85 |
+
}
|
| 86 |
+
],
|
| 87 |
+
"properties": {
|
| 88 |
+
"Node name for S&R": "RobinCheckDataset"
|
| 89 |
+
},
|
| 90 |
+
"widgets_values": [
|
| 91 |
+
"",
|
| 92 |
+
"English"
|
| 93 |
+
],
|
| 94 |
+
"widgets_values_named": {
|
| 95 |
+
"folder": "",
|
| 96 |
+
"language": "English"
|
| 97 |
+
},
|
| 98 |
+
"color": "#D9302A",
|
| 99 |
+
"bgcolor": "#1B1B1C"
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"id": 7,
|
| 103 |
+
"type": "RobinTrainLoRA",
|
| 104 |
+
"pos": [
|
| 105 |
+
21.434194487518035,
|
| 106 |
+
-197.34760850287083
|
| 107 |
+
],
|
| 108 |
+
"size": [
|
| 109 |
+
457.283380681818,
|
| 110 |
+
611.6058238636364
|
| 111 |
+
],
|
| 112 |
+
"flags": {},
|
| 113 |
+
"order": 2,
|
| 114 |
+
"mode": 0,
|
| 115 |
+
"showAdvanced": true,
|
| 116 |
+
"inputs": [
|
| 117 |
+
{
|
| 118 |
+
"name": "robin",
|
| 119 |
+
"type": "ROBIN_MODEL",
|
| 120 |
+
"link": 7
|
| 121 |
+
},
|
| 122 |
+
{
|
| 123 |
+
"name": "dataset",
|
| 124 |
+
"type": "ROBIN_DATASET",
|
| 125 |
+
"link": 9
|
| 126 |
+
}
|
| 127 |
+
],
|
| 128 |
+
"outputs": [
|
| 129 |
+
{
|
| 130 |
+
"name": "robin",
|
| 131 |
+
"type": "ROBIN_MODEL",
|
| 132 |
+
"links": null
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"name": "lora_name",
|
| 136 |
+
"type": "STRING",
|
| 137 |
+
"links": null
|
| 138 |
+
}
|
| 139 |
+
],
|
| 140 |
+
"properties": {
|
| 141 |
+
"Node name for S&R": "RobinTrainLoRA"
|
| 142 |
+
},
|
| 143 |
+
"widgets_values": [
|
| 144 |
+
"my_voice",
|
| 145 |
+
1000,
|
| 146 |
+
200,
|
| 147 |
+
"Hello there! This is a quick test of my new voice. How does it sound to you?",
|
| 148 |
+
false,
|
| 149 |
+
32,
|
| 150 |
+
64,
|
| 151 |
+
0.00005,
|
| 152 |
+
0.0002,
|
| 153 |
+
8,
|
| 154 |
+
0
|
| 155 |
+
],
|
| 156 |
+
"widgets_values_named": {
|
| 157 |
+
"name": "my_voice",
|
| 158 |
+
"steps": 1000,
|
| 159 |
+
"save_every": 200,
|
| 160 |
+
"sample_text": "Hello there! This is a quick test of my new voice. How does it sound to you?",
|
| 161 |
+
"restart": false,
|
| 162 |
+
"rank_planner": 32,
|
| 163 |
+
"rank_decoder": 64,
|
| 164 |
+
"lr_planner": 0.00005,
|
| 165 |
+
"lr_decoder": 0.0002,
|
| 166 |
+
"clips_per_step": 8,
|
| 167 |
+
"seed": 0
|
| 168 |
+
},
|
| 169 |
+
"color": "#D9302A",
|
| 170 |
+
"bgcolor": "#1B1B1C"
|
| 171 |
+
}
|
| 172 |
+
],
|
| 173 |
+
"links": [
|
| 174 |
+
[
|
| 175 |
+
7,
|
| 176 |
+
1,
|
| 177 |
+
0,
|
| 178 |
+
7,
|
| 179 |
+
0,
|
| 180 |
+
"ROBIN_MODEL"
|
| 181 |
+
],
|
| 182 |
+
[
|
| 183 |
+
9,
|
| 184 |
+
8,
|
| 185 |
+
0,
|
| 186 |
+
7,
|
| 187 |
+
1,
|
| 188 |
+
"ROBIN_DATASET"
|
| 189 |
+
]
|
| 190 |
+
],
|
| 191 |
+
"groups": [],
|
| 192 |
+
"config": {},
|
| 193 |
+
"extra": {
|
| 194 |
+
"ds": {
|
| 195 |
+
"scale": 1.1,
|
| 196 |
+
"offset": [
|
| 197 |
+
767.8659901715729,
|
| 198 |
+
334.53234926991666
|
| 199 |
+
]
|
| 200 |
+
},
|
| 201 |
+
"frontendVersion": "1.51.10"
|
| 202 |
+
},
|
| 203 |
+
"version": 0.4
|
| 204 |
+
}
|
config.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model": {
|
| 3 |
+
"vocab_size": 184704,
|
| 4 |
+
"hidden_size": 2048,
|
| 5 |
+
"intermediate_size": 6144,
|
| 6 |
+
"num_hidden_layers": 28,
|
| 7 |
+
"num_attention_heads": 16,
|
| 8 |
+
"num_key_value_heads": 8,
|
| 9 |
+
"head_dim": 128,
|
| 10 |
+
"rope_theta": 1000000.0,
|
| 11 |
+
"rms_norm_eps": 1e-06,
|
| 12 |
+
"max_position_embeddings": 24576,
|
| 13 |
+
"latent_dim": 64
|
| 14 |
+
},
|
| 15 |
+
"tokens": {
|
| 16 |
+
"eod": 151643,
|
| 17 |
+
"score_start": 151847,
|
| 18 |
+
"score_end": 151848,
|
| 19 |
+
"audio_start": 151851,
|
| 20 |
+
"audio_end": 151852,
|
| 21 |
+
"audio_offset": 151853,
|
| 22 |
+
"audio_codes": 6561
|
| 23 |
+
},
|
| 24 |
+
"instruction": "Generate music with codec tokens from the given conditions.",
|
| 25 |
+
"sampling": {
|
| 26 |
+
"temperature": 0.9,
|
| 27 |
+
"top_k": 25,
|
| 28 |
+
"top_p": 0.8,
|
| 29 |
+
"pause_guard": 40,
|
| 30 |
+
"guard_distinct": 4,
|
| 31 |
+
"decoder_steps": 32,
|
| 32 |
+
"decoder_sampler": "dpm_2"
|
| 33 |
+
},
|
| 34 |
+
"audio": {
|
| 35 |
+
"sample_rate": 48000,
|
| 36 |
+
"frame_rate": 25
|
| 37 |
+
}
|
| 38 |
+
}
|
images/banner.png
ADDED
|
images/comfyui-speak.png
ADDED
|
Git LFS Details
|
images/comfyui-train.png
ADDED
|
Git LFS Details
|
images/pill-github.png
AD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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Fixed Seed Open License
|
| 3 |
+
Version 1.0, November 2026
|
| 4 |
+
|
| 5 |
+
This License is based on the Apache License, Version 2.0. It adds a
|
| 6 |
+
limit on Commercial Use above a revenue threshold (Section 5), a section
|
| 7 |
+
on Output (Section 6), termination (Section 12) and governing law
|
| 8 |
+
(Section 13), and makes the grants in Sections 2 and 3 subject to the
|
| 9 |
+
limit. Fixed Seed may publish new versions of this License; a Work
|
| 10 |
+
stays under the version it was released with.
|
| 11 |
+
|
| 12 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 13 |
+
|
| 14 |
+
1. Definitions.
|
| 15 |
+
|
| 16 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 17 |
+
and distribution as defined by Sections 1 through 13 of this document.
|
| 18 |
+
|
| 19 |
+
"Licensor" shall mean Fixed Seed LLC, a California limited liability
|
| 20 |
+
company doing business as Fixed Seed Research Laboratory ("Fixed
|
| 21 |
+
Seed").
|
| 22 |
+
|
| 23 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 24 |
+
other entities that control, are controlled by, or are under common
|
| 25 |
+
control with that entity. For the purposes of this definition,
|
| 26 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 27 |
+
direction or management of such entity, whether by contract or
|
| 28 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 29 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 30 |
+
|
| 31 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 32 |
+
exercising permissions granted by this License.
|
| 33 |
+
|
| 34 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 35 |
+
including but not limited to model weights and parameters, software
|
| 36 |
+
source code, documentation source, and configuration files.
|
| 37 |
+
|
| 38 |
+
"Object" form shall mean any form resulting from mechanical
|
| 39 |
+
transformation or translation of a Source form, including but
|
| 40 |
+
not limited to compiled object code, generated documentation,
|
| 41 |
+
and conversions to other media types.
|
| 42 |
+
|
| 43 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 44 |
+
Object form, made available under the License, as indicated by a
|
| 45 |
+
copyright notice that is included in or attached to the work
|
| 46 |
+
(an example is provided in the Appendix below).
|
| 47 |
+
|
| 48 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 49 |
+
form, that is based on (or derived from) the Work and for which the
|
| 50 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 51 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 52 |
+
of this License, Derivative Works shall not include works that remain
|
| 53 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 54 |
+
the Work and Derivative Works thereof. For the avoidance of doubt,
|
| 55 |
+
Derivative Works include any model, weights or adapter (including
|
| 56 |
+
LoRA and similar adapter weights) made by training, fine-tuning,
|
| 57 |
+
merging, quantizing, pruning or distilling the Work or a Derivative
|
| 58 |
+
Work.
|
| 59 |
+
|
| 60 |
+
"Contribution" shall mean any work of authorship, including
|
| 61 |
+
the original version of the Work and any modifications or additions
|
| 62 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 63 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 64 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 65 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 66 |
+
means any form of electronic, verbal, or written communication sent
|
| 67 |
+
to the Licensor or its representatives, including but not limited to
|
| 68 |
+
communication on electronic mailing lists, source code control systems,
|
| 69 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 70 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 71 |
+
excluding communication that is conspicuously marked or otherwise
|
| 72 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 73 |
+
|
| 74 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 75 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 76 |
+
subsequently incorporated within the Work.
|
| 77 |
+
|
| 78 |
+
"Output" shall mean audio, speech, speech tokens, latents and any
|
| 79 |
+
other content generated by running the Work or a Derivative Work.
|
| 80 |
+
|
| 81 |
+
"Commercial Use" shall mean any use of the Work, a Derivative Work or
|
| 82 |
+
Output that is directed toward commercial advantage or monetary
|
| 83 |
+
compensation, including offering the Work or a Derivative Work, or
|
| 84 |
+
access to either, as a product or service, and using the Work, a
|
| 85 |
+
Derivative Work or Output in or to make products, services or
|
| 86 |
+
content that are sold, licensed or otherwise monetized.
|
| 87 |
+
|
| 88 |
+
"Attributable Revenue" shall mean the gross revenue, before
|
| 89 |
+
deductions of any kind, that You receive from (i) the Work or any
|
| 90 |
+
Derivative Work, or access to either (for example through an
|
| 91 |
+
application, an API or a hosted service), and (ii) any product,
|
| 92 |
+
service or content that uses, includes or was made with the Work, a
|
| 93 |
+
Derivative Work or Output, including through sales, subscriptions,
|
| 94 |
+
licensing, advertising and usage fees. Revenue from such a product,
|
| 95 |
+
service or content counts in full and is not apportioned among its
|
| 96 |
+
parts. Where You are a Legal Entity, Attributable Revenue includes
|
| 97 |
+
the revenue of every entity that makes up that Legal Entity.
|
| 98 |
+
|
| 99 |
+
"Threshold" shall mean two million United States dollars
|
| 100 |
+
(US$2,000,000) of Attributable Revenue in any period of twelve (12)
|
| 101 |
+
consecutive months.
|
| 102 |
+
|
| 103 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 104 |
+
this License, including the Commercial Use Limitation in Section 5,
|
| 105 |
+
each Contributor hereby grants to You a perpetual, worldwide,
|
| 106 |
+
non-exclusive, no-charge, royalty-free, irrevocable (except as stated
|
| 107 |
+
in Sections 5 and 12) copyright license to reproduce, prepare
|
| 108 |
+
Derivative Works of, publicly display, publicly perform, sublicense,
|
| 109 |
+
and distribute the Work and such Derivative Works in Source or
|
| 110 |
+
Object form.
|
| 111 |
+
|
| 112 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 113 |
+
this License, including the Commercial Use Limitation in Section 5,
|
| 114 |
+
each Contributor hereby grants to You a perpetual, worldwide,
|
| 115 |
+
non-exclusive, no-charge, royalty-free, irrevocable (except as stated
|
| 116 |
+
in this section and in Sections 5 and 12) patent license to make,
|
| 117 |
+
have made, use, offer to sell, sell, import, and otherwise transfer
|
| 118 |
+
the Work,
|
| 119 |
+
where such license applies only to those patent claims licensable
|
| 120 |
+
by such Contributor that are necessarily infringed by their
|
| 121 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 122 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 123 |
+
institute patent litigation against any entity (including a
|
| 124 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 125 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 126 |
+
or contributory patent infringement, then any patent licenses
|
| 127 |
+
granted to You under this License for that Work shall terminate
|
| 128 |
+
as of the date such litigation is filed.
|
| 129 |
+
|
| 130 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 131 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 132 |
+
modifications, and in Source or Object form, provided that You
|
| 133 |
+
meet the following conditions:
|
| 134 |
+
|
| 135 |
+
(a) You must give any other recipients of the Work or
|
| 136 |
+
Derivative Works a copy of this License; and
|
| 137 |
+
|
| 138 |
+
(b) You must cause any modified files to carry prominent notices
|
| 139 |
+
stating that You changed the files; and
|
| 140 |
+
|
| 141 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 142 |
+
that You distribute, all copyright, patent, trademark, and
|
| 143 |
+
attribution notices from the Source form of the Work,
|
| 144 |
+
excluding those notices that do not pertain to any part of
|
| 145 |
+
the Derivative Works; and
|
| 146 |
+
|
| 147 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 148 |
+
distribution, then any Derivative Works that You distribute must
|
| 149 |
+
include a readable copy of the attribution notices contained
|
| 150 |
+
within such NOTICE file, excluding those notices that do not
|
| 151 |
+
pertain to any part of the Derivative Works, in at least one
|
| 152 |
+
of the following places: within a NOTICE text file distributed
|
| 153 |
+
as part of the Derivative Works; within the Source form or
|
| 154 |
+
documentation, if provided along with the Derivative Works; or,
|
| 155 |
+
within a display generated by the Derivative Works, if and
|
| 156 |
+
wherever such third-party notices normally appear. The contents
|
| 157 |
+
of the NOTICE file are for informational purposes only and
|
| 158 |
+
do not modify the License. You may add Your own attribution
|
| 159 |
+
notices within Derivative Works that You distribute, alongside
|
| 160 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 161 |
+
that such additional attribution notices cannot be construed
|
| 162 |
+
as modifying the License.
|
| 163 |
+
|
| 164 |
+
(e) You must distribute the Work and any Derivative Works under the
|
| 165 |
+
terms of this License, so that every recipient's Commercial Use
|
| 166 |
+
is subject to Section 5.
|
| 167 |
+
|
| 168 |
+
You may add Your own copyright statement to Your modifications and
|
| 169 |
+
may provide additional or different license terms and conditions
|
| 170 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 171 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 172 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 173 |
+
the conditions stated in this License, and provided that no such
|
| 174 |
+
terms remove or limit Section 5 for any recipient.
|
| 175 |
+
|
| 176 |
+
5. Commercial Use Limitation.
|
| 177 |
+
|
| 178 |
+
(a) Below the Threshold. You may make Commercial Use of the Work,
|
| 179 |
+
Derivative Works and Output under this License for as long as
|
| 180 |
+
Your Attributable Revenue has not exceeded the Threshold.
|
| 181 |
+
|
| 182 |
+
(b) Above the Threshold. If Your Attributable Revenue exceeds the
|
| 183 |
+
Threshold, You must tell Fixed Seed in writing within thirty (30)
|
| 184 |
+
days, at support@fixedseed.com or at another address Fixed Seed
|
| 185 |
+
publishes for this purpose, so that You and Fixed Seed can discuss
|
| 186 |
+
a separate commercial license. Your Commercial Use may continue
|
| 187 |
+
under this License for ninety (90) days after Your Attributable
|
| 188 |
+
Revenue first exceeded the Threshold, while You and Fixed Seed
|
| 189 |
+
negotiate in good faith. After that, this License grants You no
|
| 190 |
+
rights for Commercial Use, and Commercial Use requires a separate
|
| 191 |
+
written agreement with Fixed Seed. Fixed Seed may extend that
|
| 192 |
+
period in writing.
|
| 193 |
+
|
| 194 |
+
(c) Other use. Use that is not Commercial Use, such as personal use,
|
| 195 |
+
research, education and evaluation, is not limited by this
|
| 196 |
+
Section, whatever Your revenue.
|
| 197 |
+
|
| 198 |
+
(d) Good faith. If Fixed Seed asks in writing, You will tell Fixed
|
| 199 |
+
Seed in good faith whether Your Attributable Revenue has
|
| 200 |
+
exceeded the Threshold.
|
| 201 |
+
|
| 202 |
+
6. Output. Fixed Seed claims no ownership of Output. You are responsible
|
| 203 |
+
for Output and for how You use it, including for having any rights
|
| 204 |
+
You need in the text, recordings and other material You give the
|
| 205 |
+
Work or a Derivative Work. Commercial Use of Output is subject to
|
| 206 |
+
Section 5.
|
| 207 |
+
|
| 208 |
+
7. Submission of Contributions. Unless You explicitly state otherwise,
|
| 209 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 210 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 211 |
+
this License, without any additional terms or conditions.
|
| 212 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 213 |
+
the terms of any separate license agreement you may have executed
|
| 214 |
+
with Licensor regarding such Contributions.
|
| 215 |
+
|
| 216 |
+
8. Trademarks. This License does not grant permission to use the trade
|
| 217 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 218 |
+
except as required for reasonable and customary use in describing the
|
| 219 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 220 |
+
|
| 221 |
+
9. Disclaimer of Warranty. Unless required by applicable law or
|
| 222 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 223 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 224 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 225 |
+
implied, including, without limitation, any warranties or conditions
|
| 226 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 227 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 228 |
+
appropriateness of using or redistributing the Work and assume any
|
| 229 |
+
risks associated with Your exercise of permissions under this License.
|
| 230 |
+
|
| 231 |
+
10. Limitation of Liability. In no event and under no legal theory,
|
| 232 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 233 |
+
unless required by applicable law (such as deliberate and grossly
|
| 234 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 235 |
+
liable to You for damages, including any direct, indirect, special,
|
| 236 |
+
incidental, or consequential damages of any character arising as a
|
| 237 |
+
result of this License or out of the use or inability to use the
|
| 238 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 239 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 240 |
+
other commercial damages or losses), even if such Contributor
|
| 241 |
+
has been advised of the possibility of such damages.
|
| 242 |
+
|
| 243 |
+
11. Accepting Warranty or Additional Liability. While redistributing
|
| 244 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 245 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 246 |
+
or other liability obligations and/or rights consistent with this
|
| 247 |
+
License. However, in accepting such obligations, You may act only
|
| 248 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 249 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 250 |
+
defend, and hold each Contributor harmless for any liability
|
| 251 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 252 |
+
of your accepting any such warranty or additional liability.
|
| 253 |
+
|
| 254 |
+
12. Termination. If You fail to comply with any term of this License,
|
| 255 |
+
Your rights under it terminate automatically. They are reinstated if
|
| 256 |
+
You cure the failure within thirty (30) days after You first learn of
|
| 257 |
+
it, unless You have failed to comply with this License before.
|
| 258 |
+
Termination does not end the licenses of anyone who received the Work
|
| 259 |
+
or a Derivative Work from You and complies with this License.
|
| 260 |
+
Sections 9, 10, 12 and 13 survive termination.
|
| 261 |
+
|
| 262 |
+
13. Governing Law. This License is governed by the laws of the State of
|
| 263 |
+
California, without regard to its conflict-of-laws rules.
|
| 264 |
+
|
| 265 |
+
END OF TERMS AND CONDITIONS
|
| 266 |
+
|
| 267 |
+
APPENDIX: How to apply this License to your work.
|
| 268 |
+
|
| 269 |
+
Include a copy of this License with the Work, and a NOTICE file that
|
| 270 |
+
names the Work and its copyright owner, for example:
|
| 271 |
+
|
| 272 |
+
Robin
|
| 273 |
+
Copyright 2026 Fixed Seed LLC
|
| 274 |
+
|
| 275 |
+
Licensed under the Fixed Seed Open License, Version 1.0 (the
|
| 276 |
+
"License"); you may not use this file except in compliance with the
|
| 277 |
+
License. You may obtain a copy of the License in the LICENSE file
|
| 278 |
+
distributed with this Work.
|
| 279 |
+
|
| 280 |
+
Unless required by applicable law or agreed to in writing, software
|
| 281 |
+
and models distributed under the License are distributed on an
|
| 282 |
+
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
|
| 283 |
+
express or implied. See the License for the specific language
|
| 284 |
+
governing permissions and limitations under the License.
|
package/pyproject.toml
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[project]
|
| 2 |
+
name = "robin"
|
| 3 |
+
version = "0.1.0"
|
| 4 |
+
license = { file = "LICENSE" }
|
| 5 |
+
requires-python = ">=3.10"
|
| 6 |
+
dependencies = ["torch>=2.5", "torchaudio", "safetensors", "tokenizers", "huggingface_hub", "numpy", "soundfile", "s3tokenizer>=0.3.0"]
|
| 7 |
+
|
| 8 |
+
[project.optional-dependencies]
|
| 9 |
+
gui = ["gradio>=6"]
|
| 10 |
+
|
| 11 |
+
[build-system]
|
| 12 |
+
requires = ["setuptools>=68"]
|
| 13 |
+
build-backend = "setuptools.build_meta"
|
| 14 |
+
|
| 15 |
+
[tool.setuptools]
|
| 16 |
+
packages = ["robin"]
|
package/requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch>=2.5
|
| 2 |
+
torchaudio
|
| 3 |
+
safetensors
|
| 4 |
+
tokenizers
|
| 5 |
+
huggingface_hub
|
| 6 |
+
numpy
|
| 7 |
+
soundfile
|
| 8 |
+
s3tokenizer>=0.3.0
|
package/robin/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .pipeline import Cancelled, Robin
|
| 2 |
+
|
| 3 |
+
__all__ = ['Cancelled', 'Robin']
|
package/robin/__main__.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def model_args(p, required=True):
|
| 6 |
+
p.add_argument('--model', required=required, help='a weights folder or Hugging Face repo')
|
| 7 |
+
p.add_argument('--vae', help='the VAE weights (.safetensors); by default the robin_vae.safetensors in the --model folder')
|
| 8 |
+
p.add_argument('--device', default='cuda')
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def main():
|
| 12 |
+
p = argparse.ArgumentParser(prog='python -m robin')
|
| 13 |
+
sub = p.add_subparsers(dest='command', required=True)
|
| 14 |
+
|
| 15 |
+
s = sub.add_parser('speak', help='text to speech, and voice changing')
|
| 16 |
+
s.add_argument('text', help='what to say, any length; [laughs] and [coughs] can go inline')
|
| 17 |
+
s.add_argument('--voice', help='the voice in words, e.g. "a warm, low voice, unhurried and close to the mic"')
|
| 18 |
+
s.add_argument('--convert', help='a recording (up to 45 s) to perform again in the --voice (or --lora) voice; the text must be exactly '
|
| 19 |
+
'what it says')
|
| 20 |
+
s.add_argument('--lora', help='a LoRA file trained with "python -m robin train"')
|
| 21 |
+
s.add_argument('--lora-scale', type=float, default=1., help='how strongly the LoRA applies (1 = as trained)')
|
| 22 |
+
s.add_argument('--lang', default='en', choices=('en', 'ja', 'mix'))
|
| 23 |
+
s.add_argument('--as-written', action='store_true', help='read English exactly as typed, without spelling out numbers, symbols and '
|
| 24 |
+
'abbreviations first')
|
| 25 |
+
s.add_argument('--seed', type=int, default=0)
|
| 26 |
+
s.add_argument('--temperature', type=float); s.add_argument('--top-k', type=int); s.add_argument('--top-p', type=float)
|
| 27 |
+
s.add_argument('--cfg', type=float, default=1., help='above 1 follows --voice more closely (try 3)')
|
| 28 |
+
s.add_argument('--steps', type=int); s.add_argument('--sampler', choices=('dpm_2', 'dpmpp_2m'))
|
| 29 |
+
s.add_argument('--out', default='robin.flac')
|
| 30 |
+
model_args(s)
|
| 31 |
+
|
| 32 |
+
g = sub.add_parser('gui', help='Robin in your browser: speak, change voices and train voices')
|
| 33 |
+
g.add_argument('--out', default='robin_studio', help='where saved takes and trained voices go')
|
| 34 |
+
g.add_argument('--host', default='127.0.0.1'); g.add_argument('--port', type=int, default=7860)
|
| 35 |
+
model_args(g)
|
| 36 |
+
|
| 37 |
+
def data_args(q):
|
| 38 |
+
q.add_argument('data', help='a folder of audio clips, each with a .txt transcript of the same name, plus an optional voice.txt '
|
| 39 |
+
'describing the voice')
|
| 40 |
+
q.add_argument('--lang', default='en', choices=('en', 'ja', 'mix'))
|
| 41 |
+
q.add_argument('--min-seconds', type=float, default=1., help='shorter clips are left out')
|
| 42 |
+
q.add_argument('--max-seconds', type=float, default=30., help='longer clips are left out (split them first)')
|
| 43 |
+
|
| 44 |
+
q = sub.add_parser('prep', help='check a LoRA dataset; with --out, also prepare it for training')
|
| 45 |
+
data_args(q)
|
| 46 |
+
q.add_argument('--out', help='the LoRA folder to prepare (the same --out you will give train)')
|
| 47 |
+
model_args(q, required=False)
|
| 48 |
+
|
| 49 |
+
t = sub.add_parser('train', help='train a LoRA on a voice')
|
| 50 |
+
data_args(t)
|
| 51 |
+
t.add_argument('--out', required=True, help='a folder for the LoRA, its checkpoints and samples')
|
| 52 |
+
t.add_argument('--steps', type=int, default=1000)
|
| 53 |
+
t.add_argument('--save-every', type=int, default=200)
|
| 54 |
+
t.add_argument('--rank-planner', type=int, default=32); t.add_argument('--rank-decoder', type=int, default=64)
|
| 55 |
+
t.add_argument('--lr-planner', type=float, default=5e-5); t.add_argument('--lr-decoder', type=float, default=2e-4)
|
| 56 |
+
t.add_argument('--accum', type=int, default=8, help='clips per step')
|
| 57 |
+
t.add_argument('--sample-text', help='the line rendered at every save, so you can pick a checkpoint by ear')
|
| 58 |
+
t.add_argument('--seed', type=int, default=0)
|
| 59 |
+
t.add_argument('--restart', action='store_true', help='start over instead of continuing an unfinished run')
|
| 60 |
+
model_args(t)
|
| 61 |
+
|
| 62 |
+
a = p.parse_args()
|
| 63 |
+
from .pipeline import Robin
|
| 64 |
+
|
| 65 |
+
if a.command == 'gui':
|
| 66 |
+
try:
|
| 67 |
+
from . import gui
|
| 68 |
+
except ModuleNotFoundError as e:
|
| 69 |
+
if e.name != 'gradio': raise
|
| 70 |
+
raise SystemExit("The GUI needs Gradio: pip install 'robin[gui]'")
|
| 71 |
+
gui.launch(Robin.from_pretrained(a.model, a.vae, device=a.device), a.out, a.host, a.port)
|
| 72 |
+
return
|
| 73 |
+
|
| 74 |
+
if a.command == 'speak':
|
| 75 |
+
import soundfile as sf
|
| 76 |
+
from . import pieces
|
| 77 |
+
tts = Robin.from_pretrained(a.model, a.vae, device=a.device, lora=a.lora, lora_scale=a.lora_scale)
|
| 78 |
+
sampling = dict(temperature=a.temperature, top_k=a.top_k, top_p=a.top_p, steps=a.steps, sampler=a.sampler)
|
| 79 |
+
if a.convert:
|
| 80 |
+
if not (a.voice or a.lora): s.error('--convert needs --voice (a description of the new voice) or --lora')
|
| 81 |
+
x, rate = sf.read(a.convert, dtype='float32', always_2d=True)
|
| 82 |
+
if len(x) / rate > 45: s.error(f'{a.convert} is {len(x) / rate:.0f} s long; convert up to 45 s at a time')
|
| 83 |
+
wav = pieces.change(tts, x.mean(1), rate, a.text, voice=a.voice, lang=a.lang, seed=a.seed, **sampling)
|
| 84 |
+
else:
|
| 85 |
+
wav = pieces.read(tts, a.text, a.voice, lang=a.lang, seed=a.seed, cfg=a.cfg, as_written=a.as_written, **sampling)
|
| 86 |
+
sf.write(a.out, wav, pieces.RATE, subtype='PCM_24')
|
| 87 |
+
print(f'wrote {a.out}: {len(wav) / pieces.RATE:.1f} s')
|
| 88 |
+
return
|
| 89 |
+
|
| 90 |
+
from . import train as tr
|
| 91 |
+
if a.command == 'prep':
|
| 92 |
+
found = tr.scan(a.data, a.lang, a.min_seconds, a.max_seconds); tr.describe(found)
|
| 93 |
+
if a.out:
|
| 94 |
+
if not a.model: q.error('--out needs --model')
|
| 95 |
+
from pathlib import Path
|
| 96 |
+
clips = tr.encode(Robin.from_pretrained(a.model, a.vae, device=a.device), found, Path(a.out)/'cache')
|
| 97 |
+
print(f'{len(clips)} clips prepared in {Path(a.out)/"cache"}')
|
| 98 |
+
return
|
| 99 |
+
|
| 100 |
+
robin = Robin.from_pretrained(a.model, a.vae, device=a.device)
|
| 101 |
+
tr.train(robin, a.data, a.out, lang=a.lang, min_seconds=a.min_seconds, max_seconds=a.max_seconds, restart=a.restart,
|
| 102 |
+
steps=a.steps, save_every=a.save_every, rank_planner=a.rank_planner, rank_decoder=a.rank_decoder, lr_planner=a.lr_planner,
|
| 103 |
+
lr_decoder=a.lr_decoder, accum=a.accum, sample_text=a.sample_text, seed=a.seed)
|
| 104 |
+
|
| 105 |
+
|
| 106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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
import re
|
| 3 |
+
import threading
|
| 4 |
+
import time
|
| 5 |
+
import traceback
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import gradio as gr
|
| 10 |
+
import numpy as np
|
| 11 |
+
import soundfile as sf
|
| 12 |
+
import torch
|
| 13 |
+
|
| 14 |
+
from . import pieces
|
| 15 |
+
from . import train as tr
|
| 16 |
+
from .pipeline import Cancelled
|
| 17 |
+
|
| 18 |
+
LANGUAGES = {'English': 'en', 'Japanese': 'ja', 'English + Japanese': 'mix'}
|
| 19 |
+
MAX_SOURCE_SECONDS = 45
|
| 20 |
+
GROUND, PANEL, LINE, CREAM, RED, RED_FILL, RED_TEXT = '#121212', '#1b1b1c', '#2c2c2d', '#F2EEE6', '#D9302A', '#BF2A24', '#F0564F'
|
| 21 |
+
STEP_LINE = re.compile(r'^step (\d+)/(\d+) .*?\| ([\d.]+) s/step \| (\d+) min left(?: \| GPU ([\d.]+) GB)?')
|
| 22 |
+
NONE = ''
|
| 23 |
+
|
| 24 |
+
CSS = f"""
|
| 25 |
+
.gradio-container {{ max-width: 1200px !important; margin: 0 auto !important; }}
|
| 26 |
+
#robin-head {{ align-items: baseline; border-bottom: 2px solid {RED}; padding: 2px 2px 10px; margin-bottom: 2px; }}
|
| 27 |
+
#robin-head h1 {{ margin: 0; font-size: 34px; line-height: 1; letter-spacing: .32em; font-weight: 800; color: {RED_TEXT}; }}
|
| 28 |
+
#robin-head p {{ margin: 0; color: {CREAM}; opacity: .7; }}
|
| 29 |
+
#adapter {{ border: 1px solid {LINE}; border-radius: 12px; padding: 4px 8px; background: {PANEL}; }}
|
| 30 |
+
.take {{ border: 1px solid {RED}88 !important; border-radius: 12px !important; background: {PANEL} !important; }}
|
| 31 |
+
.kept {{ outline: 2px solid {RED}; }}
|
| 32 |
+
.bar {{ height: 10px; border-radius: 6px; background: {RED}2a; overflow: hidden; }}
|
| 33 |
+
.bar i {{ display: block; height: 100%; background: {RED}; }}
|
| 34 |
+
.summary table {{ width: 100%; }}
|
| 35 |
+
.summary td, .summary th {{ text-align: center !important; }}
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def theme():
|
| 40 |
+
red = gr.themes.Color(c50='#fdf0ef', c100='#fadcd9', c200='#f4b6b1', c300='#ec8a82', c400=RED_TEXT, c500=RED, c600=RED_FILL,
|
| 41 |
+
c700='#9a1f1a', c800='#771814', c900='#55110e', c950='#3a0b09', name='robin')
|
| 42 |
+
look = dict(body_background_fill=GROUND, background_fill_primary=GROUND, background_fill_secondary=PANEL, block_background_fill=PANEL,
|
| 43 |
+
panel_background_fill=PANEL, block_border_color=LINE, border_color_primary=LINE, body_text_color=CREAM,
|
| 44 |
+
body_text_color_subdued='#b8b2a9', block_label_text_color=CREAM, block_title_text_color=CREAM, block_info_text_color='#b8b2a9',
|
| 45 |
+
block_label_background_fill=PANEL, input_background_fill=GROUND, input_border_color='#3a3a3b', input_placeholder_color='#7d7872',
|
| 46 |
+
button_primary_background_fill=RED_FILL, button_primary_background_fill_hover=RED, button_primary_text_color=CREAM,
|
| 47 |
+
button_secondary_background_fill=CREAM, button_secondary_background_fill_hover='#ffffff', button_secondary_text_color=GROUND,
|
| 48 |
+
slider_color=RED, color_accent=RED, color_accent_soft=f'{RED}33', link_text_color=RED_TEXT, checkbox_background_color=GROUND,
|
| 49 |
+
checkbox_background_color_selected=RED_FILL, checkbox_border_color='#3a3a3b')
|
| 50 |
+
base = gr.themes.Base(primary_hue=red, neutral_hue=gr.themes.colors.stone, font=['ui-sans-serif', 'system-ui', 'sans-serif'],
|
| 51 |
+
font_mono=['ui-monospace', 'monospace'])
|
| 52 |
+
return base.set(**look, **{f'{k}_dark': v for k, v in look.items() if hasattr(base, f'{k}_dark')})
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
GUIDE = """
|
| 56 |
+
### The voice learns what's in the folder.
|
| 57 |
+
|
| 58 |
+
You bring the recordings and the transcripts. Clean, consistent audio with exact transcripts makes the biggest difference to how a
|
| 59 |
+
trained voice sounds.
|
| 60 |
+
|
| 61 |
+
```
|
| 62 |
+
my_voice/
|
| 63 |
+
voice.txt (optional: the voice in words)
|
| 64 |
+
line_001.wav
|
| 65 |
+
line_001.txt (what line_001.wav says)
|
| 66 |
+
...
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
The surest way to exact transcripts: write the script first, then record it line by line. The script is the transcript.
|
| 70 |
+
|
| 71 |
+
- **How much:** 20 minutes of speech or more. Our test voice used 23 minutes across 227 clips.
|
| 72 |
+
- **Each clip:** one or two sentences, 3 to 15 seconds. Anything from 1 to 30 seconds is accepted, so split longer takes.
|
| 73 |
+
- **Recording:** one speaker in a quiet, dead-sounding room, with the same mic and distance throughout. No music, effects or other
|
| 74 |
+
voices. Keep peaks around −6 dBFS.
|
| 75 |
+
- **Format:** WAV or FLAC at 44.1 or 48 kHz. Lower rates train a duller top end, and clips below 16 kHz are left out.
|
| 76 |
+
- **Transcripts:** exactly the words spoken. Write numbers the way they're said ("fifty percent"), and put [laughs] or [coughs] where
|
| 77 |
+
they happen. Re-record a stumble instead of transcribing it.
|
| 78 |
+
- **Range:** mix statements, questions and exclamations, short lines and long ones. A calm read trains a calm voice, so record the
|
| 79 |
+
delivery you want back.
|
| 80 |
+
|
| 81 |
+
**What Check data does**
|
| 82 |
+
|
| 83 |
+
- **Leaves out:** no transcript or an empty one, an unreadable file or a format it can't read, below 16 kHz, almost silent, under 1 s
|
| 84 |
+
or over 30 s, a transcript far too long or short for its audio.
|
| 85 |
+
- **Keeps, with a note:** below 44.1 kHz, clipped peaks, digits in a transcript, a transcript that may not match, the same line twice.
|
| 86 |
+
It also points out transcripts that have no audio file.
|
| 87 |
+
|
| 88 |
+
Train on voices you have the rights to use.
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
def read_mono(path):
|
| 92 |
+
x, rate = sf.read(str(path), dtype='float32', always_2d=True)
|
| 93 |
+
return np.ascontiguousarray(x.mean(1)), rate
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def slug(text, n=40):
|
| 97 |
+
return re.sub(r'[^a-z0-9]+', '-', text.lower())[:n].strip('-')
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def new_seed():
|
| 101 |
+
return random.randrange(2 ** 31)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class Meter:
|
| 105 |
+
def __init__(self, progress, renders, halt, label):
|
| 106 |
+
self.progress, self.total, self.done, self.halt, self.label = progress, max(1, renders), 0, halt, label
|
| 107 |
+
self.expected, self.frac = 1., 0.
|
| 108 |
+
|
| 109 |
+
def start(self, seconds):
|
| 110 |
+
self.expected, self.frac = max(1., seconds * 25), 0.
|
| 111 |
+
self.show()
|
| 112 |
+
|
| 113 |
+
def finish(self, extra=0):
|
| 114 |
+
self.done += 1; self.total += extra; self.frac = 0.
|
| 115 |
+
self.show()
|
| 116 |
+
|
| 117 |
+
def __call__(self, stage, step, total):
|
| 118 |
+
if self.halt.is_set(): return False
|
| 119 |
+
self.frac = .8 * min(1., step / self.expected) if stage == 'plan' else .8 + .2 * step / total
|
| 120 |
+
if stage == 'decode' or step % 10 == 0: self.show()
|
| 121 |
+
|
| 122 |
+
def show(self):
|
| 123 |
+
self.progress(min(1., (self.done + self.frac) / self.total), desc=self.label)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class Studio:
|
| 127 |
+
def __init__(self, robin, out):
|
| 128 |
+
self.robin, self.out = robin, Path(out).expanduser().resolve()
|
| 129 |
+
for d in ('saved', 'voices', '.listen'): (self.out/d).mkdir(parents=True, exist_ok=True)
|
| 130 |
+
self.lock, self.halt = threading.Lock(), threading.Event()
|
| 131 |
+
self.job, self.adapter = None, None
|
| 132 |
+
|
| 133 |
+
def training(self):
|
| 134 |
+
return self.job is not None and self.job['thread'].is_alive()
|
| 135 |
+
|
| 136 |
+
def claim(self):
|
| 137 |
+
if self.training(): raise gr.Error('A voice is training. Robin speaks again when the training finishes or you stop it.')
|
| 138 |
+
if not self.lock.acquire(blocking=False): raise gr.Error('Robin is busy with another request. Try again in a moment.')
|
| 139 |
+
self.halt.clear()
|
| 140 |
+
|
| 141 |
+
def stop(self):
|
| 142 |
+
self.halt.set()
|
| 143 |
+
|
| 144 |
+
def saved(self):
|
| 145 |
+
return [str(p) for p in sorted((self.out/'saved').glob('*.flac'), key=lambda p: p.stat().st_mtime, reverse=True)[:60]]
|
| 146 |
+
|
| 147 |
+
def listen(self, x):
|
| 148 |
+
d = self.out/'.listen'
|
| 149 |
+
for old in sorted(d.glob('*.flac'), key=lambda p: p.stat().st_mtime)[:-40]: old.unlink(missing_ok=True)
|
| 150 |
+
f = d/f'{datetime.now():%Y%m%d-%H%M%S-%f}.flac'
|
| 151 |
+
sf.write(str(f), np.clip(x, -1, 1), pieces.RATE, subtype='PCM_24')
|
| 152 |
+
return str(f)
|
| 153 |
+
|
| 154 |
+
def save(self, take):
|
| 155 |
+
if not take: raise gr.Error('There is no take to save yet.')
|
| 156 |
+
name = f"{datetime.now():%Y%m%d-%H%M%S}_{slug(take['text']) or 'take'}_seed{take['seed']}.flac"
|
| 157 |
+
sf.write(str(self.out/'saved'/name), take['audio'], pieces.RATE, subtype='PCM_24')
|
| 158 |
+
gr.Info(f'Saved {name}')
|
| 159 |
+
return self.saved()
|
| 160 |
+
|
| 161 |
+
def label(self, path):
|
| 162 |
+
path = Path(path)
|
| 163 |
+
try:
|
| 164 |
+
run = path.parent.parent if path.parent.name == 'checkpoints' else path.parent
|
| 165 |
+
name = run.relative_to(self.out/'voices').as_posix()
|
| 166 |
+
return f"{name} · {'final' if path.name == 'lora.safetensors' else 'step ' + str(int(path.stem.split('_')[1]))}"
|
| 167 |
+
except (ValueError, IndexError):
|
| 168 |
+
return path.name
|
| 169 |
+
|
| 170 |
+
def adapters(self):
|
| 171 |
+
found = []
|
| 172 |
+
for run in sorted(p for p in (self.out/'voices').iterdir() if p.is_dir()):
|
| 173 |
+
if (run/'lora.safetensors').exists(): found.append(run/'lora.safetensors')
|
| 174 |
+
found += sorted((run/'checkpoints').glob('step_*.safetensors'), reverse=True)
|
| 175 |
+
return [('None: Robin as it comes', NONE)] + [(self.label(p), str(p)) for p in found]
|
| 176 |
+
|
| 177 |
+
def adapter_status(self):
|
| 178 |
+
if self.adapter is None: return 'No voice adapter: Robin as it comes.'
|
| 179 |
+
path, scale = self.adapter
|
| 180 |
+
return f'Using **{self.label(path)}** at strength {scale:g}, in every tab.'
|
| 181 |
+
|
| 182 |
+
def apply(self, choice, scale):
|
| 183 |
+
choice = str(choice or '').strip()
|
| 184 |
+
self.claim()
|
| 185 |
+
try:
|
| 186 |
+
if choice == NONE:
|
| 187 |
+
self.robin.remove_lora(); self.adapter = None
|
| 188 |
+
else:
|
| 189 |
+
path = Path(choice).expanduser()
|
| 190 |
+
if not path.is_file(): raise gr.Error(f'No voice adapter file at {path}')
|
| 191 |
+
try:
|
| 192 |
+
self.robin.load_lora(path, scale)
|
| 193 |
+
except ValueError as e:
|
| 194 |
+
raise gr.Error(str(e))
|
| 195 |
+
self.adapter = (str(path), scale)
|
| 196 |
+
finally:
|
| 197 |
+
self.lock.release()
|
| 198 |
+
return self.adapter_status()
|
| 199 |
+
|
| 200 |
+
def strength(self, scale):
|
| 201 |
+
if self.adapter is not None:
|
| 202 |
+
self.robin.set_lora_scale(scale); self.adapter = (self.adapter[0], scale)
|
| 203 |
+
return self.adapter_status()
|
| 204 |
+
|
| 205 |
+
def takes(self, which, text, voice, seed, cfg, temperature, top_k, top_p, language, state, progress):
|
| 206 |
+
lang = LANGUAGES.get(language, 'en')
|
| 207 |
+
text = (text or '').strip()
|
| 208 |
+
if not text: raise gr.Error('Type something for Robin to say.')
|
| 209 |
+
state = dict(state or {}); kept = state.get('kept', set())
|
| 210 |
+
if which == 'both':
|
| 211 |
+
roll = [k for k in 'AB' if k not in kept]
|
| 212 |
+
if not roll: raise gr.Error('Both takes are kept. Un-keep one to roll it again.')
|
| 213 |
+
seeds = {k: int(seed) + i for i, k in enumerate(roll)}
|
| 214 |
+
else:
|
| 215 |
+
seeds = {which: new_seed()}
|
| 216 |
+
meter = Meter(progress, len(pieces.split(text, 35, lang)) * len(seeds), self.halt, 'Robin is speaking')
|
| 217 |
+
self.claim()
|
| 218 |
+
try:
|
| 219 |
+
for k, s in seeds.items():
|
| 220 |
+
audio = pieces.read(self.robin, text, voice, seed=s, cfg=cfg, lang=lang, progress=meter, temperature=temperature, top_k=top_k,
|
| 221 |
+
top_p=top_p)
|
| 222 |
+
state[k] = dict(seed=s, audio=audio, text=text)
|
| 223 |
+
except Cancelled:
|
| 224 |
+
raise gr.Error('Stopped.')
|
| 225 |
+
finally:
|
| 226 |
+
self.lock.release()
|
| 227 |
+
out = []
|
| 228 |
+
for k in 'AB':
|
| 229 |
+
if k in seeds: out += [self.listen(state[k]['audio']), f"seed {state[k]['seed']} · {len(state[k]['audio']) / pieces.RATE:.1f} s"]
|
| 230 |
+
else: out += [gr.skip(), gr.skip()]
|
| 231 |
+
return out + [state]
|
| 232 |
+
|
| 233 |
+
def keep(self, which, state):
|
| 234 |
+
state = dict(state or {}); kept = set(state.get('kept', set()))
|
| 235 |
+
if which not in state: raise gr.Error(f'There is no take {which} yet.')
|
| 236 |
+
kept ^= {which}; state['kept'] = kept
|
| 237 |
+
on = which in kept
|
| 238 |
+
return gr.update(value=f'Kept {which}' if on else f'Keep {which}', variant='primary' if on else 'secondary'), state
|
| 239 |
+
|
| 240 |
+
def change(self, source, source_text, voice, seed, temperature, top_k, top_p, language, progress):
|
| 241 |
+
if source is None: raise gr.Error('Add the recording to change.')
|
| 242 |
+
if not (source_text or '').strip(): raise gr.Error('Type exactly what the recording says.')
|
| 243 |
+
if not (voice or '').strip() and self.adapter is None: raise gr.Error('Describe the new voice, or use a voice adapter.')
|
| 244 |
+
x, rate = read_mono(source)
|
| 245 |
+
if len(x) / rate > MAX_SOURCE_SECONDS:
|
| 246 |
+
raise gr.Error(f'The recording is {len(x) / rate:.0f} s long; the voice changer takes up to {MAX_SOURCE_SECONDS} s at a time.')
|
| 247 |
+
meter = Meter(progress, 2, self.halt, 'Robin is changing the voice')
|
| 248 |
+
self.claim()
|
| 249 |
+
try:
|
| 250 |
+
audio = pieces.change(self.robin, x, rate, source_text, voice=voice, seed=int(seed), lang=LANGUAGES.get(language, 'en'), progress=meter,
|
| 251 |
+
temperature=temperature, top_k=top_k, top_p=top_p)
|
| 252 |
+
except Cancelled:
|
| 253 |
+
raise gr.Error('Stopped.')
|
| 254 |
+
finally:
|
| 255 |
+
self.lock.release()
|
| 256 |
+
return self.listen(audio), f'seed {int(seed)} · {len(audio) / pieces.RATE:.1f} s', dict(seed=int(seed), audio=audio, text=source_text)
|
| 257 |
+
|
| 258 |
+
def check(self, data, language):
|
| 259 |
+
data = Path(str(data or '').strip()).expanduser()
|
| 260 |
+
if not str(data).strip() or not data.is_dir(): raise gr.Error(f'{data} is not a folder.')
|
| 261 |
+
found = tr.scan(data, LANGUAGES.get(language, 'en'))
|
| 262 |
+
lines = []
|
| 263 |
+
try:
|
| 264 |
+
tr.describe(found, lines.append)
|
| 265 |
+
except SystemExit as e:
|
| 266 |
+
lines.append(str(e))
|
| 267 |
+
left = sum(len(v) for v in found['problems'].values())
|
| 268 |
+
notes = sum(len(v) for v in found['warnings'].values())
|
| 269 |
+
minutes = sum(c['seconds'] for c in found['clips']) / 60
|
| 270 |
+
table = ('| Ready clips | Minutes of speech | Left out | Notes |\n|---|---|---|---|\n'
|
| 271 |
+
f"| {len(found['clips'])} | {minutes:.1f} | {left} | {notes} |")
|
| 272 |
+
return table, '\n'.join(lines[1:]), slug(data.name) or 'my-voice'
|
| 273 |
+
|
| 274 |
+
def where(self, name):
|
| 275 |
+
name = slug(str(name or ''))
|
| 276 |
+
return f'Saves to `{self.out/"voices"/name}`' if name else 'Give the voice a name.'
|
| 277 |
+
|
| 278 |
+
def start(self, data, name, steps, save_every, sample_text, restart, language):
|
| 279 |
+
data, name = Path(str(data or '').strip()).expanduser(), slug(str(name or ''))
|
| 280 |
+
if not data.is_dir(): raise gr.Error(f'{data} is not a folder.')
|
| 281 |
+
if not name: raise gr.Error('Give the voice a name.')
|
| 282 |
+
if self.training(): raise gr.Error('A voice is already training.')
|
| 283 |
+
if self.lock.locked(): raise gr.Error('Robin is busy with another request. Try again in a moment.')
|
| 284 |
+
job = dict(data=data, out=self.out/'voices'/name, steps=int(steps), save_every=int(save_every),
|
| 285 |
+
sample_text=(sample_text or '').strip() or None, restart=bool(restart), lang=LANGUAGES.get(language, 'en'),
|
| 286 |
+
stop=threading.Event(), log=[], result=None,
|
| 287 |
+
error=None, ended=None)
|
| 288 |
+
job['thread'] = threading.Thread(target=self._train, args=(job,), daemon=True)
|
| 289 |
+
self.job = job; job['thread'].start()
|
| 290 |
+
gr.Info('Training started.')
|
| 291 |
+
|
| 292 |
+
def _train(self, job):
|
| 293 |
+
log = job['log'].append
|
| 294 |
+
try:
|
| 295 |
+
with self.lock:
|
| 296 |
+
if self.robin.lora is not None:
|
| 297 |
+
self.robin.remove_lora(); self.adapter = None
|
| 298 |
+
log('The voice adapter in use was taken off for training.')
|
| 299 |
+
job['result'] = tr.train(self.robin, job['data'], job['out'], lang=job['lang'], restart=job['restart'], log=log, stop=job['stop'].is_set,
|
| 300 |
+
steps=job['steps'], save_every=job['save_every'], sample_text=job['sample_text'])
|
| 301 |
+
except SystemExit as e:
|
| 302 |
+
log(str(e))
|
| 303 |
+
except Exception as e:
|
| 304 |
+
job['error'] = f'{type(e).__name__}: {e}'
|
| 305 |
+
log(f"Training stopped with an error: {job['error']}"); log(traceback.format_exc(limit=4))
|
| 306 |
+
finally:
|
| 307 |
+
job['ended'] = time.time()
|
| 308 |
+
if torch.cuda.is_available(): torch.cuda.empty_cache()
|
| 309 |
+
|
| 310 |
+
def stop_training(self):
|
| 311 |
+
if not self.training(): raise gr.Error('Nothing is training.')
|
| 312 |
+
self.job['stop'].set()
|
| 313 |
+
gr.Info('Stopping after the current step...')
|
| 314 |
+
|
| 315 |
+
def saves(self, out):
|
| 316 |
+
rows = []
|
| 317 |
+
if (out/'samples'/'base.wav').exists(): rows.append(('before training', str(out/'samples'/'base.wav')))
|
| 318 |
+
rows += [(f"step {int(p.stem.split('_')[1])}", str(p)) for p in sorted((out/'samples').glob('step_*.wav'))]
|
| 319 |
+
return rows
|
| 320 |
+
|
| 321 |
+
def poll(self, name, shown):
|
| 322 |
+
job = self.job
|
| 323 |
+
out = job['out'] if job else self.out/'voices'/(slug(str(name or '')) or '_')
|
| 324 |
+
if job is None:
|
| 325 |
+
status, bar, log = 'Nothing is training.', '', ''
|
| 326 |
+
else:
|
| 327 |
+
m = next((STEP_LINE.match(l) for l in reversed(job['log']) if STEP_LINE.match(l)), None)
|
| 328 |
+
alive = job['thread'].is_alive()
|
| 329 |
+
if alive and m:
|
| 330 |
+
step, total, pace, left, gb = m.groups()
|
| 331 |
+
status = (f"Training **{out.name}**: step {step} of {total} · {float(pace):.1f} s/step · about {left} min left"
|
| 332 |
+
+ (f' · {gb} GB of GPU memory' if gb else ''))
|
| 333 |
+
elif alive: status = f'Training **{out.name}**: preparing the clips...'
|
| 334 |
+
elif job['error']: status = f"Training stopped with an error: {job['error']}"
|
| 335 |
+
elif job['result']: status = f"Finished **{out.name}**. Pick a step below and use it."
|
| 336 |
+
else: status = 'Stopped. Start again with the same name to continue where it left off.'
|
| 337 |
+
if alive and job['stop'].is_set(): status += ' (stopping after this step)'
|
| 338 |
+
pct = 100 * int(m.group(1)) / int(m.group(2)) if m else 0
|
| 339 |
+
bar = f'<div class="bar"><i style="width:{pct:.1f}%"></i></div>' if m else ''
|
| 340 |
+
log = '\n'.join(job['log'][-300:])
|
| 341 |
+
rows = self.saves(out)
|
| 342 |
+
paths = [r[1] for r in rows]
|
| 343 |
+
choices = gr.update(choices=rows, value=paths[-1] if paths else None) if paths != (shown or []) else gr.skip()
|
| 344 |
+
return status, bar, log, choices, paths
|
| 345 |
+
|
| 346 |
+
def use(self, sample, scale):
|
| 347 |
+
if not sample: raise gr.Error('Pick a saved step first.')
|
| 348 |
+
p = Path(sample)
|
| 349 |
+
if p.stem == 'base': raise gr.Error('That is Robin before training. Pick a saved step.')
|
| 350 |
+
lora = p.parent.parent/'checkpoints'/f'{p.stem}.safetensors'
|
| 351 |
+
if not lora.exists(): raise gr.Error(f'No voice adapter was saved for {p.stem}.')
|
| 352 |
+
status = self.apply(str(lora), scale)
|
| 353 |
+
gr.Info(f'Using {self.label(lora)}')
|
| 354 |
+
return status, gr.update(choices=self.adapters(), value=str(lora))
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def knobs(cfg=True):
|
| 358 |
+
with gr.Row():
|
| 359 |
+
g = gr.Slider(1, 10, 1, step=.1, label='Guidance', info='Above 1 follows the voice description more closely; try 3.', visible=cfg)
|
| 360 |
+
temperature = gr.Slider(0, 2, .9, step=.01, label='Temperature', info='Higher is livelier and less predictable.')
|
| 361 |
+
top_k = gr.Slider(0, 500, 25, step=1, label='Top-k', info='Choose among only this many likeliest sounds (0 = no limit).')
|
| 362 |
+
top_p = gr.Slider(.01, 1, .8, step=.01, label='Top-p', info='Choose among the likeliest sounds that add up to this share.')
|
| 363 |
+
with gr.Row():
|
| 364 |
+
seed = gr.Number(0, label='Seed', precision=0, minimum=0, scale=3)
|
| 365 |
+
reseed = gr.Button('New seed', scale=1)
|
| 366 |
+
reseed.click(new_seed, None, seed)
|
| 367 |
+
return g, temperature, top_k, top_p, seed
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def speak_tab(studio, language):
|
| 371 |
+
with gr.Row():
|
| 372 |
+
with gr.Column(scale=3):
|
| 373 |
+
text = gr.Textbox(label='What to say', lines=6, info='Any length. [laughs] and [coughs] can go anywhere in the text.',
|
| 374 |
+
value="Okay, okay, [laughs] I really didn't think you'd do it! [coughs] Sorry. Anyway, that was brilliant.")
|
| 375 |
+
with gr.Row():
|
| 376 |
+
laugh = gr.Button('+ [laughs]', size='sm')
|
| 377 |
+
cough = gr.Button('+ [coughs]', size='sm')
|
| 378 |
+
voice = gr.Textbox(label='The voice', lines=8, scale=2,
|
| 379 |
+
info='Describe it in plain words: age, pitch, pace, mood, how close to the mic. Leave it empty to let Robin choose.',
|
| 380 |
+
value='A cheerful woman in her thirties with a clear, medium-pitched voice, chatting casually with a friend.')
|
| 381 |
+
cfg, temperature, top_k, top_p, seed = knobs()
|
| 382 |
+
with gr.Row():
|
| 383 |
+
go = gr.Button('Speak: two takes', variant='primary', scale=4)
|
| 384 |
+
stop = gr.Button('Stop', scale=1)
|
| 385 |
+
takes, state = {}, gr.State({})
|
| 386 |
+
with gr.Row(equal_height=True):
|
| 387 |
+
for k in 'AB':
|
| 388 |
+
with gr.Column(elem_classes='take'):
|
| 389 |
+
audio = gr.Audio(label=f'Take {k}', type='numpy', interactive=False, buttons=['download'])
|
| 390 |
+
info = gr.Markdown('')
|
| 391 |
+
with gr.Row():
|
| 392 |
+
keep = gr.Button(f'Keep {k}', size='sm')
|
| 393 |
+
redo = gr.Button(f'Redo {k}', size='sm')
|
| 394 |
+
save = gr.Button(f'Save {k}', size='sm')
|
| 395 |
+
takes[k] = (audio, info, keep, redo, save)
|
| 396 |
+
saved = gr.Files(label='Saved takes', value=studio.saved, interactive=False)
|
| 397 |
+
inputs = [text, voice, seed, cfg, temperature, top_k, top_p, language, state]
|
| 398 |
+
outputs = [takes['A'][0], takes['A'][1], takes['B'][0], takes['B'][1], state]
|
| 399 |
+
go.click(lambda *a, progress=gr.Progress(): studio.takes('both', *a, progress), inputs, outputs)
|
| 400 |
+
for k in 'AB':
|
| 401 |
+
takes[k][2].click(lambda st, k=k: studio.keep(k, st), state, [takes[k][2], state])
|
| 402 |
+
takes[k][3].click(lambda *a, k=k, progress=gr.Progress(): studio.takes(k, *a, progress), inputs, outputs)
|
| 403 |
+
takes[k][4].click(lambda st, k=k: studio.save(st.get(k)), state, saved)
|
| 404 |
+
laugh.click(lambda t: (t or '').rstrip() + ' [laughs] ', text, text)
|
| 405 |
+
cough.click(lambda t: (t or '').rstrip() + ' [coughs] ', text, text)
|
| 406 |
+
stop.click(studio.stop)
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def changer_tab(studio, language):
|
| 410 |
+
gr.Markdown(f'Performs a recording again in another voice: the same words, timing and delivery, up to {MAX_SOURCE_SECONDS} seconds at '
|
| 411 |
+
'a time. The new voice comes from the description, and from the voice adapter when one is in use.')
|
| 412 |
+
with gr.Row():
|
| 413 |
+
with gr.Column():
|
| 414 |
+
source = gr.Audio(sources=['upload', 'microphone'], type='filepath', label='The recording to change')
|
| 415 |
+
source_text = gr.Textbox(label='Exactly what it says', lines=3)
|
| 416 |
+
voice = gr.Textbox(label='The new voice', lines=6, info='Describe it in plain words. It can stay empty when a voice adapter is in use.',
|
| 417 |
+
value='A soft-spoken young man with a calm, low voice.')
|
| 418 |
+
_, temperature, top_k, top_p, seed = knobs(cfg=False)
|
| 419 |
+
with gr.Row():
|
| 420 |
+
go = gr.Button('Change the voice', variant='primary', scale=4)
|
| 421 |
+
stop = gr.Button('Stop', scale=1)
|
| 422 |
+
with gr.Column(elem_classes='take'):
|
| 423 |
+
result = gr.Audio(label='Changed', type='numpy', interactive=False, buttons=['download'])
|
| 424 |
+
info = gr.Markdown('')
|
| 425 |
+
save = gr.Button('Save', size='sm')
|
| 426 |
+
take = gr.State(None)
|
| 427 |
+
saved = gr.Files(label='Saved takes', value=studio.saved, interactive=False)
|
| 428 |
+
go.click(lambda *a, progress=gr.Progress(): studio.change(*a, progress), [source, source_text, voice, seed, temperature, top_k, top_p, language],
|
| 429 |
+
[result, info, take])
|
| 430 |
+
save.click(studio.save, take, saved)
|
| 431 |
+
stop.click(studio.stop)
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
def train_tab(studio, adapter, strength, status_line, language):
|
| 435 |
+
gr.Markdown('Teach Robin a voice from recordings: a folder of clips, each with a `.txt` file of the same name holding exactly what it '
|
| 436 |
+
'says. Every few hundred steps it saves the voice with a sample, so you can pick a step by ear.')
|
| 437 |
+
with gr.Accordion('Dataset guide', open=False):
|
| 438 |
+
gr.Markdown(GUIDE)
|
| 439 |
+
with gr.Row():
|
| 440 |
+
data = gr.Textbox(label='Folder of clips', scale=4)
|
| 441 |
+
check = gr.Button('Check data', scale=1)
|
| 442 |
+
summary = gr.Markdown('', elem_classes='summary')
|
| 443 |
+
notes = gr.Textbox(label='Notes', lines=6, interactive=False)
|
| 444 |
+
with gr.Row():
|
| 445 |
+
name = gr.Textbox(label='Name', scale=2)
|
| 446 |
+
steps = gr.Number(1000, label='Steps', precision=0, minimum=10)
|
| 447 |
+
save_every = gr.Number(200, label='Save every', precision=0, minimum=10)
|
| 448 |
+
where = gr.Markdown('')
|
| 449 |
+
with gr.Row():
|
| 450 |
+
sample_text = gr.Textbox(tr.SAMPLE_TEXT['en'], label='Sample line read at every save', scale=4)
|
| 451 |
+
restart = gr.Checkbox(False, label='Start over (replaces an earlier run with this name)')
|
| 452 |
+
with gr.Row():
|
| 453 |
+
start = gr.Button('Start', variant='primary', scale=4)
|
| 454 |
+
halt = gr.Button('Stop', scale=1)
|
| 455 |
+
status = gr.Markdown('Nothing is training.')
|
| 456 |
+
bar = gr.HTML('')
|
| 457 |
+
with gr.Accordion('Training log', open=False):
|
| 458 |
+
log = gr.Textbox(show_label=False, lines=12, max_lines=12, interactive=False, autoscroll=True)
|
| 459 |
+
with gr.Row(equal_height=True):
|
| 460 |
+
sample = gr.Dropdown([], label='Saves', scale=2)
|
| 461 |
+
player = gr.Audio(label='Sample', type='filepath', interactive=False, scale=3)
|
| 462 |
+
use = gr.Button('Use this step', variant='primary', scale=1)
|
| 463 |
+
shown = gr.State([])
|
| 464 |
+
check.click(studio.check, [data, language], [summary, notes, name]).then(studio.where, name, where)
|
| 465 |
+
name.change(studio.where, name, where)
|
| 466 |
+
start.click(studio.start, [data, name, steps, save_every, sample_text, restart, language])
|
| 467 |
+
language.change(lambda l: tr.SAMPLE_TEXT[LANGUAGES.get(l, 'en')], language, sample_text)
|
| 468 |
+
halt.click(studio.stop_training)
|
| 469 |
+
sample.change(lambda p: p or None, sample, player)
|
| 470 |
+
use.click(studio.use, [sample, strength], [status_line, adapter])
|
| 471 |
+
gr.Timer(2).tick(studio.poll, [name, shown], [status, bar, log, sample, shown])
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def build(studio):
|
| 475 |
+
with gr.Blocks(title='Robin', analytics_enabled=False) as demo:
|
| 476 |
+
with gr.Row(elem_id='robin-head'):
|
| 477 |
+
gr.HTML('<h1>ROBIN</h1>')
|
| 478 |
+
gr.HTML('<p>Speak, change voices, train voices.</p>')
|
| 479 |
+
with gr.Row(elem_id='adapter', equal_height=True):
|
| 480 |
+
adapter = gr.Dropdown(studio.adapters(), value=NONE, label='Voice adapter', allow_custom_value=True, scale=3,
|
| 481 |
+
info='A voice trained in "Train a voice", or the path to one.')
|
| 482 |
+
strength = gr.Slider(0, 2, 1, step=.05, label='Strength', info='1 is the voice as trained.', scale=2)
|
| 483 |
+
language = gr.Dropdown(list(LANGUAGES), value='English', label='Language', scale=1,
|
| 484 |
+
info='The language Robin speaks, on every tab.')
|
| 485 |
+
with gr.Column(scale=1, min_width=120):
|
| 486 |
+
apply = gr.Button('Use', variant='primary', size='sm')
|
| 487 |
+
refresh = gr.Button('Refresh list', size='sm')
|
| 488 |
+
status_line = gr.Markdown(studio.adapter_status)
|
| 489 |
+
demo.load(lambda: (gr.update(choices=studio.adapters(), value=studio.adapter[0] if studio.adapter else NONE),
|
| 490 |
+
studio.adapter[1] if studio.adapter else 1, studio.adapter_status()), None, [adapter, strength, status_line])
|
| 491 |
+
apply.click(studio.apply, [adapter, strength], status_line)
|
| 492 |
+
refresh.click(lambda: gr.update(choices=studio.adapters()), None, adapter)
|
| 493 |
+
strength.change(studio.strength, strength, status_line)
|
| 494 |
+
with gr.Tabs():
|
| 495 |
+
with gr.Tab('Speak'):
|
| 496 |
+
speak_tab(studio, language)
|
| 497 |
+
with gr.Tab('Voice changer'):
|
| 498 |
+
changer_tab(studio, language)
|
| 499 |
+
with gr.Tab('Train a voice'):
|
| 500 |
+
train_tab(studio, adapter, strength, status_line, language)
|
| 501 |
+
return demo
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
def launch(robin, out='robin_studio', host='127.0.0.1', port=7860):
|
| 505 |
+
studio = Studio(robin, out)
|
| 506 |
+
demo = build(studio)
|
| 507 |
+
demo.queue(default_concurrency_limit=1)
|
| 508 |
+
demo.launch(server_name=host, server_port=port, theme=theme(), css=CSS, allowed_paths=[str(studio.out)], show_error=True)
|
package/robin/lora.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import hashlib
|
| 2 |
+
import json
|
| 3 |
+
import math
|
| 4 |
+
import os
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from safetensors import safe_open
|
| 9 |
+
from safetensors.torch import save_file
|
| 10 |
+
from torch import nn
|
| 11 |
+
|
| 12 |
+
TARGETS = ('self_attn.qkv_proj', 'self_attn.o_proj', 'mlp.gate_up_proj')
|
| 13 |
+
FORMAT = 'robin-lora-1'
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def file_sha256(path):
|
| 17 |
+
path = Path(path).resolve(); st = path.stat()
|
| 18 |
+
key = f'{path}:{st.st_size}:{st.st_mtime_ns}'
|
| 19 |
+
cache = Path(os.environ.get('ROBIN_CACHE', Path.home()/'.cache'/'robin'))/'sha256.json'
|
| 20 |
+
known = {}
|
| 21 |
+
try: known = json.loads(cache.read_text())
|
| 22 |
+
except (OSError, ValueError): pass
|
| 23 |
+
if key not in known:
|
| 24 |
+
h = hashlib.sha256()
|
| 25 |
+
with path.open('rb') as f:
|
| 26 |
+
for chunk in iter(lambda: f.read(1 << 24), b''): h.update(chunk)
|
| 27 |
+
known[key] = h.hexdigest()
|
| 28 |
+
try:
|
| 29 |
+
cache.parent.mkdir(parents=True, exist_ok=True); cache.write_text(json.dumps(known))
|
| 30 |
+
except OSError: pass
|
| 31 |
+
return known[key]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class LoRA(nn.Module):
|
| 35 |
+
def __init__(self, nets, ranks, alphas=None, targets=TARGETS, seed=0):
|
| 36 |
+
super().__init__()
|
| 37 |
+
self.ranks, self.alphas, self.targets = dict(ranks), dict(alphas or ranks), tuple(targets)
|
| 38 |
+
self.scale, self.names, self._mods, self._factor, self._handles = 1.0, [], [], [], []
|
| 39 |
+
self.A, self.B = nn.ParameterList(), nn.ParameterList()
|
| 40 |
+
g = torch.Generator().manual_seed(seed)
|
| 41 |
+
for net, layers in nets.items():
|
| 42 |
+
r = self.ranks[net]
|
| 43 |
+
for i, layer in enumerate(layers):
|
| 44 |
+
for t in self.targets:
|
| 45 |
+
m = layer.get_submodule(t)
|
| 46 |
+
a = torch.randn(r, m.in_features, generator=g) / math.sqrt(m.in_features)
|
| 47 |
+
self.A.append(nn.Parameter(a.to(m.weight.device)))
|
| 48 |
+
self.B.append(nn.Parameter(torch.zeros(m.out_features, r, device=m.weight.device)))
|
| 49 |
+
self.names.append(f'{net}.layers.{i}.{t}'); self._mods.append(m); self._factor.append(self.alphas[net] / r)
|
| 50 |
+
|
| 51 |
+
def attach(self):
|
| 52 |
+
if not self._handles:
|
| 53 |
+
self._handles = [m.register_forward_hook(self._hook(i)) for i, m in enumerate(self._mods)]
|
| 54 |
+
return self
|
| 55 |
+
|
| 56 |
+
def detach(self):
|
| 57 |
+
for h in self._handles: h.remove()
|
| 58 |
+
self._handles = []
|
| 59 |
+
|
| 60 |
+
def _hook(self, i):
|
| 61 |
+
def hook(_module, args, out):
|
| 62 |
+
if self.scale == 0: return out
|
| 63 |
+
delta = (args[0].float() @ self.A[i].T) @ self.B[i].T
|
| 64 |
+
return out + (delta * (self._factor[i] * self.scale)).to(out.dtype)
|
| 65 |
+
return hook
|
| 66 |
+
|
| 67 |
+
def config(self, base_sha256=None):
|
| 68 |
+
return dict(format=FORMAT, ranks=self.ranks, alphas=self.alphas, targets=list(self.targets), base_sha256=base_sha256)
|
| 69 |
+
|
| 70 |
+
def save(self, path, base_sha256=None, dtype=torch.bfloat16):
|
| 71 |
+
path = Path(path); tmp = path.with_name(path.name + '.tmp')
|
| 72 |
+
state = {}
|
| 73 |
+
for name, a, b in zip(self.names, self.A, self.B):
|
| 74 |
+
state[f'{name}.lora_A'] = a.detach().to(dtype).cpu().contiguous(); state[f'{name}.lora_B'] = b.detach().to(dtype).cpu().contiguous()
|
| 75 |
+
save_file(state, str(tmp), metadata=dict(robin_lora=json.dumps(self.config(base_sha256))))
|
| 76 |
+
os.replace(tmp, path)
|
| 77 |
+
|
| 78 |
+
@classmethod
|
| 79 |
+
def load(cls, path, nets, device='cuda'):
|
| 80 |
+
with safe_open(str(path), framework='pt', device='cpu') as f:
|
| 81 |
+
meta = f.metadata() or {}
|
| 82 |
+
if 'robin_lora' not in meta:
|
| 83 |
+
raise ValueError(f'{path} is not a Robin LoRA')
|
| 84 |
+
config = json.loads(meta['robin_lora'])
|
| 85 |
+
lora = cls({k: v for k, v in nets.items() if k in config['ranks']}, config['ranks'], config['alphas'], config['targets'])
|
| 86 |
+
keys = set(f.keys())
|
| 87 |
+
for i, name in enumerate(lora.names):
|
| 88 |
+
for which, params in (('lora_A', lora.A), ('lora_B', lora.B)):
|
| 89 |
+
k = f'{name}.{which}'
|
| 90 |
+
if k not in keys: raise ValueError(f'{path} is missing {k}')
|
| 91 |
+
t = f.get_tensor(k)
|
| 92 |
+
if t.shape != params[i].shape: raise ValueError(f'{path}: {k} has shape {tuple(t.shape)}, expected {tuple(params[i].shape)}')
|
| 93 |
+
params[i].data.copy_(t)
|
| 94 |
+
return lora.to(device).requires_grad_(False), config
|
package/robin/model.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from torch import nn
|
| 7 |
+
from torch.utils.checkpoint import checkpoint
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@dataclass
|
| 11 |
+
class Config:
|
| 12 |
+
vocab_size: int = 184704
|
| 13 |
+
hidden_size: int = 2048
|
| 14 |
+
intermediate_size: int = 6144
|
| 15 |
+
num_hidden_layers: int = 28
|
| 16 |
+
num_attention_heads: int = 16
|
| 17 |
+
num_key_value_heads: int = 8
|
| 18 |
+
head_dim: int = 128
|
| 19 |
+
rope_theta: float = 1_000_000.0
|
| 20 |
+
rms_norm_eps: float = 1e-6
|
| 21 |
+
max_position_embeddings: int = 24576
|
| 22 |
+
latent_dim: int = 64
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class RMSNorm(nn.Module):
|
| 26 |
+
def __init__(self, dim, eps):
|
| 27 |
+
super().__init__()
|
| 28 |
+
self.weight = nn.Parameter(torch.ones(dim)); self.eps = eps
|
| 29 |
+
|
| 30 |
+
def forward(self, x):
|
| 31 |
+
return F.rms_norm(x, self.weight.shape, self.weight.to(x.dtype), self.eps)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def rope(positions, head_dim, theta, device):
|
| 35 |
+
inv = 1.0 / (theta ** (torch.arange(0, head_dim, 2, dtype=torch.float32, device=device) / head_dim))
|
| 36 |
+
ang = positions.float().to(device)[:, None] * inv[None]
|
| 37 |
+
return ang.cos(), ang.sin()
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def apply_rope(x, cos, sin):
|
| 41 |
+
f = x.float(); h = f.shape[-1] // 2
|
| 42 |
+
lo, hi = f[..., :h], f[..., h:]
|
| 43 |
+
return torch.cat([lo * cos - hi * sin, hi * cos + lo * sin], dim=-1).to(x.dtype)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class Attention(nn.Module):
|
| 47 |
+
def __init__(self, c):
|
| 48 |
+
super().__init__()
|
| 49 |
+
self.h, self.kv, self.d = c.num_attention_heads, c.num_key_value_heads, c.head_dim
|
| 50 |
+
self.qkv_proj = nn.Linear(c.hidden_size, (self.h + 2 * self.kv) * self.d, bias=False)
|
| 51 |
+
self.o_proj = nn.Linear(self.h * self.d, c.hidden_size, bias=False)
|
| 52 |
+
self.q_norm, self.k_norm = RMSNorm(self.d, c.rms_norm_eps), RMSNorm(self.d, c.rms_norm_eps)
|
| 53 |
+
|
| 54 |
+
def qkv(self, x, cos, sin):
|
| 55 |
+
B, T, _ = x.shape
|
| 56 |
+
q, k, v = self.qkv_proj(x).split((self.h * self.d, self.kv * self.d, self.kv * self.d), dim=-1)
|
| 57 |
+
q = self.q_norm(q.view(B, T, self.h, self.d)).transpose(1, 2)
|
| 58 |
+
k = self.k_norm(k.view(B, T, self.kv, self.d)).transpose(1, 2)
|
| 59 |
+
v = v.view(B, T, self.kv, self.d).transpose(1, 2)
|
| 60 |
+
return apply_rope(q, cos, sin), apply_rope(k, cos, sin), v
|
| 61 |
+
|
| 62 |
+
def attend(self, q, k, v, mask=None):
|
| 63 |
+
o = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, enable_gqa=self.h != self.kv)
|
| 64 |
+
return self.o_proj(o.transpose(1, 2).reshape(q.shape[0], q.shape[2], -1))
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class MLP(nn.Module):
|
| 68 |
+
def __init__(self, c):
|
| 69 |
+
super().__init__()
|
| 70 |
+
self.gate_up_proj = nn.Linear(c.hidden_size, 2 * c.intermediate_size, bias=False)
|
| 71 |
+
self.down_proj = nn.Linear(c.intermediate_size, c.hidden_size, bias=False)
|
| 72 |
+
|
| 73 |
+
def forward(self, x):
|
| 74 |
+
g, u = self.gate_up_proj(x).chunk(2, dim=-1)
|
| 75 |
+
return self.down_proj(F.silu(g) * u)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class Block(nn.Module):
|
| 79 |
+
def __init__(self, c):
|
| 80 |
+
super().__init__()
|
| 81 |
+
self.input_layernorm = RMSNorm(c.hidden_size, c.rms_norm_eps)
|
| 82 |
+
self.self_attn = Attention(c)
|
| 83 |
+
self.post_attention_layernorm = RMSNorm(c.hidden_size, c.rms_norm_eps)
|
| 84 |
+
self.mlp = MLP(c)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def planner_block(layer, x, cos, sin, mask):
|
| 88 |
+
q, k, v = layer.self_attn.qkv(layer.input_layernorm(x), cos, sin)
|
| 89 |
+
x = x + layer.self_attn.attend(q, k, v, mask)
|
| 90 |
+
return x + layer.mlp(layer.post_attention_layernorm(x))
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def decoder_block(layer, s, cos, sin, prefix_k, prefix_v):
|
| 94 |
+
q, k, v = layer.self_attn.qkv(layer.input_layernorm(s), cos, sin)
|
| 95 |
+
k = torch.cat((prefix_k.to(k.dtype), k), dim=2); v = torch.cat((prefix_v.to(v.dtype), v), dim=2)
|
| 96 |
+
s = s + layer.self_attn.attend(q, k, v)
|
| 97 |
+
return s + layer.mlp(layer.post_attention_layernorm(s))
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class Planner(nn.Module):
|
| 101 |
+
def __init__(self, c: Config):
|
| 102 |
+
super().__init__()
|
| 103 |
+
self.c = c
|
| 104 |
+
self.embed_tokens = nn.Embedding(c.vocab_size, c.hidden_size)
|
| 105 |
+
self.layers = nn.ModuleList(Block(c) for _ in range(c.num_hidden_layers))
|
| 106 |
+
self.norm = RMSNorm(c.hidden_size, c.rms_norm_eps)
|
| 107 |
+
self.lm_head = nn.Linear(c.hidden_size, c.vocab_size, bias=False)
|
| 108 |
+
|
| 109 |
+
def forward(self, ids, mask):
|
| 110 |
+
x = self.embed_tokens(ids)
|
| 111 |
+
cos, sin = rope(torch.arange(ids.shape[1]), self.c.head_dim, self.c.rope_theta, x.device)
|
| 112 |
+
mask = mask.to(x.dtype)
|
| 113 |
+
for layer in self.layers:
|
| 114 |
+
x = checkpoint(planner_block, layer, x, cos, sin, mask, use_reentrant=False)
|
| 115 |
+
return self.norm(x)
|
| 116 |
+
|
| 117 |
+
@torch.no_grad()
|
| 118 |
+
def prefill(self, ids, mask):
|
| 119 |
+
x = self.embed_tokens(ids[None]); T = ids.shape[0]
|
| 120 |
+
cos, sin = rope(torch.arange(T), self.c.head_dim, self.c.rope_theta, x.device)
|
| 121 |
+
ks, vs = [], []
|
| 122 |
+
for layer in self.layers:
|
| 123 |
+
q, k, v = layer.self_attn.qkv(layer.input_layernorm(x), cos, sin)
|
| 124 |
+
x = x + layer.self_attn.attend(q, k, v, mask.to(x.dtype))
|
| 125 |
+
x = x + layer.mlp(layer.post_attention_layernorm(x))
|
| 126 |
+
ks.append(k); vs.append(v)
|
| 127 |
+
return ks, vs, self.norm(x)
|
| 128 |
+
|
| 129 |
+
@torch.no_grad()
|
| 130 |
+
def step(self, token, pos, kbuf, vbuf):
|
| 131 |
+
x = self.embed_tokens(torch.tensor([[token]], device=self.lm_head.weight.device))
|
| 132 |
+
cos, sin = rope(torch.tensor([pos]), self.c.head_dim, self.c.rope_theta, x.device)
|
| 133 |
+
for i, layer in enumerate(self.layers):
|
| 134 |
+
q, k, v = layer.self_attn.qkv(layer.input_layernorm(x), cos, sin)
|
| 135 |
+
kbuf[i][:, :, pos] = k[:, :, 0]; vbuf[i][:, :, pos] = v[:, :, 0]
|
| 136 |
+
x = x + layer.self_attn.attend(q, kbuf[i][:, :, :pos + 1], vbuf[i][:, :, :pos + 1])
|
| 137 |
+
x = x + layer.mlp(layer.post_attention_layernorm(x))
|
| 138 |
+
return self.lm_head(self.norm(x)[:, -1]).float()[0]
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
class TimestepEmbedder(nn.Module):
|
| 142 |
+
def __init__(self, hidden):
|
| 143 |
+
super().__init__()
|
| 144 |
+
self.mlp = nn.Sequential(nn.Linear(256, hidden), nn.SiLU(), nn.Linear(hidden, hidden))
|
| 145 |
+
|
| 146 |
+
def forward(self, t):
|
| 147 |
+
half = 128
|
| 148 |
+
freqs = torch.exp(-math.log(10000) * torch.arange(half, dtype=torch.float32, device=t.device) / half)
|
| 149 |
+
a = t.float()[:, None] * freqs[None]
|
| 150 |
+
return self.mlp(torch.cat([a.cos(), a.sin()], dim=-1).to(self.mlp[0].weight.dtype))
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def positions(n, dim, device):
|
| 154 |
+
pos = torch.arange(n, dtype=torch.float32, device=device)[:, None]
|
| 155 |
+
ang = pos * torch.exp(torch.arange(0, dim, 2, dtype=torch.float32, device=device) * (-math.log(10000.0) / dim))
|
| 156 |
+
pe = torch.zeros(n, dim, device=device)
|
| 157 |
+
pe[:, 0::2], pe[:, 1::2] = ang.sin(), ang.cos()
|
| 158 |
+
return pe
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class _Stack(nn.Module):
|
| 162 |
+
def __init__(self, c):
|
| 163 |
+
super().__init__()
|
| 164 |
+
self.layers = nn.ModuleList(Block(c) for _ in range(c.num_hidden_layers))
|
| 165 |
+
self.norm = RMSNorm(c.hidden_size, c.rms_norm_eps)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class Decoder(nn.Module):
|
| 169 |
+
def __init__(self, c: Config):
|
| 170 |
+
super().__init__()
|
| 171 |
+
self.c = c
|
| 172 |
+
self.model = _Stack(c)
|
| 173 |
+
self.vae2llm = nn.Linear(c.latent_dim, c.hidden_size)
|
| 174 |
+
self.llm2vae = nn.Linear(c.hidden_size, c.latent_dim)
|
| 175 |
+
self.time_embedder = TimestepEmbedder(c.hidden_size)
|
| 176 |
+
self._pe = None
|
| 177 |
+
|
| 178 |
+
@torch.no_grad()
|
| 179 |
+
def velocity(self, x, sigma, prefix_k, prefix_v):
|
| 180 |
+
return self(x, sigma, prefix_k, prefix_v)
|
| 181 |
+
|
| 182 |
+
def forward(self, x, sigma, prefix_k, prefix_v, checkpointing=False):
|
| 183 |
+
dt = self.vae2llm.weight.dtype
|
| 184 |
+
A = prefix_k[0].shape[2]; n = x.shape[1] + 2
|
| 185 |
+
s = F.pad(x.to(dt), (0, 0, 1, 1))
|
| 186 |
+
if self._pe is None or self._pe.shape[0] < n or self._pe.device != x.device:
|
| 187 |
+
self._pe = positions(max(n, 1024), self.c.hidden_size, x.device).to(dt)
|
| 188 |
+
s = self.vae2llm(s) + self.time_embedder(sigma.to(dt))[:, None] + self._pe[:n][None]
|
| 189 |
+
cos, sin = rope(torch.arange(A, A + n), self.c.head_dim, self.c.rope_theta, x.device)
|
| 190 |
+
for i, layer in enumerate(self.model.layers):
|
| 191 |
+
if checkpointing:
|
| 192 |
+
s = checkpoint(decoder_block, layer, s, cos, sin, prefix_k[i], prefix_v[i], use_reentrant=False)
|
| 193 |
+
else:
|
| 194 |
+
s = decoder_block(layer,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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
from .text import speakable
|
| 6 |
+
|
| 7 |
+
RATE = 48000
|
| 8 |
+
SAMPLE_LINE = 'Here is a short sample of my voice, read clearly and at an easy pace.'
|
| 9 |
+
SAMPLE_LINES = dict(en=SAMPLE_LINE, ja='これは私の声の短いサンプルです。はっきりと、ゆっくり読んでいます。', mix=SAMPLE_LINE)
|
| 10 |
+
TAG = re.compile(r'\[[^\]]*\]')
|
| 11 |
+
ENDS = re.compile(r'(?<=[.!?])\s+|(?<=[.!?]")\s+|(?<=[。!?])\s*')
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def size(text, lang='en'):
|
| 15 |
+
text = TAG.sub(' ', text)
|
| 16 |
+
if lang == 'en':
|
| 17 |
+
return len(re.findall(r"[A-Za-z0-9']+", text))
|
| 18 |
+
return len(re.sub(r'[\s\W]', '', text)) / 2.8
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def sentences(text):
|
| 22 |
+
out, cur = [], ''
|
| 23 |
+
for part in ENDS.split(text.strip()):
|
| 24 |
+
if not part: continue
|
| 25 |
+
cur = f'{cur} {part}'.strip() if cur else part
|
| 26 |
+
if cur.count('"') % 2 == 0: out.append(cur); cur = ''
|
| 27 |
+
return out + ([cur] if cur else [])
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def clauses(s, limit, lang):
|
| 31 |
+
if size(s, lang) <= limit: return [s]
|
| 32 |
+
best = None
|
| 33 |
+
for m in re.finditer(r'[,;:、,]\s*', s):
|
| 34 |
+
i = m.end()
|
| 35 |
+
if s[:i].count('"') % 2 or i >= len(s): continue
|
| 36 |
+
d = abs(size(s[:i], lang) - size(s, lang) / 2)
|
| 37 |
+
if best is None or d < best[0]: best = (d, i)
|
| 38 |
+
if best is None: return [s]
|
| 39 |
+
return clauses(s[:best[1]].strip(), limit, lang) + clauses(s[best[1]:].strip(), limit, lang)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def glue(parts, lang):
|
| 43 |
+
if lang == 'en': return ' '.join(parts)
|
| 44 |
+
out = ''
|
| 45 |
+
for p in parts:
|
| 46 |
+
out += (' ' if lang == 'mix' and out and (out[-1].isascii() or p[0].isascii()) else '') + p
|
| 47 |
+
return out
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def split(text, max_words=35, lang='en', as_written=False):
|
| 51 |
+
if lang == 'en' and not as_written: text = speakable(text)
|
| 52 |
+
parts = [c for s in sentences(text) for c in clauses(s, max_words, lang)]
|
| 53 |
+
chunks, cur = [], []
|
| 54 |
+
for p in parts:
|
| 55 |
+
if cur and size(glue(cur + [p], lang), lang) > max_words:
|
| 56 |
+
chunks.append(glue(cur, lang)); cur = []
|
| 57 |
+
cur.append(p)
|
| 58 |
+
return chunks + ([glue(cur, lang)] if cur else [])
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def frames_on(x, rate=RATE):
|
| 62 |
+
f = rate // 20; n = len(x) // f
|
| 63 |
+
return 20 * np.log10(np.sqrt((x[:n * f].reshape(n, f) ** 2).mean(1)) + 1e-9) > -45
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def stats(x, rate=RATE):
|
| 67 |
+
on = frames_on(x, rate); idx = np.flatnonzero(on); dur = len(on) / 20
|
| 68 |
+
if not len(idx): return dict(sound=0., lead=dur, gap=0., tail=0.)
|
| 69 |
+
gap = run = 0
|
| 70 |
+
for v in on[idx[0]:idx[-1] + 1]:
|
| 71 |
+
run = 0 if v else run + 1; gap = max(gap, run)
|
| 72 |
+
return dict(sound=on.sum() / 20, lead=idx[0] / 20, gap=gap / 20, tail=dur - (idx[-1] + 1) / 20)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def expected_seconds(text, lang='en'):
|
| 76 |
+
per_second = 2.7 if lang == 'en' else 2.5
|
| 77 |
+
return max(1., size(text, lang) / per_second + .8 * len(TAG.findall(text)))
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def check(x, text, lang='en', capped=False):
|
| 81 |
+
st = stats(x); ratio = st['sound'] / expected_seconds(text, lang); problems = []
|
| 82 |
+
if st['sound'] < .3: problems.append('no sound')
|
| 83 |
+
if st['lead'] > 1.: problems.append('starts late')
|
| 84 |
+
if st['gap'] > 2.5: problems.append('goes quiet')
|
| 85 |
+
if ratio < .45: problems.append('too short')
|
| 86 |
+
if ratio > 1.8: problems.append('too long')
|
| 87 |
+
if capped and st['tail'] < .5: problems.append('still talking at the length limit')
|
| 88 |
+
return (10 * len(problems) + abs(np.log(max(ratio, 1e-3)))), problems
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def trim(x):
|
| 92 |
+
f = RATE // 20; idx = np.flatnonzero(frames_on(x))
|
| 93 |
+
if not len(idx): return x[:0]
|
| 94 |
+
y = x[max(0, idx[0] * f - RATE // 20):min(len(x), (idx[-1] + 1) * f + int(.12 * RATE))].copy()
|
| 95 |
+
f = min(len(y) // 2, RATE // 100)
|
| 96 |
+
y[:f] *= np.linspace(0, 1, f); y[len(y) - f:] *= np.linspace(1, 0, f)
|
| 97 |
+
return y
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def loudness(x):
|
| 101 |
+
f = RATE // 20; n = len(x) // f
|
| 102 |
+
e = (x[:n * f].reshape(n, f) ** 2).mean(1); on = 10 * np.log10(e + 1e-12) > -45
|
| 103 |
+
return float(np.sqrt(e[on].mean())) if on.any() else 0.
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def join(pieces, texts):
|
| 107 |
+
ref = loudness(pieces[0]) or 1.; out = []
|
| 108 |
+
for i, (y, t) in enumerate(zip(pieces, texts)):
|
| 109 |
+
level = loudness(y)
|
| 110 |
+
out.append(y * (min(2., max(.5, ref / level)) if level else 1.))
|
| 111 |
+
if i < len(pieces) - 1:
|
| 112 |
+
pause = .35 if re.search(r'[.!?。!?]["\]]?\s*$', t) else .2
|
| 113 |
+
out.append(np.zeros(int(pause * RATE), dtype=np.float32))
|
| 114 |
+
return np.concatenate(out).astype(np.float32)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class Quiet:
|
| 118 |
+
def start(self, seconds): pass
|
| 119 |
+
|
| 120 |
+
def finish(self, extra=0): pass
|
| 121 |
+
|
| 122 |
+
def __call__(self, stage, step, total): pass
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def _best_take(robin, text, voice, lang, seed, retries, progress, **kwargs):
|
| 126 |
+
best = None
|
| 127 |
+
for k in range(retries + 1):
|
| 128 |
+
progress.start(expected_seconds(text, lang))
|
| 129 |
+
audio, _, info = robin.speak(text, voice, lang=lang, seed=seed + 7919 * k, callback=progress, **kwargs)
|
| 130 |
+
score, problems = check(audio, text, lang, info['capped'])
|
| 131 |
+
if best is None or score < best[0]: best = (score, problems, audio)
|
| 132 |
+
if not problems or k == retries:
|
| 133 |
+
progress.finish(); break
|
| 134 |
+
progress.finish(extra=1)
|
| 135 |
+
return best[2], best[1]
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def read(robin, text, voice=None, *, reference=None, reference_rate=None, reference_text=None, seed=0, cfg=1., retries=2, max_words=35,
|
| 139 |
+
lang='en', as_written=False, progress=None, **sampling):
|
| 140 |
+
progress = progress or Quiet()
|
| 141 |
+
chunks = split(text, max_words, lang, as_written)
|
| 142 |
+
if not chunks: raise ValueError('There is no text to read.')
|
| 143 |
+
voice = (voice or '').strip() or None
|
| 144 |
+
ref = None if reference is None else (reference, reference_rate, (reference_text or '').strip() or None)
|
| 145 |
+
kept = []
|
| 146 |
+
for i, chunk in enumerate(chunks):
|
| 147 |
+
audio, problems = _best_take(robin, chunk, voice, lang, seed + 1000 * i, retries, progress, cfg=cfg,
|
| 148 |
+
reference=ref[0] if ref else None, reference_rate=ref[1] if ref else None,
|
| 149 |
+
reference_text=ref[2] if ref else None, **sampling)
|
| 150 |
+
take = trim(audio)
|
| 151 |
+
kept.append(take)
|
| 152 |
+
if not problems and len(chunks) > 1 and len(take):
|
| 153 |
+
ref = (take, RATE, chunk)
|
| 154 |
+
return join(kept, chunks)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def change(robin, source, source_rate, source_text, *, reference=None, reference_rate=None, reference_text=None, voice=None, seed=0,
|
| 158 |
+
retries=2, lang='en', progress=None, **sampling):
|
| 159 |
+
progress = progress or Quiet()
|
| 160 |
+
voice = (voice or '').strip() or None
|
| 161 |
+
if not (source_text or '').strip(): raise ValueError('The source text must say exactly what the source clip says.')
|
| 162 |
+
if reference is None:
|
| 163 |
+
line = SAMPLE_LINES.get(lang, SAMPLE_LINE)
|
| 164 |
+
audio, _ = _best_take(robin, line, voice, lang, seed, retries, progress, **sampling)
|
| 165 |
+
reference, reference_rate, reference_text = trim(audio), RATE, line
|
| 166 |
+
seconds = len(source) / source_rate
|
| 167 |
+
target = stats(source, source_rate)['sound'] or seconds
|
| 168 |
+
best = None
|
| 169 |
+
for k in range(retries + 1):
|
| 170 |
+
progress.start(seconds)
|
| 171 |
+
audio, _, info = robin.convert(source, source_text.strip(), reference, reference_text=(reference_text or '').strip() or None,
|
| 172 |
+
source_rate=source_rate, reference_rate=reference_rate, description=voice, lang=lang,
|
| 173 |
+
seed=seed + 7919 * k, callback=progress, **sampling)
|
| 174 |
+
st = stats(audio); ratio = st['sound'] / max(target, .1)
|
| 175 |
+
problems = st['sound'] < .3 or not .5 <= ratio <= 2. or (info['capped'] and st['tail'] < .5)
|
| 176 |
+
score = 10 * problems + abs(np.log(max(ratio, 1e-3)))
|
| 177 |
+
if best is None or score < best[0]: best = (score, audio)
|
| 178 |
+
if not problems or k == retries:
|
| 179 |
+
progress.finish(); break
|
| 180 |
+
progress.finish(extra=1)
|
| 181 |
+
return best[1]
|
package/rob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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import warnings
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
from safetensors.torch import load_file
|
| 8 |
+
from tokenizers import Tokenizer
|
| 9 |
+
|
| 10 |
+
from .model import Config, Planner, Decoder
|
| 11 |
+
|
| 12 |
+
LANGS = dict(en='English', ja='Japanese', mix='English and Japanese')
|
| 13 |
+
WEIGHTS = 'robin_v1.safetensors'
|
| 14 |
+
VAE = 'robin_vae.safetensors'
|
| 15 |
+
SPEECH = 'speech_tokenizer_v3_25hz.onnx'
|
| 16 |
+
APOSTROPHES = str.maketrans(dict.fromkeys('\u2019\u2018\u201b\u02bc\uff07\u2032\u00b4`', "'"))
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def plain(s):
|
| 20 |
+
return s.translate(APOSTROPHES) if s else s
|
| 21 |
+
FRAME_RATE, SAMPLE_RATE = 25, 48000
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class Cancelled(Exception):
|
| 25 |
+
pass
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def prefix_mask(n, ss, device):
|
| 29 |
+
m = torch.full((n, n), float('-inf'), device=device).triu_(1)
|
| 30 |
+
m[:ss, :ss] = 0
|
| 31 |
+
return m
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class Robin:
|
| 35 |
+
def __init__(self, planner, decoder, vae, tokenizer, config, device):
|
| 36 |
+
self.planner, self.decoder, self.vae, self.tok, self.device = planner, decoder, vae, tokenizer, device
|
| 37 |
+
t = config['tokens']
|
| 38 |
+
self.eod, self.score_start, self.score_end = t['eod'], t['score_start'], t['score_end']
|
| 39 |
+
self.audio_start, self.audio_end, self.offset, self.codes = t['audio_start'], t['audio_end'], t['audio_offset'], t['audio_codes']
|
| 40 |
+
self.instruction, self.defaults = config['instruction'], config['sampling']
|
| 41 |
+
self._speech, self.lora, self.weights_file, self.vae_file = None, None, None, None
|
| 42 |
+
|
| 43 |
+
@classmethod
|
| 44 |
+
def from_pretrained(cls, path, vae=None, device='cuda', dtype=torch.bfloat16, lora=None, lora_scale=1.0):
|
| 45 |
+
path = Path(path)
|
| 46 |
+
if not path.exists():
|
| 47 |
+
from huggingface_hub import snapshot_download
|
| 48 |
+
path = Path(snapshot_download(str(path)))
|
| 49 |
+
if vae is None:
|
| 50 |
+
vae = path/VAE
|
| 51 |
+
if not vae.is_file():
|
| 52 |
+
raise ValueError(f'VAE weights are required: put {VAE} in {path}, or pass vae=<path to the .safetensors file>')
|
| 53 |
+
config = json.loads((path/'config.json').read_text())
|
| 54 |
+
c = Config(**config['model'])
|
| 55 |
+
with torch.device('meta'):
|
| 56 |
+
planner, decoder = Planner(c), Decoder(c)
|
| 57 |
+
sd = load_file(str(path/WEIGHTS), device=str(torch.device(device)))
|
| 58 |
+
for net, prefix in ((planner, 'robin.planner.'), (decoder, 'robin.decoder.')):
|
| 59 |
+
net.load_state_dict({k[len(prefix):]: sd.pop(k) for k in [k for k in sd if k.startswith(prefix)]}, strict=True, assign=True)
|
| 60 |
+
if sd: raise ValueError(f'unexpected weights in {path/WEIGHTS}: {", ".join(list(sd)[:5])}')
|
| 61 |
+
del sd
|
| 62 |
+
vae_file = None
|
| 63 |
+
if not isinstance(vae, torch.nn.Module):
|
| 64 |
+
from .vae import load_vae
|
| 65 |
+
vae_file, vae = Path(vae), load_vae(vae, device)
|
| 66 |
+
planner = planner.to(device, dtype).eval().requires_grad_(False); decoder = decoder.to(device, dtype).eval().requires_grad_(False)
|
| 67 |
+
robin = cls(planner, decoder, vae, Tokenizer.from_file(str(path/'tokenizer.json')), config, device)
|
| 68 |
+
robin.weights_file, robin.vae_file = path/WEIGHTS, vae_file
|
| 69 |
+
if lora is not None:
|
| 70 |
+
robin.load_lora(lora, lora_scale)
|
| 71 |
+
return robin
|
| 72 |
+
|
| 73 |
+
def base_sha256(self):
|
| 74 |
+
from .lora import file_sha256
|
| 75 |
+
return file_sha256(self.weights_file) if self.weights_file else None
|
| 76 |
+
|
| 77 |
+
def load_lora(self, path, scale=1.0):
|
| 78 |
+
from .lora import LoRA
|
| 79 |
+
self.remove_lora()
|
| 80 |
+
lora, config = LoRA.load(path, dict(planner=self.planner.layers, decoder=self.decoder.model.layers), self.device)
|
| 81 |
+
base = config.get('base_sha256')
|
| 82 |
+
if base and self.weights_file and base != self.base_sha256():
|
| 83 |
+
warnings.warn(f'{Path(path).name} was trained on different Robin weights; it may not sound right')
|
| 84 |
+
lora.scale = scale
|
| 85 |
+
self.lora = lora.attach()
|
| 86 |
+
return self
|
| 87 |
+
|
| 88 |
+
def set_lora_scale(self, scale):
|
| 89 |
+
if self.lora is None: raise ValueError('no LoRA is loaded')
|
| 90 |
+
self.lora.scale = scale
|
| 91 |
+
|
| 92 |
+
def remove_lora(self):
|
| 93 |
+
if self.lora is not None:
|
| 94 |
+
self.lora.detach(); self.lora = None
|
| 95 |
+
|
| 96 |
+
@property
|
| 97 |
+
def speech(self):
|
| 98 |
+
if self._speech is None:
|
| 99 |
+
from .speech import SpeechTokenizer
|
| 100 |
+
self._speech = SpeechTokenizer(self.weights_file.parent/SPEECH, self.device)
|
| 101 |
+
return self._speech
|
| 102 |
+
|
| 103 |
+
def tags(self, description=None, lang='en'):
|
| 104 |
+
base = f"speech, spoken word, {LANGS.get(lang, lang)}"
|
| 105 |
+
return f"{base}. {description.strip()}" if description and description.strip() else base
|
| 106 |
+
|
| 107 |
+
def _block(self, label, tokens, text=None):
|
| 108 |
+
head = f'[{label}]\n' + (f'{text}\n' if text else '')
|
| 109 |
+
return self.tok.encode(head).ids + [self.audio_start] + [int(t) + self.offset for t in tokens] + [self.audio_end] + self.tok.encode('\n').ids
|
| 110 |
+
|
| 111 |
+
def prompt(self, text, description=None, lang='en', reference=None, reference_text=None, source=None):
|
| 112 |
+
text, description, reference_text = plain(text), plain(description), plain(reference_text)
|
| 113 |
+
ids = [self.eod] + self.tok.encode(f"{self.instruction}\n[Tags]\n{self.tags(description, lang)}\n[Lyrics]\n{text}\n").ids
|
| 114 |
+
if reference is not None:
|
| 115 |
+
ids += self._block('Reference voice', reference, reference_text)
|
| 116 |
+
if source is not None:
|
| 117 |
+
ids += self._block('Source performance', source)
|
| 118 |
+
return ids + [self.score_start, self.score_end, self.audio_start]
|
| 119 |
+
|
| 120 |
+
def reference_tokens(self, audio, text=None, sample_rate=None, max_frames=400, excerpt_frames=375):
|
| 121 |
+
tokens = self.speech(audio, sample_rate)
|
| 122 |
+
if len(tokens) <= max_frames:
|
| 123 |
+
return tokens, text
|
| 124 |
+
s = (len(tokens) - excerpt_frames) // 2
|
| 125 |
+
return tokens[s:s + excerpt_frames], None
|
| 126 |
+
|
| 127 |
+
def _branch(self, ids, budget):
|
| 128 |
+
ks, vs, h = self.planner.prefill(torch.tensor(ids, device=self.device), prefix_mask(len(ids), len(ids), self.device))
|
| 129 |
+
cap = len(ids) + budget + 1
|
| 130 |
+
kb, vb = [], []
|
| 131 |
+
for k, v in zip(ks, vs):
|
| 132 |
+
kbuf = torch.zeros(1, k.shape[1], cap, k.shape[3], dtype=k.dtype, device=self.device); kbuf[:, :, :len(ids)] = k
|
| 133 |
+
vbuf = torch.zeros_like(kbuf); vbuf[:, :, :len(ids)] = v
|
| 134 |
+
kb.append(kbuf); vb.append(vbuf)
|
| 135 |
+
return dict(k=kb, v=vb, pos=len(ids), logits=self.planner.lm_head(h[:, -1]).float()[0])
|
| 136 |
+
|
| 137 |
+
@torch.no_grad()
|
| 138 |
+
def plan(self, ids, budget, *, seed=0, temperature=None, top_k=None, top_p=None, min_tokens=25, negative=None, cfg=1.,
|
| 139 |
+
pause_guard=None, guard_distinct=None, callback=None):
|
| 140 |
+
d = self.defaults
|
| 141 |
+
temperature = d['temperature'] if temperature is None else temperature
|
| 142 |
+
top_k = d['top_k'] if top_k is None else top_k
|
| 143 |
+
top_p = d['top_p'] if top_p is None else top_p
|
| 144 |
+
pause_guard = d['pause_guard'] if pause_guard is None else pause_guard
|
| 145 |
+
guard_distinct = d['guard_distinct'] if guard_distinct is None else guard_distinct
|
| 146 |
+
g = torch.Generator(device=self.device).manual_seed(int(seed) % 2 ** 64)
|
| 147 |
+
branches = [self._branch(ids, budget)] + ([self._branch(negative, budget)] if negative is not None and cfg != 1. else [])
|
| 148 |
+
allowed = torch.full_like(branches[0]['logits'], float('-inf'))
|
| 149 |
+
allowed[self.offset:self.offset + self.codes] = 0; allowed[self.audio_end] = 0
|
| 150 |
+
out = []
|
| 151 |
+
for step in range(budget):
|
| 152 |
+
lg = branches[0]['logits'] if len(branches) == 1 else branches[1]['logits'] + cfg * (branches[0]['logits'] - branches[1]['logits'])
|
| 153 |
+
s = lg + allowed
|
| 154 |
+
if step < min_tokens: s[self.audio_end] = float('-inf')
|
| 155 |
+
if pause_guard and len(out) >= pause_guard:
|
| 156 |
+
recent = set(out[-pause_guard:])
|
| 157 |
+
if len(recent) <= guard_distinct: s[torch.tensor(sorted(recent), device=self.device)] = float('-inf')
|
| 158 |
+
if temperature == 0:
|
| 159 |
+
tok = int(s.argmax())
|
| 160 |
+
else:
|
| 161 |
+
s = s / temperature
|
| 162 |
+
if top_k: s = s.masked_fill(s < s.topk(min(top_k, s.numel())).values[-1], float('-inf'))
|
| 163 |
+
if top_p < 1:
|
| 164 |
+
v, ix = s.sort(descending=True); cp = v.softmax(-1).cumsum(-1)
|
| 165 |
+
drop = cp - v.softmax(-1) > top_p; s = s.masked_fill(torch.zeros_like(s, dtype=torch.bool).scatter(0, ix, drop), float('-inf'))
|
| 166 |
+
tok = int(torch.multinomial(s.softmax(-1), 1, generator=g))
|
| 167 |
+
if tok == self.audio_end: return out, False
|
| 168 |
+
out.append(tok)
|
| 169 |
+
if callback is not None and callback('plan', step + 1, budget) is False: raise Cancelled()
|
| 170 |
+
for b in branches:
|
| 171 |
+
b['logits'] = self.planner.step(tok, b['pos'], b['k'], b['v']); b['pos'] += 1
|
| 172 |
+
return out, True
|
| 173 |
+
|
| 174 |
+
@torch.no_grad()
|
| 175 |
+
def latents(self, ids, tokens, *, seed=0, steps=None, sampler=None, callback=None):
|
| 176 |
+
steps = self.defaults['decoder_steps'] if steps is None else steps
|
| 177 |
+
sampler = self.defaults['decoder_sampler'] if sampler is None else sampler
|
| 178 |
+
full = list(ids) + list(tokens) + [self.audio_end]
|
| 179 |
+
ks, vs, _ = self.planner.prefill(torch.tensor(full, device=self.device), prefix_mask(len(full), len(ids), self.device))
|
| 180 |
+
T = len(tokens)
|
| 181 |
+
x = torch.randn((1, 64, T), generator=torch.Generator().manual_seed(int(seed) % 2 ** 64)).to(self.device).transpose(1, 2)
|
| 182 |
+
sig = torch.cat([torch.linspace(1.0, 0.001, steps + 1)[:-1], torch.zeros(1)]).to(self.device)
|
| 183 |
+
|
| 184 |
+
def denoised(x_, s_):
|
| 185 |
+
return x_ - self.decoder.velocity(x_, s_.reshape(1), ks, vs) * s_
|
| 186 |
+
|
| 187 |
+
if sampler == 'dpm_2':
|
| 188 |
+
for i in range(steps):
|
| 189 |
+
s0, s1 = sig[i], sig[i + 1]
|
| 190 |
+
d = (x - denoised(x, s0)) / s0
|
| 191 |
+
if s1 == 0:
|
| 192 |
+
x = x + d * (s1 - s0)
|
| 193 |
+
else:
|
| 194 |
+
sm = s0.log().lerp(s1.log(), 0.5).exp()
|
| 195 |
+
x2 = x + d * (sm - s0)
|
| 196 |
+
x = x + (x2 - denoised(x2, sm)) / sm * (s1 - s0)
|
| 197 |
+
if callback is not None and callback('decode', i + 1, steps) is False: raise Cancelled()
|
| 198 |
+
elif sampler == 'dpmpp_2m':
|
| 199 |
+
old = None
|
| 200 |
+
for i in range(steps):
|
| 201 |
+
s0, s1 = sig[i], sig[i + 1]
|
| 202 |
+
den = denoised(x, s0)
|
| 203 |
+
t, tn = -s0.log(), -s1.log()
|
| 204 |
+
h = tn - t
|
| 205 |
+
if old is None or s1 == 0:
|
| 206 |
+
x = (s1 / s0) * x - (-h).expm1() * den
|
| 207 |
+
else:
|
| 208 |
+
r = (t + sig[i - 1].log()) / h
|
| 209 |
+
x = (s1 / s0) * x - (-h).expm1() * ((1 + 1 / (2 * r)) * den - (1 / (2 * r)) * old)
|
| 210 |
+
old = den
|
| 211 |
+
if callback is not None and callback('decode', i + 1, steps) is False: raise Cancelled()
|
| 212 |
+
else:
|
| 213 |
+
raise ValueError(f'unknown sampler {sampler}')
|
| 214 |
+
return x.transpose(1, 2).float()
|
| 215 |
+
|
| 216 |
+
@torch.no_grad()
|
| 217 |
+
def decode(self, latents):
|
| 218 |
+
return self.vae.decode(latents.to(self.device, torch.float32))[0].float().mean(0).cpu().numpy()
|
| 219 |
+
|
| 220 |
+
def _budget(self, text, lang, max_seconds):
|
| 221 |
+
if lang == 'mix': frames = sum(5.0 if ord(c) > 127 else 2.2 for c in text)
|
| 222 |
+
else: frames = len(text) * (5.0 if lang == 'ja' else 2.2)
|
| 223 |
+
return int(min(max_seconds * FRAME_RATE, frames + 100))
|
| 224 |
+
|
| 225 |
+
def _render(self, ids, budget, seed, negative=None, cfg=1., steps=None, sampler=None, callback=None, **sampling):
|
| 226 |
+
tokens, capped = self.plan(ids, budget, seed=seed, negative=negative, cfg=cfg, callback=callback, **sampling)
|
| 227 |
+
if not tokens: raise RuntimeError('nothing was generated')
|
| 228 |
+
lat = self.latents(ids, tokens, seed=seed, steps=steps, sampler=sampler, callback=callback)
|
| 229 |
+
return self.decode(lat), SAMPLE_RATE, dict(frames=len(tokens), seconds=len(tokens) / FRAME_RATE, capped=capped,
|
| 230 |
+
tokens=[t - self.offset for t in tokens])
|
| 231 |
+
|
| 232 |
+
@torch.no_grad()
|
| 233 |
+
def speak(self, text, description=None, *, reference=None, reference_text=None, reference_rate=None, lang='en', seed=0, cfg=1.,
|
| 234 |
+
max_seconds=45, steps=None, sampler=None, callback=None, **sampling):
|
| 235 |
+
ref = None
|
| 236 |
+
if reference is not None:
|
| 237 |
+
ref, reference_text = self.reference_tokens(reference, reference_text, reference_rate)
|
| 238 |
+
ids = self.prompt(text, description, lang, ref, reference_text)
|
| 239 |
+
negative = self.prompt(text, None, lang) if description and cfg != 1. and ref is None else None
|
| 240 |
+
return self._render(ids, self._budget(text, lang, max_seconds), seed, negative, cfg, steps, sampler, callback, **sampling)
|
| 241 |
+
|
| 242 |
+
@torch.no_grad()
|
| 243 |
+
def convert(self, source, text, reference, *, reference_text=None, source_rate=None, reference_rate=None, description=None,
|
| 244 |
+
lang='en', seed=0, steps=None, sampler=None, callback=None, **sampling):
|
| 245 |
+
src = self.speech(source, source_rate)
|
| 246 |
+
ref, reference_text = self.reference_tokens(reference, reference_text, reference_rate)
|
| 247 |
+
ids = self.prompt(text, description, lang, ref, reference_text, src)
|
| 248 |
+
return self._render(ids, int(len(src) * 1.6) + 50, seed, None, 1., steps, sampler, callback, **sampling)
|
package/robin/speech.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import soundfile as sf
|
| 5 |
+
import torch
|
| 6 |
+
from torchaudio.functional import resample
|
| 7 |
+
|
| 8 |
+
HOP = 640
|
| 9 |
+
CORE, CTX = 700, 25
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def load_audio(audio, sample_rate=None):
|
| 13 |
+
if isinstance(audio, (str, bytes)) or hasattr(audio, '__fspath__'):
|
| 14 |
+
x, sample_rate = sf.read(str(audio), dtype='float32', always_2d=True)
|
| 15 |
+
return torch.from_numpy(x.mean(1)), sample_rate
|
| 16 |
+
if sample_rate is None:
|
| 17 |
+
raise ValueError('pass sample_rate with an array')
|
| 18 |
+
x = torch.as_tensor(np.asarray(audio, dtype=np.float32))
|
| 19 |
+
return (x.mean(1) if x.ndim == 2 else x), sample_rate
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class SpeechTokenizer:
|
| 23 |
+
def __init__(self, path, device='cuda'):
|
| 24 |
+
import s3tokenizer
|
| 25 |
+
path = Path(path)
|
| 26 |
+
if not path.is_file():
|
| 27 |
+
raise ValueError(f'The speech tokenizer is missing: put {path.name} in {path.parent}. It comes with Robin on Hugging Face.')
|
| 28 |
+
self.s3, self.device = s3tokenizer, device
|
| 29 |
+
self.model = s3tokenizer.load_model(str(path)).to(device).eval()
|
| 30 |
+
|
| 31 |
+
@torch.no_grad()
|
| 32 |
+
def _codes(self, wav16):
|
| 33 |
+
m, lens = self.s3.padding([self.s3.log_mel_spectrogram(wav16, n_mels=128)])
|
| 34 |
+
codes, clens = self.model.quantize(m.to(self.device), lens.to(self.device))
|
| 35 |
+
return codes[0, :clens[0]].cpu().numpy()
|
| 36 |
+
|
| 37 |
+
def __call__(self, audio, sample_rate=None):
|
| 38 |
+
x, rate = load_audio(audio, sample_rate)
|
| 39 |
+
wav16 = resample(x, rate, 16000)
|
| 40 |
+
total = int(round(len(wav16) / HOP))
|
| 41 |
+
if total <= CORE:
|
| 42 |
+
return self._codes(wav16).astype(np.int64)
|
| 43 |
+
out = []
|
| 44 |
+
for s in range(0, total, CORE):
|
| 45 |
+
a = max(0, s - CTX); b = min(total, s + CORE + CTX)
|
| 46 |
+
c = self._codes(wav16[a * HOP:b * HOP])
|
| 47 |
+
keep = min(CORE, total - s); piece = c[s - a:s - a + keep]
|
| 48 |
+
if len(piece) < keep: piece = np.concatenate([piece, np.repeat(c[-1:], keep - len(piece))])
|
| 49 |
+
out.append(piece)
|
| 50 |
+
return np.concatenate(out).astype(np.int64)
|
package/robin/text.py
ADDED
|
@@ -0,0 +1,699 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
ONES = ('zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen '
|
| 4 |
+
'nineteen').split()
|
| 5 |
+
TENS = ('', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety')
|
| 6 |
+
SCALES = ('', ' thousand', ' million', ' billion', ' trillion')
|
| 7 |
+
IRREGULAR = dict(one='first', two='second', three='third', five='fifth', eight='eighth', nine='ninth', twelve='twelfth')
|
| 8 |
+
MONTHS = ('January February March April May June July August September October November December').split()
|
| 9 |
+
MONTH = re.compile(r'(Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?|July?|Aug(?:ust)?|Sept?(?:ember)?|Oct(?:ober)?|'
|
| 10 |
+
r'Nov(?:ember)?|Dec(?:ember)?)')
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def number(n):
|
| 14 |
+
if n < 0: return 'minus ' + number(-n)
|
| 15 |
+
if n < 20: return ONES[n]
|
| 16 |
+
if n < 100: return TENS[n // 10] + ('-' + ONES[n % 10] if n % 10 else '')
|
| 17 |
+
if n < 1000: return ONES[n // 100] + ' hundred' + (' ' + number(n % 100) if n % 100 else '')
|
| 18 |
+
if n >= 10 ** 15: return digits(str(n))
|
| 19 |
+
out, i = [], 0
|
| 20 |
+
while n:
|
| 21 |
+
n, r = divmod(n, 1000)
|
| 22 |
+
if r: out.append(number(r) + SCALES[i])
|
| 23 |
+
i += 1
|
| 24 |
+
return ' '.join(reversed(out))
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def digits(s, zero='zero'):
|
| 28 |
+
return ' '.join(zero if c == '0' else ONES[int(c)] for c in s if c.isdigit())
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def ordinal(n):
|
| 32 |
+
head, last = re.match(r'(.*?)([a-z]+)$', number(n)).groups()
|
| 33 |
+
return head + (IRREGULAR.get(last) or (last[:-1] + 'ieth' if last.endswith('y') else last + 'th'))
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def year(n):
|
| 37 |
+
if not 1000 <= n <= 9999 or n % 1000 == 0 or 2000 < n < 2010: return number(n)
|
| 38 |
+
hi, lo = divmod(n, 100)
|
| 39 |
+
return number(hi) + (' hundred' if lo == 0 else ' oh ' + ONES[lo] if lo < 10 else ' ' + number(lo))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def pairs(s):
|
| 43 |
+
if len(s) > 1 and s[0] == '0' or len(s) > 4: return digits(s)
|
| 44 |
+
n = int(s)
|
| 45 |
+
if len(s) == 4: return year(n)
|
| 46 |
+
if len(s) < 3 or n % 100 == 0: return number(n)
|
| 47 |
+
return ONES[n // 100] + (' oh ' + ONES[n % 100] if n % 100 < 10 else ' ' + number(n % 100))
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def cardinal(s):
|
| 51 |
+
s = s.replace(',', '')
|
| 52 |
+
return digits(s) if len(s) > 1 and s[0] == '0' or len(s) > 15 else number(int(s))
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def decimal(s):
|
| 56 |
+
whole, _, frac = s.replace(',', '').partition('.')
|
| 57 |
+
words = cardinal(whole) if whole else ''
|
| 58 |
+
return (words + ' point ' if words else 'point ') + digits(frac) if frac else words
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def plural(words):
|
| 62 |
+
return words[:-1] + 'ies' if words.endswith('y') else words + ('es' if words.endswith(('x', 's')) else 's')
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def fraction(n, d, of_unit=None):
|
| 66 |
+
name = {2: 'half', 4: 'quarter'}.get(d) or ordinal(d)
|
| 67 |
+
if of_unit:
|
| 68 |
+
if n == 1: return f'half a {of_unit}' if d == 2 else ('an ' if name[0] in 'aeiou' else 'a ') + f'{name} {of_unit}'
|
| 69 |
+
return f'{number(n)} {"halves" if d == 2 else name + "s"} of a {of_unit}'
|
| 70 |
+
return f'{number(n)} ' + (name if n == 1 else 'halves' if d == 2 else name + 's')
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
UNITS = {
|
| 74 |
+
'mm': 'millimeter', 'cm': 'centimeter', 'km': 'kilometer', 'm': 'meter', 'nm': 'nanometer', 'µm': 'micrometer',
|
| 75 |
+
'mi': 'mile', 'ft': ('foot', 'feet'), 'yd': 'yard', 'in.': ('inch', 'inches'), 'ly': 'light-year',
|
| 76 |
+
'mg': 'milligram', 'mcg': 'microgram', 'µg': 'microgram', 'g': 'gram', 'kg': 'kilogram', 'lb': 'pound', 'lbs': 'pound',
|
| 77 |
+
'oz': 'ounce', 'fl oz': 'fluid ounce', 'ml': 'milliliter', 'mL': 'milliliter', 'L': 'liter', 'dL': 'deciliter', 'dl': 'deciliter',
|
| 78 |
+
'tsp': 'teaspoon', 'tbsp': 'tablespoon', 'Tbsp': 'tablespoon', 'TBSP': 'tablespoon', 'qt': 'quart', 'gal': 'gallon',
|
| 79 |
+
'ms': 'millisecond', 'sec': 'second', 'secs': 'second', 'min': 'minute', 'mins': 'minute', 'hr': 'hour', 'hrs': 'hour',
|
| 80 |
+
'yr': 'year', 'yrs': 'year', 'wk': 'week', 'wks': 'week',
|
| 81 |
+
'Hz': ('hertz', 'hertz'), 'kHz': ('kilohertz', 'kilohertz'), 'MHz': ('megahertz', 'megahertz'), 'GHz': ('gigahertz', 'gigahertz'),
|
| 82 |
+
'KB': 'kilobyte', 'kB': 'kilobyte', 'MB': 'megabyte', 'GB': 'gigabyte', 'TB': 'terabyte', 'PB': 'petabyte',
|
| 83 |
+
'Kb': 'kilobit', 'kb': 'kilobit', 'Mb': 'megabit', 'Gb': 'gigabit',
|
| 84 |
+
'kbps': ('kilobit per second', 'kilobits per second'), 'Kbps': ('kilobit per second', 'kilobits per second'),
|
| 85 |
+
'Mbps': ('megabit per second', 'megabits per second'), 'Gbps': ('gigabit per second', 'gigabits per second'),
|
| 86 |
+
'MB/s': ('megabyte per second', 'megabytes per second'), 'GB/s': ('gigabyte per second', 'gigabytes per second'),
|
| 87 |
+
'W': 'watt', 'kW': 'kilowatt', 'MW': 'megawatt', 'GW': 'gigawatt', 'Wh': 'watt-hour', 'kWh': 'kilowatt-hour',
|
| 88 |
+
'MWh': 'megawatt-hour', 'GWh': 'gigawatt-hour', 'mAh': 'milliamp-hour', 'V': 'volt', 'mV': 'millivolt', 'kV': 'kilovolt',
|
| 89 |
+
'mA': 'milliamp', 'kcal': 'kilocalorie', 'cal': 'calorie', 'kJ': 'kilojoule',
|
| 90 |
+
'Pa': 'pascal', 'kPa': 'kilopascal', 'hPa': 'hectopascal', 'psi': ('P S I', 'P S I'), 'mmHg': ('millimeter of mercury',
|
| 91 |
+
'millimeters of mercury'),
|
| 92 |
+
'mph': ('mile per hour', 'miles per hour'), 'kph': ('kilometer per hour', 'kilometers per hour'),
|
| 93 |
+
'km/h': ('kilometer per hour', 'kilometers per hour'), 'm/s': ('meter per second', 'meters per second'),
|
| 94 |
+
'mg/dL': ('milligram per deciliter', 'milligrams per deciliter'), 'mmol/L': ('millimole per liter', 'millimoles per liter'),
|
| 95 |
+
'rpm': ('R P M', 'R P M'), 'RPM': ('R P M', 'R P M'), 'bpm': ('B P M', 'B P M'), 'BPM': ('B P M', 'B P M'),
|
| 96 |
+
'fps': ('F P S', 'F P S'), 'FPS': ('F P S', 'F P S'), 'dB': 'decibel', 'dpi': ('D P I', 'D P I'), 'DPI': ('D P I', 'D P I'),
|
| 97 |
+
'ppi': ('P P I', 'P P I'), 'px': 'pixel', 'IU': ('I U', 'I U'), 'N·m': ('newton-meter', 'newton-meters'), 'Nm': ('newton-meter', 'newton-meters'),
|
| 98 |
+
'lb-ft': ('pound-foot', 'pound-feet'), 'lb·ft': ('pound-foot', 'pound-feet'),
|
| 99 |
+
}
|
| 100 |
+
POWERS = {'²': 'square', '³': 'cubic', '^2': 'square', '^3': 'cubic'}
|
| 101 |
+
CURRENCIES = {
|
| 102 |
+
'$': ('dollar', 'dollars', 'cent', 'cents'), 'US$': ('dollar', 'dollars', 'cent', 'cents'),
|
| 103 |
+
'A$': ('Australian dollar', 'Australian dollars', 'cent', 'cents'), 'AU$': ('Australian dollar', 'Australian dollars', 'cent', 'cents'),
|
| 104 |
+
'C$': ('Canadian dollar', 'Canadian dollars', 'cent', 'cents'), 'CA$': ('Canadian dollar', 'Canadian dollars', 'cent', 'cents'),
|
| 105 |
+
'NZ$': ('New Zealand dollar', 'New Zealand dollars', 'cent', 'cents'), 'HK$': ('Hong Kong dollar', 'Hong Kong dollars', 'cent', 'cents'),
|
| 106 |
+
'S$': ('Singapore dollar', 'Singapore dollars', 'cent', 'cents'), 'R$': ('real', 'reais', 'centavo', 'centavos'),
|
| 107 |
+
'MX$': ('peso', 'pesos', 'centavo', 'centavos'), '€': ('euro', 'euros', 'cent', 'cents'), '£': ('pound', 'pounds', 'penny', 'pence'),
|
| 108 |
+
'¥': ('yen', 'yen', None, None), '₹': ('rupee', 'rupees', 'paisa', 'paise'), '₩': ('won', 'won', None, None),
|
| 109 |
+
'₽': ('ruble', 'rubles', 'kopek', 'kopeks'), '₱': ('peso', 'pesos', 'centavo', 'centavos'), '₺': ('lira', 'lira', 'kurus', 'kurus'),
|
| 110 |
+
}
|
| 111 |
+
CODES = {'USD': ('U S dollar', 'U S dollars'), 'EUR': ('euro', 'euros'), 'GBP': ('pound', 'pounds'), 'JPY': ('yen', 'yen'),
|
| 112 |
+
'CHF': ('Swiss franc', 'Swiss francs'), 'CAD': ('Canadian dollar', 'Canadian dollars'), 'AUD': ('Australian dollar',
|
| 113 |
+
'Australian dollars'), 'NZD': ('New Zealand dollar', 'New Zealand dollars'), 'INR': ('rupee', 'rupees'), 'CNY': ('yuan', 'yuan'),
|
| 114 |
+
'MXN': ('peso', 'pesos'), 'BRL': ('real', 'reais'), 'KRW': ('won', 'won'), 'SEK': ('krona', 'kronor'), 'NOK': ('krone', 'kroner'),
|
| 115 |
+
'DKK': ('krone', 'kroner'), 'BTC': ('bitcoin', 'bitcoin'), 'ETH': ('ether', 'ether'), 'HKD': ('Hong Kong dollar', 'Hong Kong dollars'),
|
| 116 |
+
'SGD': ('Singapore dollar', 'Singapore dollars'), 'ZAR': ('rand', 'rand'), 'TRY': ('lira', 'lira'), 'PLN': ('zloty', 'zlotys')}
|
| 117 |
+
SCALE_WORDS = {'k': 'thousand', 'K': 'thousand', 'm': 'million', 'M': 'million', 'mm': 'million', 'mn': 'million', 'MM': 'million',
|
| 118 |
+
'b': 'billion', 'B': 'billion', 'bn': 'billion', 'Bn': 'billion', 't': 'trillion', 'T': 'trillion', 'tn': 'trillion'}
|
| 119 |
+
AS_WORDS = {
|
| 120 |
+
'NASA': 'NASA', 'NATO': 'NATO', 'UNESCO': 'UNESCO', 'UNICEF': 'UNICEF', 'FIFA': 'FIFA', 'FEMA': 'FEMA', 'OPEC': 'OPEC',
|
| 121 |
+
'NAFTA': 'NAFTA', 'POTUS': 'POTUS', 'SCOTUS': 'SCOTUS', 'SWAT': 'SWAT', 'AIDS': 'AIDS', 'COVID': 'COVID', 'SARS': 'SARS',
|
| 122 |
+
'SCUBA': 'scuba', 'LASER': 'laser', 'RADAR': 'radar', 'SONAR': 'sonar', 'CAPTCHA': 'captcha', 'YOLO': 'yolo', 'FOMO': 'fomo',
|
| 123 |
+
'ROM': 'rom', 'RAM': 'ram', 'PIN': 'pin', 'ZIP': 'zip', 'SIM': 'sim', 'GIF': 'gif', 'JPEG': 'jay-peg', 'JSON': 'jay-son',
|
| 124 |
+
'GUI': 'gooey', 'ASCII': 'ask-ee', 'IKEA': 'Ikea', 'LEGO': 'Lego', 'OK': 'OK', 'TBD': 'T B D', 'WWII': 'World War Two',
|
| 125 |
+
'WWI': 'World War One', 'ASAP': 'A S A P', 'NIMBY': 'nimby', 'IMAX': 'IMAX', 'AWOL': 'AWOL', 'MASH': 'MASH', 'GOAT': 'GOAT',
|
| 126 |
+
'UCLA': 'U C L A', 'ACLU': 'A C L U', 'AARP': 'A A R P', 'IEEE': 'I triple E', 'NAACP': 'N double A C P', 'USAF': 'U S A F',
|
| 127 |
+
'OLED': 'O L E D', 'SQL': 'S Q L', 'AMOLED': 'A M O L E D', 'URL': 'U R L', 'UI': 'U I', 'API': 'A P I',
|
| 128 |
+
'DOS': 'doss', 'LAN': 'lan', 'VLAN': 'vee-lan', 'NAS': 'nass', 'SCSI': 'scuzzy', 'NGINX': 'engine-ex', 'WYSIWYG': 'wizzy-wig',
|
| 129 |
+
'CMOS': 'see-moss', 'BIOS': 'bye-oss', 'SATA': 'say-tuh', 'RAID': 'raid', 'VRAM': 'vee-ram', 'DRAM': 'dee-ram', 'SRAM': 'ess-ram',
|
| 130 |
+
'SDRAM': 'ess-dee-ram', 'IMAP': 'eye-map', 'YAML': 'yamel', 'POP': 'pop', 'WAV': 'wave', 'OGG': 'ogg', 'FLAC': 'flack',
|
| 131 |
+
'MPEG': 'em-peg', 'MIDI': 'middy', 'LUFS': 'luffs', 'LUT': 'lut', 'SMPTE': 'simp-tee', 'PAL': 'pal', 'HUD': 'hud', 'LARP': 'larp',
|
| 132 |
+
'MOBA': 'moba', 'LIDAR': 'lidar', 'PAC': 'pack', 'TED': 'Ted', 'HIPAA': 'hippa',
|
| 133 |
+
}
|
| 134 |
+
ONSETS = set('BL BR CH CL CR DR DW FL FR GL GN GR KL KN KR KW PH PL PR PS QU SC SH SK SL SM SN SP ST SW TH TR TW WH WR SCH SCR SHR SPL '
|
| 135 |
+
'SPR STR THR'.split())
|
| 136 |
+
CODAS = set('CH CK CT FT GH LB LD LF LK LL LM LP LT MB MP ND NG NK NS NT PH PT RB RC RD RF RG RK RL RM RN RP RS RT SH SK SP SS ST TH TS '
|
| 137 |
+
'TZ XT'.split())
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def pronounceable(w):
|
| 141 |
+
if not re.search('[AEIOUY]', w): return False
|
| 142 |
+
if len(w) >= 6: return True
|
| 143 |
+
w = re.sub(r'(?<=[AEIOU])[HWY]', 'E', w)
|
| 144 |
+
for run in re.findall(r'[^AEIOUY]+', w):
|
| 145 |
+
if len(run) > 3: return False
|
| 146 |
+
m = re.match(r'[^AEIOUY]+', w)
|
| 147 |
+
if m and len(m.group(0)) > 1 and m.group(0) not in ONSETS: return False
|
| 148 |
+
m = re.search(r'[^AEIOUY]+$', w)
|
| 149 |
+
if m and len(m.group(0)) > 1 and m.group(0) not in CODAS: return False
|
| 150 |
+
return all(len(r) < 2 or r in ONSETS or r in CODAS or r[:-1] in CODAS and r[-1:] + 'R' in ONSETS | {r[-1:] + 'R'}
|
| 151 |
+
for r in re.findall(r'(?<=[AEIOUY])[^AEIOUY]{2,}(?=[AEIOUY])', w)) or len(w) >= 6
|
| 152 |
+
RESPELLING_CUES = re.compile(r'\b(?:pronounced?|pronouncing|pronunciation|rhymes?|stress(?:ed)?|syllables?|spelled|accent on)\b', re.I)
|
| 153 |
+
RESPELLING = re.compile(r'\b[A-Za-z]+(?:-[A-Za-z]+)+\b')
|
| 154 |
+
RESPELL = {'codec': 'koh-deck', 'codecs': 'koh-decks', 'bitrate': 'bit rate', 'bitrates': 'bit rates', 'iOS': 'eye O S',
|
| 155 |
+
'MySQL': 'my S Q L', 'NoSQL': 'no S Q L', 'PhD': 'P H D', 'PhDs': 'P H Ds',
|
| 156 |
+
'macOS': 'mac O S', 'iPadOS': 'eye-pad O S', 'tvOS': 'T V O S', 'watchOS': 'watch O S'}
|
| 157 |
+
COMMON = set('''a about after again all also always an and any are as at away back bad be because been before being best better big
|
| 158 |
+
both but by call came can come could day did do does done down each even ever every far few find first for from get give go goes going
|
| 159 |
+
gone good got great had has have he her here him his how i if in into is its just keep kind know last least left less let like
|
| 160 |
+
little long look lot love made make man many may me might mine more most much must my need never new next nice no none nor not
|
| 161 |
+
nothing now of off oh old on once one only or our out over own please put real really right run said same saw say see seen she
|
| 162 |
+
should show since so some still stop such sure take tell than thank thanks that the their them then there these they thing think
|
| 163 |
+
this those though through time to too took true try turn two under until up upon use very wait want was watch way we well went
|
| 164 |
+
were what when where which while who whole why will wish with without wow yeah yes yet you your yours hey help hello go stay run
|
| 165 |
+
listen look out right left never ever again done over here there love hate fire free gold big huge boom bang ugh omg wait'''.split())
|
| 166 |
+
REGNAL = set('''Henry Louis Elizabeth George Charles Edward William James Richard John Mary Victoria Anne Philip Felipe Juan Carlos
|
| 167 |
+
Frederick Friedrich Wilhelm Napoleon Peter Catherine Ivan Nicholas Alexander Alfonso Ferdinand Leopold Rudolf Francis Franz Pius
|
| 168 |
+
Benedict Gregory Leo Innocent Clement Boniface Urban Paul Ramesses Ramses Thutmose Amenhotep Ptolemy Constantine Justinian Otto
|
| 169 |
+
Gustav Gustavus Christian Olaf Haakon Harald Pedro Manuel Afonso Henri Ludwig Maximilian Selim Suleiman Mehmed Murad Ahmed Rama
|
| 170 |
+
David Robert Kamehameha Willem Carl Gustaf Harold Edmund Stephen Matilda Sancho Wenceslaus Sigismund Casimir Boleslaw Vladimir
|
| 171 |
+
Basil Michael Andronikos Theodore Sixtus Julius Martin Nicolas Augustus Antiochus Seleucus Darius Xerxes Cyrus Artaxerxes'''.split())
|
| 172 |
+
ROMAN_AFTER = set('''War Part Chapter Act Book Volume Vol Phase Episode Season Level Stage Type Class Gen Generation Mark Bowl Rocky
|
| 173 |
+
Fantasy Edition Round Wave Tier Grade Section Article Title Division Appendix Psalm Canto Scene Movement Symphony Op Opus Unit Year
|
| 174 |
+
Form Saga Quest Wars Kombat Rising Revelations Legacy Origins Collection Chronicles Trilogy Remastered Zero Force Command'''.split())
|
| 175 |
+
STATES = set('AL AK AZ AR CA CO CT DE FL GA HI ID IL IN IA KS KY LA ME MD MA MI MN MS MO MT NE NV NH NJ NM NY NC ND OH OK OR PA RI SC SD '
|
| 176 |
+
'TN TX UT VT VA WA WV WI WY DC'.split())
|
| 177 |
+
TLD_WORDS = set('com net org edu gov mil int info biz shop store blog news art design games site online tech app dev co me so to page '
|
| 178 |
+
'live media cloud space world club life today zone'.split())
|
| 179 |
+
TLDS = TLD_WORDS | set('io ai uk us tv gg ly fm ca de jp fr au nz in xyz eu es it nl se no ch be at dk fi pl ru br mx cn kr'.split())
|
| 180 |
+
EXTENSIONS = {'jpg': 'J P G', 'jpeg': 'jay-peg', 'png': 'P N G', 'gif': 'gif', 'webp': 'web P', 'heic': 'H E I C', 'svg': 'S V G',
|
| 181 |
+
'pdf': 'P D F', 'doc': 'doc', 'docx': 'doc X', 'xls': 'X L S', 'xlsx': 'X L S X', 'ppt': 'P P T', 'pptx': 'P P T X',
|
| 182 |
+
'txt': 'T X T', 'csv': 'C S V', 'md': 'M D', 'json': 'jay-son', 'xml': 'X M L', 'yaml': 'yaml', 'yml': 'Y M L',
|
| 183 |
+
'html': 'H T M L', 'htm': 'H T M', 'css': 'C S S', 'js': 'J S', 'ts': 'T S', 'py': 'P Y', 'rb': 'R B', 'go': 'go',
|
| 184 |
+
'rs': 'R S', 'java': 'java', 'cpp': 'C P P', 'sh': 'S H', 'exe': 'E X E', 'dmg': 'D M G', 'apk': 'A P K',
|
| 185 |
+
'zip': 'zip', 'rar': 'rar', 'tar': 'tar', 'gz': 'G Z', 'iso': 'I S O', 'mp3': 'M P three', 'mp4': 'M P four',
|
| 186 |
+
'm4a': 'M four A', 'wav': 'wave', 'flac': 'flack', 'ogg': 'ogg', 'mov': 'mov', 'avi': 'A V I', 'mkv': 'M K V',
|
| 187 |
+
'webm': 'web M', 'srt': 'S R T', 'epub': 'E pub', 'ttf': 'T T F', 'otf': 'O T F', 'psd': 'P S D', 'raw': 'raw',
|
| 188 |
+
'arw': 'A R W', 'cr2': 'C R two', 'cr3': 'C R three', 'nef': 'N E F', 'dng': 'D N G', 'tif': 'tiff', 'tiff': 'tiff',
|
| 189 |
+
'bmp': 'B M P', 'log': 'log', 'ini': 'I N I', 'cfg': 'C F G', 'sql': 'S Q L', 'db': 'D B', 'bak': 'back',
|
| 190 |
+
'pages': 'pages', 'key': 'key', 'numbers': 'numbers', 'ipynb': 'I P Y N B', 'kt': 'K T', 'swift': 'swift',
|
| 191 |
+
'odt': 'O D T', 'ods': 'O D S', 'odp': 'O D P', 'rtf': 'R T F'}
|
| 192 |
+
ABBREVIATIONS = {
|
| 193 |
+
'Mr.': 'Mister', 'Mrs.': 'Missus', 'Ms.': 'Miz', 'Prof.': 'Professor', 'Lt.': 'Lieutenant', 'Sgt.': 'Sergeant',
|
| 194 |
+
'Capt.': 'Captain', 'Col.': 'Colonel', 'Gen.': 'General', 'Gov.': 'Governor', 'Sen.': 'Senator', 'Rep.': 'Representative',
|
| 195 |
+
'Pres.': 'President', 'Rev.': 'Reverend', 'Hon.': 'Honorable', 'Supt.': 'Superintendent', 'Cmdr.': 'Commander',
|
| 196 |
+
'vs.': 'versus', 'vs': 'versus', 'etc.': 'et cetera', 'e.g.': 'for example', 'i.e.': 'that is', 'approx.': 'approximately',
|
| 197 |
+
'dept.': 'department', 'Dept.': 'Department', 'est.': 'established', 'Est.': 'Established', 'misc.': 'miscellaneous',
|
| 198 |
+
'govt.': 'government', 'Govt.': 'Government', 'Inc.': 'Incorporated', 'Ltd.': 'Limited', 'Corp.': 'Corporation',
|
| 199 |
+
'Bros.': 'Brothers', 'Assn.': 'Association', 'Univ.': 'University', 'Intl.': 'International', 'Natl.': 'National',
|
| 200 |
+
'Ave.': 'Avenue', 'Blvd.': 'Boulevard', 'Rd.': 'Road', 'Ln.': 'Lane', 'Hwy.': 'Highway', 'Rte.': 'Route', 'Pkwy.': 'Parkway',
|
| 201 |
+
'Apt.': 'Apartment', 'Ste.': 'Suite', 'Mt.': 'Mount', 'Ft.': 'Fort', 'Jr.': 'Junior', 'Sr.': 'Senior', 'Ph.D.': 'P H D',
|
| 202 |
+
'Fig.': 'Figure', 'fig.': 'figure', 'Vol.': 'Volume', 'vol.': 'volume', 'Ch.': 'Chapter', 'ch.': 'chapter', 'pp.': 'pages',
|
| 203 |
+
'pg.': 'page', 'max.': 'maximum', 'min.': 'minimum', 'avg.': 'average', 'temp.': 'temperature', 'ext.': 'extension',
|
| 204 |
+
'Mon.': 'Monday', 'Tue.': 'Tuesday', 'Tues.': 'Tuesday', 'Wed.': 'Wednesday', 'Thu.': 'Thursday', 'Thur.': 'Thursday',
|
| 205 |
+
'Thurs.': 'Thursday', 'Fri.': 'Friday', 'Sat.': 'Saturday', 'Sun.': 'Sunday',
|
| 206 |
+
'w/': 'with', 'w/o': 'without', 'b/c': 'because', 'c/o': 'care of', 'N/A': 'not applicable', 'n/a': 'not applicable',
|
| 207 |
+
'a/c': 'A C', 'A/C': 'A C', 'P/E': 'P E', 'TL;DR': 'T L D R', 'tl;dr': 'T L D R',
|
| 208 |
+
}
|
| 209 |
+
TITLES = {'Mr.', 'Mrs.', 'Ms.', 'Prof.', 'Lt.', 'Sgt.', 'Capt.', 'Col.', 'Gen.', 'Gov.', 'Sen.', 'Rep.', 'Pres.', 'Rev.', 'Hon.', 'Supt.',
|
| 210 |
+
'Cmdr.', 'Mt.', 'Ft.'}
|
| 211 |
+
ENDS_SENTENCE = {'etc.', 'Inc.', 'Ltd.', 'Corp.', 'Bros.', 'Jr.', 'Sr.', 'Ave.', 'Blvd.', 'Rd.', 'Ln.', 'Hwy.', 'Pkwy.', 'Ph.D.',
|
| 212 |
+
'approx.', 'misc.', 'Assn.', 'Univ.'}
|
| 213 |
+
NETSPEAK = {'rn': 'right now', 'gtg': 'got to go', 'brb': 'be right back', 'idk': "I don't know", 'tbh': 'to be honest',
|
| 214 |
+
'imo': 'in my opinion', 'imho': 'in my humble opinion', 'btw': 'by the way', 'irl': 'in real life', 'np': 'no problem',
|
| 215 |
+
'thx': 'thanks', 'ty': 'thank you', 'pls': 'please', 'plz': 'please', 'ngl': 'not gonna lie', 'jk': 'just kidding',
|
| 216 |
+
'nvm': 'never mind', 'ikr': 'I know, right', 'afaik': 'as far as I know', 'smh': 'S M H', 'lol': 'L O L', 'lmao': 'L M A O',
|
| 217 |
+
'omg': 'O M G', 'wtf': 'W T F', 'fyi': 'F Y I', 'dm': 'D M', 'dms': 'D Ms', 'gg': 'G G', 'afk': 'A F K', 'ftw': 'for the win',
|
| 218 |
+
'ngmi': 'N G M I', 'wagmi': 'wag me', 'bc': 'because', 'atm': 'at the moment', 'iirc': 'if I recall correctly',
|
| 219 |
+
'ootd': 'outfit of the day', 'ianal': 'I A N A L', 'npc': 'N P C', 'npcs': 'N P Cs', 'eli5': 'E L I five', 'iykyk': 'I Y K Y K',
|
| 220 |
+
'qotd': 'Q O T D', 'tfw': 'T F W', 'mfw': 'M F W', 'pov': 'P O V', 'pfp': 'P F P', 'ofc': 'of course', 'nsfw': 'N S F W',
|
| 221 |
+
'omw': 'on my way', 'hmu': 'hit me up', 'wyd': 'what are you doing', 'hbu': 'how about you', 'ily': 'I love you',
|
| 222 |
+
'idc': "I don't care", 'tmi': 'T M I', 'lmk': 'let me know', 'ttyl': 'talk to you later', 'nbd': 'no big deal',
|
| 223 |
+
'wfh': 'work from home', 'lfg': 'L F G', 'icymi': 'in case you missed it', 'tbt': 'T B T', 'fwiw': "for what it's worth",
|
| 224 |
+
'tbf': 'to be fair', 'tysm': 'thank you so much', 'pvp': 'P V P', 'pve': 'P V E', 'mmo': 'M M O', 'rpg': 'R P G',
|
| 225 |
+
'fr': 'for real', 'ymmv': 'Y M M V', 'fyp': 'F Y P', 'istg': 'I swear to God', 'tl;dr': 'T L D R'}
|
| 226 |
+
KEYS = {'Cmd': 'Command', 'Ctrl': 'Control', 'Alt': 'Alt', 'Opt': 'Option', 'Option': 'Option', 'Shift': 'Shift', 'Win': 'Windows',
|
| 227 |
+
'Fn': 'Function', 'Esc': 'Escape', 'Del': 'Delete', 'Tab': 'Tab', 'Enter': 'Enter', 'Return': 'Return', 'Space': 'Space',
|
| 228 |
+
'Super': 'Super', 'Meta': 'Meta', 'Backspace': 'Backspace', 'PgUp': 'Page Up', 'PgDn': 'Page Down', 'Home': 'Home', 'End': 'End'}
|
| 229 |
+
YEAR_CUES = set('in since from by until till til circa c. ca. during before after around of year years spring summer fall autumn winter '
|
| 230 |
+
'early late mid the and to through between class vintage born died founded built released'.split())
|
| 231 |
+
FRACTION_DENOMS = {2, 3, 4, 5, 6, 8, 10, 12, 16, 32, 64, 100}
|
| 232 |
+
CODE_WORDS = set('zip code pin id ext extension account acct order confirmation ticket serial reference ref tracking postcode passcode'.split())
|
| 233 |
+
STREET = r'(?:St|Street|Ave|Avenue|Rd|Road|Blvd|Boulevard|Dr|Drive|Ln|Lane|Way|Ct|Court|Pl|Place|Pkwy|Parkway|Hwy|Highway|Ter|Terrace|Cir|Circle|Trail)\b'
|
| 234 |
+
QUANTITY_NOUNS = set('people men women children kids staff crew personnel feet foot money cash fish sheep deer'.split())
|
| 235 |
+
NOT_PLURAL = set('''was is has does gives goes makes takes sees says gets comes means seems marks changes brings starts ends begins
|
| 236 |
+
sits stands looks feels works runs plays shows its this his hers as us yes plus minus versus whereas always perhaps unless besides
|
| 237 |
+
thus across less series news '''.split())
|
| 238 |
+
NUM = r'\d{1,3}(?:,\d{3})+|\d+'
|
| 239 |
+
DEC = rf'(?:{NUM})(?:\.\d+)?|\.\d+'
|
| 240 |
+
BEFORE = r'(?<![\w.,/$€£¥₹#@-])'
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def _unit(u):
|
| 244 |
+
v = UNITS[u]
|
| 245 |
+
return v if isinstance(v, tuple) else (v, v + 's')
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def letters(s):
|
| 249 |
+
return ' '.join(s.upper())
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def ident(s):
|
| 253 |
+
out = []
|
| 254 |
+
for part in re.split(r'([_.\-])', s):
|
| 255 |
+
if part in ('_', '.', '-'): out.append({'_': 'underscore', '.': 'dot', '-': 'dash'}[part]); continue
|
| 256 |
+
for run in re.findall(r'[A-Za-z]+|\d+', part):
|
| 257 |
+
if run.isdigit(): out.append(year(int(run)) if len(run) == 4 and 1900 <= int(run) <= 2099 else
|
| 258 |
+
cardinal(run) if len(run) <= 2 else digits(run))
|
| 259 |
+
elif run.isupper() and len(run) > 1 and run not in AS_WORDS: out.append(letters(run))
|
| 260 |
+
else: out.append(AS_WORDS.get(run, run))
|
| 261 |
+
return ' '.join(out)
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def alnum(s):
|
| 265 |
+
out = []
|
| 266 |
+
chem = re.fullmatch(r'(?:[A-Z][a-z]?\d*){2,}', s) and re.search(r'\d', s) and not re.search(r'[a-z]{2}', s)
|
| 267 |
+
for part in s.split('-'):
|
| 268 |
+
for run in re.findall(r'[A-Za-z]+|\d+\.\d+|\d+', part):
|
| 269 |
+
if run[0].isdigit(): out.append(decimal(run) if '.' in run else pairs(run))
|
| 270 |
+
elif chem or len(run) == 1 or run.isupper() and run not in AS_WORDS or len(run) <= 3 and not re.search(r'[aeiouyAEIOUY]', run):
|
| 271 |
+
out.append(letters(run))
|
| 272 |
+
else: out.append(AS_WORDS.get(run, run))
|
| 273 |
+
return ' '.join(out)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def roman(s):
|
| 277 |
+
vals = dict(I=1, V=5, X=10, L=50, C=100)
|
| 278 |
+
total = 0
|
| 279 |
+
for a, b in zip(s, s[1:] + ' '):
|
| 280 |
+
total += -vals[a] if vals.get(b, 0) > vals[a] else vals[a]
|
| 281 |
+
return total if 0 < total < 400 and re.fullmatch(r'C{0,3}(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})', s) else None
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def _sub(pattern, fn, s, flags=0):
|
| 285 |
+
return re.sub(pattern, fn, s, flags=flags)
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def _money(m):
|
| 289 |
+
neg, cur, a, sa, b, sb = m.group('neg'), m.group('cur'), m.group('a'), m.group('sa'), m.group('b'), m.group('sb')
|
| 290 |
+
one, many, sub1, subs = CURRENCIES[cur]
|
| 291 |
+
|
| 292 |
+
def amount(x, scale):
|
| 293 |
+
if scale:
|
| 294 |
+
return f'{decimal(x)} {SCALE_WORDS.get(scale, scale.lower())}', True
|
| 295 |
+
whole, _, frac = x.replace(',', '').partition('.')
|
| 296 |
+
if not sub1 or not frac: return decimal(x), (x.replace(',', '') != '1')
|
| 297 |
+
cents = int((frac + '0')[:2])
|
| 298 |
+
w = int(whole or 0)
|
| 299 |
+
if not w: return f'{number(cents)} {sub1 if cents == 1 else subs}', None
|
| 300 |
+
return f'{number(w)} {one if w == 1 else many}' + (f' and {number(cents)} {sub1 if cents == 1 else subs}' if cents else ''), None
|
| 301 |
+
|
| 302 |
+
first, plural_a = amount(a, sa)
|
| 303 |
+
out = ('minus ' if neg else '')
|
| 304 |
+
if b:
|
| 305 |
+
second, plural_b = amount(b, sb or sa)
|
| 306 |
+
if plural_a is not None and plural_b is not None: return out + f'{first} to {second} {many}'
|
| 307 |
+
if plural_a is not None: first += f' {many if plural_a else one}'
|
| 308 |
+
if plural_b is not None: second += f' {many if plural_b else one}'
|
| 309 |
+
return out + f'{first} to {second}'
|
| 310 |
+
return out + (first if plural_a is None else f'{first} {many if plural_a else one}')
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def _time(m):
|
| 314 |
+
h, mm, ap = int(m.group(1)), int(m.group(2)), m.group(3)
|
| 315 |
+
hw = number(h % 12 or 12) if ap else number(h)
|
| 316 |
+
if mm == 0: words = hw if ap else (f'{hw} hundred' if h >= 13 or h == 0 else f"{hw} o'clock")
|
| 317 |
+
else: words = f'{hw} oh {ONES[mm]}' if mm < 10 else f'{hw} {number(mm)}'
|
| 318 |
+
return words + (f' {ap[0].upper()} M' if ap else '')
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def _duration(m):
|
| 322 |
+
h, mi, se = int(m.group(1)), int(m.group(2)), int(m.group(3))
|
| 323 |
+
parts = [f'{number(v)} {u}{"" if v == 1 else "s"}' for v, u in ((h, 'hour'), (mi, 'minute'), (se, 'second')) if v]
|
| 324 |
+
return ', '.join(parts[:-1]) + (' and ' if len(parts) > 1 else '') + parts[-1] if parts else 'zero seconds'
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def _date_words(mo, d, y=None, order='us'):
|
| 328 |
+
month = MONTHS[mo - 1]
|
| 329 |
+
out = f'{month} {ordinal(d)}' if order == 'us' else f'the {ordinal(d)} of {month}'
|
| 330 |
+
if y is not None: out += ', ' + (year(y) if len(str(y)) == 4 else short_year(str(y).zfill(2)))
|
| 331 |
+
return out
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def short_year(yy):
|
| 335 |
+
return 'oh ' + ONES[int(yy[1])] if yy[0] == '0' else number(int(yy))
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def _month_index(name):
|
| 339 |
+
return [m[:3] for m in MONTHS].index(name[:3].title()) + 1
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def _unit_amount(m):
|
| 343 |
+
a, b, u, pw = m.group('a'), m.group('b'), m.group('u'), m.group('pw')
|
| 344 |
+
one, many = _unit(u)
|
| 345 |
+
if pw:
|
| 346 |
+
p = POWERS[pw]; one, many = f'{p} {one}', f'{p} {many}'
|
| 347 |
+
first = decimal(a)
|
| 348 |
+
if b: return f'{first} to {decimal(b)} {many}'
|
| 349 |
+
return f'{first} {one if a == "1" else many}'
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def _number_in_context(m):
|
| 353 |
+
raw, s = m.group(0), m.string
|
| 354 |
+
if len(raw) > 1 and raw[0] == '0': return digits(raw)
|
| 355 |
+
before, after = s[:m.start()], s[m.end():]
|
| 356 |
+
pm = re.search(r"([A-Za-z][\w.']*)\s+$", before)
|
| 357 |
+
prev = pm.group(1) if pm else ''
|
| 358 |
+
starts = not pm or re.search(r'(^|[.!?:;]\s+|["(]\s*)$', before[:pm.start()]) is not None
|
| 359 |
+
nm = re.match(r'\s+([a-z]+)', after); nxt = nm.group(1) if nm else ''
|
| 360 |
+
v = int(raw)
|
| 361 |
+
counted = nxt in QUANTITY_NOUNS or nxt.endswith('s') and nxt not in NOT_PLURAL
|
| 362 |
+
if prev.lower().rstrip('.') in CODE_WORDS and len(raw) >= 4 and not counted: return digits(raw)
|
| 363 |
+
if 3 <= len(raw) <= 5 and re.match(r'\s+(?:[A-Z][\w]*\.?\s+){1,3}' + STREET, after): return pairs(raw)
|
| 364 |
+
if len(raw) == 4:
|
| 365 |
+
if prev.lower() in YEAR_CUES or not counted: return year(v)
|
| 366 |
+
return number(v // 100) + ' hundred' if v % 100 == 0 and v % 1000 else number(v)
|
| 367 |
+
if len(raw) == 3 and prev and (prev.isupper() and len(prev) > 1 or prev[0].isupper() and not starts):
|
| 368 |
+
return pairs(raw)
|
| 369 |
+
return number(v)
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def _words(s):
|
| 373 |
+
s = re.sub(r'(^|[.!?]["\')\]]?\s+)(?=[-$€£¥₹#~+]?\d)', _opener, s)
|
| 374 |
+
s = _rules(s)
|
| 375 |
+
return re.sub('\x01(.)', lambda m: m.group(1).upper(), s).replace('\x01', '')
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
SHORT_ABBR = re.compile(r'\b(?:[A-Z][a-z]{0,3}|no|vol|pp|pg|ch|fig|sec|art|ca|vs|ex|est|ed|p|c)\.$')
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def _opener(m):
|
| 382 |
+
lead = m.group(1)
|
| 383 |
+
return lead if lead.startswith('.') and SHORT_ABBR.search(m.string[:m.start() + 1]) else lead + '\x01'
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def _rules(s):
|
| 387 |
+
s = s.replace(' ', ' ').replace(' ', ' ').replace(' ', ' ').replace('‑', '-').replace('−', '-')
|
| 388 |
+
s = s.translate(str.maketrans('₀₁₂₃₄₅₆₇₈₉′″', "0123456789'\""))
|
| 389 |
+
for f, (n, d) in {'½': (1, 2), '⅓': (1, 3), '⅔': (2, 3), '¼': (1, 4), '¾': (3, 4), '⅕': (1, 5), '⅛': (1, 8), '⅜': (3, 8),
|
| 390 |
+
'⅝': (5, 8), '⅞': (7, 8)}.items():
|
| 391 |
+
s = re.sub(rf'(\d)\s?{f}', rf'\1 {n}/{d}', s).replace(f, f'{n}/{d}')
|
| 392 |
+
|
| 393 |
+
s = _sub(r'\b([\w.+-]+)@([\w-]+(?:\.[\w-]+)+)\b',
|
| 394 |
+
lambda m: f'{ident(m.group(1))} at {_domain(m.group(2))}', s)
|
| 395 |
+
s = _sub(r'\b(?:(https?)://)?((?:www\.)?(?:[A-Za-z0-9-]+\.)+(?:' + '|'.join(sorted(TLDS, key=len, reverse=True)) + r'))\b(/[^\s,;!?)"]*[^\s,;!?)".])?',
|
| 396 |
+
lambda m: _url(m), s)
|
| 397 |
+
s = _sub(r'(?<![\w@/])([ur])/([A-Za-z0-9_]{2,})', lambda m: f'{m.group(1)} slash {ident(m.group(2))}', s)
|
| 398 |
+
s = _sub(r'(?<![\w@])@([A-Za-z0-9_]{2,})', lambda m: f'at {ident(m.group(1))}', s)
|
| 399 |
+
s = _sub(r'(?<![\w&#])#\s?(\d+)\b', lambda m: f'number {cardinal(m.group(1)) if len(m.group(1)) <= 4 else digits(m.group(1))}', s)
|
| 400 |
+
s = _sub(r'(?<![\w&#])#([A-Za-z]\w*)', lambda m: f'hashtag {m.group(1)}', s)
|
| 401 |
+
ext = '|'.join(sorted(EXTENSIONS, key=len, reverse=True))
|
| 402 |
+
s = _sub(rf'\b([\w-]+)((?:\.(?:{ext}))+)\b', lambda m: ident(m.group(1)) + ''.join(
|
| 403 |
+
f' dot {EXTENSIONS[e.lower()]}' for e in m.group(2).split('.')[1:]), s, flags=re.I)
|
| 404 |
+
s = _sub(r'\b(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\b', lambda m: ' dot '.join(pairs(g) if len(g) == 3 else cardinal(g)
|
| 405 |
+
for g in m.groups()), s)
|
| 406 |
+
|
| 407 |
+
s = _sub(r'\b(' + '|'.join(NETSPEAK) + r')\b', lambda m: NETSPEAK[m.group(1)], s)
|
| 408 |
+
|
| 409 |
+
s = _sub(r'\b(?:' + '|'.join(KEYS) + r')(?:\s?\+\s?(?:' + '|'.join(KEYS) + r'|F\d{1,2}|[A-Za-z0-9]))+\b',
|
| 410 |
+
lambda m: ' '.join(KEYS.get(k, alnum(k) if re.search(r'\d', k) else k) for k in re.split(r'\s?\+\s?', m.group(0))), s)
|
| 411 |
+
s = _sub(r'\b([A-Z]{2,})/(?=\d)', r'\1 ', s)
|
| 412 |
+
s = _sub(r'(?<![\w+])(\+\d{1,3}[\s.-]?)?(\(\d{3}\)\s?|\b\d{3}[.-])(\d{3})[.-](\d{4})\b',
|
| 413 |
+
lambda m: (f'plus {digits(m.group(1), "oh")}, ' if m.group(1) else '') +
|
| 414 |
+
', '.join(digits(g, 'oh') for g in (m.group(2), m.group(3), m.group(4))), s)
|
| 415 |
+
s = _sub(r'(?<![\w+])\+(\d{1,3})((?:[\s.-]\(?\d{1,4}\)?){2,5})(?![\d.,]\d)',
|
| 416 |
+
lambda m: f'plus {digits(m.group(1), "oh")}, ' + ', '.join(digits(g, 'oh') for g in re.findall(r'\d+', m.group(2))), s)
|
| 417 |
+
s = _sub(r'(?<![\w.])[vV](\d+(?:\.\d+)*)\b', lambda m: 'version ' + ' point '.join(cardinal(p) for p in m.group(1).split('.')), s)
|
| 418 |
+
s = _sub(r'(?<![\w.])(\d+)\.(\d+)\.(\d+)(?:\.(\d+))?(?![\w.])', lambda m: ' point '.join(cardinal(p) for p in m.groups() if p), s)
|
| 419 |
+
s = _sub(r'\b(\d{5})-(\d{4})\b', lambda m: f'{digits(m.group(1))}, {digits(m.group(2))}', s)
|
| 420 |
+
s = _sub(r'(?<![\w$.-])(\d{3})-(\d{4})\b', lambda m: m.group(0) if int(m.group(1)) % 100 == 0 and int(m.group(2)) % 100 == 0
|
| 421 |
+
else f'{digits(m.group(1), "oh")}, {digits(m.group(2), "oh")}', s)
|
| 422 |
+
s = _sub(r'\b([A-Z]{2})\s+(\d{5})\b', lambda m: f'{m.group(1)} {digits(m.group(2))}' if m.group(1) in STATES else m.group(0), s)
|
| 423 |
+
|
| 424 |
+
s = _sub(r'(\d+(?:\.\d+)?)\s?°\s?(?:(\d+(?:\.\d+)?)\s?\'\s?)?(?:(\d+(?:\.\d+)?)\s?"\s?)?([NSEW])\b',
|
| 425 |
+
lambda m: f'{decimal(m.group(1))} degrees' + (f' {decimal(m.group(2))} minutes' if m.group(2) else '') +
|
| 426 |
+
(f' {decimal(m.group(3))} seconds' if m.group(3) else '') + ' ' + dict(N='north', S='south', E='east', W='west')[m.group(4)], s)
|
| 427 |
+
s = _sub(BEFORE + r'(-?)(\d+(?:\.\d+)?)\s?°\s?([FCK])\b', lambda m: ('minus ' if m.group(1) else '') + f'{decimal(m.group(2))} degrees ' +
|
| 428 |
+
dict(F='Fahrenheit', C='Celsius', K='Kelvin')[m.group(3)], s)
|
| 429 |
+
s = _sub(BEFORE + r'(-?)(\d+(?:\.\d+)?)\s?°', lambda m: ('minus ' if m.group(1) else '') + f'{decimal(m.group(2))} degrees', s)
|
| 430 |
+
s = _sub(r"\b(\d+)'\s?(\d{1,2})(?:\"|'')", lambda m: f'{number(int(m.group(1)))} foot {number(int(m.group(2)))}', s)
|
| 431 |
+
s = _sub(r"\b(\d+)'(?=[\s,.;!?]|$)", lambda m: f'{number(int(m.group(1)))} feet', s)
|
| 432 |
+
|
| 433 |
+
s = _sub(r'\b(\d{1,2}):([0-5]\d):([0-5]\d)\b', _duration, s)
|
| 434 |
+
s = _sub(r'\b([01]?\d|2[0-3]):([0-5]\d)(?:\s?([AaPp])\.?\s?[Mm]\.?(?![\w]))?(?![\w:])', _time, s)
|
| 435 |
+
s = _sub(r'\b(\d{1,2})\s?([AaPp])\.?\s?[Mm]\.?(?![\w])', lambda m: f'{number(int(m.group(1)))} {m.group(2).upper()} M', s)
|
| 436 |
+
s = _sub(r'\b(\d+)\s?h(?:rs?)?\s?(\d+)\s?m(?:ins?)?(?:\s?(\d+)\s?s(?:ecs?)?)?\b',
|
| 437 |
+
lambda m: ' '.join(f'{number(int(v))} {u}{"" if v == "1" else "s"}' for v, u in
|
| 438 |
+
((m.group(1), 'hour'), (m.group(2), 'minute'), (m.group(3), 'second')) if v), s)
|
| 439 |
+
s = _sub(r'\b(\d+)\s?m(?:ins?)?\s?(\d+)\s?s(?:ecs?)?\b',
|
| 440 |
+
lambda m: f'{number(int(m.group(1)))} minute{"" if m.group(1) == "1" else "s"} {number(int(m.group(2)))} second'
|
| 441 |
+
f'{"" if m.group(2) == "1" else "s"}', s)
|
| 442 |
+
s = _sub(r'\b(\d+)h\b', lambda m: f'{number(int(m.group(1)))} hour{"" if m.group(1) == "1" else "s"}', s)
|
| 443 |
+
|
| 444 |
+
s = _sub(r'\b' + MONTH.pattern + r'\.?\s+(\d{1,2})(?:st|nd|rd|th)?\b(?:,?\s+(\d{4})\b)?(?!:)',
|
| 445 |
+
lambda m: _date_words(_month_index(m.group(1)), int(m.group(2)), int(m.group(3)) if m.group(3) else None)
|
| 446 |
+
if 1 <= int(m.group(2)) <= 31 else m.group(0), s)
|
| 447 |
+
s = _sub(r'\b' + MONTH.pattern + r"\.?\s+'(\d{2})\b", lambda m: f'{MONTHS[_month_index(m.group(1)) - 1]} {short_year(m.group(2))}', s)
|
| 448 |
+
s = _sub(r'\b(\d{1,2})(?:st|nd|rd|th)?\s+' + MONTH.pattern + r'\b\.?(?:,?\s+(\d{4})\b)?',
|
| 449 |
+
lambda m: _date_words(_month_index(m.group(2)), int(m.group(1)), int(m.group(3)) if m.group(3) else None, 'uk')
|
| 450 |
+
if 1 <= int(m.group(1)) <= 31 else m.group(0), s)
|
| 451 |
+
s = _sub(r'\b(\d{4})-(\d{2})-(\d{2})\b', lambda m: _date_words(int(m.group(2)), int(m.group(3)), int(m.group(1)))
|
| 452 |
+
if 1 <= int(m.group(2)) <= 12 and 1 <= int(m.group(3)) <= 31 else m.group(0), s)
|
| 453 |
+
s = _sub(r'(?<![\w/.])(\d{1,2})/(\d{1,2})/(\d{4}|\d{2})(?![\w/])', _numeric_date, s)
|
| 454 |
+
s = _sub(r'\b(Jan|Feb|Mar|Apr|Jun|Jul|Aug|Sep|Sept|Oct|Nov|Dec)\.(?=\s|$)',
|
| 455 |
+
lambda m: MONTHS[_month_index(m.group(1)) - 1] + ('.' if _ends(m) else ''), s)
|
| 456 |
+
|
| 457 |
+
s = _sub(r'\b(\d{3})\(([a-z])\)', lambda m: f'{pairs(m.group(1))} {m.group(2).upper()}', s)
|
| 458 |
+
s = _sub(rf'{BEFORE}(\d+)\^(-?\d+)\b', lambda m: f'{number(int(m.group(1)))} to the ' +
|
| 459 |
+
('minus ' if m.group(2)[0] == '-' else '') + ordinal(abs(int(m.group(2)))), s)
|
| 460 |
+
s = _sub(r'\b(ft|in|yd|m|cm|km|mi|mm)\.(?=[²³])', r'\1', s)
|
| 461 |
+
s = _sub(r'\${2,4}', lambda m: f'{number(len(m.group(0)))} dollar signs', s)
|
| 462 |
+
codes = '|'.join(CODES)
|
| 463 |
+
s = _sub(rf'\b({codes})\s?({DEC})\b', lambda m: f'{decimal(m.group(2))} {CODES[m.group(1)][m.group(2) != "1"]}', s)
|
| 464 |
+
s = _sub(rf'{BEFORE}({DEC})\s?({codes})\b', lambda m: f'{decimal(m.group(1))} {CODES[m.group(2)][m.group(1) != "1"]}', s)
|
| 465 |
+
cur = '|'.join(re.escape(c) for c in sorted(CURRENCIES, key=len, reverse=True))
|
| 466 |
+
scale = r'(?:k|K|mm|MM|mn|m|M|bn|Bn|b|B|tn|t|T|thousand|million|billion|trillion)\b'
|
| 467 |
+
s = _sub(rf'(?<![\w$])(?P<neg>-)?(?P<cur>{cur})\s?(?P<a>{DEC})(?:\s?(?P<sa>{scale}))?'
|
| 468 |
+
rf'(?:\s?(?:-|–|to)\s?(?:{cur})?\s?(?P<b>{DEC})(?:\s?(?P<sb>{scale}))?)?', _money, s)
|
| 469 |
+
s = _sub(r'\b3M\b', 'three M', s)
|
| 470 |
+
s = _sub(rf'{BEFORE}({DEC})\s?(M|MM|mn|B|bn|Bn|T|tn)(?=[\s,.;:!?)]|$)', lambda m: f'{decimal(m.group(1))} {SCALE_WORDS[m.group(2)]}', s)
|
| 471 |
+
s = _sub(rf'{BEFORE}(\d+)\s?¢', lambda m: f'{number(int(m.group(1)))} cent{"" if m.group(1) == "1" else "s"}', s)
|
| 472 |
+
s = _sub(rf'{BEFORE}(-?)({DEC})(?:\s?(?:-|–|to)\s?({DEC}))?\s?%',
|
| 473 |
+
lambda m: ('minus ' if m.group(1) else '') + decimal(m.group(2)) + (f' to {decimal(m.group(3))}' if m.group(3) else '') + ' percent', s)
|
| 474 |
+
units = '|'.join(re.escape(u) for u in sorted(UNITS, key=len, reverse=True))
|
| 475 |
+
s = _sub(rf'{BEFORE}(?P<a>{DEC})(?:\s?(?:-|–|to)\s?(?P<b>{DEC}))?\s?(?P<u>{units})(?P<pw>²|³|\^2|\^3)?(?![\w/])', _unit_amount, s)
|
| 476 |
+
s = _sub(rf'{BEFORE}(\d+)\s(\d)/(\d+)\s?(?P<u>{units})(?![\w/])',
|
| 477 |
+
lambda m: f'{number(int(m.group(1)))} and {fraction(int(m.group(2)), int(m.group(3)))} {_unit(m.group("u"))[1]}', s)
|
| 478 |
+
s = _sub(rf'{BEFORE}(\d)/(\d+)\s?(?P<u>{units})(?![\w/])',
|
| 479 |
+
lambda m: fraction(int(m.group(1)), int(m.group(2)), _unit(m.group('u'))[0]), s)
|
| 480 |
+
s = _sub(rf'{BEFORE}({DEC})\s?×\s?({DEC})', lambda m: f'{decimal(m.group(1))} by {decimal(m.group(2))}', s)
|
| 481 |
+
s = _sub(rf'{BEFORE}({DEC})\s?[x×](?=\s|$|[,.;!?])', lambda m: f'{decimal(m.group(1))} times', s)
|
| 482 |
+
s = _sub(r'(?<![\w])[x×](\d+(?:\.\d+)?)\b', lambda m: f'times {decimal(m.group(1))}', s)
|
| 483 |
+
s = _sub(r'\b(\d+)v(\d+)\b', lambda m: f'{number(int(m.group(1)))} versus {number(int(m.group(2)))}', s)
|
| 484 |
+
s = _sub(r'\b(\d{3,4})p\b', lambda m: f'{pairs(m.group(1))} p', s)
|
| 485 |
+
|
| 486 |
+
s = _sub(r'\b24/7\b', 'twenty-four seven', s)
|
| 487 |
+
s = _sub(r'\b9[-/]11\b', 'nine eleven', s)
|
| 488 |
+
s = _sub(rf'{BEFORE}(\d+)\s(\d)/(\d+)(?![\w/])', lambda m: f'{number(int(m.group(1)))} and ' +
|
| 489 |
+
('a half' if m.group(2) + m.group(3) == '12' else fraction(int(m.group(2)), int(m.group(3)))), s)
|
| 490 |
+
s = _sub(rf'{BEFORE}(\d{{1,3}})/(\d{{1,3}})(?![\w/])', _slash_numbers, s)
|
| 491 |
+
s = _sub(r'\b(\d+):(\d+)\b', lambda m: f'{cardinal(m.group(1))} to {cardinal(m.group(2))}', s)
|
| 492 |
+
s = _sub(r'\b(\d+)(?:-(\d+)){2,}\b', lambda m: ' '.join(cardinal(g) for g in m.group(0).split('-')), s)
|
| 493 |
+
s = _sub(r'\b(\d{4})s\b|\b(\d{4})\'s\b', lambda m: plural(year(int(m.group(1) or m.group(2)))), s)
|
| 494 |
+
s = _sub(r"(?<![\w'])'(\d)0s\b", lambda m: plural(TENS[int(m.group(1))]), s)
|
| 495 |
+
s = _sub(r'\b([2-9])0s\b', lambda m: plural(TENS[int(m.group(1))]), s)
|
| 496 |
+
s = _sub(r"(?<![\w'])'(\d{2})\b(?!')", lambda m: short_year(m.group(1)), s)
|
| 497 |
+
s = _sub(rf'{BEFORE}(\d{{4}})\s?[–-]\s?(\d{{2}}|\d{{4}})(?![\w-])', _year_range, s)
|
| 498 |
+
s = _sub(rf'{BEFORE}(-?{DEC})\s?(?:–|-)\s?(-?{DEC})(?![\w-])', lambda m: f'{decimal_signed(m.group(1))} to {decimal_signed(m.group(2))}', s)
|
| 499 |
+
s = _sub(r'\b(\d+)(st|nd|rd|th|ST|ND|RD|TH)\b', lambda m: ordinal(int(m.group(1))), s)
|
| 500 |
+
s = _sub(r'\b(\d+)s\b', lambda m: {'1': 'ones', '0': 'zeros'}.get(m.group(1)) or f'{number(int(m.group(1)))} seconds', s)
|
| 501 |
+
|
| 502 |
+
s = _sub(rf'{BEFORE}(\d{{1,3}}(?:,\d{{3}})+(?:\.\d+)?|\d+\.\d+)-(?=[A-Za-z])', lambda m: decimal(m.group(1)) + ' ', s)
|
| 503 |
+
s = _sub(r'\b(\d+)[x×](\d+)\b', lambda m: f'{cardinal(m.group(1)) if len(m.group(1)) < 4 else pairs(m.group(1))} by '
|
| 504 |
+
f'{cardinal(m.group(2)) if len(m.group(2)) < 4 else pairs(m.group(2))}', s)
|
| 505 |
+
s = _sub(r'\b(?=[A-Za-z0-9.-]*\d)(?=[A-Za-z0-9.-]*[A-Za-z])[A-Za-z0-9]+(?:\.\d+)?(?:-[A-Za-z0-9]+(?:\.\d+)?)*\b',
|
| 506 |
+
lambda m: alnum(m.group(0)), s)
|
| 507 |
+
s = _sub(r'\b([A-Z][a-z]+(?:\s[A-Z][a-z]+)?)\s(I|[IVXLC]{2,8})\b(?!\.\w)', _roman, s)
|
| 508 |
+
|
| 509 |
+
s = _sub(rf'(?<![\w.,-])-(?={DEC})', 'minus ', s)
|
| 510 |
+
s = _sub(r'(?<![\w.,])(\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d*\.\d+)(?![\w,]|\.\d)', lambda m: decimal(m.group(1)), s)
|
| 511 |
+
s = re.sub(r'(?<![\w.,])\d+(?![\w])', _number_in_context, s)
|
| 512 |
+
s = re.sub(r'\d+', lambda m: cardinal(m.group(0)), s)
|
| 513 |
+
|
| 514 |
+
s = _sub(r'\b([A-Za-z])\+\+', r'\1 plus plus', s)
|
| 515 |
+
s = _sub(r'\b([A-Z]{1,4})&([A-Z]{1,4})(s?)\b', lambda m: f'{letters(m.group(1))} and {letters(m.group(2))}{m.group(3)}', s)
|
| 516 |
+
s = _sub(r'\s?&\s?', ' and ', s)
|
| 517 |
+
s = _sub(r'\s@\s', ' at ', s)
|
| 518 |
+
s = _sub(r'(?<!\w)#(?=\s)', 'number', s)
|
| 519 |
+
s = _sub(r'(?<=\w)\+(?=\w)|\s\+\s', ' plus ', s)
|
| 520 |
+
s = _sub(r'(?<=\w)\+(?=[\s,.;!?)]|$)', ' plus', s)
|
| 521 |
+
s = _sub(r'(?<![\w])\+(?=\w)', 'plus ', s)
|
| 522 |
+
s = _sub(r'\s?=\s?', ' equals ', s)
|
| 523 |
+
s = _sub(r'~\s?', 'about ', s)
|
| 524 |
+
s = _sub(r'≈\s?', 'approximately ', s)
|
| 525 |
+
s = _sub(r'\s?±\s?', ' plus or minus ', s)
|
| 526 |
+
s = _sub(r'\s?÷\s?', ' divided by ', s)
|
| 527 |
+
s = _sub(r'\s?×\s?', ' times ', s)
|
| 528 |
+
s = _sub(r'\s?≥\s?', ' greater than or equal to ', s)
|
| 529 |
+
s = _sub(r'\s?≤\s?', ' less than or equal to ', s)
|
| 530 |
+
s = _sub(r'\s?≠\s?', ' not equal to ', s)
|
| 531 |
+
s = _sub(r'(\w)\^2\b|(\w)²', lambda m: (m.group(1) or m.group(2)) + ' squared', s)
|
| 532 |
+
s = _sub(r'(\w)\^3\b|(\w)³', lambda m: (m.group(1) or m.group(2)) + ' cubed', s)
|
| 533 |
+
s = _sub(r'√\s?', 'square root of ', s)
|
| 534 |
+
s = _sub(r'%', ' percent', s)
|
| 535 |
+
s = _sub(r'°', ' degrees', s)
|
| 536 |
+
s = _sub(r'©\s?', 'copyright ', s)
|
| 537 |
+
s = _sub(r'[™®]', '', s)
|
| 538 |
+
s = _sub(r'§\s?', 'section ', s)
|
| 539 |
+
s = _sub(r'(?<=[A-Za-z])_(?=[A-Za-z0-9])', ' underscore ', s)
|
| 540 |
+
s = _sub(r'\$(?=[A-Z]{1,5}\b)', '', s)
|
| 541 |
+
|
| 542 |
+
for k, v in ABBREVIATIONS.items():
|
| 543 |
+
tail = r'(?=\s+[A-Z])' if k in TITLES else r'(?=[\s,;:!?)"]|$)' if k.endswith(('.', '/')) else r'\b'
|
| 544 |
+
s = re.sub(r'(?<![\w.])' + re.escape(k) + tail, lambda m, k=k, v=v: v + ('.' if k in ENDS_SENTENCE and _ends(m) else ''), s)
|
| 545 |
+
s = _sub(r'(?<![\w.])(Dr|St)\.(?=\s|$)', _dr_st, s)
|
| 546 |
+
s = _sub(r'\b(Street|Avenue|Road|Boulevard|Drive|Lane|Highway|Parkway|Way|Court|Place)\.?\s(NW|NE|SW|SE)\b',
|
| 547 |
+
lambda m: f'{m.group(1)} ' + dict(NW='Northwest', NE='Northeast', SW='Southwest', SE='Southeast')[m.group(2)], s)
|
| 548 |
+
s = _sub(r'(?<![\w.])([Nn]o)\.\s?(?=\d|[a-z]+\b)', lambda m: ('Number' if m.group(1) == 'No' else 'number') + ' ', s)
|
| 549 |
+
s = _sub(r'(?<![\w.])p\.\s?(?=\d)', 'page ', s)
|
| 550 |
+
s = _sub(r'\b([A-Z]{1,6}\d*)/([A-Z0-9]{1,6})\b', lambda m: f'{m.group(1)} slash {m.group(2)}', s)
|
| 551 |
+
s = _sub(r'\bd([a-z])/d([a-z])\b', r'd \1 d \2', s)
|
| 552 |
+
s = _sub(r'\b([a-z]+)/([a-z]+)\b', r'\1 \2', s)
|
| 553 |
+
s = _sub(r'(?<=\w)/(?=\w)', ' ', s)
|
| 554 |
+
s = _sub(r'(?<![\w.])((?:[A-Za-z]\.){2,})(?=[\s,;:!?)"]|$)', lambda m: letters(m.group(1).replace('.', '')) + ('.' if _ends(m) else ''), s)
|
| 555 |
+
s = _acronyms(s)
|
| 556 |
+
s = _sub(r'\b(' + '|'.join(re.escape(k) for k in RESPELL) + r')\b', lambda m: RESPELL[m.group(1)], s)
|
| 557 |
+
s = _sub(r'\b(' + '|'.join(re.escape(k) for k in RESPELL if k.islower()) + r')\b',
|
| 558 |
+
lambda m: RESPELL[m.group(1).lower()].capitalize() if m.group(1)[0].isupper() else m.group(0), s, flags=re.I)
|
| 559 |
+
s = _sub(r'\*+', '', s)
|
| 560 |
+
s = _sub(r'[ \t]{2,}', ' ', s)
|
| 561 |
+
s = _sub(r' +([,.;:!?])', r'\1', s)
|
| 562 |
+
return s
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
def _ends(m):
|
| 566 |
+
rest = m.string[m.end():]
|
| 567 |
+
return not rest.strip() or bool(re.match(r'\s+["\']?[A-Z](?![A-Z])', rest))
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
def _dr_st(m):
|
| 571 |
+
before, after = m.string[:m.start()], m.string[m.end():]
|
| 572 |
+
pm = re.search(r'([A-Z][\w]*|\w*\d\w*)\s+$', before)
|
| 573 |
+
named = pm is not None and re.search(r'(^|[.!?:;]\s+|["(]\s*)$', before[:pm.start()]) is None
|
| 574 |
+
if not named and re.match(r'\s+[A-Z]', after): return 'Doctor' if m.group(1) == 'Dr' else 'Saint'
|
| 575 |
+
return ('Drive' if m.group(1) == 'Dr' else 'Street') + ('.' if _ends(m) else '')
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
def _domain(d):
|
| 579 |
+
labels = d.split('.')
|
| 580 |
+
tld = labels[-1].lower()
|
| 581 |
+
out = [ident(x) for x in labels[:-1]] + [tld if tld in TLD_WORDS else letters(tld)]
|
| 582 |
+
return ' dot '.join(out)
|
| 583 |
+
|
| 584 |
+
|
| 585 |
+
def _url(m):
|
| 586 |
+
host, path = m.group(2), m.group(3) or ''
|
| 587 |
+
words = []
|
| 588 |
+
if host.lower().startswith('www.'): words.append('w w w dot'); host = host[4:]
|
| 589 |
+
words.append(_domain(host))
|
| 590 |
+
for p in [p for p in path.split('/') if p][:6]:
|
| 591 |
+
words.append('slash ' + ident(p))
|
| 592 |
+
return ' '.join(words)
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
def _numeric_date(m):
|
| 596 |
+
a, b, y = int(m.group(1)), int(m.group(2)), m.group(3)
|
| 597 |
+
yv = int(y)
|
| 598 |
+
if 1 <= a <= 12 and 1 <= b <= 31: return _date_words(a, b, yv if len(y) == 4 else y)
|
| 599 |
+
if 1 <= b <= 12 and 1 <= a <= 31: return _date_words(b, a, yv if len(y) == 4 else y, 'uk')
|
| 600 |
+
return m.group(0)
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
def _slash_numbers(m):
|
| 604 |
+
n, d = int(m.group(1)), int(m.group(2))
|
| 605 |
+
special = {'9/11': 'nine eleven', '50/50': 'fifty fifty', '20/20': 'twenty twenty', '9/10': 'nine out of ten'}
|
| 606 |
+
if m.group(0) in special: return special[m.group(0)]
|
| 607 |
+
if d in (5, 10, 100) and n <= d: return f'{number(n)} out of {number(d)}'
|
| 608 |
+
if d in FRACTION_DENOMS and 0 < n < d: return fraction(n, d)
|
| 609 |
+
if 1 <= n <= 12 and 1 <= d <= 31: return f'{MONTHS[n - 1]} {ordinal(d)}'
|
| 610 |
+
return f'{number(n)} {"out of" if n <= d else "over"} {number(d)}'
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
def _year_range(m):
|
| 614 |
+
a, b = m.group(1), m.group(2)
|
| 615 |
+
if not 1000 <= int(a) <= 2099: return m.group(0)
|
| 616 |
+
if len(b) == 2: return f'{year(int(a))} to {short_year(b) if b[0] == "0" else number(int(b))}'
|
| 617 |
+
return f'{year(int(a))} to {year(int(b))}' if 1000 <= int(b) <= 2099 else m.group(0)
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
def decimal_signed(x):
|
| 621 |
+
return 'minus ' + decimal(x[1:]) if x.startswith('-') else decimal(x)
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
def _roman(m):
|
| 625 |
+
name, num = m.group(1), m.group(2)
|
| 626 |
+
v = roman(num)
|
| 627 |
+
last = name.split()[-1]
|
| 628 |
+
if v is None or num in ('XL', 'XXL', 'XXXL', 'LV', 'CV', 'CI', 'LI', 'XC', 'CC', 'CL') or num == 'I' and last not in REGNAL:
|
| 629 |
+
return m.group(0)
|
| 630 |
+
if last in REGNAL: return f'{name} the {ordinal(v).capitalize()}'
|
| 631 |
+
if last in ROMAN_AFTER or len(num) >= 2: return f'{name} {number(v)}'
|
| 632 |
+
return m.group(0)
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
def _respelling(w):
|
| 636 |
+
parts = w.split('-'); low = [p for p in parts if p.islower()]
|
| 637 |
+
return any(p.isupper() for p in parts) and low and all(len(p) <= 5 for p in low) and (len(parts) >= 3 or any(len(p) <= 3 for p in low))
|
| 638 |
+
|
| 639 |
+
|
| 640 |
+
def _acronyms(s):
|
| 641 |
+
out = []
|
| 642 |
+
for sent in re.split(r'(?<=[.!?])(\s+)', s):
|
| 643 |
+
words = re.findall(r'[A-Za-z]{2,}', sent)
|
| 644 |
+
caps = [w for w in words if w.isupper()]
|
| 645 |
+
shouting = len(caps) >= 3 and len(caps) >= .6 * len(words)
|
| 646 |
+
respelled = [w for w in RESPELLING.findall(sent) if _respelling(w)]
|
| 647 |
+
if shouting or RESPELLING_CUES.search(sent): out.append(sent); continue
|
| 648 |
+
if respelled:
|
| 649 |
+
keep = {}
|
| 650 |
+
for i, w in enumerate(respelled):
|
| 651 |
+
keep[f'\x00{i}\x00'] = w; sent = sent.replace(w, f'\x00{i}\x00', 1)
|
| 652 |
+
sent = _acronym_words(sent)
|
| 653 |
+
for k, w in keep.items(): sent = sent.replace(k, w)
|
| 654 |
+
out.append(sent); continue
|
| 655 |
+
out.append(_acronym_words(sent))
|
| 656 |
+
return ''.join(out)
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def _acronym_words(sent):
|
| 660 |
+
sent = re.sub(r'\b([A-Z]{2,6})-(?=[A-Z]{2,6}\b)', r'\1 ', sent)
|
| 661 |
+
sent = re.sub(r'\b(?![A-Z]{2,}s\b)(?=[A-Za-z]*[a-z])(?=[A-Za-z]*[A-Z][a-z]?[A-Z])(?:[A-Z]+[a-z]?)+\b', _mixed_caps, sent)
|
| 662 |
+
return re.sub(r"\b([A-Z]{2,8})(s|'s)?\b", _acronym, sent)
|
| 663 |
+
|
| 664 |
+
|
| 665 |
+
def _mixed_caps(m):
|
| 666 |
+
w = m.group(0)
|
| 667 |
+
if w in RESPELL or len(w) > 6 or sum(c.isupper() for c in w) <= sum(c.islower() for c in w): return w
|
| 668 |
+
return letters(w)
|
| 669 |
+
|
| 670 |
+
|
| 671 |
+
def _acronym(m):
|
| 672 |
+
w, suffix = m.group(1), m.group(2) or ''
|
| 673 |
+
if w in AS_WORDS: return AS_WORDS[w] + suffix
|
| 674 |
+
if w.lower() in COMMON and not suffix: return w
|
| 675 |
+
if len(w) >= 4 and pronounceable(w): return w + suffix
|
| 676 |
+
return letters(w) + ("'s" if suffix else '')
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
LETTER_NAMES = dict(A='ay', B='bee', C='see', D='dee', E='ee', F='ef', G='jee', H='aitch', I='eye', J='jay', K='kay', L='el', M='em',
|
| 680 |
+
N='en', O='oh', P='pee', Q='cue', R='ar', S='ess', T='tee', U='you', V='vee', W='double-you', X='ex', Y='why', Z='zee')
|
| 681 |
+
LETTER_RUN = re.compile(r"(?<![\w'-])[A-Z](?:'s|s)?(?: [A-Z](?:'s|s)?)+(?![\w'-])")
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
def _names(said, written):
|
| 685 |
+
said = re.sub(r'(?<=\b[A-Z] [A-Z])-(?=\w)|(?<=\w)-(?=[A-Z] [A-Z]\b)', ' ', said)
|
| 686 |
+
said = re.sub(r'\b([A-Z])-([A-Z])\b', r'\1 \2', said)
|
| 687 |
+
|
| 688 |
+
def run(m):
|
| 689 |
+
letters = m.group(0).split(' ')
|
| 690 |
+
keep = letters[0] in ('A', 'I') and re.search(rf"\b{letters[0]} {re.escape(''.join(t[0] for t in letters[1:]))}", written)
|
| 691 |
+
named = [LETTER_NAMES[t[0]] + t[1:] for t in letters[1 if keep else 0:]]
|
| 692 |
+
return ' '.join(([letters[0]] if keep else []) + named) if len(named) > 1 or not keep else m.group(0)
|
| 693 |
+
return LETTER_RUN.sub(run, said)
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
def speakable(text):
|
| 697 |
+
if not text or re.search(r'[\u3040-\u30ff\u3400-\u9fff\uac00-\ud7af]', text): return text
|
| 698 |
+
parts = re.split(r'(\[[^\]]*\])', text)
|
| 699 |
+
return ''.join(p if i % 2 else _names(_words(p), p) for i, p in enumerate(parts))
|
package/robin/train.py
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import soundfile as sf
|
| 13 |
+
import torch
|
| 14 |
+
import torch.nn.functional as F
|
| 15 |
+
from torch.utils.checkpoint import checkpoint
|
| 16 |
+
|
| 17 |
+
from .lora import LoRA, file_sha256
|
| 18 |
+
from .pipeline import plain, prefix_mask
|
| 19 |
+
|
| 20 |
+
AUDIO = ('.wav', '.flac', '.mp3', '.ogg', '.opus', '.aiff', '.aif')
|
| 21 |
+
OTHER_AUDIO = ('.m4a', '.aac', '.wma', '.mp4', '.webm', '.mov')
|
| 22 |
+
SPEECH_TOKENS = 'speech_tokenizer_v3_25hz'
|
| 23 |
+
REF_WHOLE, REF_EXCERPT = 400, 375
|
| 24 |
+
SAMPLE_TEXT = dict(en='Hello there! This is a quick test of my new voice. How does it sound to you?',
|
| 25 |
+
ja='こんにちは。これは新しい声のテストです。どう聞こえますか?',
|
| 26 |
+
mix='Hello! これは新しい声のテストです。How does it sound?')
|
| 27 |
+
CHARS_PER_SECOND = dict(en=((2.5, 35), (6, 24)), ja=((1, 25), (3, 15)), mix=((1, 35), (3, 24)))
|
| 28 |
+
|
| 29 |
+
PROBLEMS = {
|
| 30 |
+
'no_text': 'no transcript (add a .txt file with the same name)',
|
| 31 |
+
'empty_text': 'the transcript is empty',
|
| 32 |
+
'unreadable': "the audio can't be read",
|
| 33 |
+
'other_format': "this audio format can't be read (convert it to .wav or .flac)",
|
| 34 |
+
'low_rate': 'recorded below 16 kHz (too low to learn a voice from)',
|
| 35 |
+
'silent': 'almost silent',
|
| 36 |
+
'short': 'too short',
|
| 37 |
+
'long': 'too long (split it into shorter clips)',
|
| 38 |
+
'mismatch': "the transcript doesn't fit the length of the audio (check the .txt)",
|
| 39 |
+
'tokens': "the audio couldn't be processed",
|
| 40 |
+
}
|
| 41 |
+
WARNINGS = {
|
| 42 |
+
'rate': 'recorded below 44.1 kHz: the voice will learn a duller top end',
|
| 43 |
+
'clipped': 'clipped (distorted peaks)',
|
| 44 |
+
'digits': 'digits in the transcript: write numbers out as words, the way they are spoken',
|
| 45 |
+
'pace': 'the transcript may not fit the audio (unusually fast or slow speech for its length)',
|
| 46 |
+
'duplicate': 'the same transcript appears more than once',
|
| 47 |
+
'orphan': 'a transcript with no audio file of the same name',
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def frames_db(x, rate):
|
| 52 |
+
n = max(1, rate // 100); k = len(x) // n
|
| 53 |
+
if k == 0: return np.full(1, -120.)
|
| 54 |
+
return 20 * np.log10(np.sqrt((x[:k * n].reshape(k, n) ** 2).mean(1)) + 1e-9)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def trim(x, rate):
|
| 58 |
+
db = frames_db(x, rate); loud = float(db.max())
|
| 59 |
+
on = np.where(db > max(min(-45., loud - 30), -60.))[0]
|
| 60 |
+
if len(on) == 0: return x[:0], loud
|
| 61 |
+
n = rate // 100
|
| 62 |
+
return x[max(0, on[0] * n - int(.15 * rate)):min(len(x), (on[-1] + 1) * n + int(.25 * rate))], loud
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def read_mono(path):
|
| 66 |
+
x, rate = sf.read(str(path), dtype='float32', always_2d=True)
|
| 67 |
+
return x.mean(1), rate
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def scan(folder, lang='en', min_seconds=1., max_seconds=30.):
|
| 71 |
+
folder = Path(folder)
|
| 72 |
+
if not folder.is_dir(): raise SystemExit(f'{folder} is not a folder')
|
| 73 |
+
desc_file = folder/'voice.txt'
|
| 74 |
+
description = plain(' '.join(desc_file.read_text(encoding='utf-8').split())) if desc_file.exists() else None
|
| 75 |
+
problems, warnings, clips, seen = defaultdict(list), defaultdict(list), [], defaultdict(list)
|
| 76 |
+
files = sorted(p for p in folder.rglob('*') if p.is_file() and not any(part.startswith('.') for part in p.relative_to(folder).parts))
|
| 77 |
+
hard, soft = CHARS_PER_SECOND.get(lang, CHARS_PER_SECOND['en'])
|
| 78 |
+
for p in files:
|
| 79 |
+
rel = p.relative_to(folder).as_posix(); ext = p.suffix.lower()
|
| 80 |
+
if ext in OTHER_AUDIO: problems['other_format'].append(rel); continue
|
| 81 |
+
if ext not in AUDIO: continue
|
| 82 |
+
txt = p.with_suffix('.txt')
|
| 83 |
+
if not txt.exists(): problems['no_text'].append(rel); continue
|
| 84 |
+
text = plain(' '.join(txt.read_text(encoding='utf-8', errors='replace').split()))
|
| 85 |
+
if not text: problems['empty_text'].append(rel); continue
|
| 86 |
+
try:
|
| 87 |
+
x, rate = read_mono(p)
|
| 88 |
+
except Exception:
|
| 89 |
+
problems['unreadable'].append(rel); continue
|
| 90 |
+
if rate < 16000: problems['low_rate'].append(rel); continue
|
| 91 |
+
y, loud = trim(x, rate); seconds = len(y) / rate
|
| 92 |
+
if loud < -40 or seconds == 0: problems['silent'].append(rel); continue
|
| 93 |
+
if seconds < min_seconds: problems['short'].append(f'{rel} ({seconds:.1f} s)'); continue
|
| 94 |
+
if seconds > max_seconds: problems['long'].append(f'{rel} ({seconds:.0f} s)'); continue
|
| 95 |
+
cps = len(re.sub(r'\[[^\]]*\]|[\W_]', '', text)) / seconds
|
| 96 |
+
if not hard[0] <= cps <= hard[1]: problems['mismatch'].append(rel); continue
|
| 97 |
+
if not soft[0] <= cps <= soft[1]: warnings['pace'].append(rel)
|
| 98 |
+
if rate < 44100: warnings['rate'].append(rel)
|
| 99 |
+
if (np.abs(x) >= .999).mean() > 1e-3: warnings['clipped'].append(rel)
|
| 100 |
+
if re.search(r'\d', re.sub(r'\[[^\]]*\]', '', text)): warnings['digits'].append(rel)
|
| 101 |
+
seen[text.lower()].append(rel)
|
| 102 |
+
st = p.stat()
|
| 103 |
+
key = hashlib.sha1(f'{rel}|{st.st_size}|{st.st_mtime_ns}|{text}|{min_seconds}|{max_seconds}'.encode()).hexdigest()[:20]
|
| 104 |
+
clips.append(dict(file=rel, text=text, seconds=round(seconds, 2), rate=rate, key=key))
|
| 105 |
+
for rels in seen.values():
|
| 106 |
+
if len(rels) > 1: warnings['duplicate'] += rels
|
| 107 |
+
audio = {p.with_suffix('') for p in files if p.suffix.lower() in AUDIO + OTHER_AUDIO}
|
| 108 |
+
warnings['orphan'] += [p.relative_to(folder).as_posix() for p in files
|
| 109 |
+
if p.suffix.lower() == '.txt' and p != desc_file and p.with_suffix('') not in audio]
|
| 110 |
+
if not warnings['orphan']: del warnings['orphan']
|
| 111 |
+
return dict(clips=clips, problems=problems, warnings=warnings, description=description, folder=folder)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def describe(found, log=print):
|
| 115 |
+
clips, problems, warnings = found['clips'], found['problems'], found['warnings']
|
| 116 |
+
left = sum(len(v) for v in problems.values())
|
| 117 |
+
minutes = sum(c['seconds'] for c in clips) / 60
|
| 118 |
+
log(f"Checked {len(clips) + left} clips in {found['folder']}")
|
| 119 |
+
log(f' ready: {len(clips)} clips, {minutes:.1f} minutes of speech')
|
| 120 |
+
if left:
|
| 121 |
+
log(f' left out: {left} clips')
|
| 122 |
+
for kind, rels in problems.items():
|
| 123 |
+
log(f' {PROBLEMS[kind]}: {len(rels)}')
|
| 124 |
+
for r in rels[:8]: log(f' {r}')
|
| 125 |
+
if len(rels) > 8: log(f' ... and {len(rels) - 8} more')
|
| 126 |
+
for kind, rels in warnings.items():
|
| 127 |
+
log(f' note, {WARNINGS[kind]}: {len(rels)}' + (f' ({", ".join(rels[:3])}{"..." if len(rels) > 3 else ""})' if len(rels) < len(clips) else ''))
|
| 128 |
+
log(f' voice description (voice.txt): {found["description"]!r}' if found['description'] else
|
| 129 |
+
' voice description: none (optional: describe the voice in a voice.txt file in the folder)')
|
| 130 |
+
if minutes < 2:
|
| 131 |
+
raise SystemExit(f'Only {minutes:.1f} minutes of usable speech. A LoRA needs at least 2 minutes; 20 to 60 minutes works best.')
|
| 132 |
+
if minutes < 10:
|
| 133 |
+
log(' note: under 10 minutes of speech. It can work, but 20 to 60 minutes gives a much closer voice.')
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
@torch.no_grad()
|
| 137 |
+
def encode(robin, found, cache, log=print, stop=None, progress=None):
|
| 138 |
+
from torchaudio.functional import resample
|
| 139 |
+
cache = Path(cache); cache.mkdir(parents=True, exist_ok=True)
|
| 140 |
+
vae_id = file_sha256(robin.vae_file) if getattr(robin, 'vae_file', None) else 'module'
|
| 141 |
+
meta_file = cache/'meta.json'; meta = dict(vae=vae_id, speech_tokens=SPEECH_TOKENS)
|
| 142 |
+
if meta_file.exists() and json.loads(meta_file.read_text()) != meta:
|
| 143 |
+
for f in cache.glob('*.npz'): f.unlink()
|
| 144 |
+
meta_file.write_text(json.dumps(meta))
|
| 145 |
+
out, bad, t0, done = [], [], time.time(), 0
|
| 146 |
+
todo = sum(not (cache/f"{c['key']}.npz").exists() for c in found['clips'])
|
| 147 |
+
if todo: log(f'Preparing {todo} clips...')
|
| 148 |
+
for c in found['clips']:
|
| 149 |
+
f = cache/f"{c['key']}.npz"
|
| 150 |
+
if not f.exists():
|
| 151 |
+
if stop is not None and stop():
|
| 152 |
+
raise SystemExit(f'Stopped while preparing clips ({done} of {todo} done; they are kept for next time).')
|
| 153 |
+
try:
|
| 154 |
+
x, rate = read_mono(found['folder']/c['file'])
|
| 155 |
+
y = torch.from_numpy(trim(x, rate)[0])
|
| 156 |
+
tokens = robin.speech(y.numpy(), rate)
|
| 157 |
+
z = robin.vae.encode(resample(y, rate, 48000)[None].repeat(2, 1)[None].to(robin.device))[0].T.float().cpu().numpy()
|
| 158 |
+
if abs(len(tokens) - len(z)) > 2: raise ValueError('length mismatch')
|
| 159 |
+
k = min(len(tokens), len(z))
|
| 160 |
+
np.savez(f, tokens=tokens[:k].astype(np.int16), latents=z[:k].astype(np.float16))
|
| 161 |
+
except Exception:
|
| 162 |
+
bad.append(c['file']); continue
|
| 163 |
+
done += 1
|
| 164 |
+
if progress is not None: progress('prepare', done, todo)
|
| 165 |
+
if done % 25 == 0 or done == todo: log(f' {done}/{todo} prepared ({time.time() - t0:.0f} s)')
|
| 166 |
+
d = np.load(f)
|
| 167 |
+
out.append(dict(c, tokens=d['tokens'].astype(np.int64), latents=d['latents']))
|
| 168 |
+
if bad:
|
| 169 |
+
found['problems']['tokens'] += bad
|
| 170 |
+
log(f" left out {len(bad)} clips: {PROBLEMS['tokens']}: {', '.join(bad[:5])}{'...' if len(bad) > 5 else ''}")
|
| 171 |
+
return out
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
class Trainer:
|
| 175 |
+
def __init__(self, robin, clips, description, out, *, lang='en', steps=1000, rank_planner=32, rank_decoder=64, lr_planner=5e-5,
|
| 176 |
+
lr_decoder=2e-4, accum=8, warmup=100, lr_floor=.2, p_reference=.4, save_every=200, sample_text=None, seed=0, log=print, stop=None,
|
| 177 |
+
progress=None):
|
| 178 |
+
self.robin, self.description, self.out, self.lang, self.log, self.stop = robin, description, Path(out), lang, log, stop
|
| 179 |
+
self.progress = progress
|
| 180 |
+
self.hp = dict(steps=steps, rank_planner=rank_planner, rank_decoder=rank_decoder, lr_planner=lr_planner, lr_decoder=lr_decoder,
|
| 181 |
+
accum=accum, warmup=min(warmup, max(1, steps // 10)), lr_floor=lr_floor, p_reference=p_reference, save_every=save_every,
|
| 182 |
+
lang=lang, seed=seed)
|
| 183 |
+
self.sample_text = sample_text or SAMPLE_TEXT.get(lang, SAMPLE_TEXT['en'])
|
| 184 |
+
rng = random.Random(seed); order = list(range(len(clips))); rng.shuffle(order); torch.manual_seed(seed)
|
| 185 |
+
hold = min(10, len(clips) // 20) if len(clips) >= 40 else 0
|
| 186 |
+
self.holdout = [clips[i] for i in order[:hold]]; self.clips = [clips[i] for i in order[hold:]]
|
| 187 |
+
self.short = [c for c in self.clips if len(c['tokens']) <= REF_WHOLE]
|
| 188 |
+
ranks = {k: r for k, r in (('planner', rank_planner), ('decoder', rank_decoder)) if r > 0}
|
| 189 |
+
nets = dict(planner=robin.planner.layers, decoder=robin.decoder.model.layers)
|
| 190 |
+
self.lora = LoRA({k: nets[k] for k in ranks}, ranks, seed=seed).attach()
|
| 191 |
+
groups = [dict(params=[p for n, p in zip(self.lora.names, getattr(self.lora, which)) if n.startswith(net + '.')],
|
| 192 |
+
lr=dict(planner=lr_planner, decoder=lr_decoder)[net]) for net in ranks for which in ('A', 'B')]
|
| 193 |
+
for g in groups: g['base_lr'] = g['lr']
|
| 194 |
+
self.optimizer = torch.optim.AdamW(groups, betas=(.9, .95), weight_decay=0., eps=1e-8)
|
| 195 |
+
self.rng, self.step, self.norms = rng, 0, []
|
| 196 |
+
self.sel = torch.cat((torch.arange(robin.offset, robin.offset + 32768), torch.tensor([robin.audio_end]))).to(robin.device)
|
| 197 |
+
self.base_sha = robin.base_sha256()
|
| 198 |
+
|
| 199 |
+
def lr_scale(self, step):
|
| 200 |
+
hp = self.hp
|
| 201 |
+
if step <= hp['warmup']: return step / hp['warmup']
|
| 202 |
+
f = min(1., (step - hp['warmup']) / max(1, hp['steps'] - hp['warmup']))
|
| 203 |
+
return hp['lr_floor'] + (1 - hp['lr_floor']) * .5 * (1 + math.cos(math.pi * f))
|
| 204 |
+
|
| 205 |
+
def example(self, clip, rng):
|
| 206 |
+
mode = 'reference' if len(self.clips) > 1 and rng.random() < self.hp['p_reference'] else 'tts'
|
| 207 |
+
desc = self.description if mode == 'tts' or rng.random() < .5 else None
|
| 208 |
+
if mode == 'tts' and rng.random() < .1: desc = None
|
| 209 |
+
ref = ref_text = None
|
| 210 |
+
if mode == 'reference':
|
| 211 |
+
pool = [c for c in (self.short or self.clips) if c is not clip] or [c for c in self.clips if c is not clip]
|
| 212 |
+
other = rng.choice(pool); tok = other['tokens']
|
| 213 |
+
if len(tok) <= REF_WHOLE:
|
| 214 |
+
ref, ref_text = tok, other['text']
|
| 215 |
+
else:
|
| 216 |
+
s = rng.randrange(len(tok) - REF_EXCERPT + 1); ref = tok[s:s + REF_EXCERPT]
|
| 217 |
+
return self.robin.prompt(clip['text'], desc, self.lang, ref, ref_text)
|
| 218 |
+
|
| 219 |
+
def losses(self, ids, clip, train=True, gen=None, sigmas=None):
|
| 220 |
+
r = self.robin; dev = r.device
|
| 221 |
+
seq = torch.tensor(list(ids) + [int(t) + r.offset for t in clip['tokens']] + [r.audio_end], device=dev)
|
| 222 |
+
ss, n = len(ids), len(seq)
|
| 223 |
+
mask = prefix_mask(n, ss, dev)
|
| 224 |
+
h = r.planner(seq[None], mask)[0][ss - 1:-1]
|
| 225 |
+
targets = seq[ss:]
|
| 226 |
+
targets = torch.where(targets == r.audio_end, torch.full_like(targets, 32768), targets - r.offset)
|
| 227 |
+
W = r.planner.lm_head.weight[self.sel]
|
| 228 |
+
ce = h.new_zeros((), dtype=torch.float32)
|
| 229 |
+
for s in range(0, len(targets), 256):
|
| 230 |
+
ce = ce + checkpoint(lambda hs, ys: F.cross_entropy(F.linear(hs, W).float(), ys, reduction='sum'),
|
| 231 |
+
h[s:s + 256], targets[s:s + 256], use_reentrant=False)
|
| 232 |
+
ce = ce / len(targets)
|
| 233 |
+
if train: (ce / self.hp['accum']).backward()
|
| 234 |
+
del h
|
| 235 |
+
with torch.no_grad():
|
| 236 |
+
ks, vs, _ = r.planner.prefill(seq, mask)
|
| 237 |
+
clean = torch.from_numpy(clip['latents'].astype(np.float32)).to(dev)
|
| 238 |
+
flows, sigmas = [], sigmas or [min(.98, max(.02, self.rng.betavariate(2, 2))) for _ in range(2)]
|
| 239 |
+
for sigma in sigmas:
|
| 240 |
+
noise = torch.randn(clean.shape, device=dev, generator=gen)
|
| 241 |
+
xt = sigma * noise + (1 - sigma) * clean
|
| 242 |
+
v = r.decoder(xt[None], torch.tensor([sigma], device=dev), ks, vs, checkpointing=train)[0]
|
| 243 |
+
fl = F.mse_loss(v, noise - clean)
|
| 244 |
+
if train: (fl / (len(sigmas) * self.hp['accum'])).backward()
|
| 245 |
+
flows.append(float(fl.detach()))
|
| 246 |
+
return float(ce.detach()), sum(flows) / len(flows)
|
| 247 |
+
|
| 248 |
+
@torch.no_grad()
|
| 249 |
+
def evaluate(self):
|
| 250 |
+
if not self.holdout: return None
|
| 251 |
+
gen = torch.Generator(device=self.robin.device).manual_seed(1)
|
| 252 |
+
rows = [self.losses(self.robin.prompt(c['text'], self.description, self.lang), c, train=False, gen=gen, sigmas=(.25, .5, .75))
|
| 253 |
+
for c in self.holdout]
|
| 254 |
+
return dict(planner=round(sum(r[0] for r in rows) / len(rows), 4), decoder=round(sum(r[1] for r in rows) / len(rows), 4))
|
| 255 |
+
|
| 256 |
+
@torch.no_grad()
|
| 257 |
+
def sample(self, name):
|
| 258 |
+
if self.robin.vae is None: return
|
| 259 |
+
try:
|
| 260 |
+
wav, sr, _ = self.robin.speak(self.sample_text, self.description, lang=self.lang, seed=0)
|
| 261 |
+
(self.out/'samples').mkdir(exist_ok=True)
|
| 262 |
+
path = self.out/'samples'/f'{name}.wav'
|
| 263 |
+
sf.write(str(path), wav, sr, subtype='PCM_16')
|
| 264 |
+
except Exception as e:
|
| 265 |
+
self.log(f' (could not render a sample: {e})')
|
| 266 |
+
return
|
| 267 |
+
if self.progress is not None: self.progress('sample', self.step, self.hp['steps'], path=path)
|
| 268 |
+
|
| 269 |
+
def save(self, final=False, light=False):
|
| 270 |
+
(self.out/'checkpoints').mkdir(exist_ok=True)
|
| 271 |
+
path = self.out/'checkpoints'/f'step_{self.step:05d}.safetensors'
|
| 272 |
+
self.lora.save(path, self.base_sha)
|
| 273 |
+
if final: self.lora.save(self.out/'lora.safetensors', self.base_sha)
|
| 274 |
+
state = dict(step=self.step, hp=self.hp, lora=self.lora.state_dict(), optimizer=self.optimizer.state_dict(), rng=self.rng.getstate(),
|
| 275 |
+
torch_rng=torch.get_rng_state(), cuda_rng=torch.cuda.get_rng_state() if torch.cuda.is_available() else None, norms=self.norms)
|
| 276 |
+
tmp = self.out/'resume.pt.tmp'; torch.save(state, tmp); os.replace(tmp, self.out/'resume.pt')
|
| 277 |
+
ev = None if light else self.evaluate()
|
| 278 |
+
if not light: self.sample(f'step_{self.step:05d}')
|
| 279 |
+
self.log(f' saved {path.relative_to(self.out)}' + (f' | held-out loss: planner {ev["planner"]:.3f}, decoder {ev["decoder"]:.4f}' if ev else ''))
|
| 280 |
+
with (self.out/'log.jsonl').open('a') as f: f.write(json.dumps(dict(step=self.step, saved=path.name, heldout=ev)) + '\n')
|
| 281 |
+
|
| 282 |
+
def resume(self):
|
| 283 |
+
state = torch.load(self.out/'resume.pt', map_location='cpu', weights_only=False)
|
| 284 |
+
keep = ('rank_planner', 'rank_decoder', 'lang')
|
| 285 |
+
if any(state['hp'][k] != self.hp[k] for k in keep):
|
| 286 |
+
raise SystemExit(f'{self.out} holds a run with different settings ({", ".join(f"{k}={state["hp"][k]}" for k in keep)}). '
|
| 287 |
+
'Use the same settings, a new output folder, or start over (--restart).')
|
| 288 |
+
self.lora.load_state_dict(state['lora']); self.optimizer.load_state_dict(state['optimizer'])
|
| 289 |
+
self.rng.setstate(state['rng']); torch.set_rng_state(state['torch_rng'])
|
| 290 |
+
if state.get('cuda_rng') is not None and torch.cuda.is_available(): torch.cuda.set_rng_state(state['cuda_rng'])
|
| 291 |
+
self.step, self.norms = state['step'], state.get('norms', [])
|
| 292 |
+
|
| 293 |
+
def run(self):
|
| 294 |
+
hp, r = self.hp, self.robin
|
| 295 |
+
self.out.mkdir(parents=True, exist_ok=True)
|
| 296 |
+
(self.out/'train_config.json').write_text(json.dumps(dict(hp, clips=len(self.clips), held_out=len(self.holdout),
|
| 297 |
+
description=bool(self.description)), indent=1))
|
| 298 |
+
if self.step == 0:
|
| 299 |
+
self.lora.scale = 0; self.sample('base'); self.lora.scale = 1
|
| 300 |
+
params = [p for p in self.lora.parameters()]
|
| 301 |
+
n_params = sum(p.numel() for p in params)
|
| 302 |
+
self.log(f'Training a LoRA ({n_params / 1e6:.0f}M parameters) on {len(self.clips)} clips'
|
| 303 |
+
+ (f', {len(self.holdout)} held out for checking' if self.holdout else '') + f', {hp["steps"]} steps.')
|
| 304 |
+
if torch.cuda.is_available(): torch.cuda.reset_peak_memory_stats()
|
| 305 |
+
t_start, step_times, run_loss = time.time(), [], []
|
| 306 |
+
while self.step < hp['steps']:
|
| 307 |
+
t0 = time.time(); self.step += 1
|
| 308 |
+
ces, flows = [], []
|
| 309 |
+
for _ in range(hp['accum']):
|
| 310 |
+
for _attempt in range(4):
|
| 311 |
+
clip = self.rng.choice(self.clips)
|
| 312 |
+
try:
|
| 313 |
+
ce, fl = self.losses(self.example(clip, self.rng), clip)
|
| 314 |
+
ces.append(ce); flows.append(fl); break
|
| 315 |
+
except torch.cuda.OutOfMemoryError:
|
| 316 |
+
self.optimizer.zero_grad(set_to_none=True); torch.cuda.empty_cache(); ces, flows = [], []
|
| 317 |
+
self.log(f" ran out of GPU memory on {clip['file']} ({clip['seconds']:.0f} s), leaving it out. "
|
| 318 |
+
'If this keeps happening, use a smaller --max-seconds.')
|
| 319 |
+
except Exception as e:
|
| 320 |
+
self.optimizer.zero_grad(set_to_none=True); ces, flows = [], []
|
| 321 |
+
self.log(f" couldn't train on {clip['file']} ({type(e).__name__}: {e}), leaving it out.")
|
| 322 |
+
self.clips = [c for c in self.clips if c is not clip]
|
| 323 |
+
self.short = [c for c in self.short if c is not clip]
|
| 324 |
+
if not self.clips: raise SystemExit('No clips left to train on.')
|
| 325 |
+
for g in self.optimizer.param_groups: g['lr'] = g['base_lr'] * self.lr_scale(self.step)
|
| 326 |
+
norm = float(torch.nn.utils.clip_grad_norm_(params, 1.0))
|
| 327 |
+
med = sorted(self.norms)[len(self.norms) // 2] if len(self.norms) >= 50 else None
|
| 328 |
+
if not ces or not math.isfinite(norm) or (med is not None and norm > 20 * med):
|
| 329 |
+
self.optimizer.zero_grad(set_to_none=True)
|
| 330 |
+
if ces: self.log(f' step {self.step}: an unusual update (gradient {norm:.2f}) was skipped')
|
| 331 |
+
else:
|
| 332 |
+
self.norms = (self.norms + [norm])[-200:]
|
| 333 |
+
self.optimizer.step(); self.optimizer.zero_grad(set_to_none=True)
|
| 334 |
+
step_times.append(time.time() - t0); run_loss.append((np.mean(ces) if ces else float('nan'), np.mean(flows) if flows else float('nan')))
|
| 335 |
+
with (self.out/'log.jsonl').open('a') as f:
|
| 336 |
+
f.write(json.dumps(dict(step=self.step, planner=round(float(run_loss[-1][0]), 4), decoder=round(float(run_loss[-1][1]), 5),
|
| 337 |
+
grad=round(norm, 4), seconds=round(step_times[-1], 2))) + '\n')
|
| 338 |
+
pace = float(np.mean(step_times[-20:])); left = (hp['steps'] - self.step) * pace
|
| 339 |
+
pl, dl = np.nanmean([x[0] for x in run_loss[-10:]]), np.nanmean([x[1] for x in run_loss[-10:]])
|
| 340 |
+
if self.progress is not None:
|
| 341 |
+
self.progress('train', self.step, hp['steps'], planner=float(pl), decoder=float(dl), pace=pace, left=left)
|
| 342 |
+
if self.step % 10 == 0 or self.step <= 3 or self.step == hp['steps']:
|
| 343 |
+
mem = f' | GPU {torch.cuda.max_memory_allocated() / 2 ** 30:.1f} GB' if torch.cuda.is_available() else ''
|
| 344 |
+
self.log(f"step {self.step}/{hp['steps']} | planner loss {pl:.3f} | decoder loss {dl:.4f} | {pace:.1f} s/step | "
|
| 345 |
+
f"{left / 60:.0f} min left{mem}")
|
| 346 |
+
if self.step % hp['save_every'] == 0 or self.step == hp['steps']:
|
| 347 |
+
self.save(final=self.step == hp['steps'])
|
| 348 |
+
elif self.stop is not None and self.stop():
|
| 349 |
+
self.save(light=True)
|
| 350 |
+
if self.stop is not None and self.stop() and self.step < hp['steps']:
|
| 351 |
+
self.log(f'Stopped at step {self.step}. Train again with the same folder to continue from here.')
|
| 352 |
+
return None
|
| 353 |
+
self.log(f"Done in {(time.time() - t_start) / 60:.0f} min. The LoRA is {self.out/'lora.safetensors'}; every saved step is in "
|
| 354 |
+
f"{self.out/'checkpoints'} with a sample of each in {self.out/'samples'}.")
|
| 355 |
+
return self.out/'lora.safetensors'
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def train(robin, data, out, *, lang='en', min_seconds=1., max_seconds=30., restart=False, log=print, stop=None, progress=None, **settings):
|
| 359 |
+
out = Path(out)
|
| 360 |
+
if restart:
|
| 361 |
+
old = [out/f for f in ('resume.pt', 'lora.safetensors', 'log.jsonl')] + list(out.glob('checkpoints/step_*.safetensors')) + list(out.glob('samples/*.wav'))
|
| 362 |
+
for f in old:
|
| 363 |
+
if f.exists(): f.unlink()
|
| 364 |
+
elif (out/'lora.safetensors').exists() and not (out/'resume.pt').exists():
|
| 365 |
+
raise SystemExit(f'{out} already holds a finished LoRA. Use a new output folder, or start over (--restart) to train again.')
|
| 366 |
+
found = scan(data, lang, min_seconds, max_seconds); describe(found, log)
|
| 367 |
+
clips = encode(robin, found, out/'cache', log, stop, progress)
|
| 368 |
+
robin._speech = None
|
| 369 |
+
if torch.cuda.is_available(): torch.cuda.empty_cache()
|
| 370 |
+
trainer = Trainer(robin, clips, found['description'], out, lang=lang, log=log, stop=stop, progress=progress, **settings)
|
| 371 |
+
try:
|
| 372 |
+
if (out/'resume.pt').exists():
|
| 373 |
+
trainer.resume()
|
| 374 |
+
if trainer.step >= trainer.hp['steps']:
|
| 375 |
+
if not (out/'lora.safetensors').exists(): trainer.lora.save(out/'lora.safetensors', trainer.base_sha)
|
| 376 |
+
log(f'This run already finished ({trainer.step} steps). Start over (--restart) to train again, or give more steps (--steps) to keep going.')
|
| 377 |
+
return out/'lora.safetensors'
|
| 378 |
+
log(f'Continuing the unfinished run from step {trainer.step}.')
|
| 379 |
+
return trainer.run()
|
| 380 |
+
finally:
|
| 381 |
+
trainer.lora.detach()
|