Dionyssos commited on
Commit
26bbca3
·
1 Parent(s): 13909fb

try .74s LM on CPU

Browse files
README.md CHANGED
@@ -1,14 +1,18 @@
1
  ---
2
- title: Audiogen2
3
- emoji: 🌖
4
- colorFrom: purple
5
- colorTo: indigo
6
  sdk: gradio
7
- sdk_version: 5.44.1
8
  app_file: app.py
9
- pinned: false
10
- license: cc-by-nc-4.0
11
  short_description: AudioGen for CPU
 
 
 
 
 
 
12
  ---
13
 
14
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: Audiogen
3
+ emoji: 🍍
4
+ colorFrom: gray
5
+ colorTo: gray
6
  sdk: gradio
7
+ sdk_version: 5.41.1
8
  app_file: app.py
 
 
9
  short_description: AudioGen for CPU
10
+ license: cc-by-nc-4.0
11
+ tags:
12
+ - audiogen
13
+ - soundscapes
14
+ - shift
15
+ - tts
16
  ---
17
 
18
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,715 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import json
4
+ import soundfile
5
+ import re
6
+ import unicodedata
7
+ import gradio as gr
8
+ import textwrap
9
+ import numpy as np
10
+ import torch
11
+ import nltk
12
+ from num2words import num2words
13
+ from num2word_greek.numbers2words import convert_numbers
14
+ from vits import VitsModel, VitsTokenizer
15
+ from audiocraft.builders import AudioGen # fixed bug for repeated calls
16
+ nltk.download('punkt', download_dir='./') # comment if downloaded once
17
+ nltk.download('punkt_tab', download_dir='./')
18
+ nltk.data.path.append('.')
19
+
20
+ device = 'cpu'
21
+
22
+
23
+ def fix_vocals(text, lang='ron'):
24
+
25
+ # Longer phrases should come before shorter ones to prevent partial matches.
26
+
27
+ ron_replacements = {
28
+ 'ţ': 'ț',
29
+ 'ț': 'ts',
30
+ 'î': 'u',
31
+ 'â': 'a',
32
+ 'ş': 's',
33
+ 'w': 'oui',
34
+ 'k': 'c',
35
+ 'l': 'll',
36
+ # Math symbols
37
+ 'sqrt': ' rădăcina pătrată din ',
38
+ '^': ' la puterea ',
39
+ '+': ' plus ',
40
+ ' - ': ' minus ', # only replace if standalone so to not say minus if is a-b-c
41
+ '*': ' ori ', # times
42
+ '/': ' împărțit la ', # divided by
43
+ '=': ' egal cu ', # equals
44
+ 'pi': ' pi ',
45
+ '<': ' mai mic decât ',
46
+ '>': ' mai mare decât',
47
+ '%': ' la sută ', # percent (from previous)
48
+ '(': ' paranteză deschisă ',
49
+ ')': ' paranteză închisă ',
50
+ '[': ' paranteză pătrată deschisă ',
51
+ ']': ' paranteză pătrată închisă ',
52
+ '{': ' acoladă deschisă ',
53
+ '}': ' acoladă închisă ',
54
+ '≠': ' nu este egal cu ',
55
+ '≤': ' mai mic sau egal cu ',
56
+ '≥': ' mai mare sau egal cu ',
57
+ '≈': ' aproximativ ',
58
+ '∞': ' infinit ',
59
+ '€': ' euro ',
60
+ '$': ' dolar ',
61
+ '£': ' liră ',
62
+ '&': ' și ', # and
63
+ '@': ' la ', # at
64
+ '#': ' diez ', # hash
65
+ '∑': ' sumă ',
66
+ '∫': ' integrală ',
67
+ '√': ' rădăcina pătrată a ', # more generic square root
68
+ }
69
+
70
+ eng_replacements = {
71
+ 'wik': 'weaky',
72
+ 'sh': 'ss',
73
+ 'ch': 'ttss',
74
+ 'oo': 'oeo',
75
+ # Math symbols for English
76
+ 'sqrt': ' square root of ',
77
+ '^': ' to the power of ',
78
+ '+': ' plus ',
79
+ ' - ': ' minus ',
80
+ '*': ' times ',
81
+ ' / ': ' divided by ',
82
+ '=': ' equals ',
83
+ 'pi': ' pi ',
84
+ '<': ' less than ',
85
+ '>': ' greater than ',
86
+ # Additional common math symbols from previous list
87
+ '%': ' percent ',
88
+ '(': ' open parenthesis ',
89
+ ')': ' close parenthesis ',
90
+ '[': ' open bracket ',
91
+ ']': ' close bracket ',
92
+ '{': ' open curly brace ',
93
+ '}': ' close curly brace ',
94
+ '∑': ' sum ',
95
+ '∫': ' integral ',
96
+ '√': ' square root of ',
97
+ '≠': ' not equals ',
98
+ '≤': ' less than or equals ',
99
+ '≥': ' greater than or equals ',
100
+ '≈': ' approximately ',
101
+ '∞': ' infinity ',
102
+ '€': ' euro ',
103
+ '$': ' dollar ',
104
+ '£': ' pound ',
105
+ '&': ' and ',
106
+ '@': ' at ',
107
+ '#': ' hash ',
108
+ }
109
+
110
+ serbian_replacements = {
111
+ 'rn': 'rrn',
112
+ 'ć': 'č',
113
+ 'c': 'č',
114
+ 'đ': 'd',
115
+ 'j': 'i',
116
+ 'l': 'lll',
117
+ 'w': 'v',
118
+ # https://huggingface.co/facebook/mms-tts-rmc-script_latin
119
+ 'sqrt': 'kvadratni koren iz',
120
+ '^': ' na stepen ',
121
+ '+': ' plus ',
122
+ ' - ': ' minus ',
123
+ '*': ' puta ',
124
+ ' / ': ' podeljeno sa ',
125
+ '=': ' jednako ',
126
+ 'pi': ' pi ',
127
+ '<': ' manje od ',
128
+ '>': ' veće od ',
129
+ '%': ' procenat ',
130
+ '(': ' otvorena zagrada ',
131
+ ')': ' zatvorena zagrada ',
132
+ '[': ' otvorena uglasta zagrada ',
133
+ ']': ' zatvorena uglasta zagrada ',
134
+ '{': ' otvorena vitičasta zagrada ',
135
+ '}': ' zatvorena vitičasta zagrada ',
136
+ '∑': ' suma ',
137
+ '∫': ' integral ',
138
+ '√': ' kvadratni koren ',
139
+ '≠': ' nije jednako ',
140
+ '≤': ' manje ili jednako od ',
141
+ '≥': ' veće ili jednako od ',
142
+ '≈': ' približno ',
143
+ '∞': ' beskonačnost ',
144
+ '€': ' evro ',
145
+ '$': ' dolar ',
146
+ '£': ' funta ',
147
+ '&': ' i ',
148
+ '@': ' et ',
149
+ '#': ' taraba ',
150
+ # Others
151
+ # 'rn': 'rrn',
152
+ # 'ć': 'č',
153
+ # 'c': 'č',
154
+ # 'đ': 'd',
155
+ # 'l': 'le',
156
+ # 'ij': 'i',
157
+ # 'ji': 'i',
158
+ # 'j': 'i',
159
+ # 'služ': 'sloooozz', # 'službeno'
160
+ # 'suver': 'siuveeerra', # 'suverena'
161
+ # 'država': 'dirrezav', # 'država'
162
+ # 'iči': 'ici', # 'Graniči'
163
+ # 's ': 'se', # a s with space
164
+ # 'q': 'ku',
165
+ # 'w': 'aou',
166
+ # 'z': 's',
167
+ # "š": "s",
168
+ # 'th': 'ta',
169
+ # 'v': 'vv',
170
+ # "ć": "č",
171
+ # "đ": "ď",
172
+ # "lj": "ľ",
173
+ # "nj": "ň",
174
+ # "ž": "z",
175
+ # "c": "č"
176
+ }
177
+
178
+ deu_replacements = {
179
+ 'sch': 'sh',
180
+ 'ch': 'kh',
181
+ 'ie': 'ee',
182
+ 'ei': 'ai',
183
+ 'ä': 'ae',
184
+ 'ö': 'oe',
185
+ 'ü': 'ue',
186
+ 'ß': 'ss',
187
+ # Math symbols for German
188
+ 'sqrt': ' Quadratwurzel aus ',
189
+ '^': ' hoch ',
190
+ '+': ' plus ',
191
+ ' - ': ' minus ',
192
+ '*': ' mal ',
193
+ ' / ': ' geteilt durch ',
194
+ '=': ' gleich ',
195
+ 'pi': ' pi ',
196
+ '<': ' kleiner als ',
197
+ '>': ' größer als',
198
+ # Additional common math symbols from previous list
199
+ '%': ' prozent ',
200
+ '(': ' Klammer auf ',
201
+ ')': ' Klammer zu ',
202
+ '[': ' eckige Klammer auf ',
203
+ ']': ' eckige Klammer zu ',
204
+ '{': ' geschweifte Klammer auf ',
205
+ '}': ' geschweifte Klammer zu ',
206
+ '∑': ' Summe ',
207
+ '∫': ' Integral ',
208
+ '√': ' Quadratwurzel ',
209
+ '≠': ' ungleich ',
210
+ '≤': ' kleiner oder gleich ',
211
+ '≥': ' größer oder gleich ',
212
+ '≈': ' ungefähr ',
213
+ '∞': ' unendlich ',
214
+ '€': ' euro ',
215
+ '$': ' dollar ',
216
+ '£': ' pfund ',
217
+ '&': ' und ',
218
+ '@': ' at ', # 'Klammeraffe' is also common but 'at' is simpler
219
+ '#': ' raute ',
220
+ }
221
+
222
+ fra_replacements = {
223
+ # French specific phonetic replacements (add as needed)
224
+ # e.g., 'ç': 's', 'é': 'e', etc.
225
+ 'w': 'v',
226
+ # Math symbols for French
227
+ 'sqrt': ' racine carrée de ',
228
+ '^': ' à la puissance ',
229
+ '+': ' plus ',
230
+ ' - ': ' moins ', # tiré ;
231
+ '*': ' fois ',
232
+ ' / ': ' divisé par ',
233
+ '=': ' égale ',
234
+ 'pi': ' pi ',
235
+ '<': ' inférieur à ',
236
+ '>': ' supérieur à ',
237
+ # Add more common math symbols as needed for French
238
+ '%': ' pour cent ',
239
+ '(': ' parenthèse ouverte ',
240
+ ')': ' parenthèse fermée ',
241
+ '[': ' crochet ouvert ',
242
+ ']': ' crochet fermé ',
243
+ '{': ' accolade ouverte ',
244
+ '}': ' accolade fermée ',
245
+ '∑': ' somme ',
246
+ '∫': ' intégrale ',
247
+ '√': ' racine carrée ',
248
+ '≠': ' n\'égale pas ',
249
+ '≤': ' inférieur ou égal à ',
250
+ '≥': ' supérieur ou égal à ',
251
+ '≈': ' approximativement ',
252
+ '∞': ' infini ',
253
+ '€': ' euro ',
254
+ '$': ' dollar ',
255
+ '£': ' livre ',
256
+ '&': ' et ',
257
+ '@': ' arobase ',
258
+ '#': ' dièse ',
259
+ }
260
+
261
+ hun_replacements = {
262
+ # Hungarian specific phonetic replacements (add as needed)
263
+ # e.g., 'á': 'a', 'é': 'e', etc.
264
+ 'ch': 'ts',
265
+ 'cs': 'tz',
266
+ 'g': 'gk',
267
+ 'w': 'v',
268
+ 'z': 'zz',
269
+ # Math symbols for Hungarian
270
+ 'sqrt': ' négyzetgyök ',
271
+ '^': ' hatvány ',
272
+ '+': ' plusz ',
273
+ ' - ': ' mínusz ',
274
+ '*': ' szorozva ',
275
+ ' / ': ' osztva ',
276
+ '=': ' egyenlő ',
277
+ 'pi': ' pi ',
278
+ '<': ' kisebb mint ',
279
+ '>': ' nagyobb mint ',
280
+ # Add more common math symbols as needed for Hungarian
281
+ '%': ' százalék ',
282
+ '(': ' nyitó zárójel ',
283
+ ')': ' záró zárójel ',
284
+ '[': ' nyitó szögletes zárójel ',
285
+ ']': ' záró szögletes zárójel ',
286
+ '{': ' nyitó kapcsos zárójel ',
287
+ '}': ' záró kapcsos zárójel ',
288
+ '∑': ' szumma ',
289
+ '∫': ' integrál ',
290
+ '√': ' négyzetgyök ',
291
+ '≠': ' nem egyenlő ',
292
+ '≤': ' kisebb vagy egyenlő ',
293
+ '≥': ' nagyobb vagy egyenlő ',
294
+ '≈': ' körülbelül ',
295
+ '∞': ' végtelen ',
296
+ '€': ' euró ',
297
+ '$': ' dollár ',
298
+ '£': ' font ',
299
+ '&': ' és ',
300
+ '@': ' kukac ',
301
+ '#': ' kettőskereszt ',
302
+ }
303
+
304
+ grc_replacements = {
305
+ # Ancient Greek specific phonetic replacements (add as needed)
306
+ # These are more about transliterating Greek letters if they are in the input text.
307
+ # Math symbols for Ancient Greek (literal translations)
308
+ 'sqrt': ' τετραγωνικὴ ῥίζα ',
309
+ '^': ' εἰς δύναμιν ',
310
+ '+': ' σὺν ',
311
+ ' - ': ' χωρὶς ',
312
+ '*': ' πολλάκις ',
313
+ ' / ': ' διαιρέω ',
314
+ '=': ' ἴσον ',
315
+ 'pi': ' πῖ ',
316
+ '<': ' ἔλαττον ',
317
+ '>': ' μείζον ',
318
+ # Add more common math symbols as needed for Ancient Greek
319
+ '%': ' τοῖς ἑκατόν ', # tois hekaton - 'of the hundred'
320
+ '(': ' ἀνοικτὴ παρένθεσις ',
321
+ ')': ' κλειστὴ παρένθεσις ',
322
+ '[': ' ἀνοικτὴ ἀγκύλη ',
323
+ ']': ' κλειστὴ ἀγκύλη ',
324
+ '{': ' ἀνοικτὴ σγουρὴ ἀγκύλη ',
325
+ '}': ' κλειστὴ σγουρὴ ἀγκύλη ',
326
+ '∑': ' ἄθροισ��α ',
327
+ '∫': ' ὁλοκλήρωμα ',
328
+ '√': ' τετραγωνικὴ ῥίζα ',
329
+ '≠': ' οὐκ ἴσον ',
330
+ '≤': ' ἔλαττον ἢ ἴσον ',
331
+ '≥': ' μεῖζον ἢ ἴσον ',
332
+ '≈': ' περίπου ',
333
+ '∞': ' ἄπειρον ',
334
+ '€': ' εὐρώ ',
335
+ '$': ' δολάριον ',
336
+ '£': ' λίρα ',
337
+ '&': ' καὶ ',
338
+ '@': ' ἀτ ', # at
339
+ '#': ' δίεση ', # hash
340
+ }
341
+
342
+
343
+ # Select the appropriate replacement dictionary based on the language
344
+ replacements_map = {
345
+ 'grc': grc_replacements,
346
+ 'ron': ron_replacements,
347
+ 'eng': eng_replacements,
348
+ 'deu': deu_replacements,
349
+ 'fra': fra_replacements,
350
+ 'hun': hun_replacements,
351
+ 'rmc-script_latin': serbian_replacements,
352
+ }
353
+
354
+ current_replacements = replacements_map.get(lang)
355
+ if current_replacements:
356
+ # Sort replacements by length of the key in descending order.
357
+ # This is crucial for correctly replacing multi-character strings (like 'sqrt', 'sch')
358
+ # before their shorter substrings ('s', 'ch', 'q', 'r', 't').
359
+ sorted_replacements = sorted(current_replacements.items(), key=lambda item: len(item[0]), reverse=True)
360
+ for old, new in sorted_replacements:
361
+ text = text.replace(old, new)
362
+ return text
363
+ else:
364
+ # If the language is not supported, return the original text
365
+ print(f"Warning: Language '{lang}' not supported for text replacement. Returning original text.")
366
+ return text
367
+
368
+
369
+ import unicodedata
370
+
371
+ def only_greek_or_only_latin(text, lang='grc'):
372
+ '''
373
+ str: The converted string in the specified target script.
374
+ Characters not found in any mapping are preserved as is.
375
+ Latin accented characters in the input (e.g., 'É', 'ü') will
376
+ be preserved in their lowercase form (e.g., 'é', 'ü') if
377
+ converting to Latin.
378
+ '''
379
+
380
+ # --- Mapping Dictionaries ---
381
+ # Keys are in lowercase as input text is case-folded.
382
+ # If the output needs to maintain original casing, additional logic is required.
383
+
384
+ latin_to_greek_map = {
385
+ 'a': 'α', 'b': 'β', 'g': 'γ', 'd': 'δ', 'e': 'ε',
386
+ 'ch': 'τσο', # Example of a multi-character Latin sequence
387
+ 'z': 'ζ', 'h': 'χ', 'i': 'ι', 'k': 'κ', 'l': 'λ',
388
+ 'm': 'μ', 'n': 'ν', 'x': 'ξ', 'o': 'ο', 'p': 'π',
389
+ 'v': 'β', 'sc': 'σκ', 'r': 'ρ', 's': 'σ', 't': 'τ',
390
+ 'u': 'ου', 'f': 'φ', 'c': 'σ', 'w': 'β', 'y': 'γ',
391
+ }
392
+
393
+ greek_to_latin_map = {
394
+ 'ου': 'ou', # Prioritize common diphthongs/digraphs
395
+ 'α': 'a', 'β': 'v', 'γ': 'g', 'δ': 'd', 'ε': 'e',
396
+ 'ζ': 'z', 'η': 'i', 'θ': 'th', 'ι': 'i', 'κ': 'k',
397
+ 'λ': 'l', 'μ': 'm', 'ν': 'n', 'ξ': 'x', 'ο': 'o',
398
+ 'π': 'p', 'ρ': 'r', 'σ': 's', 'τ': 't', 'υ': 'y', # 'y' is a common transliteration for upsilon
399
+ 'φ': 'f', 'χ': 'ch', 'ψ': 'ps', 'ω': 'o',
400
+ 'ς': 's', # Final sigma
401
+ }
402
+
403
+ cyrillic_to_latin_map = {
404
+ 'а': 'a', 'б': 'b', 'в': 'v', 'г': 'g', 'д': 'd', 'е': 'e', 'ё': 'yo', 'ж': 'zh',
405
+ 'з': 'z', 'и': 'i', 'й': 'y', 'к': 'k', 'л': 'l', 'м': 'm', 'н': 'n', 'о': 'o',
406
+ 'п': 'p', 'р': 'r', 'с': 's', 'т': 't', 'у': 'u', 'ф': 'f', 'х': 'kh', 'ц': 'ts',
407
+ 'ч': 'ch', 'ш': 'sh', 'щ': 'shch', 'ъ': '', 'ы': 'y', 'ь': '', 'э': 'e', 'ю': 'yu',
408
+ 'я': 'ya',
409
+ }
410
+
411
+ # Direct Cyrillic to Greek mapping based on phonetic similarity.
412
+ # These are approximations and may not be universally accepted transliterations.
413
+ cyrillic_to_greek_map = {
414
+ 'а': 'α', 'б': 'β', 'в': 'β', 'г': 'γ', 'д': 'δ', 'е': 'ε', 'ё': 'ιο', 'ж': 'ζ',
415
+ 'з': 'ζ', 'и': 'ι', 'й': 'ι', 'κ': 'κ', 'λ': 'λ', 'м': 'μ', 'н': 'ν', 'о': 'ο',
416
+ 'π': 'π', 'ρ': 'ρ', 'σ': 'σ', 'τ': 'τ', 'у': 'ου', 'ф': 'φ', 'х': 'χ', 'ц': 'τσ',
417
+ 'ч': 'τσ', # or τζ depending on desired sound
418
+ 'ш': 'σ', 'щ': 'σ', # approximations
419
+ 'ъ': '', 'ы': 'ι', 'ь': '', 'э': 'ε', 'ю': 'ιου',
420
+ 'я': 'ια',
421
+ }
422
+
423
+ # Convert the input text to lowercase, preserving accents for Latin characters.
424
+ # casefold() is used for more robust caseless matching across Unicode characters.
425
+ lowercased_text = text.lower() #casefold()
426
+ output_chars = []
427
+ current_index = 0
428
+
429
+ if lang == 'grc':
430
+ # Combine all relevant maps for direct lookup to Greek
431
+ conversion_map = {**latin_to_greek_map, **cyrillic_to_greek_map}
432
+
433
+ # Sort keys by length in reverse order to handle multi-character sequences first
434
+ sorted_source_keys = sorted(
435
+ list(latin_to_greek_map.keys()) + list(cyrillic_to_greek_map.keys()),
436
+ key=len,
437
+ reverse=True
438
+ )
439
+
440
+ while current_index < len(lowercased_text):
441
+ found_conversion = False
442
+ for key in sorted_source_keys:
443
+ if lowercased_text.startswith(key, current_index):
444
+ output_chars.append(conversion_map[key])
445
+ current_index += len(key)
446
+ found_conversion = True
447
+ break
448
+ if not found_conversion:
449
+ # If no specific mapping found, append the character as is.
450
+ # This handles unmapped characters and already Greek characters.
451
+ output_chars.append(lowercased_text[current_index])
452
+ current_index += 1
453
+ return ''.join(output_chars)
454
+
455
+ else: # Default to 'lat' conversion
456
+ # Combine Greek to Latin and Cyrillic to Latin maps.
457
+ # Cyrillic map keys will take precedence in case of overlap if defined after Greek.
458
+ combined_to_latin_map = {**greek_to_latin_map, **cyrillic_to_latin_map}
459
+
460
+ # Sort all relevant source keys by length in reverse for replacement
461
+ sorted_source_keys = sorted(
462
+ list(greek_to_latin_map.keys()) + list(cyrillic_to_latin_map.keys()),
463
+ key=len,
464
+ reverse=True
465
+ )
466
+
467
+ while current_index < len(lowercased_text):
468
+ found_conversion = False
469
+ for key in sorted_source_keys:
470
+ if lowercased_text.startswith(key, current_index):
471
+ latin_equivalent = combined_to_latin_map[key]
472
+
473
+ # Strip accents ONLY if the source character was from the Greek map.
474
+ # This preserves accents on original Latin characters (like 'é')
475
+ # and allows for intentional accent stripping from Greek transliterations.
476
+ if key in greek_to_latin_map:
477
+ normalized_latin = unicodedata.normalize('NFD', latin_equivalent)
478
+ stripped_latin = ''.join(c for c in normalized_latin if not unicodedata.combining(c))
479
+ output_chars.append(stripped_latin)
480
+ else:
481
+ output_chars.append(latin_equivalent)
482
+
483
+ current_index += len(key)
484
+ found_conversion = True
485
+ break
486
+
487
+ if not found_conversion:
488
+ # If no conversion happened from Greek or Cyrillic, append the character as is.
489
+ # This preserves existing Latin characters (including accented ones from input),
490
+ # numbers, punctuation, and other symbols.
491
+ output_chars.append(lowercased_text[current_index])
492
+ current_index += 1
493
+
494
+ return ''.join(output_chars)
495
+
496
+
497
+ def _num2words(text='01234', lang=None):
498
+ if lang == 'grc':
499
+ return convert_numbers(text)
500
+ return num2words(text, lang=lang) # HAS TO BE kwarg lang=lang
501
+
502
+
503
+ def transliterate_number(number_string,
504
+ lang=None):
505
+ if lang == 'rmc-script_latin':
506
+ lang = 'sr'
507
+ exponential_pronoun = ' puta deset na stepen od '
508
+ comma = ' tačka '
509
+ elif lang == 'ron':
510
+ lang = 'ro'
511
+ exponential_pronoun = ' tízszer a erejéig '
512
+ comma = ' virgulă '
513
+ elif lang == 'hun':
514
+ lang = 'hu'
515
+ exponential_pronoun = ' tízszer a erejéig '
516
+ comma = ' virgula '
517
+ elif lang == 'deu':
518
+ exponential_pronoun = ' mal zehn hoch '
519
+ comma = ' komma '
520
+ elif lang == 'fra':
521
+ lang = 'fr'
522
+ exponential_pronoun = ' puissance '
523
+ comma = 'virgule'
524
+ elif lang == 'grc':
525
+ exponential_pronoun = ' εις την δυναμην του '
526
+ comma = 'κομμα'
527
+ else:
528
+ lang = lang[:2]
529
+ exponential_pronoun = ' times ten to the power of '
530
+ comma = ' point '
531
+
532
+ def replace_number(match):
533
+ prefix = match.group(1) or ""
534
+ number_part = match.group(2)
535
+ suffix = match.group(5) or ""
536
+
537
+ try:
538
+ if 'e' in number_part.lower():
539
+ base, exponent = number_part.lower().split('e')
540
+ words = _num2words(base, lang=lang) + exponential_pronoun + _num2words(exponent, lang=lang)
541
+ elif '.' in number_part:
542
+ integer_part, decimal_part = number_part.split('.')
543
+ words = _num2words(integer_part, lang=lang) + comma + " ".join(
544
+ [_num2words(digit, lang=lang) for digit in decimal_part])
545
+ else:
546
+ words = _num2words(number_part, lang=lang)
547
+ return prefix + words + suffix
548
+ except ValueError:
549
+ return match.group(0) # Return original if conversion fails
550
+
551
+ pattern = r'([^\d]*)(\d+(\.\d+)?([Ee][+-]?\d+)?)([^\d]*)'
552
+ return re.sub(pattern, replace_number, number_string)
553
+
554
+
555
+ language_names = ['Ancient greek',
556
+ 'English',
557
+ 'Deutsch',
558
+ 'French',
559
+ 'Hungarian',
560
+ 'Romanian',
561
+ 'Serbian (Approx.)']
562
+
563
+
564
+
565
+ def other_tts(text=None,
566
+ lang='romanian',
567
+ soundscape=''):
568
+
569
+ # https://huggingface.co/dkounadis/artificial-styletts2/blob/main/msinference.py
570
+
571
+ lang = lang.lower()
572
+
573
+ # https://huggingface.co/spaces/mms-meta/MMS
574
+
575
+ if 'hun' in lang:
576
+
577
+ lang_code = 'hun'
578
+
579
+ elif any([i in lang for i in ['ser', 'bosn', 'herzegov', 'montenegr', 'macedon']]):
580
+
581
+ # romani carpathian (has also Vlax) - cooler voice
582
+ lang_code = 'rmc-script_latin'
583
+
584
+ elif 'rom' in lang:
585
+
586
+ lang_code = 'ron'
587
+
588
+ elif 'ger' in lang or 'deu' in lang or 'allem' in lang:
589
+
590
+ lang_code = 'deu'
591
+
592
+ elif 'french' in lang:
593
+
594
+ lang_code = 'fra'
595
+
596
+ elif 'eng' in lang:
597
+
598
+ lang_code = 'eng'
599
+
600
+ elif 'ancient greek' in lang:
601
+
602
+ lang_code = 'grc'
603
+
604
+ else:
605
+
606
+ lang_code = lang.split()[0].strip() # latin & future option
607
+
608
+ # LATIN / GRC / CYRILLIC
609
+
610
+ text = only_greek_or_only_latin(text, lang=lang_code) # assure gr-chars if lang=='grc' / latin if lang!='grc'
611
+
612
+ # NUMERALS (^ in math expression found & substituted here before arriving to fix_vocals)
613
+
614
+ text = transliterate_number(text, lang=lang_code)
615
+
616
+ # PRONOUNC.
617
+
618
+ text = fix_vocals(text, lang=lang_code)
619
+
620
+ # VITS
621
+
622
+
623
+ global cached_lang_code, cached_net_g, cached_tokenizer
624
+
625
+ if 'cached_lang_code' not in globals() or cached_lang_code != lang_code:
626
+ cached_lang_code = lang_code
627
+ cached_net_g = VitsModel.from_pretrained(f'facebook/mms-tts-{lang_code}').eval().to(device)
628
+ cached_tokenizer = VitsTokenizer.from_pretrained(f'facebook/mms-tts-{lang_code}')
629
+
630
+ net_g = cached_net_g
631
+ tokenizer = cached_tokenizer
632
+
633
+ total_audio = []
634
+
635
+ # AUDIOGEN
636
+
637
+ audiogen = AudioGen().eval().to('cpu')
638
+
639
+ if not isinstance(text, list):
640
+
641
+ text = textwrap.wrap(text, width=439)
642
+ # text = [i + '. ' for sent in nltk.sent_tokenize(text) for i in textwrap.wrap(sent, width=420)] # short sentences call the model a lot of times - slower in CPU
643
+
644
+ for _t in text:
645
+
646
+ inputs = tokenizer(_t, return_tensors="pt")
647
+
648
+ with torch.no_grad():
649
+
650
+ x = net_g(input_ids=inputs.input_ids.to(device),
651
+ attention_mask=inputs.attention_mask.to(device),
652
+ lang_code=lang_code,
653
+ )[0, :]
654
+
655
+ total_audio.append(x) # crop the 1st audio - is PREFIX text 156000 samples to chose deu voice / VitsAttention()
656
+
657
+ print(f'\n\n_______________________________ {_t} {x.shape=}')
658
+
659
+ x = torch.cat(total_audio).cpu().numpy()
660
+
661
+ # x /= np.abs(x).max() + 1e-7 ~ Volume normalisation @api.py:tts_multi_sentence() OR demo.py
662
+
663
+ # AUDIOGEN
664
+
665
+ # --
666
+ if soundscape != '':
667
+
668
+ background = audiogen.generate(
669
+ soundscape,
670
+ duration=len(x)/16000 + .74, # duration in seconds
671
+ ).detach().cpu().numpy()
672
+
673
+ # stereo blend
674
+
675
+ background /= 1.02 * np.abs(background).max() + 1e-7 # volume to [-1,1]
676
+ background = background[:len(x), None]
677
+ x = x[:, None]
678
+ x = np.concatenate(
679
+ [.49 * x + .51 * background,
680
+ .51 * background + .49 * x], 1) # stereo
681
+ # --
682
+
683
+ tmp_file = f'_speech.wav' # N x clients (cleanup vs tmp file / client)
684
+
685
+ soundfile.write(tmp_file, x, 16000)
686
+
687
+ return tmp_file
688
+
689
+ other_tts(text='Η γρηγορη καφετι αλεπου πειδαει πανω απο τον τεμπελη σκυλο.',
690
+ lang='English',
691
+ soundscape='cats meowing')
692
+
693
+ # iface = gr.Interface(
694
+ # fn=other_tts,
695
+ # # title="audioNarTTS",
696
+ # # description='TTS - [VITS duration of oscillation](https://huggingface.co/spaces/dkounadis/audioNarTTS/blob/main/vits.py#L560) via [fairseq MMS TTS](https://github.com/facebookresearch/fairseq/blob/main/examples/mms/README.md) langs. For [SHIFT-europe](https://shift-europe.eu/).',
697
+ # inputs=[
698
+ # gr.Textbox(lines=4,
699
+ # value='Η γρηγορη καφετι αλεπου πειδαει πανω απο τον τεμπελη σκυλο.',
700
+ # label="Type text for TTS"),
701
+ # gr.Dropdown(
702
+ # choices=language_names,
703
+ # label="TTS lang",
704
+ # value="Ancient greek",
705
+ # ),
706
+ # gr.Textbox(lines=1,
707
+ # value="dogs barg",
708
+ # label="AudioGen Txt"
709
+ # ),
710
+ # ],
711
+ # outputs="audio",
712
+ # )
713
+
714
+
715
+ # iface.launch()
audiocraft/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .builders import AudioGen
audiocraft/builders.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ from omegaconf import OmegaConf
4
+ import numpy as np
5
+ from huggingface_hub import hf_hub_download
6
+ import os
7
+ from audiocraft.encodec import EncodecModel
8
+ from audiocraft.lm import LMModel
9
+
10
+
11
+
12
+
13
+ N_REPEAT = 2 # num (virtual batch_size) clones of audio sounds
14
+
15
+ def _shift(x):
16
+ #print(x.shape, 'BATCH Independent SHIFT\n AudioGen')
17
+ for i, _slice in enumerate(x):
18
+ n = x.shape[2]
19
+ offset = np.random.randint(.24 * n, max(1, .74 * n)) # high should be above >= 0 TBD
20
+ print(offset)
21
+ x[i, :, :] = torch.roll(_slice, offset, dims=1) # _slice 2D
22
+ return x
23
+
24
+ class AudioGen(torch.nn.Module):
25
+
26
+ # https://huggingface.co/facebook/audiogen-medium
27
+
28
+ def __init__(self):
29
+
30
+ super().__init__()
31
+ _file_1 = hf_hub_download(
32
+ repo_id='facebook/audiogen-medium',
33
+ filename="compression_state_dict.bin",
34
+ cache_dir=os.environ.get('AUDIOCRAFT_CACHE_DIR', None),
35
+ library_name="audiocraft",
36
+ library_version= '1.3.0a1') # Found at __init__.py #audiocraft.__version__)
37
+ pkg = torch.load(_file_1, map_location='cpu')# kwargs = OmegaConf.create(pkg['xp.cfg'])
38
+ self.compression_model = EncodecModel()
39
+ self.compression_model.load_state_dict(pkg['best_state'], strict=False)
40
+ self.compression_model.eval() # ckpt has also unused encoder weights
41
+ # T5 &
42
+ # LM
43
+ _file_2 = hf_hub_download(
44
+ repo_id='facebook/audiogen-medium',
45
+ filename="state_dict.bin",
46
+ cache_dir=os.environ.get('AUDIOCRAFT_CACHE_DIR', None),
47
+ library_name="audiocraft",
48
+ library_version= '1.3.0a1') # Found at __init__.py #audiocraft.__version__)
49
+ pkg = torch.load(_file_2, map_location='cpu')
50
+ cfg = OmegaConf.create(pkg['xp.cfg']) # CFG inside torch bin
51
+ _best = pkg['best_state']
52
+ _best['t5.output_proj.weight'] = _best.pop('condition_provider.conditioners.description.output_proj.weight')#.to(torch.float)
53
+ _best['t5.output_proj.bias'] = _best.pop('condition_provider.conditioners.description.output_proj.bias')#.to(torch.float)
54
+ self.lm = LMModel()
55
+ self.lm.load_state_dict(pkg['best_state'], strict=True)
56
+ self.lm.eval()
57
+
58
+
59
+ @torch.no_grad()
60
+ def generate(self,
61
+ prompt='dogs mewo',
62
+ duration=2.24, # seconds of audio
63
+ ):
64
+ torch.manual_seed(42) # https://github.com/facebookresearch/audiocraft/issues/111#issuecomment-1614732858
65
+ self.lm.n_draw = int(duration / .74) + 1 # different beam every 0.47 seconds of audio
66
+
67
+ with torch.autocast(device_type='cpu', dtype=torch.bfloat16):
68
+ gen_tokens = self.lm.generate(
69
+ text_condition=[prompt] * N_REPEAT + [''] * N_REPEAT,#['dogs', 'dogs...!', '', '']
70
+ max_tokens=int(duration / (N_REPEAT * self.lm.n_draw) * self.compression_model.frame_rate)
71
+ ) # [bs, 4, 74 * self.lm.n_draw]
72
+ x = self.compression_model.decode(gen_tokens) #[bs, 1, 11840]
73
+
74
+
75
+ for _ in range(7): # perhaps shift is too random as already lm.n_draw has randomness
76
+ x = _shift(x)
77
+
78
+ return x.reshape(-1) #x / (x.abs().max() + 1e-7)
audiocraft/encodec.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ from torch import nn
4
+ import math
5
+ import typing as tp
6
+ import warnings
7
+ import torch
8
+ from torch.nn import functional as F
9
+ from torch.nn.utils import weight_norm
10
+ from audiocraft.vq import ResidualVectorQuantizer
11
+
12
+
13
+ class EncodecModel(nn.Module):
14
+
15
+ def __init__(self):
16
+
17
+ super().__init__()
18
+ self.decoder = SEANetDecoder()
19
+ self.quantizer = ResidualVectorQuantizer()
20
+ self.frame_rate = 50
21
+
22
+
23
+ def decode(self, codes):
24
+ # B,K,T -> B,C,T
25
+ emb = self.quantizer.decode(codes)
26
+
27
+ out = self.decoder(emb)
28
+
29
+ return out
30
+
31
+
32
+ class StreamableLSTM(nn.Module):
33
+ """LSTM without worrying about the hidden state, nor the layout of the data.
34
+ Expects input as convolutional layout.
35
+ """
36
+ def __init__(self, dimension: int, num_layers: int = 2, skip: bool = True):
37
+ super().__init__()
38
+ self.skip = skip
39
+ self.lstm = nn.LSTM(dimension, dimension, num_layers)
40
+
41
+ def forward(self, x):
42
+ print('LSTM called 1c')
43
+ x = x.permute(2, 0, 1)
44
+ y, _ = self.lstm(x)
45
+ if self.skip:
46
+ y = y + x
47
+ y = y.permute(1, 2, 0)
48
+ return y
49
+
50
+
51
+
52
+ class SEANetResnetBlock(nn.Module):
53
+ """Residual block from SEANet model.
54
+
55
+ Args:
56
+ dim (int): Dimension of the input/output.
57
+ kernel_sizes (list): List of kernel sizes for the convolutions.
58
+ dilations (list): List of dilations for the convolutions.
59
+ activation (str): Activation function.
60
+ activation_params (dict): Parameters to provide to the activation function.
61
+ norm (str): Normalization method.
62
+ norm_params (dict): Parameters to provide to the underlying normalization used along with the convolution.
63
+ causal (bool): Whether to use fully causal convolution.
64
+ pad_mode (str): Padding mode for the convolutions.
65
+ compress (int): Reduced dimensionality in residual branches (from Demucs v3).
66
+ true_skip (bool): Whether to use true skip connection or a simple
67
+ (streamable) convolution as the skip connection.
68
+ """
69
+ def __init__(self, dim: int, kernel_sizes: tp.List[int] = [3, 1], dilations: tp.List[int] = [1, 1],
70
+ activation: str = 'ELU', activation_params: dict = {'alpha': 1.0},
71
+ norm: str = 'none', norm_params: tp.Dict[str, tp.Any] = {}, causal: bool = False,
72
+ pad_mode: str = 'reflect', compress: int = 2, true_skip: bool = True):
73
+ super().__init__()
74
+ assert len(kernel_sizes) == len(dilations), 'Number of kernel sizes should match number of dilations'
75
+ act = getattr(nn, activation)
76
+ hidden = dim // compress
77
+ block = []
78
+ for i, (kernel_size, dilation) in enumerate(zip(kernel_sizes, dilations)):
79
+ in_chs = dim if i == 0 else hidden
80
+ out_chs = dim if i == len(kernel_sizes) - 1 else hidden
81
+ block += [
82
+ act(**activation_params),
83
+ StreamableConv1d(in_chs, out_chs, kernel_size=kernel_size, dilation=dilation,
84
+ norm=norm, norm_kwargs=norm_params,
85
+ causal=causal, pad_mode=pad_mode),
86
+ ]
87
+ self.block = nn.Sequential(*block)
88
+ self.shortcut: nn.Module
89
+ if true_skip:
90
+ self.shortcut = nn.Identity()
91
+ else:
92
+ self.shortcut = StreamableConv1d(dim, dim, kernel_size=1, norm=norm, norm_kwargs=norm_params,
93
+ causal=causal, pad_mode=pad_mode)
94
+
95
+ def forward(self, x):
96
+ return self.shortcut(x) + self.block(x)
97
+
98
+
99
+
100
+
101
+
102
+ class SEANetDecoder(nn.Module):
103
+ # channels=1 dimension=128 n_filters=64 n_residual_layers=1 ratios=[8, 5, 4, 2]
104
+ # activation='ELU' activation_params={'alpha': 1.0}, final_activation=None
105
+ # final_activation_params=None norm='weight_norm'
106
+ # norm_params={} kernel_size=7 last_kernel_size=7 residual_kernel_size=3 dilation_base=2
107
+ # causal=False pad_mode='constant'
108
+ # true_skip=True compress=2 lstm=2 disable_norm_outer_blocks=0 trim_right_ratio=1.0
109
+
110
+ def __init__(self,
111
+ channels = 1,
112
+ dimension = 128,
113
+ n_filters = 64,
114
+ n_residual_layers = 1,
115
+ ratios = [8, 5, 4, 2],
116
+ activation = 'ELU',
117
+ activation_params: dict = {'alpha': 1.0},
118
+ final_activation = None,
119
+ final_activation_params = None,
120
+ norm = 'weight_norm',
121
+ norm_params = {},
122
+ kernel_size = 7,
123
+ last_kernel_size = 7,
124
+ residual_kernel_size = 3,
125
+ dilation_base = 2,
126
+ causal = False,
127
+ pad_mode = 'constant',
128
+ true_skip = True,
129
+ compress = 2,
130
+ lstm = 2,
131
+ disable_norm_outer_blocks = 0,
132
+ trim_right_ratio = 1.0):
133
+ super().__init__()
134
+ self.dimension = dimension
135
+ self.channels = channels
136
+ self.n_filters = n_filters
137
+ self.ratios = ratios
138
+ del ratios
139
+ self.n_residual_layers = n_residual_layers
140
+ self.hop_length = np.prod(self.ratios)
141
+ self.n_blocks = len(self.ratios) + 2 # first and last conv + residual blocks
142
+ self.disable_norm_outer_blocks = disable_norm_outer_blocks
143
+ assert self.disable_norm_outer_blocks >= 0 and self.disable_norm_outer_blocks <= self.n_blocks, \
144
+ "Number of blocks for which to disable norm is invalid." \
145
+ "It should be lower or equal to the actual number of blocks in the network and greater or equal to 0."
146
+
147
+ act = getattr(nn, activation)
148
+ mult = int(2 ** len(self.ratios))
149
+ model: tp.List[nn.Module] = [
150
+ StreamableConv1d(dimension, mult * n_filters, kernel_size,
151
+ norm='none' if self.disable_norm_outer_blocks == self.n_blocks else norm,
152
+ norm_kwargs=norm_params, causal=causal, pad_mode=pad_mode)
153
+ ]
154
+
155
+ if lstm:
156
+ print('\n\n\n\nLSTM IN SEANET\n\n\n\n')
157
+ model += [StreamableLSTM(mult * n_filters, num_layers=lstm)]
158
+
159
+ # Upsample to raw audio scale
160
+ for i, ratio in enumerate(self.ratios):
161
+ block_norm = 'none' if self.disable_norm_outer_blocks >= self.n_blocks - (i + 1) else norm
162
+ # Add upsampling layers
163
+ model += [
164
+ act(**activation_params),
165
+ StreamableConvTranspose1d(mult * n_filters, mult * n_filters // 2,
166
+ kernel_size=ratio * 2, stride=ratio,
167
+ norm=block_norm, norm_kwargs=norm_params,
168
+ causal=causal, trim_right_ratio=trim_right_ratio),
169
+ ]
170
+ # Add residual layers
171
+ for j in range(n_residual_layers):
172
+ model += [
173
+ SEANetResnetBlock(mult * n_filters // 2, kernel_sizes=[residual_kernel_size, 1],
174
+ dilations=[dilation_base ** j, 1],
175
+ activation=activation, activation_params=activation_params,
176
+ norm=block_norm, norm_params=norm_params, causal=causal,
177
+ pad_mode=pad_mode, compress=compress, true_skip=true_skip)]
178
+
179
+ mult //= 2
180
+
181
+ # Add final layers
182
+ model += [
183
+ act(**activation_params),
184
+ StreamableConv1d(n_filters, channels, last_kernel_size,
185
+ norm='none' if self.disable_norm_outer_blocks >= 1 else norm,
186
+ norm_kwargs=norm_params, causal=causal, pad_mode=pad_mode)
187
+ ]
188
+ # Add optional final activation to decoder (eg. tanh)
189
+ if final_activation is not None:
190
+ final_act = getattr(nn, final_activation)
191
+ final_activation_params = final_activation_params or {}
192
+ model += [
193
+ final_act(**final_activation_params)
194
+ ]
195
+ self.model = nn.Sequential(*model)
196
+
197
+ def forward(self, z):
198
+ print(f'\n Enter seanet with shape {z.shape}\n') # arrives here with (1,128,35)
199
+ # how can this convnet care for the value that is in z so it crashes?
200
+ y = self.model(z)
201
+ print(f'\n Exit seanet with shape {y.shape}\n') # arrives here with (1,128,35)
202
+ return y
203
+
204
+
205
+ # --
206
+
207
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
208
+ # All rights reserved.
209
+ #
210
+ # This source code is licensed under the license found in the
211
+ # LICENSE file in the root directory of this source tree.
212
+
213
+
214
+
215
+ CONV_NORMALIZATIONS = frozenset(['none', 'weight_norm', 'spectral_norm',
216
+ 'time_group_norm'])
217
+
218
+
219
+ def apply_parametrization_norm(module: nn.Module, norm: str = 'none'):
220
+ assert norm in CONV_NORMALIZATIONS
221
+ if norm == 'weight_norm':
222
+ return weight_norm(module)
223
+ elif norm == 'spectral_norm':
224
+ raise FileNotFoundError
225
+ # return spectral_norm(module)
226
+ else:
227
+ raise ValueError
228
+ # We already check was in CONV_NORMALIZATION, so any other choice
229
+ # doesn't need reparametrization.
230
+ return module
231
+
232
+
233
+
234
+
235
+
236
+ def get_extra_padding_for_conv1d(x: torch.Tensor, kernel_size: int, stride: int,
237
+ padding_total: int = 0) -> int:
238
+ """See `pad_for_conv1d`."""
239
+ length = x.shape[-1]
240
+ n_frames = (length - kernel_size + padding_total) / stride + 1
241
+ ideal_length = (math.ceil(n_frames) - 1) * stride + (kernel_size - padding_total)
242
+ return ideal_length - length
243
+
244
+ def pad1d(x: torch.Tensor, paddings: tp.Tuple[int, int], mode: str = 'constant', value: float = 0.):
245
+ """Tiny wrapper around F.pad, just to allow for reflect padding on small input.
246
+ If this is the case, we insert extra 0 padding to the right before the reflection happen.
247
+ """
248
+ length = x.shape[-1]
249
+ padding_left, padding_right = paddings
250
+ assert padding_left >= 0 and padding_right >= 0, (padding_left, padding_right)
251
+ if mode == 'reflect':
252
+ max_pad = max(padding_left, padding_right)
253
+ extra_pad = 0
254
+ if length <= max_pad:
255
+ extra_pad = max_pad - length + 1
256
+ x = F.pad(x, (0, extra_pad))
257
+ padded = F.pad(x, paddings, mode, value)
258
+ end = padded.shape[-1] - extra_pad
259
+ return padded[..., :end]
260
+ else:
261
+ return F.pad(x, paddings, mode, value)
262
+
263
+
264
+ def unpad1d(x: torch.Tensor, paddings: tp.Tuple[int, int]):
265
+ """Remove padding from x, handling properly zero padding. Only for 1d!"""
266
+ padding_left, padding_right = paddings
267
+ assert padding_left >= 0 and padding_right >= 0, (padding_left, padding_right)
268
+ assert (padding_left + padding_right) <= x.shape[-1]
269
+ end = x.shape[-1] - padding_right
270
+ return x[..., padding_left: end]
271
+
272
+
273
+ class NormConv1d(nn.Module):
274
+ def __init__(self, *args,
275
+ causal = False, norm = 'none',
276
+ norm_kwargs = {}, **kwargs):
277
+ super().__init__()
278
+ self.conv = apply_parametrization_norm(nn.Conv1d(*args, **kwargs), norm) # norm = weight_norm
279
+ def forward(self, x):
280
+ return self.conv(x)
281
+
282
+
283
+
284
+
285
+
286
+ class NormConvTranspose1d(nn.Module):
287
+ def __init__(self, *args, causal: bool = False, norm: str = 'none',
288
+ norm_kwargs: tp.Dict[str, tp.Any] = {}, **kwargs):
289
+ super().__init__()
290
+ self.convtr = apply_parametrization_norm(nn.ConvTranspose1d(*args, **kwargs), norm)
291
+
292
+ def forward(self, x):
293
+ return self.convtr(x)
294
+
295
+
296
+
297
+
298
+
299
+
300
+ class StreamableConv1d(nn.Module):
301
+ """Conv1d with some builtin handling of asymmetric or causal padding
302
+ and normalization.
303
+ """
304
+ def __init__(self,
305
+ in_channels,
306
+ out_channels,
307
+ kernel_size,
308
+ stride=1,
309
+ dilation=1,
310
+ groups=1,
311
+ bias=True,
312
+ causal=False,
313
+ norm='none',
314
+ norm_kwargs={},
315
+ pad_mode='reflect'):
316
+ super().__init__()
317
+ # warn user on unusual setup between dilation and stride
318
+ # if stride > 1 and dilation > 1:
319
+ # warnings.warn("StreamableConv1d has been initialized with stride > 1 and dilation > 1"
320
+ # f" (kernel_size={kernel_size} stride={stride}, dilation={dilation}).")
321
+ self.conv = NormConv1d(in_channels, out_channels, kernel_size, stride,
322
+ dilation=dilation, groups=groups, bias=bias, causal=causal,
323
+ norm=norm, norm_kwargs=norm_kwargs)
324
+ self.causal = causal
325
+ self.pad_mode = pad_mode
326
+
327
+ def forward(self, x):
328
+ B, C, T = x.shape
329
+ kernel_size = self.conv.conv.kernel_size[0]
330
+ stride = self.conv.conv.stride[0]
331
+ dilation = self.conv.conv.dilation[0]
332
+ kernel_size = (kernel_size - 1) * dilation + 1 # effective kernel size with dilations
333
+ padding_total = kernel_size - stride
334
+ extra_padding = get_extra_padding_for_conv1d(x, kernel_size, stride, padding_total)
335
+ if self.causal:
336
+ # Left padding for causal
337
+ # x = pad1d(x, (padding_total, extra_padding), mode=self.pad_mode)
338
+ print('\n \n\n\nn\n\n\nnCAUSAL N\n\n\n')
339
+
340
+ else:
341
+
342
+ # Asymmetric padding required for odd strides
343
+ padding_right = padding_total // 2
344
+ padding_left = padding_total - padding_right
345
+
346
+ print(f'L147 PADs {padding_left=} {padding_right=} {extra_padding=}')
347
+
348
+ x = pad1d(x, (padding_left, padding_right + extra_padding), mode=self.pad_mode)
349
+ # print(f'\n \/n\n\n\nANTICaus N {x.shape=}\n')
350
+ # ANTICaus CONV OLD_SHAPE=torch.Size([1, 512, 280]) x.shape=torch.Size([1, 512, 282])
351
+ return self.conv(x)
352
+
353
+
354
+ class StreamableConvTranspose1d(nn.Module):
355
+ """ConvTranspose1d with some builtin handling of asymmetric or causal padding
356
+ and normalization.
357
+ """
358
+ def __init__(self, in_channels: int, out_channels: int,
359
+ kernel_size: int, stride: int = 1, causal: bool = False,
360
+ norm: str = 'none', trim_right_ratio: float = 1.,
361
+ norm_kwargs: tp.Dict[str, tp.Any] = {}):
362
+ super().__init__()
363
+ self.convtr = NormConvTranspose1d(in_channels, out_channels, kernel_size, stride,
364
+ causal=causal, norm=norm, norm_kwargs=norm_kwargs)
365
+ self.causal = causal
366
+ self.trim_right_ratio = trim_right_ratio
367
+ assert self.causal or self.trim_right_ratio == 1., \
368
+ "`trim_right_ratio` != 1.0 only makes sense for causal convolutions"
369
+ assert self.trim_right_ratio >= 0. and self.trim_right_ratio <= 1.
370
+
371
+ def forward(self, x):
372
+ kernel_size = self.convtr.convtr.kernel_size[0]
373
+ stride = self.convtr.convtr.stride[0]
374
+ padding_total = kernel_size - stride
375
+
376
+ y = self.convtr(x)
377
+
378
+ # We will only trim fixed padding. Extra padding from `pad_for_conv1d` would be
379
+ # removed at the very end, when keeping only the right length for the output,
380
+ # as removing it here would require also passing the length at the matching layer
381
+ # in the encoder.
382
+ if self.causal:
383
+ print('\n \n\n\nn\n\n\nnCAUSAL T\n\n\n\n\n')
384
+ else:
385
+ # Asymmetric padding required for odd strides
386
+ # print('\n \n\n\nn\n\n\nnANTICAUSAL T\n\n\n')
387
+ padding_right = padding_total // 2
388
+ padding_left = padding_total - padding_right
389
+ y = unpad1d(y, (padding_left, padding_right))
390
+ return y
audiocraft/lm.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from audiocraft.transformer import StreamingTransformer
3
+ from torch import nn
4
+ from transformers import T5EncoderModel, T5Tokenizer # type: ignore
5
+
6
+ class T5(nn.Module):
7
+
8
+ def __init__(self):
9
+
10
+ super().__init__()
11
+ self.output_proj = nn.Linear(1024, # t5-large
12
+ 1536) # lm hidden
13
+ self.t5_tokenizer = T5Tokenizer.from_pretrained('t5-large', legacy=True)
14
+ t5 = T5EncoderModel.from_pretrained('t5-large').train(mode=False)
15
+
16
+ # this makes sure that the t5 is not part
17
+ # of the saved checkpoint
18
+ self.__dict__['t5'] = t5.to('cpu')
19
+
20
+ def forward(self, prompt):
21
+ with torch.set_grad_enabled(False): #, torch.autocast(device_type='cpu', dtype=torch.float32):
22
+
23
+ bs = len(prompt) // 2
24
+ d = self.t5_tokenizer(prompt,
25
+ return_tensors='pt',
26
+ padding=True).to(self.output_proj.bias.device)
27
+ d['attention_mask'][bs:, :] = 0 # null condition t5 attn_mask should be zero
28
+
29
+ x = self.t5(input_ids=d['input_ids'],
30
+ attention_mask=d['attention_mask']).last_hidden_state # no kv
31
+ # Float 16
32
+ # > self.output_proj() is outside of autocast of t5 - however inside the autocast of lm thus computed in torch.float16
33
+ x = self.output_proj(x) # nn.Linear() - produces different result if there is no duplicate txt condition here
34
+ x[bs:, :, :] = 0 # venv/../site-packages/audiocraft/modules/conditioners.py -> tokenize()
35
+ return x
36
+
37
+
38
+ class LMModel(nn.Module):
39
+
40
+ def __init__(self,
41
+ n_q = 4,
42
+ card = 2048,
43
+ dim = 1536
44
+ ):
45
+ super().__init__()
46
+ self.t5 = T5()
47
+ self.card = card # 2048
48
+ self.n_draw = 1 # draw > 1 tokens of different CFG scale
49
+ # batch size > 1 is slower from n_draw as calls transformer on larger batch
50
+ self.emb = nn.ModuleList([nn.Embedding(self.card + 1, dim) for _ in range(n_q)]) # EMBEDDING HAS 2049
51
+ self.transformer = StreamingTransformer()
52
+ self.out_norm = nn.LayerNorm(dim, eps=1e-5)
53
+ self.linears = nn.ModuleList([nn.Linear(dim, self.card, bias=False) for _ in range(n_q)]) # LINEAR DOESNT HAVE 2049
54
+
55
+ def forward(self,
56
+ sequence,
57
+ condition_tensors=None,
58
+ cache_position=None):
59
+
60
+ bs, n_q, time_frames = sequence.shape # [bs, 4, time]
61
+
62
+ input_ = sum([self.emb[k](sequence[:, k]) for k in range(n_q)])
63
+
64
+ out = self.transformer(torch.cat([input_, input_], 0), # duplicate null condition (bs x 2) for ClassifierFreeGuidance
65
+ cross_attention_src=condition_tensors,
66
+ cache_position=cache_position
67
+ )
68
+
69
+ logits = torch.stack([self.linears[k](self.out_norm(out)) for k in range(n_q)], dim=1) # [2*bs, 4, 1, 2048]
70
+ logits = 3 * logits[:bs, :, :, :] - self._scale * logits[bs:, :, :, :] # [ bs, 4, n_draw, 2048]
71
+
72
+ k = 24
73
+ logits = torch.softmax(logits / 1.0, dim=3) # [bs, 4, 1, 2048]
74
+ p, ix = torch.topk(logits, k, dim=3) # p = [bs, 4, 1, 24], ix = [bs, 4, 1, 2048]
75
+ # Exponential Distribution
76
+ deflation = torch.empty_like(p).exponential_(lambd=1)
77
+ p = p / deflation
78
+ # divide large probs with exp(prob) If prob=.001 then 1/exp(1*.001) -> almost by 0 --> exp doesnt really produce (0, Inf)
79
+ p = p.argmax(dim=3, keepdim=True) # [bs, 4, n_draw, 24]
80
+ tok = ix.gather(dim=3, index=p).to(torch.int64) # [bs, 4, n_draw, 1]
81
+ return tok[:, :, :, 0].transpose(1, 2) # [bs, n_draw, 4]
82
+
83
+ @torch.no_grad()
84
+ def generate(self,
85
+ max_tokens=None,
86
+ text_condition=None):
87
+ x = self.t5(text_condition)
88
+ bs = x.shape[0] // 2 # has null conditions - bs*2*N_REPEAT applys in builders.py
89
+ self._scale = .3 * torch.rand(1, 1, self.n_draw, 1, device=x.device) + 1.94
90
+ cache_position = 0
91
+
92
+ out_codes = torch.full((bs,
93
+ self.n_draw,
94
+ 4,
95
+ 4 + 3 + max_tokens), # 4 + max_tokens + 4-1 to have sufficient to index the 1st antidiagonal of 4x4 + 4 xtra tokens
96
+ self.card,
97
+ dtype=torch.long,
98
+ device=x.device) # [bs, n_draw, 4, dur]
99
+
100
+ # A/R
101
+ for offset in range(0, max_tokens + 4 - 1): # max_tokens + n_q - 1
102
+
103
+ # extract diagonal via indexing out_codes[ [0, 1, 2, 3], [0, 1, 2, 3] ]
104
+ next_token = self.forward(out_codes[:, 0, [0, 1, 2, 3], torch.tensor([3, 2, 1, 0]) + offset][:, :, None], # index diagonal & exapnd to [bs, n_q, dur=1]
105
+ #gen_sequence[:, 0, :, offset-1:offset], # DIAGINDEXING for setting prediction of lm into gen_sequence THE GENSEQUENCE has to be un-delayed in the end [Because it has to be de-delayed for the vocoder then is actually only the lm input that requires to see the delay thus we could just feed by diaggather] so it matches gen_codes -1 a[[0, 1, 2, 3], torch.tensor([0, 1, 2, 3]) + 5] the gen_sequence is indexed by vertical column and fed to lm however the prediction of lm is place diagonally with delay to the gen_sequence
106
+ condition_tensors=x, # utilisation of the attention mask of txt condition ?
107
+ cache_position=cache_position) # [bs, n_draw, 4]
108
+
109
+ # Fill of next_token should be also placed on antidiagonal [not column]
110
+
111
+ # Do Not Overwrite 2048 of TRIU/TRIL = START/END => Do Not Fill them by Predicted Tokens
112
+ # 0-th antidiagonal should be full of card = [2048, 2048, 2048, 2048]
113
+ #
114
+ # [2048, 2048, 2048, 2048, 0, 1, 2, 3, 4, 5, 6, 2048, 2048, 2048],
115
+ # [2048, 2048, 2048, 2048, 2048, 0, 1, 2, 3, 4, 5, 6, 2048, 2048],
116
+ # [2048, 2048, 2048, 2048, 2048, 2048, 0, 1, 2, 3, 4, 5, 6, 2048],
117
+ # [2048, 2048, 2048, 2048, 2048, 2048, 2048, 0, 1, 2, 3, 4, 5, 6]]
118
+ # NO OVerWriting
119
+ if offset == 0:
120
+
121
+ next_token[:, :, 1:4] = 2048 # self.card - bottom 3 entries of the antidiagonal should remain 2048
122
+
123
+ elif offset == 1:
124
+
125
+ next_token[:, :, 2:4] = 2048 # bottom 2 entries of the antidiagonal should remain 2048
126
+
127
+ elif offset == 2:
128
+
129
+ next_token[:, :, 3:4] = 2048
130
+
131
+ elif offset == max_tokens:
132
+
133
+ next_token[:, :, 0:1] = 2048 # top 1 entry of the antidiagonal should stay to 2048
134
+
135
+ elif offset == (max_tokens + 1):
136
+
137
+ next_token[:, :, 0:2] = 2048
138
+
139
+ elif offset == (max_tokens + 2):
140
+
141
+ next_token[:, :, 0:3] = 2048
142
+
143
+ else: # offset 3,4,5,6,7...... max_tokens-1 # FILL Complete n_q = 4 ANTIDIAGONAL ENTRIES
144
+
145
+ pass #print('No delete anti-diag')
146
+
147
+ out_codes[:, :, [0, 1, 2, 3], torch.tensor([3, 2, 1, 0]) + offset + 1] = next_token
148
+ # Sink Attn
149
+ if (offset > 0) and (offset % 71) == 0:
150
+ n_preserve = 4
151
+ self.transformer._flush(n_preserve=n_preserve)
152
+ cache_position = n_preserve
153
+ else:
154
+ cache_position += 1
155
+
156
+ # [bs, n_draw, 4, time+xtra] -> [bs, 4, n_draw, time] -> [bs, 4, time * n_draw]
157
+ out_codes = out_codes[:, :, :, 4:max_tokens+4].transpose(1, 2).reshape(bs, 4, self.n_draw * max_tokens)
158
+
159
+ # flush for next API call
160
+ self.transformer._flush()
161
+
162
+ return out_codes # SKIP THE 4 fill 2048
audiocraft/transformer.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torch.nn import functional as F
4
+ from einops import rearrange
5
+
6
+ torch.backends.cuda.enable_mem_efficient_sdp(True)
7
+
8
+
9
+ def create_sin_embedding(positions,
10
+ dim,
11
+ max_period=10000
12
+ ):
13
+ # assert dim % 2 == 0
14
+ half_dim = dim // 2
15
+ positions = positions.to(torch.float)
16
+ adim = torch.arange(half_dim, device=positions.device,
17
+ dtype=torch.float).view(1, 1, -1)
18
+ max_period_tensor = torch.full([],
19
+ max_period,
20
+ device=positions.device,
21
+ dtype=torch.float) # avoid sync point
22
+ phase = positions / (max_period_tensor ** (adim / (half_dim - 1)))
23
+ # OFFICIAL is torch.float32 HOWEVER self_attn.in_prod_weight = torch.float16
24
+ return torch.cat([torch.cos(phase), torch.sin(phase)], dim=-1)
25
+
26
+
27
+ class StreamingMultiheadAttention(nn.Module):
28
+
29
+ def __init__(self,
30
+ embed_dim,
31
+ num_heads,
32
+ cross_attention=False,
33
+ ):
34
+
35
+ super().__init__()
36
+
37
+ self.cross_attention = cross_attention
38
+ # if not self.cross_attention then it has kvcachingn
39
+ self.k_history = None
40
+ # cleanup history through LM inside GENERATION - Each 0,..,47 mha has different kv history
41
+ self.v_history = None
42
+ self.num_heads = num_heads
43
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=False)
44
+ self.register_buffer('in_proj_weight', torch.ones((3 * embed_dim, embed_dim),
45
+ dtype=torch.float))
46
+
47
+ def forward(self,
48
+ query,
49
+ key=None,
50
+ value=None):
51
+ layout = "b h t d"
52
+ if self.cross_attention:
53
+
54
+ # Different queries, keys, values > split in_proj_weight
55
+
56
+ dim = self.in_proj_weight.shape[0] // 3
57
+
58
+ q = nn.functional.linear(query, self.in_proj_weight[:dim])
59
+ k = nn.functional.linear(key, self.in_proj_weight[dim: 2 * dim])
60
+ v = nn.functional.linear(value, self.in_proj_weight[2 * dim:])
61
+
62
+ q, k, v = [
63
+ rearrange(x, f"b t (h d) -> {layout}", h=self.num_heads) for x in [q, k, v]]
64
+
65
+ else:
66
+ # 1st projected makes k,v (instantaneous)
67
+ # Here else is self_attention for audio with itself (above is cross attention txt)
68
+
69
+ # HISTORY - DIFFERENT FOR EACH TRANSF LAYER
70
+
71
+ # here we have different floating values from official
72
+ projected = nn.functional.linear(query, self.in_proj_weight, None)
73
+ # print(query.sum(), projected.sum() , self.in_proj_weight.sum(), 'Lc') # verified official AudioGen values
74
+ bound_layout = "b h p t d"
75
+ packed = rearrange(
76
+ projected, f"b t (p h d) -> {bound_layout}", p=3, h=self.num_heads)
77
+ q, k, v = packed.unbind(dim=2)
78
+ if self.k_history is not None:
79
+ # IF ctrl^c during live_demo the assigning of each of kv is non-atomic k!=v
80
+ # thus it will try to continue with incompatible k/v dims!
81
+ self.k_history = torch.cat([self.k_history, k], 2)
82
+ self.v_history = torch.cat([self.v_history, v], 2)
83
+ else:
84
+ self.k_history = k
85
+ self.v_history = v
86
+
87
+ # Assign Completed k / v to k / v
88
+
89
+ k = self.k_history
90
+ v = self.v_history
91
+
92
+ # -> kv CACHE ONLY APPLIES if not self.cross_attention
93
+
94
+ x = torch.nn.functional.scaled_dot_product_attention(
95
+ q, k, v, attn_mask=None, is_causal=False, dropout_p=0.0)
96
+
97
+ x = rearrange(x, f"{layout} -> b t (h d)", h=self.num_heads)
98
+ x = self.out_proj(x)
99
+ return x
100
+
101
+
102
+ class StreamingTransformerLayer(nn.Module):
103
+
104
+ def __init__(self,
105
+ d_model,
106
+ num_heads,
107
+ dim_feedforward):
108
+
109
+ super().__init__()
110
+
111
+ self.self_attn = StreamingMultiheadAttention(embed_dim=d_model,
112
+ num_heads=num_heads)
113
+ self.linear1 = nn.Linear(d_model, dim_feedforward, bias=False)
114
+ self.linear2 = nn.Linear(dim_feedforward, d_model, bias=False)
115
+ self.cross_attention = StreamingMultiheadAttention(embed_dim=d_model,
116
+ num_heads=num_heads,
117
+ cross_attention=True)
118
+ self.norm_cross = nn.LayerNorm(d_model, eps=1e-5)
119
+ self.norm1 = nn.LayerNorm(d_model, eps=1e-5)
120
+ self.norm2 = nn.LayerNorm(d_model, eps=1e-5)
121
+
122
+ def forward(self,
123
+ x,
124
+ cross_attention_src=None):
125
+ x = x + self.self_attn(self.norm1(x))
126
+ x = x + self.cross_attention(query=self.norm_cross(x),
127
+ key=cross_attention_src,
128
+ value=cross_attention_src) # txtcondition
129
+ x = x + self.linear2(F.gelu(self.linear1(self.norm2(x))))
130
+ return x
131
+
132
+
133
+ class StreamingTransformer(nn.Module):
134
+
135
+ def __init__(self,
136
+ d_model=1536,
137
+ num_heads=24,
138
+ num_layers=48,
139
+ dim_feedforward=6144):
140
+ super().__init__()
141
+
142
+ self.layers = nn.ModuleList(
143
+ [
144
+ StreamingTransformerLayer(d_model=d_model,
145
+ num_heads=num_heads,
146
+ dim_feedforward=dim_feedforward) for _ in range(num_layers)
147
+ ]
148
+ )
149
+
150
+ def forward(self,
151
+ x,
152
+ cache_position=None,
153
+ cross_attention_src=None):
154
+
155
+ x = x + create_sin_embedding(
156
+ torch.zeros(x.shape[0], 1, 1, device=x.device) + cache_position, 1536)
157
+
158
+ for lay in self.layers:
159
+ x = lay(x,
160
+ cross_attention_src=cross_attention_src)
161
+ return x
162
+
163
+ def _flush(self,
164
+ n_preserve=None):
165
+
166
+ for lay in self.layers:
167
+ if n_preserve is not None:
168
+ # cache position is difficult to choose to also preserve kv from end
169
+ lay.self_attn.k_history = lay.self_attn.k_history[:, :, :n_preserve, :]
170
+ lay.self_attn.v_history = lay.self_attn.v_history[:, :, :n_preserve, :]
171
+ else:
172
+ lay.self_attn.k_history = None
173
+ lay.self_attn.v_history = None
audiocraft/vq.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch import nn
4
+ from einops import rearrange
5
+ import torch.nn.functional as F
6
+
7
+
8
+ class EuclideanCodebook(nn.Module):
9
+ def __init__(self,
10
+ dim,
11
+ codebook_size):
12
+ super().__init__()
13
+ self.register_buffer("embed", torch.zeros(codebook_size, dim))
14
+
15
+ def decode(self, embed_ind):
16
+ return F.embedding(embed_ind, self.embed)
17
+
18
+
19
+
20
+ class VectorQuantization(nn.Module):
21
+
22
+ def __init__(
23
+ self,
24
+ dim,
25
+ codebook_size,
26
+ codebook_dim=None,
27
+ decay=0.8,
28
+ epsilon=1e-5,
29
+ kmeans_init=False,
30
+ kmeans_iters=10,
31
+ channels_last=False,
32
+ ):
33
+ super().__init__()
34
+ _codebook_dim = codebook_dim if codebook_dim is not None else dim
35
+ self._codebook = EuclideanCodebook(dim=_codebook_dim, codebook_size=codebook_size)
36
+ self.codebook_size = codebook_size
37
+ self.channels_last = channels_last
38
+
39
+ def _postprocess(self, quantize):
40
+ if not self.channels_last:
41
+ # raise ValueError
42
+ quantize = rearrange(quantize, "b n d -> b d n")
43
+ return quantize
44
+
45
+ def decode(self, embed_ind):
46
+ quantize = self._codebook.decode(embed_ind)
47
+ # quantize = self.project_out(quantize)
48
+ quantize = self._postprocess(quantize)
49
+ return quantize
50
+
51
+
52
+ class ResidualVectorQuantization(nn.Module):
53
+ """Residual vector quantization implementation.
54
+
55
+ Follows Algorithm 1. in https://arxiv.org/pdf/2107.03312.pdf
56
+ """
57
+ def __init__(self, *, num_quantizers, **kwargs):
58
+ super().__init__()
59
+ self.layers = nn.ModuleList(
60
+ [VectorQuantization(**kwargs) for _ in range(num_quantizers)]
61
+ )
62
+
63
+ def decode(self, q_indices: torch.Tensor) -> torch.Tensor:
64
+ quantized_out = torch.tensor(0.0, device=q_indices.device)
65
+ for i, indices in enumerate(q_indices):
66
+ layer = self.layers[i]
67
+ quantized = layer.decode(indices)
68
+ quantized_out = quantized_out + quantized
69
+ return quantized_out
70
+
71
+
72
+ class ResidualVectorQuantizer(nn.Module):
73
+
74
+ # dimension=128 n_q=4 q_dropout=False bins=2048 decay=0.99 kmeans_init=True kmeans_iters=50 threshold_ema_dead_code=2
75
+ # orthogonal_reg_weight=0.0 orthogonal_reg_active_codes_only=False orthogonal_reg_max_codes=None
76
+
77
+ def __init__(
78
+ self,
79
+ dimension = 128,
80
+ n_q = 4,
81
+ q_dropout = False,
82
+ bins = 2048,
83
+ decay = 0.99,
84
+ kmeans_init = True,
85
+ kmeans_iters = 50,
86
+ threshold_ema_dead_code = 2,
87
+ orthogonal_reg_weight = 0.0,
88
+ orthogonal_reg_active_codes_only = False,
89
+ orthogonal_reg_max_codes = None,
90
+ ):
91
+ super().__init__()
92
+ self.max_n_q = n_q
93
+ self.n_q = n_q
94
+ self.q_dropout = q_dropout
95
+ self.dimension = dimension
96
+ self.bins = bins
97
+ self.decay = decay
98
+ self.kmeans_init = kmeans_init
99
+ self.kmeans_iters = kmeans_iters
100
+ self.threshold_ema_dead_code = threshold_ema_dead_code
101
+ self.orthogonal_reg_weight = orthogonal_reg_weight
102
+ self.orthogonal_reg_active_codes_only = orthogonal_reg_active_codes_only
103
+ self.orthogonal_reg_max_codes = orthogonal_reg_max_codes
104
+ print(f' {kmeans_init=}\n\n\n\n')
105
+ self.vq = ResidualVectorQuantization(
106
+ dim=self.dimension,
107
+ codebook_size=self.bins,
108
+ num_quantizers=self.n_q,
109
+ decay=self.decay,
110
+ kmeans_init=self.kmeans_init,
111
+ kmeans_iters=self.kmeans_iters,
112
+ channels_last=False
113
+ )
114
+
115
+ def decode(self, codes):
116
+ """Decode the given codes to the quantized representation."""
117
+ # codes is [B, K, T], with T frames, K nb of codebooks, vq.decode expects [K, B, T].
118
+ codes = codes.transpose(0, 1)
119
+ return self.vq.decode(codes)
vits.py ADDED
@@ -0,0 +1,623 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import numpy as np
3
+ import torch
4
+ from torch import nn
5
+ from transformers.modeling_utils import PreTrainedModel
6
+ from transformers.configuration_utils import PretrainedConfig
7
+ import json
8
+ import os
9
+ import re
10
+ from transformers.tokenization_utils import PreTrainedTokenizer
11
+ import phonemizer
12
+ import torch.nn.functional as F
13
+
14
+
15
+
16
+ OSCILLATION = {
17
+ 'deu': [1, 2, 1, 2, 1, 2, 2, 1, 2, 1, 2, 1, 2, 2, 1],
18
+ 'rmc-script_latin': [2, 2, 1, 2, 2],
19
+ 'hun': [1, 2, 1, 2, 1, 2, 2, 1, 2, 1, 2, 1, 2, 2, 1],
20
+ 'fra': [1, 2, 1, 2, 1, 2, 2, 1, 2, 1, 2, 1, 2, 2, 1],
21
+ 'eng': [1, 2, 2, 1, 2, 2],
22
+ 'grc': [1, 2, 1, 2, 1, 2, 2, 1, 2, 1, 2, 1, 2, 2, 1],
23
+ 'ron': [1, 2, 1, 2, 1, 2, 2, 1, 2, 1, 2, 1, 2, 2],
24
+ }
25
+
26
+
27
+ def has_non_roman_characters(input_string):
28
+ # Find any character outside the ASCII range
29
+ non_roman_pattern = re.compile(r"[^\x00-\x7F]")
30
+
31
+ # Search the input string for non-Roman characters
32
+ match = non_roman_pattern.search(input_string)
33
+ has_non_roman = match is not None
34
+ return has_non_roman
35
+
36
+
37
+ class VitsConfig(PretrainedConfig):
38
+
39
+ model_type = "vits"
40
+
41
+ def __init__(
42
+ self,
43
+ vocab_size=38,
44
+ hidden_size=192,
45
+ num_hidden_layers=6,
46
+ num_attention_heads=2,
47
+ use_bias=True,
48
+ ffn_dim=768,
49
+ ffn_kernel_size=3,
50
+ flow_size=192,
51
+ # hidden_act="relu",
52
+ upsample_initial_channel=512,
53
+ upsample_rates=[8, 8, 2, 2],
54
+ upsample_kernel_sizes=[16, 16, 4, 4],
55
+ resblock_kernel_sizes=[3, 7, 11],
56
+ resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5], [1, 3, 5]],
57
+ prior_encoder_num_flows=4,
58
+ prior_encoder_num_wavenet_layers=4,
59
+ wavenet_kernel_size=5,
60
+ **kwargs,
61
+ ):
62
+ self.vocab_size = vocab_size
63
+ self.hidden_size = hidden_size
64
+ self.num_hidden_layers = num_hidden_layers
65
+ self.num_attention_heads = num_attention_heads
66
+ self.use_bias = use_bias
67
+ self.ffn_dim = ffn_dim
68
+ self.ffn_kernel_size = ffn_kernel_size
69
+ self.flow_size = flow_size
70
+ self.upsample_initial_channel = upsample_initial_channel
71
+ self.upsample_rates = upsample_rates
72
+ self.upsample_kernel_sizes = upsample_kernel_sizes
73
+ self.resblock_kernel_sizes = resblock_kernel_sizes
74
+ self.resblock_dilation_sizes = resblock_dilation_sizes
75
+ self.prior_encoder_num_flows = prior_encoder_num_flows
76
+ self.prior_encoder_num_wavenet_layers = prior_encoder_num_wavenet_layers
77
+ self.wavenet_kernel_size = wavenet_kernel_size
78
+ super().__init__()
79
+
80
+
81
+ class VitsWaveNet(torch.nn.Module):
82
+ def __init__(self, config, num_layers):
83
+ super().__init__()
84
+ self.hidden_size = config.hidden_size
85
+ self.num_layers = num_layers
86
+ self.in_layers = torch.nn.ModuleList()
87
+ self.res_skip_layers = torch.nn.ModuleList()
88
+ # if hasattr(nn.utils.parametrizations, "weight_norm"):
89
+ # # raise ValueError
90
+ weight_norm = nn.utils.parametrizations.weight_norm
91
+ # else:
92
+ # raise ValueError
93
+ # # weight_norm = nn.utils.weight_norm
94
+ for i in range(num_layers):
95
+
96
+ in_layer = torch.nn.Conv1d(
97
+ in_channels=config.hidden_size,
98
+ out_channels=2 * config.hidden_size,
99
+ kernel_size=config.wavenet_kernel_size,
100
+ dilation=1,
101
+ padding=2,
102
+ )
103
+ in_layer = weight_norm(in_layer, name="weight")
104
+ self.in_layers.append(in_layer)
105
+
106
+ # last one is not necessary
107
+ if i < num_layers - 1:
108
+ res_skip_channels = 2 * config.hidden_size
109
+ else:
110
+ res_skip_channels = config.hidden_size
111
+ res_skip_layer = torch.nn.Conv1d(config.hidden_size, res_skip_channels, 1)
112
+ res_skip_layer = weight_norm(res_skip_layer, name="weight")
113
+ self.res_skip_layers.append(res_skip_layer)
114
+
115
+ def forward(self,
116
+ inputs):
117
+ outputs = torch.zeros_like(inputs)
118
+ num_channels = torch.IntTensor([self.hidden_size])[0]
119
+ for i in range(self.num_layers):
120
+ in_act = self.in_layers[i](inputs)
121
+ # global_states = torch.zeros_like(hidden_states) # style ?
122
+ # acts = fused_add_tanh_sigmoid_multiply(hidden_states, global_states, num_channels_tensor[0])
123
+ # --
124
+ # def fused_add_tanh_sigmoid_multiply(input_a, input_b, num_channels):
125
+ # in_act = input_a # + input_b
126
+ t_act = torch.tanh(in_act[:, :num_channels, :])
127
+ s_act = torch.sigmoid(in_act[:, num_channels:, :])
128
+ acts = t_act * s_act
129
+ res_skip_acts = self.res_skip_layers[i](acts)
130
+ if i < self.num_layers - 1:
131
+ res_acts = res_skip_acts[:, : self.hidden_size, :]
132
+ inputs = inputs + res_acts
133
+ outputs = outputs + res_skip_acts[:, self.hidden_size :, :]
134
+ else:
135
+ outputs = outputs + res_skip_acts
136
+ return outputs
137
+
138
+ # Copied from transformers.models.speecht5.modeling_speecht5.HifiGanResidualBlock
139
+ class HifiGanResidualBlock(nn.Module):
140
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5), leaky_relu_slope=0.1):
141
+ super().__init__()
142
+ self.leaky_relu_slope = leaky_relu_slope
143
+
144
+ self.convs1 = nn.ModuleList(
145
+ [
146
+ nn.Conv1d(
147
+ channels,
148
+ channels,
149
+ kernel_size,
150
+ stride=1,
151
+ dilation=dilation[i],
152
+ padding=self.get_padding(kernel_size, dilation[i]),
153
+ )
154
+ for i in range(len(dilation))
155
+ ]
156
+ )
157
+ self.convs2 = nn.ModuleList(
158
+ [
159
+ nn.Conv1d(
160
+ channels,
161
+ channels,
162
+ kernel_size,
163
+ stride=1,
164
+ dilation=1,
165
+ padding=self.get_padding(kernel_size, 1),
166
+ )
167
+ for _ in range(len(dilation))
168
+ ]
169
+ )
170
+
171
+ def get_padding(self, kernel_size, dilation=1):
172
+ # 1, 3, 5, 15
173
+ return (kernel_size * dilation - dilation) // 2
174
+
175
+ def forward(self, hidden_states):
176
+ for conv1, conv2 in zip(self.convs1, self.convs2):
177
+ residual = hidden_states
178
+ hidden_states = nn.functional.leaky_relu(hidden_states, negative_slope=self.leaky_relu_slope)
179
+ hidden_states = conv1(hidden_states)
180
+ hidden_states = nn.functional.leaky_relu(hidden_states, negative_slope=self.leaky_relu_slope)
181
+ hidden_states = conv2(hidden_states)
182
+ hidden_states = hidden_states + residual
183
+ return hidden_states
184
+
185
+
186
+ class VitsHifiGan(nn.Module):
187
+ def __init__(self, config):
188
+ super().__init__()
189
+ self.config = config
190
+ self.num_kernels = len(config.resblock_kernel_sizes)
191
+ self.num_upsamples = len(config.upsample_rates)
192
+ self.conv_pre = nn.Conv1d(
193
+ config.flow_size,
194
+ config.upsample_initial_channel,
195
+ kernel_size=7,
196
+ stride=1,
197
+ padding=3,
198
+ )
199
+
200
+ self.upsampler = nn.ModuleList()
201
+ for i, (upsample_rate, kernel_size) in enumerate(zip(config.upsample_rates, config.upsample_kernel_sizes)):
202
+ self.upsampler.append(
203
+ nn.ConvTranspose1d(
204
+ config.upsample_initial_channel // (2**i),
205
+ config.upsample_initial_channel // (2 ** (i + 1)),
206
+ kernel_size=kernel_size,
207
+ stride=upsample_rate,
208
+ padding=(kernel_size - upsample_rate) // 2,
209
+ )
210
+ )
211
+
212
+ self.resblocks = nn.ModuleList()
213
+ for i in range(len(self.upsampler)):
214
+ channels = config.upsample_initial_channel // (2 ** (i + 1))
215
+ for kernel_size, dilation in zip(config.resblock_kernel_sizes, config.resblock_dilation_sizes):
216
+ self.resblocks.append(HifiGanResidualBlock(channels, kernel_size, dilation))
217
+ self.conv_post = nn.Conv1d(channels, 1, kernel_size=7, stride=1, padding=3, bias=False)
218
+
219
+ def forward(self,
220
+ spectrogram):
221
+ hidden_states = self.conv_pre(spectrogram)
222
+ for i in range(self.num_upsamples):
223
+ hidden_states = F.leaky_relu(hidden_states, negative_slope=.1, inplace=True)
224
+ hidden_states = self.upsampler[i](hidden_states)
225
+ res_state = self.resblocks[i * self.num_kernels](hidden_states)
226
+ for j in range(1, self.num_kernels):
227
+ res_state += self.resblocks[i * self.num_kernels + j](hidden_states)
228
+ hidden_states = res_state / self.num_kernels
229
+ hidden_states = F.leaky_relu(hidden_states, negative_slope=.01, inplace=True)
230
+ hidden_states = self.conv_post(hidden_states)
231
+ waveform = torch.tanh(hidden_states)
232
+ return waveform
233
+
234
+
235
+ class VitsResidualCouplingLayer(nn.Module):
236
+ def __init__(self, config):
237
+ super().__init__()
238
+ self.half_channels = config.flow_size // 2
239
+ self.conv_pre = nn.Conv1d(self.half_channels, config.hidden_size, 1)
240
+ self.wavenet = VitsWaveNet(config, num_layers=config.prior_encoder_num_wavenet_layers)
241
+ self.conv_post = nn.Conv1d(config.hidden_size, self.half_channels, 1)
242
+
243
+ def forward(self,
244
+ x,
245
+ reverse=False):
246
+ first_half, second_half = torch.split(x, [self.half_channels] * 2, dim=1)
247
+ hidden_states = self.conv_pre(first_half)
248
+ hidden_states = self.wavenet(hidden_states)
249
+ mean = self.conv_post(hidden_states)
250
+ second_half = (second_half - mean)
251
+ outputs = torch.cat([first_half, second_half], dim=1)
252
+ return outputs
253
+
254
+
255
+ class VitsResidualCouplingBlock(nn.Module):
256
+ def __init__(self, config):
257
+ super().__init__()
258
+ self.flows = nn.ModuleList()
259
+ for _ in range(config.prior_encoder_num_flows):
260
+ self.flows.append(VitsResidualCouplingLayer(config))
261
+
262
+ def forward(self, x, reverse=False):
263
+ # x L [1, 192, 481]
264
+ for flow in reversed(self.flows):
265
+ x = torch.flip(x, [1]) # flipud CHANNELs
266
+ x = flow(x, reverse=True)
267
+ return x
268
+
269
+
270
+ class VitsAttention(nn.Module):
271
+ """has no positional info"""
272
+
273
+ def __init__(self, config):
274
+ super().__init__()
275
+ self.embed_dim = config.hidden_size
276
+ self.num_heads = config.num_attention_heads
277
+
278
+
279
+
280
+ self.head_dim = self.embed_dim // self.num_heads
281
+ self.scaling = self.head_dim**-0.5
282
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.use_bias)
283
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.use_bias)
284
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.use_bias)
285
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.use_bias)
286
+
287
+ def _shape(self, tensor, seq_len, bsz):
288
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
289
+
290
+ def forward(
291
+ self,
292
+ hidden_states,
293
+ layer_head_mask = None,
294
+ output_attentions = False,
295
+ ):
296
+
297
+
298
+ bsz, tgt_len, _ = hidden_states.size()
299
+
300
+ # Q
301
+
302
+ query_states = self.q_proj(hidden_states) * self.scaling
303
+
304
+ # K/V
305
+ hidden_states = hidden_states[:, :40, :] # drop time-frames from k/v [bs*2, time, 96=ch]
306
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
307
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
308
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
309
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
310
+ key_states = key_states.view(*proj_shape)
311
+ value_states = value_states.view(*proj_shape)
312
+
313
+
314
+
315
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
316
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
317
+ attn_output = torch.bmm(attn_weights,
318
+ value_states)
319
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
320
+ attn_output = attn_output.transpose(1, 2)
321
+
322
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
323
+ # partitioned aross GPUs when using tensor-parallelism.
324
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
325
+
326
+ attn_output = self.out_proj(attn_output)
327
+
328
+ return attn_output
329
+
330
+
331
+ class VitsFeedForward(nn.Module):
332
+ def __init__(self, config):
333
+ super().__init__()
334
+ self.conv_1 = nn.Conv1d(config.hidden_size, config.ffn_dim, config.ffn_kernel_size, padding=1)
335
+ self.conv_2 = nn.Conv1d(config.ffn_dim, config.hidden_size, config.ffn_kernel_size, padding=1)
336
+
337
+ def forward(self, hidden_states):
338
+ hidden_states = hidden_states.permute(0, 2, 1)
339
+ hidden_states = F.relu(self.conv_1(hidden_states)) # inplace changes sound ;
340
+ hidden_states = self.conv_2(hidden_states)
341
+ hidden_states = hidden_states.permute(0, 2, 1)
342
+ return hidden_states
343
+
344
+
345
+ class VitsEncoderLayer(nn.Module):
346
+ def __init__(self, config):
347
+ super().__init__()
348
+ self.attention = VitsAttention(config)
349
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=1e-5)
350
+ self.feed_forward = VitsFeedForward(config)
351
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=1e-5)
352
+
353
+ def forward(
354
+ self,
355
+ hidden_states,
356
+ output_attentions = False,
357
+ ):
358
+ residual = hidden_states
359
+ hidden_states = self.attention(
360
+ hidden_states=hidden_states,
361
+ # attention_mask=attention_mask,
362
+ output_attentions=output_attentions,
363
+ )
364
+
365
+
366
+ hidden_states = self.layer_norm(residual + hidden_states)
367
+
368
+ residual = hidden_states
369
+ hidden_states = self.feed_forward(hidden_states)
370
+
371
+ hidden_states = self.final_layer_norm(residual + hidden_states)
372
+
373
+ outputs = (hidden_states,)
374
+
375
+ return outputs
376
+
377
+
378
+ class VitsEncoder(nn.Module):
379
+ def __init__(self, config):
380
+ super().__init__()
381
+ self.config = config
382
+ self.layers = nn.ModuleList([VitsEncoderLayer(config) for _ in range(config.num_hidden_layers)])
383
+
384
+ def forward(
385
+ self,
386
+ hidden_states):
387
+ for _layer in self.layers:
388
+ layer_outputs = _layer(hidden_states)
389
+ hidden_states = layer_outputs[0]
390
+ return hidden_states
391
+
392
+
393
+
394
+ class VitsTextEncoder(nn.Module):
395
+ """
396
+ Has VitsEncoder
397
+ """
398
+
399
+ def __init__(self, config):
400
+ super().__init__()
401
+ self.config = config
402
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id)
403
+ self.encoder = VitsEncoder(config) # 6 Layers of VitsAttention
404
+ self.project = nn.Conv1d(config.hidden_size, config.flow_size * 2, kernel_size=1)
405
+
406
+ def forward(self,
407
+ input_ids
408
+ ):
409
+ hidden_states = self.embed_tokens(input_ids) * 4 #Actually4-or-4.856406460551018-@-845-len-ids-deu
410
+ stats = self.project(self.encoder(hidden_states=hidden_states).transpose(1, 2)).transpose(1, 2)
411
+ return stats[:, :, :self.config.flow_size] # prior_means
412
+
413
+
414
+ class VitsPreTrainedModel(PreTrainedModel):
415
+ config_class = VitsConfig
416
+ base_model_prefix = "vits"
417
+ main_input_name = "input_ids"
418
+ supports_gradient_checkpointing = True
419
+
420
+
421
+
422
+ class VitsModel(VitsPreTrainedModel):
423
+ def __init__(self, config):
424
+ super().__init__(config)
425
+ self.config = config
426
+ self.text_encoder = VitsTextEncoder(config) # has VitsEncoder that includes 6L of VitsAttention
427
+ self.flow = VitsResidualCouplingBlock(config)
428
+ self.decoder = VitsHifiGan(config)
429
+
430
+ def forward(
431
+ self,
432
+ input_ids = None,
433
+ attention_mask = None,
434
+ speaker_id = None,
435
+ output_attentions = None,
436
+ output_hidden_states = None,
437
+ return_dict = None,
438
+ labels = None,
439
+ speed = None,
440
+ lang_code = 'deu', # speed oscillation pattern per voice/lang
441
+ ):
442
+ mask_dtype = self.text_encoder.embed_tokens.weight.dtype
443
+ if attention_mask is not None:
444
+ input_padding_mask = attention_mask.unsqueeze(-1).to(mask_dtype)
445
+ else:
446
+ raise ValueError
447
+ input_padding_mask = torch.ones_like(input_ids).unsqueeze(-1).to(mask_dtype)
448
+ prior_means = self.text_encoder(input_ids=input_ids)
449
+
450
+ input_padding_mask = input_padding_mask.transpose(1, 2)
451
+
452
+
453
+ bs, in_len, _ = prior_means.shape
454
+ # VITS Duration Oscillation
455
+ pattern = OSCILLATION.get(lang_code, [1, 2, 1])
456
+
457
+ duration = torch.tensor(pattern,
458
+ device=prior_means.device).repeat(int(in_len / len(pattern)) + 2)[None, None, :in_len] # perhaps define [1, 2, 1] per voice or language
459
+ duration[:, :, 0] = 4
460
+ duration[:, :, -1] = 3
461
+ # ATTN
462
+ predicted_lengths = torch.clamp_min(torch.sum(duration, [1, 2]), 1).long()
463
+ indices = torch.arange(predicted_lengths.max(), dtype=predicted_lengths.dtype, device=predicted_lengths.device)
464
+ output_padding_mask = indices.unsqueeze(0) < predicted_lengths.unsqueeze(1)
465
+ output_padding_mask = output_padding_mask.unsqueeze(1).to(input_padding_mask.dtype)
466
+ attn_mask = torch.unsqueeze(input_padding_mask, 2) * torch.unsqueeze(output_padding_mask, -1)
467
+ batch_size, _, output_length, input_length = attn_mask.shape
468
+ cum_duration = torch.cumsum(duration, -1).view(batch_size * input_length, 1)
469
+ indices = torch.arange(output_length, dtype=duration.dtype, device=duration.device)
470
+ valid_indices = indices.unsqueeze(0) < cum_duration
471
+ valid_indices = valid_indices.to(attn_mask.dtype).view(batch_size, input_length, output_length)
472
+ padded_indices = valid_indices - nn.functional.pad(valid_indices, [0, 0, 1, 0, 0, 0])[:, :-1]
473
+ attn = padded_indices.unsqueeze(1).transpose(2, 3) * attn_mask
474
+ attn = attn[:, 0, :, :]
475
+
476
+
477
+ attn = attn + 1e-4 * torch.rand_like(attn)
478
+ attn /= attn.sum(2, keepdims=True)
479
+ #print(attn)
480
+ prior_means = torch.matmul(attn, prior_means) # try attn to contain .5/.5 instead of 1/0 so it smoothly interpolates repeated prior_means
481
+
482
+ #prior_means = F.interpolate(prior_means.transpose(1,2), int(1.74 * prior_means.shape[1]), mode='linear').transpose(1,2) # extend for slow speed
483
+
484
+
485
+
486
+ # prior means have now been replicated x duration of each prior mean
487
+
488
+ latents = self.flow(prior_means.transpose(1, 2), # + torch.randn_like(prior_means) * .94,
489
+ reverse=True)
490
+
491
+ waveform = self.decoder(latents) # [bs, 1, 16000]
492
+
493
+ return waveform[:, 0, :]
494
+
495
+
496
+ class VitsTokenizer(PreTrainedTokenizer):
497
+ vocab_files_names = {"vocab_file": "vocab.json"}
498
+ model_input_names = ["input_ids", "attention_mask"]
499
+
500
+ def __init__(
501
+ self,
502
+ vocab_file,
503
+ pad_token="<pad>",
504
+ unk_token="<unk>",
505
+ language=None,
506
+ add_blank=True,
507
+ normalize=True,
508
+ phonemize=True,
509
+ is_uroman=False,
510
+ **kwargs,
511
+ ):
512
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
513
+ self.encoder = json.load(vocab_handle)
514
+
515
+ self.decoder = {v: k for k, v in self.encoder.items()}
516
+ self.language = language
517
+ self.add_blank = add_blank
518
+ self.normalize = normalize
519
+ self.phonemize = phonemize
520
+
521
+ self.is_uroman = is_uroman
522
+
523
+ super().__init__(
524
+ pad_token=pad_token,
525
+ unk_token=unk_token,
526
+ language=language,
527
+ add_blank=add_blank,
528
+ normalize=normalize,
529
+ phonemize=phonemize,
530
+ is_uroman=is_uroman,
531
+ **kwargs,
532
+ )
533
+
534
+ @property
535
+ def vocab_size(self):
536
+ return len(self.encoder)
537
+
538
+ def get_vocab(self):
539
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
540
+ vocab.update(self.added_tokens_encoder)
541
+ return vocab
542
+
543
+ def normalize_text(self, input_string):
544
+ """Lowercase the input string, respecting any special token ids that may be part or entirely upper-cased."""
545
+ all_vocabulary = list(self.encoder.keys()) + list(self.added_tokens_encoder.keys())
546
+ filtered_text = ""
547
+
548
+ i = 0
549
+ while i < len(input_string):
550
+ found_match = False
551
+ for word in all_vocabulary:
552
+ if input_string[i : i + len(word)] == word:
553
+ filtered_text += word
554
+ i += len(word)
555
+ found_match = True
556
+ break
557
+
558
+ if not found_match:
559
+ filtered_text += input_string[i].lower()
560
+ i += 1
561
+
562
+ return filtered_text
563
+
564
+ def _preprocess_char(self, text):
565
+ """Special treatment of characters in certain languages"""
566
+ if self.language == "ron":
567
+ text = text.replace("ț", "ţ")
568
+ return text
569
+
570
+ def prepare_for_tokenization(
571
+ self, text: str, is_split_into_words: bool = False, normalize = None, **kwargs):
572
+
573
+ normalize = normalize if normalize is not None else self.normalize
574
+
575
+ if normalize:
576
+ # normalise for casing
577
+ text = self.normalize_text(text)
578
+
579
+ filtered_text = self._preprocess_char(text)
580
+
581
+ if has_non_roman_characters(filtered_text) and self.is_uroman:
582
+ # 7 langs - For now replace all to romans in app.py
583
+ raise ValueError
584
+
585
+ if self.phonemize:
586
+ if not is_phonemizer_available():
587
+ raise ImportError("Please install the `phonemizer` Python package to use this tokenizer.")
588
+
589
+ filtered_text = phonemizer.phonemize(
590
+ filtered_text,
591
+ language="en-us",
592
+ backend="espeak",
593
+ strip=True,
594
+ preserve_punctuation=True,
595
+ with_stress=True,
596
+ )
597
+ filtered_text = re.sub(r"\s+", " ", filtered_text)
598
+ elif normalize:
599
+ # strip any chars outside of the vocab (punctuation)
600
+ filtered_text = "".join(list(filter(lambda char: char in self.encoder, filtered_text))).strip()
601
+
602
+ return filtered_text, kwargs
603
+
604
+ def _tokenize(self, text):
605
+ """Tokenize a string by inserting the `<pad>` token at the boundary between adjacent characters."""
606
+ tokens = list(text)
607
+
608
+ if self.add_blank:
609
+ # sounds dyslexi if no space between letters
610
+ # sounds disconnected if >2 spaces between letters
611
+ interspersed = [self._convert_id_to_token(0)] * (len(tokens) * 2) # + 1) # +1 rises slice index error if tokens odd
612
+ interspersed[::2] = tokens
613
+ tokens = interspersed + [self._convert_id_to_token(0)] # append one last space (it has indexing error ::2 mismatch if tokens is odd)
614
+
615
+ return tokens
616
+
617
+ def _convert_token_to_id(self, token):
618
+ """Converts a token (str) in an id using the vocab."""
619
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
620
+
621
+ def _convert_id_to_token(self, index):
622
+ """Converts an index (integer) in a token (str) using the vocab."""
623
+ return self.decoder.get(index)