3v324v23 commited on
Commit
9cbe524
1 Parent(s): a387817

i hate git its actual mold

Browse files
.gitattributes DELETED
@@ -1,34 +0,0 @@
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
- *.tflite filter=lfs diff=lfs merge=lfs -text
29
- *.tgz filter=lfs diff=lfs merge=lfs -text
30
- *.wasm filter=lfs diff=lfs merge=lfs -text
31
- *.xz filter=lfs diff=lfs merge=lfs -text
32
- *.zip filter=lfs diff=lfs merge=lfs -text
33
- *.zst filter=lfs diff=lfs merge=lfs -text
34
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.gitignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ **/__pycache__/
3
+ beat_manipulator/beatmaps/
4
+ 1/
5
+ flagged/
6
+ /*.mp3
7
+ /*.wav
8
+ /*.flac
9
+ /*.png
LICENSE.md DELETED
@@ -1,674 +0,0 @@
1
- GNU GENERAL PUBLIC LICENSE
2
- Version 3, 29 June 2007
3
-
4
- Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
- Everyone is permitted to copy and distribute verbatim copies
6
- of this license document, but changing it is not allowed.
7
-
8
- Preamble
9
-
10
- The GNU General Public License is a free, copyleft license for
11
- software and other kinds of works.
12
-
13
- The licenses for most software and other practical works are designed
14
- to take away your freedom to share and change the works. By contrast,
15
- the GNU General Public License is intended to guarantee your freedom to
16
- share and change all versions of a program--to make sure it remains free
17
- software for all its users. We, the Free Software Foundation, use the
18
- GNU General Public License for most of our software; it applies also to
19
- any other work released this way by its authors. You can apply it to
20
- your programs, too.
21
-
22
- When we speak of free software, we are referring to freedom, not
23
- price. Our General Public Licenses are designed to make sure that you
24
- have the freedom to distribute copies of free software (and charge for
25
- them if you wish), that you receive source code or can get it if you
26
- want it, that you can change the software or use pieces of it in new
27
- free programs, and that you know you can do these things.
28
-
29
- To protect your rights, we need to prevent others from denying you
30
- these rights or asking you to surrender the rights. Therefore, you have
31
- certain responsibilities if you distribute copies of the software, or if
32
- you modify it: responsibilities to respect the freedom of others.
33
-
34
- For example, if you distribute copies of such a program, whether
35
- gratis or for a fee, you must pass on to the recipients the same
36
- freedoms that you received. You must make sure that they, too, receive
37
- or can get the source code. And you must show them these terms so they
38
- know their rights.
39
-
40
- Developers that use the GNU GPL protect your rights with two steps:
41
- (1) assert copyright on the software, and (2) offer you this License
42
- giving you legal permission to copy, distribute and/or modify it.
43
-
44
- For the developers' and authors' protection, the GPL clearly explains
45
- that there is no warranty for this free software. For both users' and
46
- authors' sake, the GPL requires that modified versions be marked as
47
- changed, so that their problems will not be attributed erroneously to
48
- authors of previous versions.
49
-
50
- Some devices are designed to deny users access to install or run
51
- modified versions of the software inside them, although the manufacturer
52
- can do so. This is fundamentally incompatible with the aim of
53
- protecting users' freedom to change the software. The systematic
54
- pattern of such abuse occurs in the area of products for individuals to
55
- use, which is precisely where it is most unacceptable. Therefore, we
56
- have designed this version of the GPL to prohibit the practice for those
57
- products. If such problems arise substantially in other domains, we
58
- stand ready to extend this provision to those domains in future versions
59
- of the GPL, as needed to protect the freedom of users.
60
-
61
- Finally, every program is threatened constantly by software patents.
62
- States should not allow patents to restrict development and use of
63
- software on general-purpose computers, but in those that do, we wish to
64
- avoid the special danger that patents applied to a free program could
65
- make it effectively proprietary. To prevent this, the GPL assures that
66
- patents cannot be used to render the program non-free.
67
-
68
- The precise terms and conditions for copying, distribution and
69
- modification follow.
70
-
71
- TERMS AND CONDITIONS
72
-
73
- 0. Definitions.
74
-
75
- "This License" refers to version 3 of the GNU General Public License.
76
-
77
- "Copyright" also means copyright-like laws that apply to other kinds of
78
- works, such as semiconductor masks.
79
-
80
- "The Program" refers to any copyrightable work licensed under this
81
- License. Each licensee is addressed as "you". "Licensees" and
82
- "recipients" may be individuals or organizations.
83
-
84
- To "modify" a work means to copy from or adapt all or part of the work
85
- in a fashion requiring copyright permission, other than the making of an
86
- exact copy. The resulting work is called a "modified version" of the
87
- earlier work or a work "based on" the earlier work.
88
-
89
- A "covered work" means either the unmodified Program or a work based
90
- on the Program.
91
-
92
- To "propagate" a work means to do anything with it that, without
93
- permission, would make you directly or secondarily liable for
94
- infringement under applicable copyright law, except executing it on a
95
- computer or modifying a private copy. Propagation includes copying,
96
- distribution (with or without modification), making available to the
97
- public, and in some countries other activities as well.
98
-
99
- To "convey" a work means any kind of propagation that enables other
100
- parties to make or receive copies. Mere interaction with a user through
101
- a computer network, with no transfer of a copy, is not conveying.
102
-
103
- An interactive user interface displays "Appropriate Legal Notices"
104
- to the extent that it includes a convenient and prominently visible
105
- feature that (1) displays an appropriate copyright notice, and (2)
106
- tells the user that there is no warranty for the work (except to the
107
- extent that warranties are provided), that licensees may convey the
108
- work under this License, and how to view a copy of this License. If
109
- the interface presents a list of user commands or options, such as a
110
- menu, a prominent item in the list meets this criterion.
111
-
112
- 1. Source Code.
113
-
114
- The "source code" for a work means the preferred form of the work
115
- for making modifications to it. "Object code" means any non-source
116
- form of a work.
117
-
118
- A "Standard Interface" means an interface that either is an official
119
- standard defined by a recognized standards body, or, in the case of
120
- interfaces specified for a particular programming language, one that
121
- is widely used among developers working in that language.
122
-
123
- The "System Libraries" of an executable work include anything, other
124
- than the work as a whole, that (a) is included in the normal form of
125
- packaging a Major Component, but which is not part of that Major
126
- Component, and (b) serves only to enable use of the work with that
127
- Major Component, or to implement a Standard Interface for which an
128
- implementation is available to the public in source code form. A
129
- "Major Component", in this context, means a major essential component
130
- (kernel, window system, and so on) of the specific operating system
131
- (if any) on which the executable work runs, or a compiler used to
132
- produce the work, or an object code interpreter used to run it.
133
-
134
- The "Corresponding Source" for a work in object code form means all
135
- the source code needed to generate, install, and (for an executable
136
- work) run the object code and to modify the work, including scripts to
137
- control those activities. However, it does not include the work's
138
- System Libraries, or general-purpose tools or generally available free
139
- programs which are used unmodified in performing those activities but
140
- which are not part of the work. For example, Corresponding Source
141
- includes interface definition files associated with source files for
142
- the work, and the source code for shared libraries and dynamically
143
- linked subprograms that the work is specifically designed to require,
144
- such as by intimate data communication or control flow between those
145
- subprograms and other parts of the work.
146
-
147
- The Corresponding Source need not include anything that users
148
- can regenerate automatically from other parts of the Corresponding
149
- Source.
150
-
151
- The Corresponding Source for a work in source code form is that
152
- same work.
153
-
154
- 2. Basic Permissions.
155
-
156
- All rights granted under this License are granted for the term of
157
- copyright on the Program, and are irrevocable provided the stated
158
- conditions are met. This License explicitly affirms your unlimited
159
- permission to run the unmodified Program. The output from running a
160
- covered work is covered by this License only if the output, given its
161
- content, constitutes a covered work. This License acknowledges your
162
- rights of fair use or other equivalent, as provided by copyright law.
163
-
164
- You may make, run and propagate covered works that you do not
165
- convey, without conditions so long as your license otherwise remains
166
- in force. You may convey covered works to others for the sole purpose
167
- of having them make modifications exclusively for you, or provide you
168
- with facilities for running those works, provided that you comply with
169
- the terms of this License in conveying all material for which you do
170
- not control copyright. Those thus making or running the covered works
171
- for you must do so exclusively on your behalf, under your direction
172
- and control, on terms that prohibit them from making any copies of
173
- your copyrighted material outside their relationship with you.
174
-
175
- Conveying under any other circumstances is permitted solely under
176
- the conditions stated below. Sublicensing is not allowed; section 10
177
- makes it unnecessary.
178
-
179
- 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
-
181
- No covered work shall be deemed part of an effective technological
182
- measure under any applicable law fulfilling obligations under article
183
- 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
- similar laws prohibiting or restricting circumvention of such
185
- measures.
186
-
187
- When you convey a covered work, you waive any legal power to forbid
188
- circumvention of technological measures to the extent such circumvention
189
- is effected by exercising rights under this License with respect to
190
- the covered work, and you disclaim any intention to limit operation or
191
- modification of the work as a means of enforcing, against the work's
192
- users, your or third parties' legal rights to forbid circumvention of
193
- technological measures.
194
-
195
- 4. Conveying Verbatim Copies.
196
-
197
- You may convey verbatim copies of the Program's source code as you
198
- receive it, in any medium, provided that you conspicuously and
199
- appropriately publish on each copy an appropriate copyright notice;
200
- keep intact all notices stating that this License and any
201
- non-permissive terms added in accord with section 7 apply to the code;
202
- keep intact all notices of the absence of any warranty; and give all
203
- recipients a copy of this License along with the Program.
204
-
205
- You may charge any price or no price for each copy that you convey,
206
- and you may offer support or warranty protection for a fee.
207
-
208
- 5. Conveying Modified Source Versions.
209
-
210
- You may convey a work based on the Program, or the modifications to
211
- produce it from the Program, in the form of source code under the
212
- terms of section 4, provided that you also meet all of these conditions:
213
-
214
- a) The work must carry prominent notices stating that you modified
215
- it, and giving a relevant date.
216
-
217
- b) The work must carry prominent notices stating that it is
218
- released under this License and any conditions added under section
219
- 7. This requirement modifies the requirement in section 4 to
220
- "keep intact all notices".
221
-
222
- c) You must license the entire work, as a whole, under this
223
- License to anyone who comes into possession of a copy. This
224
- License will therefore apply, along with any applicable section 7
225
- additional terms, to the whole of the work, and all its parts,
226
- regardless of how they are packaged. This License gives no
227
- permission to license the work in any other way, but it does not
228
- invalidate such permission if you have separately received it.
229
-
230
- d) If the work has interactive user interfaces, each must display
231
- Appropriate Legal Notices; however, if the Program has interactive
232
- interfaces that do not display Appropriate Legal Notices, your
233
- work need not make them do so.
234
-
235
- A compilation of a covered work with other separate and independent
236
- works, which are not by their nature extensions of the covered work,
237
- and which are not combined with it such as to form a larger program,
238
- in or on a volume of a storage or distribution medium, is called an
239
- "aggregate" if the compilation and its resulting copyright are not
240
- used to limit the access or legal rights of the compilation's users
241
- beyond what the individual works permit. Inclusion of a covered work
242
- in an aggregate does not cause this License to apply to the other
243
- parts of the aggregate.
244
-
245
- 6. Conveying Non-Source Forms.
246
-
247
- You may convey a covered work in object code form under the terms
248
- of sections 4 and 5, provided that you also convey the
249
- machine-readable Corresponding Source under the terms of this License,
250
- in one of these ways:
251
-
252
- a) Convey the object code in, or embodied in, a physical product
253
- (including a physical distribution medium), accompanied by the
254
- Corresponding Source fixed on a durable physical medium
255
- customarily used for software interchange.
256
-
257
- b) Convey the object code in, or embodied in, a physical product
258
- (including a physical distribution medium), accompanied by a
259
- written offer, valid for at least three years and valid for as
260
- long as you offer spare parts or customer support for that product
261
- model, to give anyone who possesses the object code either (1) a
262
- copy of the Corresponding Source for all the software in the
263
- product that is covered by this License, on a durable physical
264
- medium customarily used for software interchange, for a price no
265
- more than your reasonable cost of physically performing this
266
- conveying of source, or (2) access to copy the
267
- Corresponding Source from a network server at no charge.
268
-
269
- c) Convey individual copies of the object code with a copy of the
270
- written offer to provide the Corresponding Source. This
271
- alternative is allowed only occasionally and noncommercially, and
272
- only if you received the object code with such an offer, in accord
273
- with subsection 6b.
274
-
275
- d) Convey the object code by offering access from a designated
276
- place (gratis or for a charge), and offer equivalent access to the
277
- Corresponding Source in the same way through the same place at no
278
- further charge. You need not require recipients to copy the
279
- Corresponding Source along with the object code. If the place to
280
- copy the object code is a network server, the Corresponding Source
281
- may be on a different server (operated by you or a third party)
282
- that supports equivalent copying facilities, provided you maintain
283
- clear directions next to the object code saying where to find the
284
- Corresponding Source. Regardless of what server hosts the
285
- Corresponding Source, you remain obligated to ensure that it is
286
- available for as long as needed to satisfy these requirements.
287
-
288
- e) Convey the object code using peer-to-peer transmission, provided
289
- you inform other peers where the object code and Corresponding
290
- Source of the work are being offered to the general public at no
291
- charge under subsection 6d.
292
-
293
- A separable portion of the object code, whose source code is excluded
294
- from the Corresponding Source as a System Library, need not be
295
- included in conveying the object code work.
296
-
297
- A "User Product" is either (1) a "consumer product", which means any
298
- tangible personal property which is normally used for personal, family,
299
- or household purposes, or (2) anything designed or sold for incorporation
300
- into a dwelling. In determining whether a product is a consumer product,
301
- doubtful cases shall be resolved in favor of coverage. For a particular
302
- product received by a particular user, "normally used" refers to a
303
- typical or common use of that class of product, regardless of the status
304
- of the particular user or of the way in which the particular user
305
- actually uses, or expects or is expected to use, the product. A product
306
- is a consumer product regardless of whether the product has substantial
307
- commercial, industrial or non-consumer uses, unless such uses represent
308
- the only significant mode of use of the product.
309
-
310
- "Installation Information" for a User Product means any methods,
311
- procedures, authorization keys, or other information required to install
312
- and execute modified versions of a covered work in that User Product from
313
- a modified version of its Corresponding Source. The information must
314
- suffice to ensure that the continued functioning of the modified object
315
- code is in no case prevented or interfered with solely because
316
- modification has been made.
317
-
318
- If you convey an object code work under this section in, or with, or
319
- specifically for use in, a User Product, and the conveying occurs as
320
- part of a transaction in which the right of possession and use of the
321
- User Product is transferred to the recipient in perpetuity or for a
322
- fixed term (regardless of how the transaction is characterized), the
323
- Corresponding Source conveyed under this section must be accompanied
324
- by the Installation Information. But this requirement does not apply
325
- if neither you nor any third party retains the ability to install
326
- modified object code on the User Product (for example, the work has
327
- been installed in ROM).
328
-
329
- The requirement to provide Installation Information does not include a
330
- requirement to continue to provide support service, warranty, or updates
331
- for a work that has been modified or installed by the recipient, or for
332
- the User Product in which it has been modified or installed. Access to a
333
- network may be denied when the modification itself materially and
334
- adversely affects the operation of the network or violates the rules and
335
- protocols for communication across the network.
336
-
337
- Corresponding Source conveyed, and Installation Information provided,
338
- in accord with this section must be in a format that is publicly
339
- documented (and with an implementation available to the public in
340
- source code form), and must require no special password or key for
341
- unpacking, reading or copying.
342
-
343
- 7. Additional Terms.
344
-
345
- "Additional permissions" are terms that supplement the terms of this
346
- License by making exceptions from one or more of its conditions.
347
- Additional permissions that are applicable to the entire Program shall
348
- be treated as though they were included in this License, to the extent
349
- that they are valid under applicable law. If additional permissions
350
- apply only to part of the Program, that part may be used separately
351
- under those permissions, but the entire Program remains governed by
352
- this License without regard to the additional permissions.
353
-
354
- When you convey a copy of a covered work, you may at your option
355
- remove any additional permissions from that copy, or from any part of
356
- it. (Additional permissions may be written to require their own
357
- removal in certain cases when you modify the work.) You may place
358
- additional permissions on material, added by you to a covered work,
359
- for which you have or can give appropriate copyright permission.
360
-
361
- Notwithstanding any other provision of this License, for material you
362
- add to a covered work, you may (if authorized by the copyright holders of
363
- that material) supplement the terms of this License with terms:
364
-
365
- a) Disclaiming warranty or limiting liability differently from the
366
- terms of sections 15 and 16 of this License; or
367
-
368
- b) Requiring preservation of specified reasonable legal notices or
369
- author attributions in that material or in the Appropriate Legal
370
- Notices displayed by works containing it; or
371
-
372
- c) Prohibiting misrepresentation of the origin of that material, or
373
- requiring that modified versions of such material be marked in
374
- reasonable ways as different from the original version; or
375
-
376
- d) Limiting the use for publicity purposes of names of licensors or
377
- authors of the material; or
378
-
379
- e) Declining to grant rights under trademark law for use of some
380
- trade names, trademarks, or service marks; or
381
-
382
- f) Requiring indemnification of licensors and authors of that
383
- material by anyone who conveys the material (or modified versions of
384
- it) with contractual assumptions of liability to the recipient, for
385
- any liability that these contractual assumptions directly impose on
386
- those licensors and authors.
387
-
388
- All other non-permissive additional terms are considered "further
389
- restrictions" within the meaning of section 10. If the Program as you
390
- received it, or any part of it, contains a notice stating that it is
391
- governed by this License along with a term that is a further
392
- restriction, you may remove that term. If a license document contains
393
- a further restriction but permits relicensing or conveying under this
394
- License, you may add to a covered work material governed by the terms
395
- of that license document, provided that the further restriction does
396
- not survive such relicensing or conveying.
397
-
398
- If you add terms to a covered work in accord with this section, you
399
- must place, in the relevant source files, a statement of the
400
- additional terms that apply to those files, or a notice indicating
401
- where to find the applicable terms.
402
-
403
- Additional terms, permissive or non-permissive, may be stated in the
404
- form of a separately written license, or stated as exceptions;
405
- the above requirements apply either way.
406
-
407
- 8. Termination.
408
-
409
- You may not propagate or modify a covered work except as expressly
410
- provided under this License. Any attempt otherwise to propagate or
411
- modify it is void, and will automatically terminate your rights under
412
- this License (including any patent licenses granted under the third
413
- paragraph of section 11).
414
-
415
- However, if you cease all violation of this License, then your
416
- license from a particular copyright holder is reinstated (a)
417
- provisionally, unless and until the copyright holder explicitly and
418
- finally terminates your license, and (b) permanently, if the copyright
419
- holder fails to notify you of the violation by some reasonable means
420
- prior to 60 days after the cessation.
421
-
422
- Moreover, your license from a particular copyright holder is
423
- reinstated permanently if the copyright holder notifies you of the
424
- violation by some reasonable means, this is the first time you have
425
- received notice of violation of this License (for any work) from that
426
- copyright holder, and you cure the violation prior to 30 days after
427
- your receipt of the notice.
428
-
429
- Termination of your rights under this section does not terminate the
430
- licenses of parties who have received copies or rights from you under
431
- this License. If your rights have been terminated and not permanently
432
- reinstated, you do not qualify to receive new licenses for the same
433
- material under section 10.
434
-
435
- 9. Acceptance Not Required for Having Copies.
436
-
437
- You are not required to accept this License in order to receive or
438
- run a copy of the Program. Ancillary propagation of a covered work
439
- occurring solely as a consequence of using peer-to-peer transmission
440
- to receive a copy likewise does not require acceptance. However,
441
- nothing other than this License grants you permission to propagate or
442
- modify any covered work. These actions infringe copyright if you do
443
- not accept this License. Therefore, by modifying or propagating a
444
- covered work, you indicate your acceptance of this License to do so.
445
-
446
- 10. Automatic Licensing of Downstream Recipients.
447
-
448
- Each time you convey a covered work, the recipient automatically
449
- receives a license from the original licensors, to run, modify and
450
- propagate that work, subject to this License. You are not responsible
451
- for enforcing compliance by third parties with this License.
452
-
453
- An "entity transaction" is a transaction transferring control of an
454
- organization, or substantially all assets of one, or subdividing an
455
- organization, or merging organizations. If propagation of a covered
456
- work results from an entity transaction, each party to that
457
- transaction who receives a copy of the work also receives whatever
458
- licenses to the work the party's predecessor in interest had or could
459
- give under the previous paragraph, plus a right to possession of the
460
- Corresponding Source of the work from the predecessor in interest, if
461
- the predecessor has it or can get it with reasonable efforts.
462
-
463
- You may not impose any further restrictions on the exercise of the
464
- rights granted or affirmed under this License. For example, you may
465
- not impose a license fee, royalty, or other charge for exercise of
466
- rights granted under this License, and you may not initiate litigation
467
- (including a cross-claim or counterclaim in a lawsuit) alleging that
468
- any patent claim is infringed by making, using, selling, offering for
469
- sale, or importing the Program or any portion of it.
470
-
471
- 11. Patents.
472
-
473
- A "contributor" is a copyright holder who authorizes use under this
474
- License of the Program or a work on which the Program is based. The
475
- work thus licensed is called the contributor's "contributor version".
476
-
477
- A contributor's "essential patent claims" are all patent claims
478
- owned or controlled by the contributor, whether already acquired or
479
- hereafter acquired, that would be infringed by some manner, permitted
480
- by this License, of making, using, or selling its contributor version,
481
- but do not include claims that would be infringed only as a
482
- consequence of further modification of the contributor version. For
483
- purposes of this definition, "control" includes the right to grant
484
- patent sublicenses in a manner consistent with the requirements of
485
- this License.
486
-
487
- Each contributor grants you a non-exclusive, worldwide, royalty-free
488
- patent license under the contributor's essential patent claims, to
489
- make, use, sell, offer for sale, import and otherwise run, modify and
490
- propagate the contents of its contributor version.
491
-
492
- In the following three paragraphs, a "patent license" is any express
493
- agreement or commitment, however denominated, not to enforce a patent
494
- (such as an express permission to practice a patent or covenant not to
495
- sue for patent infringement). To "grant" such a patent license to a
496
- party means to make such an agreement or commitment not to enforce a
497
- patent against the party.
498
-
499
- If you convey a covered work, knowingly relying on a patent license,
500
- and the Corresponding Source of the work is not available for anyone
501
- to copy, free of charge and under the terms of this License, through a
502
- publicly available network server or other readily accessible means,
503
- then you must either (1) cause the Corresponding Source to be so
504
- available, or (2) arrange to deprive yourself of the benefit of the
505
- patent license for this particular work, or (3) arrange, in a manner
506
- consistent with the requirements of this License, to extend the patent
507
- license to downstream recipients. "Knowingly relying" means you have
508
- actual knowledge that, but for the patent license, your conveying the
509
- covered work in a country, or your recipient's use of the covered work
510
- in a country, would infringe one or more identifiable patents in that
511
- country that you have reason to believe are valid.
512
-
513
- If, pursuant to or in connection with a single transaction or
514
- arrangement, you convey, or propagate by procuring conveyance of, a
515
- covered work, and grant a patent license to some of the parties
516
- receiving the covered work authorizing them to use, propagate, modify
517
- or convey a specific copy of the covered work, then the patent license
518
- you grant is automatically extended to all recipients of the covered
519
- work and works based on it.
520
-
521
- A patent license is "discriminatory" if it does not include within
522
- the scope of its coverage, prohibits the exercise of, or is
523
- conditioned on the non-exercise of one or more of the rights that are
524
- specifically granted under this License. You may not convey a covered
525
- work if you are a party to an arrangement with a third party that is
526
- in the business of distributing software, under which you make payment
527
- to the third party based on the extent of your activity of conveying
528
- the work, and under which the third party grants, to any of the
529
- parties who would receive the covered work from you, a discriminatory
530
- patent license (a) in connection with copies of the covered work
531
- conveyed by you (or copies made from those copies), or (b) primarily
532
- for and in connection with specific products or compilations that
533
- contain the covered work, unless you entered into that arrangement,
534
- or that patent license was granted, prior to 28 March 2007.
535
-
536
- Nothing in this License shall be construed as excluding or limiting
537
- any implied license or other defenses to infringement that may
538
- otherwise be available to you under applicable patent law.
539
-
540
- 12. No Surrender of Others' Freedom.
541
-
542
- If conditions are imposed on you (whether by court order, agreement or
543
- otherwise) that contradict the conditions of this License, they do not
544
- excuse you from the conditions of this License. If you cannot convey a
545
- covered work so as to satisfy simultaneously your obligations under this
546
- License and any other pertinent obligations, then as a consequence you may
547
- not convey it at all. For example, if you agree to terms that obligate you
548
- to collect a royalty for further conveying from those to whom you convey
549
- the Program, the only way you could satisfy both those terms and this
550
- License would be to refrain entirely from conveying the Program.
551
-
552
- 13. Use with the GNU Affero General Public License.
553
-
554
- Notwithstanding any other provision of this License, you have
555
- permission to link or combine any covered work with a work licensed
556
- under version 3 of the GNU Affero General Public License into a single
557
- combined work, and to convey the resulting work. The terms of this
558
- License will continue to apply to the part which is the covered work,
559
- but the special requirements of the GNU Affero General Public License,
560
- section 13, concerning interaction through a network will apply to the
561
- combination as such.
562
-
563
- 14. Revised Versions of this License.
564
-
565
- The Free Software Foundation may publish revised and/or new versions of
566
- the GNU General Public License from time to time. Such new versions will
567
- be similar in spirit to the present version, but may differ in detail to
568
- address new problems or concerns.
569
-
570
- Each version is given a distinguishing version number. If the
571
- Program specifies that a certain numbered version of the GNU General
572
- Public License "or any later version" applies to it, you have the
573
- option of following the terms and conditions either of that numbered
574
- version or of any later version published by the Free Software
575
- Foundation. If the Program does not specify a version number of the
576
- GNU General Public License, you may choose any version ever published
577
- by the Free Software Foundation.
578
-
579
- If the Program specifies that a proxy can decide which future
580
- versions of the GNU General Public License can be used, that proxy's
581
- public statement of acceptance of a version permanently authorizes you
582
- to choose that version for the Program.
583
-
584
- Later license versions may give you additional or different
585
- permissions. However, no additional obligations are imposed on any
586
- author or copyright holder as a result of your choosing to follow a
587
- later version.
588
-
589
- 15. Disclaimer of Warranty.
590
-
591
- THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
- APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
- HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
- OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
- THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
- PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
- IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
- ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
-
600
- 16. Limitation of Liability.
601
-
602
- IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
- WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
- THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
- GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
- USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
- DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
- PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
- EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
- SUCH DAMAGES.
611
-
612
- 17. Interpretation of Sections 15 and 16.
613
-
614
- If the disclaimer of warranty and limitation of liability provided
615
- above cannot be given local legal effect according to their terms,
616
- reviewing courts shall apply local law that most closely approximates
617
- an absolute waiver of all civil liability in connection with the
618
- Program, unless a warranty or assumption of liability accompanies a
619
- copy of the Program in return for a fee.
620
-
621
- END OF TERMS AND CONDITIONS
622
-
623
- How to Apply These Terms to Your New Programs
624
-
625
- If you develop a new program, and you want it to be of the greatest
626
- possible use to the public, the best way to achieve this is to make it
627
- free software which everyone can redistribute and change under these terms.
628
-
629
- To do so, attach the following notices to the program. It is safest
630
- to attach them to the start of each source file to most effectively
631
- state the exclusion of warranty; and each file should have at least
632
- the "copyright" line and a pointer to where the full notice is found.
633
-
634
- <one line to give the program's name and a brief idea of what it does.>
635
- Copyright (C) <year> <name of author>
636
-
637
- This program is free software: you can redistribute it and/or modify
638
- it under the terms of the GNU General Public License as published by
639
- the Free Software Foundation, either version 3 of the License, or
640
- (at your option) any later version.
641
-
642
- This program is distributed in the hope that it will be useful,
643
- but WITHOUT ANY WARRANTY; without even the implied warranty of
644
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
- GNU General Public License for more details.
646
-
647
- You should have received a copy of the GNU General Public License
648
- along with this program. If not, see <https://www.gnu.org/licenses/>.
649
-
650
- Also add information on how to contact you by electronic and paper mail.
651
-
652
- If the program does terminal interaction, make it output a short
653
- notice like this when it starts in an interactive mode:
654
-
655
- <program> Copyright (C) <year> <name of author>
656
- This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
- This is free software, and you are welcome to redistribute it
658
- under certain conditions; type `show c' for details.
659
-
660
- The hypothetical commands `show w' and `show c' should show the appropriate
661
- parts of the General Public License. Of course, your program's commands
662
- might be different; for a GUI interface, you would use an "about box".
663
-
664
- You should also get your employer (if you work as a programmer) or school,
665
- if any, to sign a "copyright disclaimer" for the program, if necessary.
666
- For more information on this, and how to apply and follow the GNU GPL, see
667
- <https://www.gnu.org/licenses/>.
668
-
669
- The GNU General Public License does not permit incorporating your program
670
- into proprietary programs. If your program is a subroutine library, you
671
- may consider it more useful to permit linking proprietary applications with
672
- the library. If this is what you want to do, use the GNU Lesser General
673
- Public License instead of this License. But first, please read
674
- <https://www.gnu.org/licenses/why-not-lgpl.html>.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
README.md CHANGED
@@ -1,13 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
- title: BeatManipulator
3
- emoji: 🥁
4
- colorFrom: blue
5
- colorTo: blue
6
- sdk: gradio
7
- sdk_version: 3.11.0
8
- app_file: app.py
9
- pinned: false
10
- license: cc-by-nc-sa-4.0
11
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # **stunlocked's beat manipulator**
2
+ Advanced beat swapping powered by [madmom](https://github.com/CPJKU/madmom).
3
+ ### [Try on Hugging Face](https://huggingface.co/spaces/dpe1/BeatManipulator)
4
+ ### [Try on Google Colab](https://colab.research.google.com/drive/1gEsZCCh2zMKqLmaGH5BPPLrImhEGVhv3?usp=sharing)
5
+ # Installation
6
+ For most people I recommend using Hugging Face or Google Colab. However if you run it locally, you will have access to more advanced features that I haven't added to Hugging Face yet, like using samples, mixing multiple songs, presets.
7
+
8
+ First I recommend creating a new environment to avoid dependency issues. With conda, you can do that by running `conda create --name beat_manipulator`.
9
+
10
+ Then run those commands depending on what python you have:
11
+
12
+ ### conda 3.8, 3.9:
13
+ ```
14
+ conda install pip cython mido numpy scipy pysoundfile librosa ffmpeg-python pytest pyaudio pyfftw
15
+
16
+ pip install madmom pedalboard
17
+ ```
18
+ ### conda 3.10
19
+ ```
20
+ conda install pip cython mido numpy scipy pysoundfile librosa ffmpeg-python pytest pyaudio pyfftw
21
+
22
+ pip install pedalboard
23
+
24
+ pip install git+https://github.com/CPJKU/madmom
25
+ ```
26
+ ### pip 3.8, 3.9
27
+ ```
28
+ pip install numpy cython soundfile ffmpeg-python pedalboard librosa
29
+
30
+ pip install madmom
31
+ ```
32
+ ### pip 3.10
33
+ ```
34
+ pip install numpy cython soundfile ffmpeg-python pedalboard librosa
35
+
36
+ pip install git+https://github.com/CPJKU/madmom
37
+ ```
38
+
39
  ---
40
+ After installing all necessary libraries, to download beat manipulator, download and extract this repo using green "Code" button > Download ZIP, or run `git clone https://github.com/stunlocked1/beat_manipulator`. You can now open examples.py, jupiter.ipynb, or app.py for gradio interface.
41
+ # Usage
42
+ First, import beat_manipulator and load a song
43
+ ```
44
+ import beat_manipulator as bm
45
+ your_song = bm.song(audio = 'path or numpy array')
46
+ ```
47
+ It accepts absolute or relative path to audio file, or you can directly load audio array into it. If you are loading audio array directly, make sure to also add sr=sample_rate argument. Array should be in -1 to 1 format, which is how most libraries load audio.
48
+
49
+ Now, generate the beatmap:
50
+ ```
51
+ your_song.beatmap_generate()
52
+ ```
53
+ Beatmap is generated using madmom library. When you generate it for the first time, it might take up to a minute. However all beatmaps are saved to `beat_manipulator/beatmaps`, so when you load the same file for the second time, it will be instant.
54
+
55
+ You can access beatmap in `your_song.beatmap` variable. It is a list of values that represent position of each beat in samples.
56
+
57
+ After generating the beatmap, you can do a bunch of stuff.
58
+ ### slicing
59
+ Song object supports slicing.
60
+
61
+ - `your_song[5]` will return audio of the 5th beat, indexing starts from 1.
62
+ - `your_song[4:8.5]` returns audio starting from 4th beat, ending halfway between 8th and 9th beat. `your_song[0:1]` is equivalent to `your_song[1]`
63
+ - `your_song['your_pattern']` returns a beatswapped audio using the pattern you provided. Beatswapping with patterns is the main feature if this app and you can do a whole bunch of stuff with them. There is a section below that explains how to write those patterns.
64
+ ### beatswapping
65
+ Another way to beatswap is:
66
+ ```
67
+ your_song.beatswap(pattern = '1, 3, 2, 4', scale = 1, shift = 0, length = None)
68
+ ```
69
+ This one doesn't return anything, instead it modifies the song in place.
70
+
71
+ You can also beatwap and write audio in one line:
72
+ ```
73
+ bm.beatswap(song = 'path or numpy array', pattern = '1, 3, 2, 4', scale = 1, shift = 0, output = '')
74
+ ```
75
+ ### scale
76
+ `scale = 0.5` will insert a new beat position between every existing beat position in the beatmap. That allows you to make patterns on smaller intervals.
77
+
78
+ `scale = 2`, on the other hand, will merge every two beat positions in the beatmap. Useful, for example, when beat map detection puts sees BPM as two times faster than it actually is, and puts beats in between every actual beat.
79
+
80
+ To scale the beatmap, you can use `your_song.beatmap_scale(0.5)`, or specify scale directly in `your_song.beatswap(..., scale = float)`
81
+ ### shift
82
+ Shifts the beatmap, in beats. For example, if you want to remove 4th beat every four beats, you can do it by writing `1, 2, 3, 4!`.
83
+ However sometimes it doesn't properly detect which beat is first, and for example remove 2nd beat every 4 beats instead. In that case, if you want 4th beat, use `shift = 2`. Also sometimes beats are detected right in between actual beats, so shift = 0.5 or -0.5 will fix it.
84
+
85
+ To shift the beatmap, you can use `your_song.beatmap_shift(0.5)`, or specify shift directly in `your_song.beatswap(..., shift = float)`
86
+
87
+ When you specify shift in a beatswap function, it applies before scale for consistency.
88
+ ### saving scale and shift
89
+ If you run `your_song.beatmap_save_settings(scale: float, shift: float)`, it will save a file in `beat_manipulator/beatmaps` with your scale and shift. That way, next time you load that song, it will automatically apply those scale and shift values.
90
+ ### writing audio
91
+ To write audio, use `my_song.write(output = '')`. If output is empty string, this will write the song next to your .py file, using the original filename.
92
+ # pattern syntax
93
+ The pattern syntax is quite powerful and you can do a whole bunch of stuff with it. Basic syntax is - `1, 3, 2, 4` means every 4 beats, swap 2nd and 3rd beats, but you can do much more, like applying audio effects, shuffling beats, slicing them, mixing two songs, adding samples, sidechain.
94
+
95
+ You can use spaces freely in patterns for formatting. Most other symbols have some use though. Here is how to write patterns:
96
+ #### beats
97
+ - `1` - 1st beat;
98
+ - `1>0.5` - first half of first beat
99
+ - `1<0.5 - second half of first beat
100
+ - `0:0.5` - range of beats, this also means first half of first beat, but with this you can do complex stuff like `1.25:1.5`. However this one is a bit more confusing because indexing starts from 0, so 1:2 is second beat, not first.
101
+ - Also sometimes it is more convenient to use smaller `scale`, like 0.5 or 0.25, instead of slicing beats.
102
+ #### basic patterns
103
+ - `1, 3, 2, 4` means 3rd and 2nds beats will be swapped every 4 beats. Happens every 4 beats because 4 is the biggest number in the pattern.
104
+ - `1, 2, 3, 4!` means every 4 beats, it will remove the 4th beat. `!` allows you to skip a beat but it still counts for pattern size.
105
+ - Specifying pattern length: `pattern = '1,2,3', length = 4` is another way to remove 4th beat every 4 beats.
106
+ - `1,4` skips 2nd and 3rd beat
107
+ - `1; 2` plays 1st and 2nd beat same time. They will automatically be normalzied to avoid clipping. Length of the first beat will be preserved.
108
+ #### joining operators
109
+ `,` and `;` are beat joining operators, that join beats together. Here are all available joiners:
110
+ - `,` puts the beat next to previous beat
111
+ - `;` puts the beat on top of previous beat. Normalizes the volume to avoid clipping. If previous beat is shorter, your beat will be shortened to match it.
112
+ - `^` multiplies previous beat by your beat. This can be used for fake sidechain.
113
+ - `$` adds the beat on top of previous beat + sidechains previous beat by your beat.
114
+ #### effects
115
+ beats can be followed by effects. For example `1s0.75` means take first beat and play it at 0.75x speed. Here are all available effects:
116
+ - `s` - speed. `1s2` means first beat will be played at 2x speed.
117
+ - `r` - reverse. `1r` means first beat will have reversed audio.
118
+ - `v` - volume. `1v0.5` means 1st beat will have 50% volume
119
+ - `d` - downsample, or 8-bit sound. `1d10` will downsample the first beat so that it sounds 8-bit. Good values start above 7.
120
+ - `b` - bitcrush. `1b4` will bitcrush it.
121
+ - `g` - gradient, sounds like highpass. `1g1` is the recommended value
122
+ - `c` - channel. If not followed by number, swaps channels. If followed by 0, plays only left channel. If 1, only right channel
123
+ - mixing effects - `1s2rd8` - take first beat, play at 2x speed, reversed, and downsampled.
124
+ You can also define your own effects. Check `BM_EFFECTS` dictionary from `beat_manipulator/effects.py`, this is where it reads effects from. You can add new stuff to that dictionary and use your own effects this way, or specify your own dictionary when using `your_song.beatswap(..., effects: dict)` with your `effects` argument.
125
+ By default that argument points to `BM_EFFECTS` dictionary.
126
+ #### math
127
+ mathematical expressions with `+`, `-`, `*`, `/`, and `**` are supported. For example, if you write `1/3` anywhere in the pattern, to slice beats or as effect value, it will be replaced by 0.3333...
128
+ #### using samples
129
+ To use samples, provide them in `samples` argument to `your_song.beatswap(..., samples: dict)`. The dictionary should look like this:
130
+ ```
131
+ {
132
+ 'sample name' : 'path to your sample or numpy array of your sample or bm.song object',
133
+ 'sample name 2' : 'path or audio 2',
134
+ ...
135
+ }
136
+ ````
137
+ It supports both loading audio files from a path, and directly loading arrays.
138
+
139
+ Then in pattern, you can use quotes (`'`, `"`, or `` ` ``) to access samples. For example: `1; "sample_name"` will put that sample on top of 1st beat. Samples are treated just like beats, you can apply effects to them, use any joining operators.
140
+
141
+ You can also slice samples: `"sample_name">0.5` means first half of the sample.
142
+
143
+ You can use list with samples instead of a dictionary. In that case, you can access them by their index in the list, for example `"1"` is the 1st sample.
144
+ #### mixing two songs
145
+ Add the second song that you want to mix to the `samples` argument dictionary or list, as described above. It can load path to a file, directly load a numpy array, or a bm.song object.
146
+
147
+ The difference is, instead of using quotes, for songs you use square brackets: `[song_name]`
148
+
149
+ `[song_name]4` means fourth beat of that song. So you can do stuff like `1, [song_name]2`, which will alternate beats between your two songs.
150
+ #### other stuff
151
+ - `i` will be replaced by current position, e.g. `i, i, i, i+1` is equvalent to `1, 2, 3, 4 + 1`, or `1, 2, 3, 5`.
152
+ - `#` will add shuffle all beats with the same number after it. `1#1, 2#2, 3#1, 4#2, 5#1, 6#2, 7#1, 8#2` will shuffle 1st, 3rd, 5th and 7th beats (the are in 1st group), and 2nd, 4th, 6th and 8th beats - from 2nd shuffle group.
153
+ - `!` skips that beat. If you want to remove every 4th beat, you can't just do `1, 2, 3`, because that would simply play every 3 beats. So to play 3 beats every 4 beats, you can write `1, 2, 3, 4!`
154
+ - `?` makes that beat not count for pattern size. For example, `1, 2, 3, 8` will normally repeat every 8 beats because 8 is the highest number, but `1, 2, 3, 8?` will repeat every 3 beats.
155
+ - `@` allows you to take a random beat with the following syntax: @start_stop_step. For example, `@1_4_0.5` means it will take a random beat out of 1st, 1.5, 2nd, 2.5, 3rd, 3.5, and 4th. It will take whole beat, so you can also add `>0.5` to take only first half.
156
+ - `%` - for very advanced patterns you can create variables from various metrics. For example, `%v` will create a variable with average volume of that beat, and all following `%` will be replaced by that variable until you create a new one. Useful for applying different effects based on different song metrics. All metrics are in `beat_manipulator/metrics.py`.
157
+ #### special patterns
158
+ You can write special commands into the `pattern` argument instead of actual patterns.
159
+ - `reverse` - plays all beats in reverse chronological order
160
+ - `shuffle` - shuffles all beats
161
+ - `test` - puts different pitched cowbells on each beat, useful for testing beat detection and adjusting it using scale and shift. Each cowbell is 1 beat, highest pitched cowbell is the 1st beat, lowest pitched - 4th.
162
+ #### complex patterns
163
+ You should be able to use all of the above operators in any combination, as complex as you want. Very low scales should also be fine, up to 0.001.
164
+ ## creating images
165
+ You can create cool images based on beat positions. Each song produces its own unique image. Write:
166
+ ```
167
+ your_song.image_generate()
168
+ ```
169
+ image will be saved as a numpy array to your_song.image variable. To export it to a file, use:
170
+ ```
171
+ your_song.image_write()
172
+ ```
173
+ The image will by default be resized to 4096x4096. It is also possible to export original image, which usually is too big for most image viewers to handle it. However the cool thing is that you can apply image effects to it, and then turn it back into audio. I will soon add info on how to do that.
174
+ ## quick functions
175
+ ```
176
+ bm.beatswap(song = 'path or numpy array', pattern = '1,3,2,4', scale=1, shift=0, output='')
177
+ ```
178
+ allows you to beatswap and write a song loaded from path or numpy array in one line. Returns path to the exported beatswapped song file.
179
 
180
+ ```
181
+ bm.image(song = 'path or numpy array', max_size = 4096, scale=1, shift=0, output='')
182
+ ```
183
+ creates an image and writes it in one line, returns path to exported image.
184
+ ```
185
+ bm.osu.generate(song='path or numpy array', difficulties = [0.2, 0.1, 0.05, 0.025, 0.01, 0.0075, 0.005, 0.0025, 0.0001])
186
+ ```
187
+ generates an osu! beatmap (uses madmom beat processor and peak detection). Writes an .osz file that you can install by opening it with osu! and returns path to it.
188
+ ## presets
189
+ there are some patterns in `beat_manipulator/presets.yaml` file. Those are supposed to be used on normalized beat maps, where kick + snare is two beats, so make sure to adjust beatmaps using `scale` and `shift`.
190
+ To use one of the presets from that file, write:
191
+ ```
192
+ bm.presets.use(song = song, preset = 'preset name', scale = 1, shift = 0)
193
+ ```
app.py CHANGED
@@ -2,63 +2,61 @@ import gradio as gr, numpy as np
2
  from gradio.components import Audio, Textbox, Checkbox, Image
3
  import beat_manipulator as bm
4
  import cv2
5
- def _safer_eval(string:str) -> float:
6
- if isinstance(string, str):
7
- try:
8
- string = eval(''.join([i for i in string if i.isdecimal() or i in '.+-*/']))
9
- except: string=1
10
- return string
11
 
12
  def BeatSwap(audiofile, pattern: str = 'test', scale:float = 1, shift:float = 0, caching:bool = True, variableBPM:bool = False):
13
  print()
14
  print(f'path = {audiofile}, pattern = "{pattern}", scale = {scale}, shift = {shift}, caching = {caching}, variable BPM = {variableBPM}', end=', ')
15
  if pattern == '' or pattern is None: pattern = 'test'
 
 
16
  try:
17
- scale=_safer_eval(scale)
18
  except: scale = 1
19
  try:
20
- shift=_safer_eval(shift)
21
  except: shift = 0
22
  if scale <0: scale = -scale
23
- if scale < 0.02: scale = 0.02
24
  if audiofile is not None:
25
  try:
26
- song=bm.song(path=audiofile, filename=audiofile.split('.')[-2][:-8]+'.'+audiofile.split('.')[-1], caching=caching, log=False)
27
  except Exception as e:
28
  print(f'Failed to load audio, retrying: {e}')
29
- song=bm.song(path=audiofile, caching=caching, log=False)
30
  else:
31
  print(f'Audiofile is {audiofile}')
32
  return
33
  try:
34
- print(scale, shift, len(song.audio[0])/song.samplerate)
35
- if len(song.audio[0]) > (song.samplerate*1800):
36
- song.audio = np.asarray(song.audio)
37
- song.audio = song.audio[:,:song.samplerate*1800]
38
  except Exception as e: print(f'Reducing audio size failed, why? {e}')
39
  lib = 'madmom.BeatDetectionProcessor' if variableBPM is False else 'madmom.BeatTrackingProcessor'
40
- song.beatmap.generate(lib=lib, caching=caching)
41
- song.beatmap.shift(shift)
42
- song.beatmap.scale(scale)
 
43
  try:
44
- song.beat_image.generate()
45
- image = song.beat_image.combined
46
  y=min(len(image), len(image[0]), 2048)
47
  y=max(y, 2048)
48
- image = np.clip(cv2.resize(image, (y,y), interpolation=cv2.INTER_NEAREST).T/255, -1, 1)
 
49
  #print(image)
50
  except Exception as e:
51
  print(f'Image generation failed: {e}')
52
  image = np.asarray([[0.5,-0.5],[-0.5,0.5]])
53
- song.quick_beatswap(output=None, pattern=pattern, scale=1, shift=0, lib=lib)
54
  song.audio = (np.clip(np.asarray(song.audio), -1, 1) * 32766).astype(np.int16).T
55
  #song.write_audio(output=bm.outputfilename('',song.filename, suffix=' (beatswap)'))
56
  print('___ SUCCESS ___')
57
- return ((song.samplerate, song.audio), image)
58
 
59
  audiofile=Audio(source='upload', type='filepath')
60
- patternbox = Textbox(label="Pattern, comma separated:", placeholder="1, 3, 2, 4!", value="1, 2!", lines=1)
61
- scalebox = Textbox(value=1, label="Beatmap scale, beatmap's beats per minute will be multiplied by this:", placeholder=1, lines=1)
62
  shiftbox = Textbox(value=0, label="Beatmap shift, in beats (applies before scaling):", placeholder=0, lines=1)
63
  cachebox = Checkbox(value=True, label="Enable caching generated beatmaps for faster loading. Saves a file with beat positions and loads it when you open same audio again.")
64
  beatdetectionbox = Checkbox(value=False, label='Enable support for variable BPM, however this makes beat detection slightly less accurate')
@@ -74,45 +72,73 @@ Colab version - https://colab.research.google.com/drive/1gEsZCCh2zMKqLmaGH5BPPLr
74
 
75
  # Basic usage
76
 
77
- Upload your audio, enter the beat swapping pattern, change scale and shift if needed, and run the app.
78
-
79
- It can be useful to test where each beat is by writing `test` into the `pattern` field, which will put cowbells on each beat. Highest cowbell should be the on first beat.
80
-
81
- Use scale and shift to adjust the beatmap, for example if it is shifted 0.5 beats forward, set shift to -0.5. If it is two times faster than you want, set scale to 0.5
82
-
83
- Feel free to use complex patterns and very low scales - most of the computation time is in detecting beats, not swapping them.
84
-
85
- # Pattern syntax
86
-
87
- Patterns are sequences of expressions, separated by `,` - for example, `1>3/8, 1>3/8, 1>0.25, 2, 3>0.75s2, 3>3/8, 3>0.25, 4d9`. Spaces can be freely used for formatting as they will be ignored. Any other character that isnt used in the syntax can also be used for formatting but only between beats, not inside them.
88
- - `1, 3, 2, 4` - every 4 beats, swap 2nd and 3rd beat. This pattern loops every 4 beats, because 4 is the biggest number in it.
89
- - `1, 3, 4` - every 4 beats, skip 2nd beat.
90
- - `1, 2, 2, 4` - every 4 beats, repeat 2nd beat.
91
- - `1, 2!` - skip every second beat. `!` after a number sets length of the pattern (beat isnt played). `1, 2, 3, 4!` - skip every 4th beat.
92
- - `2>0.5` - play only first half of the second beat. `>` after a beat allows you to take first `i` of that beat.
93
- - `2<0.5` - play only second half of the second beat. `<` after a beat takes last `i` of that beat.
94
- - `1.5:4.5` - play a range of beats from 1.5 to 4.5. `0:0.5` means first half of 1st beat. Keep that in mind, to play first half of 5th beat, you do `4:4.5`, not `5:5.5`. `1` is equivalent to `0:1`. `1.5` is equivalent to `0.5:1.5`. `1,2,3,4` is `0:4`.
95
-
96
- **Tip: instead of slicing beats, sometimes it is easier to make scale smaller, like 0.5 or 0.25.**
97
- - `1, 1>1/3, 1>1/3, 1<1/3` - you can use math expressions with `+`, `-`, `*`, `/` in place of numbers.
98
- - `1, 2, 3, 4!, 8?` - every 4 beats, 4th beat is replaced with 8th beat. `?` after a beat makes that number not count for looping.
99
- - `v` + number - controls volume of that beat. `1v2` means 200% volume, `1v1/3` means 33.33% volume, etc.
100
- - `r` after a beat reverses that beat. `1r, 2` - every two beats, first beat will be reversed
101
- - another way to reverse - `4:0` is reversed `0:4`.
102
- - `s` + number - changes speed and pitch of that beat. 2 will be 2 times faster, 1/2 will be 2 times slower. Note: Only integers or 1/integer numbers are supported, everything else will be rounded.
103
- - `c` - if not followed by a number, swaps left and right channels of the beat. If followed by 0, mutes left channel, 1 - right channel.
104
- - `b` + number - bitcrush. The higher the number, the stronger the effect. Barely noticeable at values less then 1
105
- - `d` + number - downsample (8-bit sound). The higher the number, the stronger the effect. Starts being noticeable at 3, good 8-bit sounding values are around 8+.
106
- - `t` + number - saturation
107
- - you can combine stuff like `0:1/3d8v2cr` - that line means 0:1/3 beat will be downsampled, 200% volume, swapped channels, and reversed
108
-
109
- there are certain commands you can write in pattern instead of the actual pattern:
110
- - `random` - each beat will be randomly selected from all beats, basically similar to shuffling all beats
111
- - `reverse` - reverses the order of all beats
112
- - `test` - test beat detection by putting cowbells on each beat. The highest pitched cowbell should be on the first beat; next cowbell should be on the snare. If it is not, use scale and shift.
113
-
114
- There are also some interesting patterns there: https://github.com/stunlocked1/BeatManipulator/blob/main/presets.json. Those are meant to be used with properly adjusted shift and scale, where 1st beat is 1st kick, 2nd beat is the snare after it, etc.
115
-
116
- Check my soundcloud https://soundcloud.com/stunlocked
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  """
118
  ).launch(share=False)
 
2
  from gradio.components import Audio, Textbox, Checkbox, Image
3
  import beat_manipulator as bm
4
  import cv2
 
 
 
 
 
 
5
 
6
  def BeatSwap(audiofile, pattern: str = 'test', scale:float = 1, shift:float = 0, caching:bool = True, variableBPM:bool = False):
7
  print()
8
  print(f'path = {audiofile}, pattern = "{pattern}", scale = {scale}, shift = {shift}, caching = {caching}, variable BPM = {variableBPM}', end=', ')
9
  if pattern == '' or pattern is None: pattern = 'test'
10
+ if caching is not False: caching == True
11
+ if variableBPM is not True: variableBPM == False
12
  try:
13
+ scale=bm.utils._safer_eval(scale)
14
  except: scale = 1
15
  try:
16
+ shift=bm.utils._safer_eval(shift)
17
  except: shift = 0
18
  if scale <0: scale = -scale
19
+ if scale < 0.01: scale = 0.01
20
  if audiofile is not None:
21
  try:
22
+ song=bm.song(audio=audiofile,log=False)
23
  except Exception as e:
24
  print(f'Failed to load audio, retrying: {e}')
25
+ song=bm.song(audio=audiofile, log=False)
26
  else:
27
  print(f'Audiofile is {audiofile}')
28
  return
29
  try:
30
+ print(f'scale = {scale}, shift = {shift}, length = {len(song.audio[0])/song.sr}')
31
+ if len(song.audio[0]) > (song.sr*1800):
32
+ song.audio = np.array(song.audio, copy=False)
33
+ song.audio = song.audio[:,:song.sr*1800]
34
  except Exception as e: print(f'Reducing audio size failed, why? {e}')
35
  lib = 'madmom.BeatDetectionProcessor' if variableBPM is False else 'madmom.BeatTrackingProcessor'
36
+ song.path = song.path.split('.')[-2][:-8]+'.'+song.path.split('.')[-1]
37
+ song.beatmap_generate(lib=lib, caching=caching)
38
+ song.beatmap_shift(shift)
39
+ song.beatmap_scale(scale)
40
  try:
41
+ song.image_generate()
42
+ image = bm.image.bw_to_colored(song.image)
43
  y=min(len(image), len(image[0]), 2048)
44
  y=max(y, 2048)
45
+ image = np.rot90(np.clip(cv2.resize(image, (y,y), interpolation=cv2.INTER_NEAREST), -1, 1))
46
+ print(image)
47
  #print(image)
48
  except Exception as e:
49
  print(f'Image generation failed: {e}')
50
  image = np.asarray([[0.5,-0.5],[-0.5,0.5]])
51
+ song.beatswap(pattern=pattern, scale=1, shift=0)
52
  song.audio = (np.clip(np.asarray(song.audio), -1, 1) * 32766).astype(np.int16).T
53
  #song.write_audio(output=bm.outputfilename('',song.filename, suffix=' (beatswap)'))
54
  print('___ SUCCESS ___')
55
+ return ((song.sr, song.audio), image)
56
 
57
  audiofile=Audio(source='upload', type='filepath')
58
+ patternbox = Textbox(label="Pattern:", placeholder="1, 3, 2, 4!", value="1, 2!", lines=1)
59
+ scalebox = Textbox(value=1, label="Beatmap scale. At 2, every two beat positions will be merged, at 0.5 - a beat position added between every two existing ones.", placeholder=1, lines=1)
60
  shiftbox = Textbox(value=0, label="Beatmap shift, in beats (applies before scaling):", placeholder=0, lines=1)
61
  cachebox = Checkbox(value=True, label="Enable caching generated beatmaps for faster loading. Saves a file with beat positions and loads it when you open same audio again.")
62
  beatdetectionbox = Checkbox(value=False, label='Enable support for variable BPM, however this makes beat detection slightly less accurate')
 
72
 
73
  # Basic usage
74
 
75
+ Upload your audio, enter the beat swapping pattern, change scale and shift if needed, and run it.
76
+
77
+ # pattern syntax
78
+ The pattern syntax is quite powerful and you can do a whole bunch of stuff with it.
79
+
80
+ Basic syntax is - `1, 3, 2, 4` means every 4 beats, swap 2nd and 3rd beats, but you can do much more, like applying audio effects, shuffling beats, slicing them, mixing two songs, adding samples, sidechain.
81
+
82
+ You can use spaces freely in patterns for formatting. Most other symbols have some use though. Here is the full syntax:
83
+ #### beats
84
+ * `1` - 1st beat;
85
+ * `1>0.5` - first half of first beat
86
+ * `1<0.5` - second half of first beat
87
+ * `0:0.5` - range of beats, this also means first half of first beat, but with this you can do complex stuff like `1.25:1.5`. However this one is a bit more confusing because indexing starts from 0, so 1:2 is second beat, not first.
88
+ * Also sometimes it is more convenient to use smaller `scale`, like 0.5 or 0.25, instead of slicing beats.
89
+ #### basic patterns
90
+ - `1, 3, 2, 4` - 3rd and 2nd beats will be swapped every 4 beats. Happens every 4 beats because 4 is the biggest number in the pattern.
91
+ - `1, 2, 3, 4!` - every 4 beats, it will remove the 4th beat. `!` allows you to skip a beat but it still counts for pattern size.
92
+ - Specifying pattern length: `pattern = '1, 2, 3', length = 4` is another way to remove 4th beat every 4 beats.
93
+ - `1, 4` skips 2nd and 3rd beat
94
+ - `1; 2` plays 1st and second beat at the same time.
95
+ #### joining operators
96
+ `,` and `;` are beat joining operators. Here are all available joiners:
97
+ - `,` puts the beat next to previous beat.
98
+ - `;` puts the beat on top of previous beat. Normalizes the volume to avoid clipping. If previous beat is shorter, your beat will be shortened to match it.
99
+ - `^` multiplies previous beat by your beat. This can be used for fake sidechain.
100
+ - `$` adds the beat on top of previous beat + sidechains previous beat by your beat (I haven't tested this one)
101
+ #### effects
102
+ beats can be followed by effects. For example `1s0.75` means take first beat and play it at 0.75x speed. Here are all available effects:
103
+ - `s` - speed. `1s2` means first beat will be played at 2x speed.
104
+ - `r` - reverse. `1r` means first beat will have reversed audio.
105
+ - `v` - volume. `1v0.5` means 1st beat will have 50% volume
106
+ - `d` - downsample, or 8-bit sound. `1d10` will downsample the first beat so that it sounds 8-bit. Good values start above 7.
107
+ - `b` - bitcrush. `1b4` will bitcrush it.
108
+ - `g` - gradient, sounds like highpass. `1g1` is the recommended value
109
+ - `c` - channel. If not followed by number, swaps channels. If followed by 0, plays only left channel. If 1, only right channel
110
+ - mixing effects - `1s2rd8` - take first beat, play at 2x speed, reversed, and downsampled.
111
+ #### math
112
+ mathematical expressions with `+`, `-`, `*`, `/`, and `**` are supported. For example, if you write `1/3` anywhere in the pattern, to slice beats or as effect value, it will be replaced by `0.33333333`
113
+ #### using samples, mixing two songs
114
+ - WIP (you can do that if you run locally, I am just figuring out gradio UI because that requires a bunch of new input interface)
115
+ #### other stuff
116
+ - `i` will be replaced by current position, e.g. `i, i, i, i+1` is equvalent to `1, 2, 3, 4 + 1`, or `1, 2, 3, 5`.
117
+ - `#` will add shuffle all beats with the same number after it. `1#1, 2#2, 3#1, 4#2, 5#1, 6#2, 7#1, 8#2` will shuffle 1st, 3rd, 5th and 7th beats (the are in 1st group), and 2nd, 4th, 6th and 8th beats - from 2nd shuffle group.
118
+ - `!` skips that beat. If you want to remove every 4th beat, you can't just do `1, 2, 3`, because that would simply play every 3 beats. So to play 3 beats every 4 beats, you can write `1, 2, 3, 4!`
119
+ - `?` makes that beat not count for pattern size. For example, `1, 2, 3, 8` will normally repeat every 8 beats because 8 is the highest number, but `1, 2, 3, 8?` will repeat every 3 beats.
120
+ - `@` allows you to take a random beat with the following syntax: @start_stop_step. For example, `@1_4_0.5` means it will take a random beat out of 1st, 1.5, 2nd, 2.5, 3rd, 3.5, and 4th. It will take whole beat, so you can also add `>0.5` to take only first half.
121
+ - `%` - for very advanced patterns you can create variables from various metrics. For example, `%v` will create a variable with average volume of that beat, and all following `%` will be replaced by that variable until you create a new one. Useful for applying different effects based on different song metrics. All metrics are in `beat_manipulator/metrics.py`.
122
+ #### special patterns
123
+ You can write special commands into the `pattern` argument instead of actual patterns.
124
+ - `reverse` - plays all beats in reverse chronological order
125
+ - `shuffle` - shuffles all beats
126
+ - `test` - puts different pitched cowbells on each beat, useful for testing beat detection and adjusting it using scale and shift. Each cowbell is 1 beat, highest pitched cowbell is the 1st beat, lowest pitched - 4th.
127
+ #### complex patterns
128
+ You should be able to use all of the above operators in any combination, as complex as you want. Very low scales should also be fine, up to 0.01.
129
+ ### scale
130
+ `scale = 0.5` will insert a new beat position between every existing beat position in the beatmap. That allows you to make patterns on smaller intervals.
131
+
132
+ `scale = 2`, on the other hand, will merge every two beat positions in the beatmap. Useful, for example, when beat map detection puts sees BPM as two times faster than it actually is, and puts beats in between every actual beat.
133
+ ### shift
134
+ Shifts the beatmap, in beats. For example, if you want to remove 4th beat every four beats, you can do it by writing `1, 2, 3, 4!`. However sometimes it doesn't properly detect which beat is first, and for example remove 2nd beat every 4 beats instead. In that case, if you want 4th beat, use `shift = 2`. Also sometimes beats are detected right in between actual beats, so shift = 0.5 or -0.5 will fix it.
135
+ ## creating images
136
+ You can create cool images based on beat positions. Each song produces its own unique image. This gradio app creates a 2048x2048 image from each song.
137
+ ## presets
138
+ A bunch of example patterns: https://github.com/stunlocked1/beat_manipulator/blob/main/beat_manipulator/presets.yaml
139
+
140
+ Those are supposed to be used on normalized beat maps, where kick + snare is two beats, so make sure to adjust beatmaps using `scale` and `shift`.
141
+
142
+ # My soundcloud https://soundcloud.com/stunlocked
143
  """
144
  ).launch(share=False)
beat_manipulator/__init__.py CHANGED
@@ -1,2 +1,2 @@
1
  from .main import *
2
- from . import analyze, effect, generate, image, mix, wrapper
 
1
  from .main import *
2
+ from . import beatmap, effects, image, io, metrics, presets, osu, utils
beat_manipulator/analyze.py DELETED
@@ -1,62 +0,0 @@
1
- import numpy
2
- #@njit SLOWER
3
- def detect_bpm(audio, samplerate, bpm_low=40, bpm_high=300, bpm_step=0.1, mode=1, shift_step=10):
4
- """A very slow and inefficient algorithm!"""
5
- audio = numpy.asarray(audio)
6
- audio = (audio[0] + audio[1]).astype(numpy.float32)
7
- length=len(audio)
8
- mlength=length- int( 1 / ((bpm_low / 60) / samplerate) ) # to make sure those parts do not affect the calculation as they will be cut sometimes
9
- #audio[:int(spb_low)]=0 # to make sure those parts do not affect the calculation as they will be cut sometimes
10
- bpmdiffs=[]
11
- bpmdiffsi=[]
12
- minimum=100000000
13
- for i in range(int((bpm_high-bpm_low)/bpm_step)):
14
- spb=int(round(1/(((bpm_low + i*bpm_step) / 60) / samplerate)))
15
- # audio is reshaped into a 2d array with bpm
16
- end=-int(length % spb)
17
- if end == 0: end = length
18
- image = audio[:end].reshape(-1, spb)
19
- if mode == 1: image=image.T
20
- # diff21, diff22, diff41, diff42 = image[:-2].flatten(), image[2:].flatten(), image[:-4].flatten(), image[4:].flatten()
21
- # difference=abs( numpy.dot(diff21, diff22)/(numpy.linalg.norm(diff21)*numpy.linalg.norm(diff22)) + numpy.dot(diff41, diff42)/(numpy.linalg.norm(diff41)*numpy.linalg.norm(diff42)) )
22
- diff2=numpy.abs ( (image[:-2] - image[2:]).flatten()[:mlength] )
23
- diff4=numpy.abs ( (image[:-4] - image[4:]).flatten()[:mlength] )
24
- difference=numpy.sum(diff2*diff2*diff2*diff2) + numpy.sum(diff4*diff4*diff4*diff4)
25
- # for i in range(len(image)-1):
26
- # difference.append(numpy.sum(image[i]-image[i]+1))
27
- if mode == 3:
28
- image=image.T
29
- diff2=numpy.abs ( (image[:-2] - image[2:]).flatten()[:mlength] )
30
- diff4=numpy.abs ( (image[:-4] - image[4:]).flatten()[:mlength] )
31
- difference=numpy.sum(diff2*diff2*diff2*diff2) + numpy.sum(diff4*diff4*diff4*diff4)
32
- bpmdiffs.append(spb)
33
- bpmdiffsi.append(difference)
34
- if difference<minimum:
35
- #print(f'{spb}: testing BPM = {(1/spb)*60*samplerate}; value = {difference}')
36
- print(i)
37
- minimum=difference
38
- spb = bpmdiffs[numpy.argmin(numpy.asarray(bpmdiffsi))]
39
- #print(f'BPM = {(1/spb)*60*samplerate}')
40
- bpmdiffs=[]
41
- bpmdiffsi=[]
42
- #audio[int(spb):]=0
43
- print(spb)
44
- for shift in range(0, spb, shift_step):
45
- #print(shift)
46
- end=-int(length % spb)
47
- if end == 0: end = length+shift
48
- image = audio[shift:end].reshape(-1, spb)
49
- length-=shift_step
50
- if mode == 1: image=image.T
51
- diff = numpy.abs ( (image[:-1] - image[1:]).flatten()[:mlength] )
52
- difference=numpy.sum(diff*diff)
53
- if mode == 3:
54
- image=image.T
55
- diff = numpy.abs ( (image[:-1] - image[1:]).flatten()[:mlength] )
56
- difference += numpy.sum(diff*diff)
57
- bpmdiffs.append(shift)
58
- bpmdiffsi.append(difference)
59
- #if shift%1000==0: print(f'testing shift = {shift}; value = {difference}')
60
- shift = bpmdiffs[numpy.argmin(numpy.asarray(bpmdiffsi))]
61
- #print(f'BPM = {(1/spb)*60*samplerate}; shift = {shift/samplerate} sec.')
62
- return numpy.arange(shift, length, spb)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beat_manipulator/beatmap.py CHANGED
@@ -1,103 +1,128 @@
1
- import numpy
2
- def _safer_eval(string:str) -> float:
3
- #print(string, end=' ')
4
- if isinstance(string, str):
5
- #print(string, end=' ')
6
- #print(''.join([i for i in string if i.isdecimal() or i in '.+-*/']), end = ' ')
7
- string = eval(''.join([i for i in string if i.isdecimal() or i in '.+-*/']))
8
- #print(string)
9
- return string
10
 
11
- class beatmap:
12
- def __init__(self, beatmap:list = None, audio = None, samplerate = None, caching = True, log = True, path=None, artist=None, title=None, filename = None):
13
- self.beatmap = beatmap
14
- self.audio = audio
15
- self.samplerate = samplerate
16
- self.caching = caching
17
- self.log = log
18
- self.path = path
19
- self.artist = artist
20
- self.title = title
21
- self.filename = filename
22
 
23
- def __getitem__(self, var):
24
- return self.beatmap[var]
25
-
26
- def __len__(self):
27
- return len(self.beatmap)
28
-
29
- def _toarray(self):
30
- if isinstance(self.beatmap, list): self.beatmap=numpy.asarray(self.beatmap, dtype=int)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
- def _add_beat_to_end(self):
33
- self.beatmap=numpy.abs(numpy.append(self.beatmap, len(self.audio[0])))
34
- self.beatmap=self.beatmap.astype(int)
35
-
36
- def generate(self, lib='madmom.BeatDetectionProcessor', caching=True, split=None):
37
- """Creates self.beatmap attribute with a list of positions of beats in samples."""
38
- if self.log is True: print(f'analyzing beats using {lib}; ', end='')
39
- #if audio is None and filename is None: (audio, samplerate) = open_audio()
40
- if caching is True and self.caching is True:
41
- audio_id=hex(len(self.audio[0]))
42
- import os
43
- if not os.path.exists('SavedBeatmaps'):
44
- os.mkdir('SavedBeatmaps')
45
- cacheDir="SavedBeatmaps/" + ''.join(self.filename.split('/')[-1]) + "_"+lib+"_"+audio_id+'.txt'
46
- try:
47
- self.beatmap=numpy.loadtxt(cacheDir, dtype=int)
48
- self.bpm=numpy.average(self.beatmap)/self.samplerate
49
- if self.log is True: print('loaded cached beatmap.')
50
- return
51
- except OSError:
52
- if self.log is True:print("beatmap hasn't been generated yet. Generating...")
53
-
54
- if lib.split('.')[0]=='madmom':
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  from collections.abc import MutableMapping, MutableSequence
56
  import madmom
 
57
  if lib=='madmom.BeatTrackingProcessor':
58
  proc = madmom.features.beats.BeatTrackingProcessor(fps=100)
59
- act = madmom.features.beats.RNNBeatProcessor()(madmom.audio.signal.Signal(self.audio.T, self.samplerate))
60
- assert len(act)>200, f'Audio file is too short, len={len(act)}'
61
- self.beatmap= proc(act)*self.samplerate
62
- if lib=='madmom.BeatTrackingProcessor.constant':
63
  proc = madmom.features.beats.BeatTrackingProcessor(fps=100, look_ahead=None)
64
- act = madmom.features.beats.RNNBeatProcessor()(madmom.audio.signal.Signal(self.audio.T, self.samplerate))
65
- self.beatmap= proc(act)*self.samplerate
66
- if lib=='madmom.BeatTrackingProcessor.consistent':
67
  proc = madmom.features.beats.BeatTrackingProcessor(fps=100, look_ahead=None, look_aside=0)
68
- act = madmom.features.beats.RNNBeatProcessor()(madmom.audio.signal.Signal(self.audio.T, self.samplerate))
69
- self.beatmap= proc(act)*self.samplerate
70
  elif lib=='madmom.BeatDetectionProcessor':
71
  proc = madmom.features.beats.BeatDetectionProcessor(fps=100)
72
- act = madmom.features.beats.RNNBeatProcessor()(madmom.audio.signal.Signal(self.audio.T, self.samplerate))
73
- #print(proc, act)
74
- assert len(act)>200, f'Audio file is too short, len={len(act)}'
75
- self.beatmap= proc(act)*self.samplerate
76
  elif lib=='madmom.BeatDetectionProcessor.consistent':
77
  proc = madmom.features.beats.BeatDetectionProcessor(fps=100, look_aside=0)
78
- act = madmom.features.beats.RNNBeatProcessor()(madmom.audio.signal.Signal(self.audio.T, self.samplerate))
79
- self.beatmap= proc(act)*self.samplerate
80
  elif lib=='madmom.CRFBeatDetectionProcessor':
81
  proc = madmom.features.beats.CRFBeatDetectionProcessor(fps=100)
82
- act = madmom.features.beats.RNNBeatProcessor()(madmom.audio.signal.Signal(self.audio.T, self.samplerate))
83
- self.beatmap= proc(act)*self.samplerate
84
  elif lib=='madmom.CRFBeatDetectionProcessor.constant':
85
  proc = madmom.features.beats.CRFBeatDetectionProcessor(fps=100, use_factors=True, factors=[0.5, 1, 2])
86
- act = madmom.features.beats.RNNBeatProcessor()(madmom.audio.signal.Signal(self.audio.T, self.samplerate))
87
- self.beatmap= proc(act)*self.samplerate
88
  elif lib=='madmom.DBNBeatTrackingProcessor':
89
  proc = madmom.features.beats.DBNBeatTrackingProcessor(fps=100)
90
- act = madmom.features.beats.RNNBeatProcessor()(madmom.audio.signal.Signal(self.audio.T, self.samplerate))
91
- self.beatmap= proc(act)*self.samplerate
92
  elif lib=='madmom.DBNBeatTrackingProcessor.1000':
93
  proc = madmom.features.beats.DBNBeatTrackingProcessor(fps=100, transition_lambda=1000)
94
- act = madmom.features.beats.RNNBeatProcessor()(madmom.audio.signal.Signal(self.audio.T, self.samplerate))
95
- self.beatmap= proc(act)*self.samplerate
96
  elif lib=='madmom.DBNDownBeatTrackingProcessor':
97
  proc = madmom.features.downbeats.DBNDownBeatTrackingProcessor(beats_per_bar=[4], fps=100)
98
- act = madmom.features.downbeats.RNNDownBeatProcessor()(madmom.audio.signal.Signal(self.audio.T, self.samplerate))
99
- self.beatmap= proc(act)*self.samplerate
100
- self.beatmap=self.beatmap[:,0]
101
  elif lib=='madmom.PatternTrackingProcessor': #broken
102
  from madmom.models import PATTERNS_BALLROOM
103
  proc = madmom.features.downbeats.PatternTrackingProcessor(PATTERNS_BALLROOM, fps=50)
@@ -107,306 +132,64 @@ class beatmap:
107
  diff = SpectrogramDifferenceProcessor(positive_diffs=True)
108
  mb = MultiBandSpectrogramProcessor(crossover_frequencies=[270])
109
  pre_proc = SequentialProcessor([log, diff, mb])
110
- act = pre_proc(madmom.audio.signal.Signal(self.audio.T, self.samplerate))
111
- self.beatmap= proc(act)*self.samplerate
112
- self.beatmap=self.beatmap[:,0]
113
  elif lib=='madmom.DBNBarTrackingProcessor': #broken
114
- beats = self.generate(audio=self.audio, samplerate=self.samplerate, filename=self.filename, lib='madmom.DBNBeatTrackingProcessor', caching = caching)
115
  proc = madmom.features.downbeats.DBNBarTrackingProcessor(beats_per_bar=[4], fps=100)
116
- act = madmom.features.downbeats.RNNBarProcessor()(((madmom.audio.signal.Signal(self.audio.T, self.samplerate)), beats))
117
- self.beatmap= proc(act)*self.samplerate
118
  elif lib=='librosa': #broken in 3.9, works in 3.8
119
  import librosa
120
- beat_frames = librosa.beat.beat_track(y=self.audio[0], sr=self.samplerate, hop_length=512)
121
- self.beatmap = librosa.frames_to_samples(beat_frames[1])
122
- # elif lib=='BeatNet':
123
- # from BeatNet.BeatNet import BeatNet # doesn't seem to work well for some reason
124
- # estimator = BeatNet(1, mode='offline', inference_model='DBN', plot=[], thread=False)
125
- # beatmap = estimator.process(filename)
126
- # beatmap=beatmap[:,0]*self.samplerate
127
- # elif lib=='jump-reward-inference': # doesn't seem to work well for some reason
128
- # from jump_reward_inference.joint_tracker import joint_inference
129
- # estimator = joint_inference(1, plot=False)
130
- # beatmap = estimator.process(filename)
131
- # beatmap=beatmap[:,0]*self.samplerate
132
-
133
- elif lib=='split':
134
- self.beatmap= list(range(0, len(self.audio[0]), len(self.audio[0])//split))
135
- elif lib=='stunlocked':
136
- from . import analyze
137
- self.beatmap = analyze.detect_bpm(self.audio, self.samplerate)
138
- if lib.split('.')[0]=='madmom':
139
- self.beatmap=numpy.absolute(self.beatmap-500)
140
- if caching is True and self.caching is True: numpy.savetxt(cacheDir, self.beatmap.astype(int), fmt='%d')
141
- self.bpm=numpy.average(self.beatmap)/self.samplerate
142
- if isinstance(self.beatmap, list): self.beatmap=numpy.asarray(self.beatmap, dtype=int)
143
- self.beatmap=self.beatmap.astype(int)
144
-
145
- def scale(self, scale:float):
146
- if isinstance(scale, str): scale = _safer_eval(scale)
147
- #print(scale)
148
- assert scale>0, f"scale should be > 0, your scale is {scale}"
149
- #print(self.beatmap)
150
- import math
151
- if scale!=1:
152
- if self.log is True: print(f'scale={scale}; ')
153
- a=0
154
- b=numpy.array([], dtype=int)
155
- if scale%1==0:
156
- while a <len( self.beatmap):
157
- #print(a, self.beatmap[int(a)], end=', ')
158
- b=numpy.append(b,self.beatmap[int(a)])
159
- a+=scale
160
- #print(self.beatmap[int(a)])
161
- else:
162
- while a+1 <len( self.beatmap):
163
- #print(a,b)
164
- b=numpy.append(b, int((1-(a%1))*self.beatmap[math.floor(a)]+(a%1)*self.beatmap[math.ceil(a)]))
165
- a+=scale
166
- self.beatmap=b
167
-
168
- def autoscale(self):
169
- if self.log is True: print(f'autoscaling; ')
170
- bpm=(self.beatmap[-1]-self.beatmap[0])/(len(self.beatmap)-1)
171
- #print('BPM =', (bpm/self.samplerate) * 240, bpm)
172
- if bpm>=160000: scale=1/8
173
- elif (bpm)>=80000: scale=1/4
174
- elif (bpm)>=40000: scale=1/2
175
- elif (bpm)<=20000: scale=2
176
- elif (bpm)<=10000: scale=4
177
- elif (bpm)<=5000: scale=8
178
- self.scale(scale)
179
-
180
- def autoinsert(self):
181
- if self.log is True: print(f'autoinserting; ')
182
- diff=(self.beatmap[1]-self.beatmap[0])
183
- a=0
184
- while diff<self.beatmap[0] and a<100:
185
- self.beatmap=numpy.insert(self.beatmap, 0, self.beatmap[0]-diff)
186
- a+=1
187
-
188
- def shift(self, shift: float):
189
- if isinstance(shift, str): shift = _safer_eval(shift)
190
- if shift!=0 and self.log is True: print(f'shift={shift}; ')
191
- elif shift==0: return
192
- if shift<0:
193
- shift=-shift # so that floor division works correctly
194
- # add integer number of beats to the start
195
- if shift >= 1: self.beatmap=numpy.insert(self.beatmap, 0, list(i+1 for i in range(int(shift//1))))
196
- if shift%1!=0:
197
- # shift by modulus from the end
198
- shift=shift%1
199
- for i in reversed(range(len(self.beatmap))):
200
- if i==0: continue
201
- #print(i, ', ',self.beatmap[i], '-', shift, '* (', self.beatmap[i], '-', self.beatmap[i-1],') =', self.beatmap[i] - shift * (self.beatmap[i] - self.beatmap[i-1]))
202
- self.beatmap[i] = int(self.beatmap[i] - shift * (self.beatmap[i] - self.beatmap[i-1]))
203
-
204
- elif shift>0:
205
- # remove integer number of beats from the start
206
- if shift >= 1: self.beatmap=self.beatmap[int(shift//1):]
207
- if shift%1!=0:
208
- # shift by modulus
209
- shift=shift%1
210
- for i in range(len(self.beatmap)-int(shift)-1):
211
- #print(self.beatmap[i], '+', shift, '* (', self.beatmap[i+1], '-', self.beatmap[i],') =', self.beatmap[i] + shift * (self.beatmap[i+1] - self.beatmap[i]))
212
- self.beatmap[i] = int(self.beatmap[i] + shift * (self.beatmap[i+1] - self.beatmap[i]))
213
 
214
- self.beatmap=sorted(list(self.beatmap))
215
- while True:
216
- n,done=0,[]
217
- for i in range(len(self.beatmap)):
218
- if self.beatmap.count(self.beatmap[i])>1 and i not in done:
219
- self.beatmap[i]+=1
220
- n+=1
221
- done.append(i)
222
- if n==0: break
223
- self.beatmap=sorted(list(self.beatmap))
224
-
225
- def cut(self, start=0, end=None):
226
- if start!=0 or end is not None and self.log is True: print(f'start={start}; end={end}; ')
227
- start*=self.samplerate
228
- self.beatmap=self.beatmap[self.beatmap>=start].astype(int)
229
- if end is not None: self.beatmap=self.beatmap[self.beatmap<=end].astype(int)
230
-
231
- class hitmap(beatmap):
232
- def generate(self, lib='madmom.MultiModelSelectionProcessor', caching=True):
233
- if self.log is True: print(f'analyzing hits using {lib}; ')
234
- self.hitlib=lib
235
- """Finds positions of actual instrument/drum hits."""
236
- if caching is True and self.caching is True:
237
- audio_id=hex(len(self.audio[0]))
238
- import os
239
- if not os.path.exists('SavedBeatmaps'):
240
- os.mkdir('SavedBeatmaps')
241
- cacheDir="SavedBeatmaps/" + ''.join(self.filename.split('/')[-1]) + "_"+lib+"_"+audio_id+'.txt'
242
- try:
243
- cached=False
244
- self.beatmap=numpy.loadtxt(cacheDir)
245
- cached=True
246
- except OSError: cached=False
247
- if cached is False:
248
- if lib=='madmom.RNNBeatProcessor': #broken
249
- import madmom
250
- proc = madmom.features.beats.RNNBeatProcessor()
251
- self.beatmap = proc(madmom.audio.signal.Signal(self.audio.T, self.samplerate))
252
- elif lib=='madmom.MultiModelSelectionProcessor':
253
- import madmom
254
- proc = madmom.features.beats.RNNBeatProcessor(post_processor=None)
255
- predictions = proc(madmom.audio.signal.Signal(self.audio.T, self.samplerate))
256
- mm_proc = madmom.features.beats.MultiModelSelectionProcessor(num_ref_predictions=None)
257
- self.beatmap= mm_proc(predictions)*self.samplerate
258
- self.beatmap/= numpy.max(self.beatmap)
259
- if caching is True and self.caching is True: numpy.savetxt(cacheDir, self.beatmap)
260
 
261
- def osu(self, difficulties = [0.2, 0.1, 0.08, 0.06, 0.04, 0.02, 0.01, 0.005]):
262
- if self.log is True: print(f'generating osu file')
263
- def _process(self, threshold):
264
- hitmap=[]
265
- actual_samplerate=int(self.samplerate/100)
266
- beat_middle=int(actual_samplerate/2)
267
- for i in range(len(self.beatmap)):
268
- if self.beatmap[i]>threshold: hitmap.append(i*actual_samplerate + beat_middle)
269
- hitmap=numpy.asarray(hitmap)
270
- clump=[]
271
- for i in range(len(hitmap)-1):
272
- #print(i, abs(self.beatmap[i]-self.beatmap[i+1]), clump)
273
- if abs(hitmap[i] - hitmap[i+1]) < self.samplerate/16: clump.append(i)
274
- elif clump!=[]:
275
- clump.append(i)
276
- actual_time=hitmap[clump[0]]
277
- hitmap[numpy.array(clump)]=0
278
- #print(self.beatmap)
279
- hitmap[clump[0]]=actual_time
280
- clump=[]
281
-
282
- hitmap=hitmap[hitmap!=0]
283
- return hitmap
284
-
285
- osufile=lambda title,artist,version: ("osu file format v14\n"
286
- "\n"
287
- "[General]\n"
288
- f"AudioFilename: {self.path.split('/')[-1]}\n"
289
- "AudioLeadIn: 0\n"
290
- "PreviewTime: -1\n"
291
- "Countdown: 0\n"
292
- "SampleSet: Normal\n"
293
- "StackLeniency: 0.5\n"
294
- "Mode: 0\n"
295
- "LetterboxInBreaks: 0\n"
296
- "WidescreenStoryboard: 0\n"
297
- "\n"
298
- "[Editor]\n"
299
- "DistanceSpacing: 1.1\n"
300
- "BeatDivisor: 4\n"
301
- "GridSize: 8\n"
302
- "TimelineZoom: 1.6\n"
303
- "\n"
304
- "[Metadata]\n"
305
- f"Title:{title}\n"
306
- f"TitleUnicode:{title}\n"
307
- f"Artist:{artist}\n"
308
- f"ArtistUnicode:{artist}\n"
309
- f'Creator:{self.hitlib} + BeatManipulator\n'
310
- f'Version:{version} {self.hitlib}\n'
311
- 'Source:\n'
312
- 'Tags:BeatManipulator\n'
313
- 'BeatmapID:0\n'
314
- 'BeatmapSetID:-1\n'
315
- '\n'
316
- '[Difficulty]\n'
317
- 'HPDrainRate:4\n'
318
- 'CircleSize:4\n'
319
- 'OverallDifficulty:7.5\n'
320
- 'ApproachRate:10\n'
321
- 'SliderMultiplier:3.3\n'
322
- 'SliderTickRate:1\n'
323
- '\n'
324
- '[Events]\n'
325
- '//Background and Video events\n'
326
- '//Break Periods\n'
327
- '//Storyboard Layer 0 (Background)\n'
328
- '//Storyboard Layer 1 (Fail)\n'
329
- '//Storyboard Layer 2 (Pass)\n'
330
- '//Storyboard Layer 3 (Foreground)\n'
331
- '//Storyboard Layer 4 (Overlay)\n'
332
- '//Storyboard Sound Samples\n'
333
- '\n'
334
- '[TimingPoints]\n'
335
- '0,140.0,4,1,0,100,1,0\n'
336
- '\n'
337
- '\n'
338
- '[HitObjects]\n')
339
- # remove the clumps
340
- #print(self.beatmap)
341
 
342
- #print(self.beatmap)
343
-
344
-
345
- #print(len(osumap))
346
- #input('banana')
347
- import shutil, os
348
- if os.path.exists('BeatManipulator_TEMP'): shutil.rmtree('BeatManipulator_TEMP')
349
- os.mkdir('BeatManipulator_TEMP')
350
- hitmap=[]
351
- import random
352
- for difficulty in difficulties:
353
- for i in range(4):
354
- #print(i)
355
- this_difficulty=_process(self, difficulty)
356
- hitmap.append(this_difficulty)
357
- for k in range(len(hitmap)):
358
- osumap=numpy.vstack((hitmap[k],numpy.zeros(len(hitmap[k])),numpy.zeros(len(hitmap[k])))).T
359
- difficulty= difficulties[k]
360
- for i in range(len(osumap)-1):
361
- if i==0:continue
362
- dist=(osumap[i,0]-osumap[i-1,0])*(1-(difficulty**0.3))
363
- if dist<1000: dist=0.005
364
- elif dist<2000: dist=0.01
365
- elif dist<3000: dist=0.015
366
- elif dist<4000: dist=0.02
367
- elif dist<5000: dist=0.25
368
- elif dist<6000: dist=0.35
369
- elif dist<7000: dist=0.45
370
- elif dist<8000: dist=0.55
371
- elif dist<9000: dist=0.65
372
- elif dist<10000: dist=0.75
373
- elif dist<12500: dist=0.85
374
- elif dist<15000: dist=0.95
375
- elif dist<20000: dist=1
376
- #elif dist<30000: dist=0.8
377
- prev_x=osumap[i-1,1]
378
- prev_y=osumap[i-1,2]
379
- if prev_x>0: prev_x=prev_x-dist*0.1
380
- elif prev_x<0: prev_x=prev_x+dist*0.1
381
- if prev_y>0: prev_y=prev_y-dist*0.1
382
- elif prev_y<0: prev_y=prev_y+dist*0.1
383
- dirx=random.uniform(-dist,dist)
384
- diry=dist-abs(dirx)*random.choice([-1, 1])
385
- if abs(prev_x+dirx)>1: dirx=-dirx
386
- if abs(prev_y+diry)>1: diry=-diry
387
- x=prev_x+dirx
388
- y=prev_y+diry
389
- #print(dirx,diry,x,y)
390
- #print(x>1, x<1, y>1, y<1)
391
- if x>1: x=0.8
392
- if x<-1: x=-0.8
393
- if y>1: y=0.8
394
- if y<-1: y=-0.8
395
- #print(dirx,diry,x,y)
396
- osumap[i,1]=x
397
- osumap[i,2]=y
398
-
399
- osumap[:,1]*=300
400
- osumap[:,1]+=300
401
- osumap[:,2]*=180
402
- osumap[:,2]+=220
403
-
404
- file=osufile(self.artist, self.title, difficulty)
405
- for j in osumap:
406
- #print('285,70,'+str(int(int(i)*1000/self.samplerate))+',1,0')
407
- file+=f'{int(j[1])},{int(j[2])},{str(int(int(j[0])*1000/self.samplerate))},1,0\n'
408
- with open(f'BeatManipulator_TEMP/{self.artist} - {self.title} [BeatManipulator {difficulty} {self.hitlib}].osu', 'x', encoding="utf-8") as f:
409
- f.write(file)
410
 
411
- def autoinsert(): raise NotImplementedError("autoinserting won't work on hitmaps")
412
- def autoscale(): raise NotImplementedError("autoscale won't work on hitmaps")
 
1
+ import numpy as np
2
+ from . import utils
 
 
 
 
 
 
 
3
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
+ def scale(beatmap:np.ndarray, scale:float, log = True, integer = True) -> np.ndarray:
6
+ if isinstance(scale, str): scale = utils._safer_eval(scale)
7
+ assert scale>0, f"scale should be > 0, your scale is {scale}"
8
+ if scale == 1: return beatmap
9
+ else:
10
+ import math
11
+ if log is True: print(f'scale={scale}; ')
12
+ a = 0
13
+ b = np.array([], dtype=int)
14
+ if scale%1==0:
15
+ while a < len(beatmap):
16
+ b = np.append(b, beatmap[int(a)])
17
+ a += scale
18
+ else:
19
+ if integer is True:
20
+ while a + 1 < len(beatmap):
21
+ b = np.append(b, int((1 - (a % 1)) * beatmap[math.floor(a)] + (a % 1) * beatmap[math.ceil(a)]))
22
+ a += scale
23
+ else:
24
+ while a + 1 < len(beatmap):
25
+ b = np.append(b, (1 - (a % 1)) * beatmap[math.floor(a)] + (a % 1) * beatmap[math.ceil(a)])
26
+ a += scale
27
+ return b
28
 
29
+ def shift(beatmap:np.ndarray, shift:float, log = True, mode = 1) -> np.ndarray:
30
+ if isinstance(shift, str): shift = utils._safer_eval(shift)
31
+ if shift == 0: return beatmap
32
+ # positive shift
33
+ elif shift > 0:
34
+ # full value of beats is removed from the beginning
35
+ if shift >= 1: beatmap = beatmap[int(shift//1):]
36
+ # shift beatmap by the decimal value
37
+ if shift%1 != 0:
38
+ shift = shift%1
39
+ for i in range(len(beatmap) - int(shift) - 1):
40
+ beatmap[i] = int(beatmap[i] + shift * (beatmap[i + 1] - beatmap[i]))
41
+
42
+ # negative shift
43
+ else:
44
+ shift = -shift
45
+ # full values are inserted in between first beats
46
+ if shift >= 1:
47
+ if mode == 1:
48
+ step = int((beatmap[1] - beatmap[0]) / (int(shift//1) + 1))
49
+ beatmap = np.insert(arr = beatmap, obj = 1, values = np.linspace(start = beatmap[0] + step - 1, stop = 1 + beatmap[1] - step, num = int(shift//1)))
50
+ elif mode == 2:
51
+ for i in range(int(shift//1)):
52
+ beatmap = np.insert(arr = beatmap, obj = (i*2)+1, values = int((beatmap[i*2] + beatmap[(i*2)+1])/2))
53
+ # shift beatmap by the decimal value
54
+ if shift%1 != 0:
55
+ shift = shift%1
56
+ for i in reversed(range(len(beatmap))):
57
+ if i==0: continue
58
+ beatmap[i] = int(beatmap[i] - shift * (beatmap[i] - beatmap[i-1]))
59
+ return beatmap
60
+
61
+ def generate(audio: np.ndarray, sr: int, lib='madmom.BeatDetectionProcessor', caching=True, filename: str = None, log = True, load_settings = True, split=None):
62
+ """Creates beatmap attribute with a list of positions of beats in samples."""
63
+ if log is True: print(f'Analyzing beats using {lib}; ', end='')
64
+
65
+ # load a beatmap if it is cached:
66
+ if caching is True and filename is not None:
67
+ audio_id=hex(len(audio[0]))
68
+ import os
69
+ if not os.path.exists('beat_manipulator/beatmaps'):
70
+ os.mkdir('beat_manipulator/beatmaps')
71
+ cacheDir="beat_manipulator/beatmaps/" + ''.join(filename.replace('\\', '/').split('/')[-1]) + "_"+lib+"_"+audio_id+'.txt'
72
+ try:
73
+ beatmap=np.loadtxt(cacheDir, dtype=int)
74
+ if log is True: print('loaded cached beatmap.')
75
+ except OSError:
76
+ if log is True:print("beatmap hasn't been generated yet. Generating...")
77
+ beatmap = None
78
+
79
+ #generate the beatmap
80
+ if beatmap is None:
81
+ if 'madmom' in lib.lower():
82
  from collections.abc import MutableMapping, MutableSequence
83
  import madmom
84
+ assert len(audio[0])>sr*2, f'Audio file is too short, len={len(audio[0])} samples, or {len(audio[0])/sr} seconds. Minimum length is 2 seconds, audio below that breaks madmom processors.'
85
  if lib=='madmom.BeatTrackingProcessor':
86
  proc = madmom.features.beats.BeatTrackingProcessor(fps=100)
87
+ act = madmom.features.beats.RNNBeatProcessor()(madmom.audio.signal.Signal(audio.T, sr))
88
+ beatmap= proc(act)*sr
89
+ elif lib=='madmom.BeatTrackingProcessor.constant':
 
90
  proc = madmom.features.beats.BeatTrackingProcessor(fps=100, look_ahead=None)
91
+ act = madmom.features.beats.RNNBeatProcessor()(madmom.audio.signal.Signal(audio.T, sr))
92
+ beatmap= proc(act)*sr
93
+ elif lib=='madmom.BeatTrackingProcessor.consistent':
94
  proc = madmom.features.beats.BeatTrackingProcessor(fps=100, look_ahead=None, look_aside=0)
95
+ act = madmom.features.beats.RNNBeatProcessor()(madmom.audio.signal.Signal(audio.T, sr))
96
+ beatmap= proc(act)*sr
97
  elif lib=='madmom.BeatDetectionProcessor':
98
  proc = madmom.features.beats.BeatDetectionProcessor(fps=100)
99
+ act = madmom.features.beats.RNNBeatProcessor()(madmom.audio.signal.Signal(audio.T, sr))
100
+ beatmap= proc(act)*sr
 
 
101
  elif lib=='madmom.BeatDetectionProcessor.consistent':
102
  proc = madmom.features.beats.BeatDetectionProcessor(fps=100, look_aside=0)
103
+ act = madmom.features.beats.RNNBeatProcessor()(madmom.audio.signal.Signal(audio.T, sr))
104
+ beatmap= proc(act)*sr
105
  elif lib=='madmom.CRFBeatDetectionProcessor':
106
  proc = madmom.features.beats.CRFBeatDetectionProcessor(fps=100)
107
+ act = madmom.features.beats.RNNBeatProcessor()(madmom.audio.signal.Signal(audio.T, sr))
108
+ beatmap= proc(act)*sr
109
  elif lib=='madmom.CRFBeatDetectionProcessor.constant':
110
  proc = madmom.features.beats.CRFBeatDetectionProcessor(fps=100, use_factors=True, factors=[0.5, 1, 2])
111
+ act = madmom.features.beats.RNNBeatProcessor()(madmom.audio.signal.Signal(audio.T, sr))
112
+ beatmap= proc(act)*sr
113
  elif lib=='madmom.DBNBeatTrackingProcessor':
114
  proc = madmom.features.beats.DBNBeatTrackingProcessor(fps=100)
115
+ act = madmom.features.beats.RNNBeatProcessor()(madmom.audio.signal.Signal(audio.T, sr))
116
+ beatmap= proc(act)*sr
117
  elif lib=='madmom.DBNBeatTrackingProcessor.1000':
118
  proc = madmom.features.beats.DBNBeatTrackingProcessor(fps=100, transition_lambda=1000)
119
+ act = madmom.features.beats.RNNBeatProcessor()(madmom.audio.signal.Signal(audio.T, sr))
120
+ beatmap= proc(act)*sr
121
  elif lib=='madmom.DBNDownBeatTrackingProcessor':
122
  proc = madmom.features.downbeats.DBNDownBeatTrackingProcessor(beats_per_bar=[4], fps=100)
123
+ act = madmom.features.downbeats.RNNDownBeatProcessor()(madmom.audio.signal.Signal(audio.T, sr))
124
+ beatmap= proc(act)*sr
125
+ beatmap=beatmap[:,0]
126
  elif lib=='madmom.PatternTrackingProcessor': #broken
127
  from madmom.models import PATTERNS_BALLROOM
128
  proc = madmom.features.downbeats.PatternTrackingProcessor(PATTERNS_BALLROOM, fps=50)
 
132
  diff = SpectrogramDifferenceProcessor(positive_diffs=True)
133
  mb = MultiBandSpectrogramProcessor(crossover_frequencies=[270])
134
  pre_proc = SequentialProcessor([log, diff, mb])
135
+ act = pre_proc(madmom.audio.signal.Signal(audio.T, sr))
136
+ beatmap= proc(act)*sr
137
+ beatmap=beatmap[:,0]
138
  elif lib=='madmom.DBNBarTrackingProcessor': #broken
139
+ beats = generate(audio=audio, sr=sr, filename=filename, lib='madmom.DBNBeatTrackingProcessor', caching = caching)
140
  proc = madmom.features.downbeats.DBNBarTrackingProcessor(beats_per_bar=[4], fps=100)
141
+ act = madmom.features.downbeats.RNNBarProcessor()(((madmom.audio.signal.Signal(audio.T, sr)), beats))
142
+ beatmap= proc(act)*sr
143
  elif lib=='librosa': #broken in 3.9, works in 3.8
144
  import librosa
145
+ beat_frames = librosa.beat.beat_track(y=audio[0], sr=sr, hop_length=512)
146
+ beatmap = librosa.frames_to_samples(beat_frames[1])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
+ # save the beatmap and return
149
+ if caching is True: np.savetxt(cacheDir, beatmap.astype(int), fmt='%d')
150
+ if not isinstance(beatmap, np.ndarray): beatmap=np.asarray(beatmap, dtype=int)
151
+ else: beatmap=beatmap.astype(int)
152
+
153
+ if load_settings is True:
154
+ settingsDir="beat_manipulator/beatmaps/" + ''.join(filename.split('/')[-1]) + "_"+lib+"_"+audio_id+'_settings.txt'
155
+ if os.path.exists(settingsDir):
156
+ with open(settingsDir, 'r') as f:
157
+ settings = f.read().split(',')
158
+ if settings[0] != 'None': beatmap = scale(beatmap, settings[0], log = False)
159
+ if settings[1] != 'None': beatmap = shift(beatmap, settings[1], log = False)
160
+ if settings[2] != 'None': beatmap = np.sort(np.absolute(beatmap - int(settings[2])))
161
+
162
+ return beatmap
163
+
164
+
165
+
166
+ def save_settings(audio: np.ndarray, filename: str = None, lib: str = 'madmom.BeatDetectionProcessor', scale: float = None, shift: float = None, adjust: int = None, normalized: str = None, log = True, overwrite = 'ask'):
167
+ if isinstance(overwrite, str): overwrite = overwrite.lower()
168
+ audio_id=hex(len(audio[0]))
169
+ cacheDir="beat_manipulator/beatmaps/" + ''.join(filename.split('/')[-1]) + "_"+lib+"_"+audio_id+'.txt'
170
+ import os
171
+ assert os.path.exists(cacheDir), f"Beatmap `{cacheDir}` doesn't exist"
172
+ settingsDir="beat_manipulator/beatmaps/" + ''.join(filename.split('/')[-1]) + "_"+lib+"_"+audio_id+'_settings.txt'
173
+
174
+ try:
175
+ a = utils._safer_eval_strict(scale)
176
+ if a == 1: scale = None
177
+ except Exception as e: assert scale is None, f'scale = `{scale}` - Not a valid scale, should be either a number, a math expression, or None: {e}'
178
+ try:
179
+ a = utils._safer_eval_strict(shift)
180
+ if a == 0: shift = None
181
+ except Exception as e: assert shift is None, f'shift = `{shift}` - Not a valid shift: {e}'
182
+ assert isinstance(adjust, int) or adjust is None, f'adjust = `{adjust}` should be int, but it is `{type(adjust)}`'
 
 
 
 
 
 
 
 
 
 
 
183
 
184
+ if adjust == 0: adjust = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
 
186
+ if os.path.exists(settingsDir):
187
+ if overwrite == 'ask' or overwrite =='a':
188
+ what = input(f'`{settingsDir}` already exists. Overwrite (y/n)?: ')
189
+ if not (what.lower() == 'y' or what.lower() == 'yes'): return
190
+ elif not (overwrite == 'true' or overwrite =='y' or overwrite =='yes' or overwrite is True): return
191
+
192
+ with open(settingsDir, 'w') as f:
193
+ f.write(f'{scale},{shift},{adjust},{normalized}')
194
+ if log is True: print(f"Saved scale = `{scale}`, shift = `{shift}`, adjust = `{adjust}` to `{settingsDir}`")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
 
 
 
beat_manipulator/effect.py DELETED
@@ -1,106 +0,0 @@
1
- import numpy
2
-
3
- def normalize(audio):
4
- audio=audio-(numpy.min(audio)+numpy.max(audio))/2
5
- return audio*(1-(max(numpy.max(audio), abs(numpy.min(audio)))))
6
-
7
- def pitch(audio, pitch, grain):
8
- grain=int(grain)
9
- if len(audio)>10: audio=[audio]
10
- if type(audio) is not list: audio=audio.tolist()
11
- length=len(audio[0])
12
- if pitch<1:
13
- pitch=int(1//pitch)
14
- if grain%2!=0: grain+=1
15
- for i in range(len(audio)):
16
- n=0
17
- while n+grain<length:
18
- #print(len(audio[i]))
19
- #print(n)
20
- audio[i][n:n+grain]=numpy.repeat(audio[i][n:n+int(grain/2)], 2)
21
- #print(len(audio[i]))
22
- n+=grain
23
- elif pitch>1:
24
- pitch=int(pitch)
25
- for i in range(len(audio)):
26
- n=0
27
- while n+grain<length:
28
- audio[i][n:n+grain]=audio[i][n:n+grain:pitch]*pitch
29
- n+=grain
30
- return audio
31
-
32
- def pitchB(audio, pitch, grain):
33
- grain=int(grain)
34
- if len(audio)>10: audio=[audio]
35
- if type(audio) is not list: audio=audio.tolist()
36
- length=len(audio[0])
37
- if pitch<1:
38
- pitch=int(1//pitch)
39
- if grain%2!=0: grain+=1
40
- for i in range(len(audio)):
41
- n=0
42
- while n+grain<length:
43
- #print(len(audio[i]))
44
- #print(n)
45
- audio[i][n:n+grain]=numpy.repeat(audio[i][n:n+int(grain/2)], 2)
46
- #print(len(audio[i]))
47
- n+=grain
48
-
49
- elif pitch>1:
50
- pitch=int(pitch)
51
- for i in range(len(audio)):
52
- n=0
53
- while n+grain<length:
54
- audio2=audio[i][n:n+grain:pitch]
55
- for j in range(pitch-1):
56
- #print(j)
57
- audio2.extend(audio2[::1] if j%2==1 else audio2[::-1])
58
- audio[i][n:n+grain]=audio2
59
- n+=grain
60
- return audio
61
-
62
- def grain(audio, grain):
63
- grain=int(grain)
64
- if len(audio)>10: audio=[audio]
65
- if type(audio) is not list: audio=audio.tolist()
66
- length=len(audio[0])
67
- n=0
68
- for i in range(len(audio)):
69
- while n+2*grain<length:
70
- audio[i][n+grain:n+2*grain]=audio[i][n:n+grain]
71
- n+=grain*2
72
- return audio
73
-
74
- def ftt(audio, inverse=True):
75
- """headphone warning: cursed effect"""
76
- import scipy.fft
77
- audio=numpy.asarray(audio).copy()
78
- for i in range(len(audio)):
79
- if inverse is False:
80
- audio[i]= scipy.fft.fft(audio[i], axis=0)
81
- else:
82
- audio[i]= scipy.fft.ifft(audio[i], axis=0)
83
- audio=(audio*(2/numpy.max(audio)))-1
84
- return normalize(audio)
85
-
86
- def fourier_shift(audio, value=5):
87
- """modulates volume for some reason"""
88
- import scipy.ndimage
89
- audio=numpy.asarray(audio).copy()
90
- audio= numpy.asarray(list(scipy.ndimage.fourier_shift(i, value, axis=-1) for i in audio)).astype(float)
91
- return normalize(audio)
92
-
93
- def gradient(audio):
94
- """acts as an interesting high pass filter that removes drums"""
95
- audio=numpy.asarray(audio).copy()
96
- return numpy.gradient(audio, axis=0)
97
-
98
- def gradient_inverse(audio):
99
- """supposed to be inverse of a gradient, but it just completely destroys the audio into a distorted mess"""
100
- audio=numpy.asarray(audio).copy()
101
- for i in range(len(audio)):
102
- a = audio[i]
103
- audio[i] = a[0] + 2 * numpy.c_[numpy.r_[0, a[1:-1:2].cumsum()], a[::2].cumsum() - a[0] / 2].ravel()[:len(a)]
104
- audio=normalize(audio)
105
- return numpy.gradient(audio, axis=0)
106
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beat_manipulator/effects.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from . import io
3
+
4
+ def deco_abs(effect):
5
+ def stuff(*args, **kwargs):
6
+ if len(args)>0: audio = args[0]
7
+ else: audio = kwargs['audio']
8
+ if not isinstance(audio, np.ndarray): audio = io._load(audio)
9
+ audio_signs = np.sign(audio)
10
+ audio = np.abs(audio)
11
+ if len(args)>0: args[0] = audio
12
+ else: kwargs['audio'] = audio
13
+ audio = effect(*args, **kwargs)
14
+ audio *= audio_signs
15
+ return stuff
16
+
17
+
18
+
19
+ def volume(audio: np.ndarray, v: float):
20
+ return audio*v
21
+
22
+ def speed(audio: np.ndarray, s: float = 2, precision:int = 24):
23
+ if s%1 != 0 and (1/s)%1 != 0:
24
+ import fractions
25
+ s = fractions.Fraction(s).limit_denominator(precision)
26
+ audio = np.repeat(audio, s.denominator, axis=1)
27
+ return audio[:,::s.numerator]
28
+ elif s%1 == 0:
29
+ return audio[:,::int(s)]
30
+ else:
31
+ return np.repeat(audio, int(1/s), axis=1)
32
+
33
+ def channel(audio: np.ndarray, c:int = None):
34
+ if c is None:
35
+ audio[0], audio[1] = audio[1], audio[0]
36
+ return audio
37
+ elif c == 0:
38
+ audio[0] = 0
39
+ return audio
40
+ else:
41
+ audio[1] = 0
42
+ return audio
43
+
44
+ def downsample(audio: np.ndarray, d:int = 10):
45
+ return np.repeat(audio[:,::d], d, axis=1)
46
+
47
+ def gradient(audio: np.ndarray, number: int = 1):
48
+ for _ in range(number):
49
+ audio = np.gradient(audio, axis=1)
50
+ return audio
51
+
52
+ def bitcrush(audio: np.ndarray, b:float = 4):
53
+ if 1/b > 1:
54
+ return np.around(audio, decimals=int(1/b))
55
+ else:
56
+ return np.around(audio*b, decimals = 1)
57
+
58
+ def reverse(audio: np.ndarray):
59
+ return audio[:,::-1]
60
+
61
+ def normalize(audio: np.ndarray):
62
+ return audio*(1/np.max(np.abs(audio)))
63
+
64
+ def clip(audio: np.ndarray):
65
+ return np.clip(audio, -1, 1)
66
+
67
+ def to_sidechain(audio: np.ndarray):
68
+ audio = np.clip(np.abs(audio), -1, 1)
69
+ for channel in range(len(audio)):
70
+ audio[channel] = np.abs(1 - np.convolve(audio[channel], np.ones(shape=(1000)), mode = 'same'))
71
+ return audio
72
+
73
+
74
+
75
+ # some stuff is defined in main.py to reduce function calls for 1 line stuff
76
+ BM_EFFECTS = {
77
+ "v": "volume",
78
+ "s": speed,
79
+ "c": channel,
80
+ "d": "downsample",
81
+ "g": "gradient",
82
+ "b": bitcrush,
83
+ "r": "reverse",
84
+ }
beat_manipulator/generate.py DELETED
@@ -1,22 +0,0 @@
1
- import numpy
2
- def sidechain(samplerate:int = 44100,
3
- length: float = 0.5,
4
- curve: float = 2,
5
- vol0: float = 0,
6
- vol1: float = 1,
7
- smoothing: int = 40,
8
- channels:int = 2) -> tuple:
9
-
10
- x = numpy.linspace(vol0,vol1,int(length*samplerate))**curve
11
- if smoothing is not None:
12
- x = numpy.concatenate(numpy.linspace(1,0,smoothing),x)
13
- return tuple(x for _ in range(channels)) if channels>1 else x
14
-
15
- def sine(len, freq, samplerate, volume=1):
16
- return numpy.sin(numpy.linspace(0, freq*3.1415926*2*len, int(len*samplerate)))*volume
17
-
18
- def saw(len, freq, samplerate, volume=1):
19
- return (numpy.linspace(0, freq*2*len, int(len*samplerate))%2 - 1)*volume
20
-
21
- def square(len, freq, samplerate, volume=1):
22
- return ((numpy.linspace(0, freq*2*len, int(len*samplerate)))//1%2 * 2 - 1)*volume
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beat_manipulator/google colab.ipynb ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "id": "ldVF6dMTbqB7"
7
+ },
8
+ "source": [
9
+ "#Beat Manipulator"
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "code",
14
+ "source": [
15
+ "#@title 1. Run this cell to install all necessary libraries. This only needs to be done once each time you open this collab.\n",
16
+ "import shutil, os\n",
17
+ "try:\n",
18
+ " if os.path.exists('BeatManipulator'): shutil.rmtree('BeatManipulator', ignore_errors=True)\n",
19
+ "except: pass\n",
20
+ "!pip install numpy cython soundfile ffmpeg-python pedalboard librosa\n",
21
+ "!pip install madmom\n",
22
+ "!git clone https://github.com/stunlocked1/BeatManipulator\n",
23
+ "%cd BeatManipulator\n",
24
+ "import beat_manipulator as bm"
25
+ ],
26
+ "metadata": {
27
+ "id": "E-gDjnzBby5-",
28
+ "cellView": "form"
29
+ },
30
+ "execution_count": null,
31
+ "outputs": []
32
+ },
33
+ {
34
+ "cell_type": "markdown",
35
+ "metadata": {
36
+ "id": "FYVs2fGzbqB9"
37
+ },
38
+ "source": [
39
+ "***\n",
40
+ "Use cells below as many times as you wish. Pattern syntax, scale and shift are explained here https://github.com/stunlocked1/BeatManipulator\n",
41
+ "\n",
42
+ "Enter pattern, scale and shift, run the cell, and it will let you upload your audio file.\n",
43
+ "\n",
44
+ "Analyzing beats for the first time will take some time, but if you open the same file for the second time, it will load a saved beat map."
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": null,
50
+ "metadata": {
51
+ "id": "TFOLf-vrbqB-",
52
+ "cellView": "form"
53
+ },
54
+ "outputs": [],
55
+ "source": [
56
+ "#@title 2. Beatswapping. Enter pattern, scale and shift, run the cell, and it will let you upload your audio file.\n",
57
+ "pattern = \"1, 3, 2, 4\" #@param {type:\"string\"}\n",
58
+ "scale = 1 #@param {type:\"number\"}\n",
59
+ "shift = 0 #@param {type:\"number\"}\n",
60
+ "\n",
61
+ "pattern_length = None # Length of the pattern. If None, this will be inferred from the highest number in the pattern\n",
62
+ "\n",
63
+ "\n",
64
+ "import beat_manipulator as bm, IPython\n",
65
+ "from google.colab import files\n",
66
+ "uploaded = list(files.upload().keys())[0]\n",
67
+ "path = bm.beatswap(audio=uploaded, pattern = pattern, scale = scale, shift = shift, length = pattern_length)\n",
68
+ "IPython.display.Audio(path)"
69
+ ]
70
+ },
71
+ {
72
+ "cell_type": "markdown",
73
+ "source": [
74
+ "***\n",
75
+ "## Other stuff\n",
76
+ "Those operate the same as the above cell"
77
+ ],
78
+ "metadata": {
79
+ "id": "fQVrYbQ_rQzm"
80
+ }
81
+ },
82
+ {
83
+ "cell_type": "markdown",
84
+ "source": [
85
+ "**Song to image**\n",
86
+ "\n",
87
+ "creates an image based on beat positions. Each song will generate a unique image. The image will be a square, you can specify maximum size.` "
88
+ ],
89
+ "metadata": {
90
+ "id": "7gc2jbelrTMb"
91
+ }
92
+ },
93
+ {
94
+ "cell_type": "code",
95
+ "source": [
96
+ "#@title Song to image\n",
97
+ "image_size = 512 #@param {type:\"integer\"}\n",
98
+ "\n",
99
+ "\n",
100
+ "import beat_manipulator as bm, IPython\n",
101
+ "from google.colab import files\n",
102
+ "uploaded = list(files.upload().keys())[0]\n",
103
+ "path = bm.image(audio=uploaded, max_size = image_size)\n",
104
+ "IPython.display.Image(path)"
105
+ ],
106
+ "metadata": {
107
+ "id": "M2ufXQaxrWZT",
108
+ "cellView": "form"
109
+ },
110
+ "execution_count": null,
111
+ "outputs": []
112
+ },
113
+ {
114
+ "cell_type": "markdown",
115
+ "source": [
116
+ "***\n",
117
+ "**osu! beatmap generator**\n",
118
+ "\n",
119
+ "generates an osu! beatmap from your song. This generates a hitmap, probabilities of hits at each sample, picks all ones above a threshold, and turns them into osu circles, trying to emulate actual osu beatmap. This doesn't generate sliders, however, because no known science has been able to comprehend the complexity of those.\n",
120
+ "\n",
121
+ "The .osz file will be downloaded automatically, open with osu! to install like any other beatmap."
122
+ ],
123
+ "metadata": {
124
+ "id": "bqOYyiCisAjM"
125
+ }
126
+ },
127
+ {
128
+ "cell_type": "code",
129
+ "source": [
130
+ "difficulties = [0.2, 0.1, 0.05, 0.025, 0.01, 0.0075, 0.005, 0.0025, 0.0001] # all difficulties will be embedded in one beatmap, Lower is typically harder, but not always.\n",
131
+ "\n",
132
+ "\n",
133
+ "import beat_manipulator.osu\n",
134
+ "from google.colab import files\n",
135
+ "uploaded = list(files.upload().keys())[0]\n",
136
+ "path = beat_manipulator.osu.generate(song=uploaded, difficulties = difficulties)\n",
137
+ "files.download(f'/content/BeatManipulator/{path}')"
138
+ ],
139
+ "metadata": {
140
+ "id": "T1wLIS1_sB_K"
141
+ },
142
+ "execution_count": null,
143
+ "outputs": []
144
+ }
145
+ ],
146
+ "metadata": {
147
+ "kernelspec": {
148
+ "display_name": "audio310",
149
+ "language": "python",
150
+ "name": "python3"
151
+ },
152
+ "language_info": {
153
+ "codemirror_mode": {
154
+ "name": "ipython",
155
+ "version": 3
156
+ },
157
+ "file_extension": ".py",
158
+ "mimetype": "text/x-python",
159
+ "name": "python",
160
+ "nbconvert_exporter": "python",
161
+ "pygments_lexer": "ipython3",
162
+ "version": "3.10.9"
163
+ },
164
+ "orig_nbformat": 4,
165
+ "vscode": {
166
+ "interpreter": {
167
+ "hash": "f56da36b984886453ea677d340712034d0bd218b2dc7a53ab7c38da0c6f67f35"
168
+ }
169
+ },
170
+ "colab": {
171
+ "provenance": []
172
+ }
173
+ },
174
+ "nbformat": 4,
175
+ "nbformat_minor": 0
176
+ }
beat_manipulator/image.py CHANGED
@@ -1,179 +1,70 @@
1
- import numpy
2
-
3
- class image:
4
- def __init__(self, image=None, audio=None, samplerate=None, beatmap=None, log=None):
5
- self.image=image
6
- self.audio = audio
7
- self.samplerate=samplerate
8
- self.beatmap=beatmap
9
- self.log=log
10
-
11
- def __getitem__(self, var):
12
- return self.beatmap[var]
13
-
14
- def _printlog(self, string, end=None, force = False, forcei = False):
15
- if (self.log is True or force is True) and forcei is False:
16
- if end is None: print(string)
17
- else:print(string,end=end)
18
-
19
- def _toshape(self):
20
- if self.image.ndim == 2:
21
- self.image = [self.image]
22
- if self.image.ndim == 3:
23
- if len(self.image[0][0]) == 3:
24
- self.image = [self.image]
25
-
26
- def _channel(self):
27
- if self.image.ndim == 2: yield self.image
28
- if self.image.ndim == 3:
29
- if len(self.image[0][0]) == 3:
30
- yield self.image
31
- if self.image.ndim > 3 or len(self.image[0][0] != 3):
32
- for i in self.image:
33
- yield i
34
-
35
- @property
36
- def combined(self):
37
- for i, channel in enumerate(self._channel()):
38
- if i==0: combined = channel.copy()
39
- else: combined += channel
40
- return combined
41
-
42
- def open(self, path):
43
- import cv2
44
- self.image = cv2.imread(path)
45
-
46
- def display(self):
47
- import cv2
48
- cv2.imshow('image', self.combined)
49
-
50
- def write(self, output, rotate = True, mode = 'square', maximum = 4096):
51
- import cv2
52
- mode = mode.lower()
53
- image = self.combined
54
- if mode=='square':
55
- y=min(len(image), len(image[0]), maximum)
56
- y=max(y, maximum)
57
- image = cv2.resize(image, (y,y), interpolation=cv2.INTER_NEAREST)
58
- elif mode=='tosmallest':
59
- y=min(len(image), len(image[0]))
60
- image = cv2.resize(image, (x,x), interpolation=cv2.INTER_NEAREST)
61
- elif mode=='maximum':
62
- x = min(len(image), maximum)
63
- y = min(len(image[0]), maximum)
64
- image = cv2.resize(image, (x,y), interpolation=cv2.INTER_NEAREST)
65
- if rotate is True: image=image.T
66
- cv2.imwrite(output, image)
67
-
68
-
69
- def effect_blur(self, value=(5,5)):
70
- """similar to echo"""
71
- import cv2
72
- if isinstance(value, int) or isinstance(value, float): value = (value, value)
73
- for i in range(len(self.image)):
74
- self.image[i]=cv2.blur(self.image[i], value)
75
-
76
- def effect_median(self, value=5):
77
- """similar to echo"""
78
- import scipy.signal
79
- for i in range(len(self.image)):
80
- self.image[i]=scipy.signal.medfilt2d(self.image[i], value)
81
-
82
- def effect_uniform(self, value=5):
83
- """similar to echo"""
84
- import scipy.ndimage
85
- for i in range(len(self.image)):
86
- self.image[i]= scipy.ndimage.uniform_filter(self.image[i], value)
87
-
88
- def effect_shift2d(self, value=5):
89
- """very weird effect, mostly produces silence"""
90
- import scipy.ndimage
91
- self.image= scipy.ndimage.fourier_gaussian(self.image, value)
92
- self.image=self.image*(255/numpy.max(self.image))
93
-
94
- def effect_spline(self, value=3):
95
- """barely noticeable echo"""
96
- import scipy.ndimage
97
- for i in range(len(self.image)):
98
- self.image[i]= scipy.ndimage.spline_filter(self.image[i], value)
99
-
100
- def effect_rotate(self, value=0.1):
101
- """rotates self.image in degrees"""
102
- import scipy.ndimage
103
- image = [0 for _ in range(len(self.image))]
104
- for i in range(len(image)):
105
- image[i] = scipy.ndimage.rotate(self.image[i], value)
106
- self.image = numpy.asarray(image)
107
-
108
- def effect_gradient(self):
109
- self.image=numpy.asarray(numpy.gradient(self.image)[0])
110
-
111
- class spectogram(image):
112
- def generate(self, hop_length:int = 512):
113
- self.hop_length=hop_length
114
- import librosa
115
- self.image=librosa.feature.melspectrogram(y=self.audio, sr=self.samplerate, hop_length=hop_length)
116
- self.mask = numpy.full(self.image.shape, True)
117
- self._toshape()
118
-
119
- def toaudio(self):
120
- import librosa
121
- self.audio=librosa.feature.inverse.mel_to_audio(M=numpy.swapaxes(numpy.swapaxes(numpy.dstack(( self.image[0,:,:], self.image[1,:,:])), 0, 2), 1,2), sr=self.samplerate, hop_length=self.hop_length)
122
- return self.audio
123
-
124
-
125
- class beat_image(image):
126
- def generate(self, mode='median'):
127
- """Turns song into an image based on beat positions."""
128
- assert self.beatmap is not None, 'Please run song.beatmap.generate() first. beat_image.generate needs beatmap to work.'
129
- self._printlog('generating beat-image; ')
130
- mode=mode.lower()
131
- if isinstance(self.audio,numpy.ndarray): self.audio=numpy.ndarray.tolist(self.audio)
132
- # add the bits before first beat
133
- self.image=([self.audio[0][0:self.beatmap[0]],], [self.audio[1][0:self.beatmap[0]],])
134
- # maximum is needed to make the array homogeneous
135
- maximum=self.beatmap[0]
136
- values=[]
137
- #print(self.beatmap)
138
- values.append(self.beatmap[0])
139
- for i in range(len(self.beatmap)-1):
140
- self.image[0].append(self.audio[0][self.beatmap[i]:self.beatmap[i+1]])
141
- self.image[1].append(self.audio[1][self.beatmap[i]:self.beatmap[i+1]])
142
- maximum = max(self.beatmap[i+1]-self.beatmap[i], maximum)
143
- values.append(self.beatmap[i+1]-self.beatmap[i])
144
- if 'max' in mode: norm=int(maximum)
145
- elif 'med' in mode: norm=int(numpy.median(values))
146
- elif 'av' in mode: norm=int(numpy.average(values))
147
- for i in range(len(self.image[0])):
148
- beat_diff=norm-len(self.image[0][i])
149
- if beat_diff>0:
150
- self.image[0][i].extend([numpy.nan]*beat_diff)
151
- self.image[1][i].extend([numpy.nan]*beat_diff)
152
- #print(0, len(self.image[0][i]), len(self.image[1][i]))
153
- elif beat_diff<0:
154
- self.image[0][i]=self.image[0][i][:beat_diff]
155
- self.image[1][i]=self.image[1][i][:beat_diff]
156
- #print(1, len(self.image[0][i]), len(self.image[1][i]))
157
- self.image=numpy.asarray(self.image)*255
158
- self.mask = self.image == numpy.nan
159
- self.image=numpy.nan_to_num(self.image)
160
- self._toshape()
161
-
162
- def toaudio(self):
163
- self._printlog('converting beat-image to audio; ')
164
- image=numpy.asarray(self.image)/255
165
- try: image[self.mask]=numpy.nan
166
- except IndexError: pass
167
- audio=list([] for _ in range(len(image)))
168
- #print(audio)
169
- #print(len(image), len(image[0]), len(image[1]), len(image[0][0]), len(image[1][0]), len(image[0][1]), len(image[1][1]))
170
- for j in range(len(image)):
171
- for i in range(len(image[j])):
172
- beat=image[j][i]
173
- #print(i,j, len(image[0][j]), len(image[1][j]), len(beat), end=' ')
174
- beat=beat[~numpy.isnan(beat)]
175
- #print(len(beat), end=' ')
176
- audio[j].extend(beat)
177
- #print(len(audio[0]), len(audio[1]))
178
- self.audio=numpy.asarray(audio)
179
- return self.audio
 
1
+ from . import io, main
2
+ import numpy as np
3
+ def generate(song, beatmap = None, mode='median', sr = None, log = True):
4
+ if log is True: print(f'Generating an image from beats...', end = ' ')
5
+ song = main.song(song, sr=sr)
6
+ if song.beatmap is None: song.beatmap = beatmap
7
+ if song.beatmap is None: song.beatmap_generate()
8
+ if isinstance(song.audio, np.ndarray): song.audio = song.audio.tolist()
9
+ # create the image
10
+ image = [[],[]]
11
+ for i in range(1, len(song.beatmap)):
12
+ beat = song[i]
13
+ image[0].append(beat[0])
14
+ image[1].append(beat[1])
15
+
16
+ # find image width
17
+ lengths = [len(i) for i in image[0]]
18
+ mode = mode.lower()
19
+ if 'max' in mode:
20
+ width = max(lengths)
21
+ elif 'med' in mode:
22
+ width = int(np.median(lengths))
23
+ elif 'av' in mode:
24
+ width = int(np.average(lengths))
25
+
26
+ # fill or crop rows:
27
+ for i in range(len(image[0])):
28
+ difference = lengths[i] - width
29
+ if difference<0:
30
+ image[0][i].extend([np.nan]*(-difference))
31
+ image[1][i].extend([np.nan]*(-difference))
32
+ elif difference>0:
33
+ image[0][i] = image[0][i][:-difference]
34
+ image[1][i] = image[1][i][:-difference]
35
+
36
+ song.audio = np.array(song.audio, copy=False)
37
+ if log is True: print('Done!')
38
+ return np.array(image, copy=False)
39
+
40
+ def bw_to_colored(image, channel = 2, fill = True):
41
+ if fill is True:
42
+ combined = image[0] * image[1]
43
+ combined = (np.abs(combined)**0.5)*np.sign(combined)
44
+ else: channel = np.zeros(shape = image[0].shape)
45
+ image = image.tolist()
46
+ if channel == 2: image.append(combined)
47
+ else: image.insert(channel, combined)
48
+ return np.rot90(np.array(image, copy=False).T)
49
+
50
+ def colored_to_bw(image, l=0, r=1):
51
+ image = np.array(image, copy=False)
52
+ return np.array([image[:,:,l],image[:,:,r]])
53
+
54
+ def write(image, output, mode = 'r', max_size = 4096, rotate = True, contrast=1):
55
+ import cv2
56
+ if max_size is not None:
57
+ w = max_size
58
+ h = min(len(image[0][0]), max_size)
59
+ if mode == 'color':
60
+ image = bw_to_colored(image)
61
+ elif mode == 'r':
62
+ image = image[0]
63
+ elif mode == 'l':
64
+ image = image[1]
65
+ elif mode == 'combine':
66
+ image = image[0] + image[1]
67
+ image = image*(255*contrast)
68
+ image = cv2.resize(src=image, dsize=(w, h), interpolation = cv2.INTER_NEAREST)
69
+ if rotate is True: image = np.rot90(image)
70
+ cv2.imwrite(output, image)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beat_manipulator/io.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import numpy as np
3
+ from . import main
4
+
5
+ def open_audio(path:str = None, lib:str = 'auto', normalize = True) -> tuple:
6
+ """Opens audio from path, returns (audio, samplerate) tuple.
7
+
8
+ Audio is returned as an array with normal volume range between -1, 1.
9
+
10
+ Example of returned audio:
11
+
12
+ [
13
+ [0.35, -0.25, ... -0.15, -0.15],
14
+
15
+ [0.31, -0.21, ... -0.11, -0.07]
16
+ ]"""
17
+
18
+ if path is None:
19
+ from tkinter.filedialog import askopenfilename
20
+ path = askopenfilename(title='select song', filetypes=[("mp3", ".mp3"),("wav", ".wav"),("flac", ".flac"),("ogg", ".ogg"),("wma", ".wma")])
21
+
22
+ path=path.replace('\\', '/')
23
+
24
+ if lib=='pedalboard.io':
25
+ import pedalboard.io
26
+ with pedalboard.io.AudioFile(path) as f:
27
+ audio = f.read(f.frames)
28
+ sr = f.samplerate
29
+
30
+ elif lib=='librosa':
31
+ import librosa
32
+ audio, sr = librosa.load(path, sr=None, mono=False)
33
+
34
+ elif lib=='soundfile':
35
+ import soundfile
36
+ audio, sr = soundfile.read(path)
37
+ audio=audio.T
38
+
39
+ elif lib=='madmom':
40
+ import madmom
41
+ audio, sr = madmom.io.audio.load_audio_file(path, dtype=float)
42
+ audio=audio.T
43
+
44
+ # elif lib=='pydub':
45
+ # from pydub import AudioSegment
46
+ # song=AudioSegment.from_file(filename)
47
+ # audio = song.get_array_of_samples()
48
+ # samplerate=song.frame_rate
49
+ # print(audio)
50
+ # print(filename)
51
+
52
+ elif lib=='auto':
53
+ for i in ('madmom', 'soundfile', 'librosa', 'pedalboard.io'):
54
+ try:
55
+ audio,sr=open_audio(path, i)
56
+ break
57
+ except Exception as e:
58
+ print(f'open_audio with {i}: {e}')
59
+
60
+ if len(audio)>16: audio=np.array([audio, audio], copy=False)
61
+ if normalize is True:
62
+ audio = np.clip(audio, -1, 1)
63
+ audio = audio*(1/np.max(np.abs(audio)))
64
+ return audio.astype(np.float32),sr
65
+
66
+ def _sr(sr):
67
+ try: return int(sr)
68
+ except (ValueError, TypeError): assert False, f"Audio is an array, but `sr` argument is not valid. If audio is an array, you have to provide samplerate as an integer in the `sr` argument. Currently sr = {sr} of type {type(sr)}"
69
+
70
+ def write_audio(audio:np.ndarray, sr:int, output:str, lib:str='auto', libs=('pedalboard.io', 'soundfile'), log = True):
71
+ """"writes audio to path specified by output. Path should end with file extension, for example `folder/audio.mp3`"""
72
+ if log is True: print(f'Writing {output}...', end=' ')
73
+ assert _iterable(audio), f"audio should be an array/iterable object, but it is {type(audio)}"
74
+ sr = _sr(sr)
75
+ if not isinstance(audio, np.ndarray): audio = np.array(audio, copy=False)
76
+ if lib=='pedalboard.io':
77
+ #print(audio)
78
+ import pedalboard.io
79
+ with pedalboard.io.AudioFile(output, 'w', sr, audio.shape[0]) as f:
80
+ f.write(audio)
81
+ elif lib=='soundfile':
82
+ audio=audio.T
83
+ import soundfile
84
+ soundfile.write(output, audio, sr)
85
+ del audio
86
+ elif lib=='auto':
87
+ for i in libs:
88
+ try:
89
+ write_audio(audio=audio, sr=sr, output=output, lib=i, log = False)
90
+ break
91
+ except Exception as e:
92
+ print(e)
93
+ else: assert False, 'Failed to write audio, chances are there is something wrong with it...'
94
+ if log is True: print(f'Done!')
95
+
96
+ def _iterable(a):
97
+ try:
98
+ _ = iter(a)
99
+ return True
100
+ except TypeError: return False
101
+
102
+ def _load(audio, sr:int = None, lib:str = 'auto', channels:int = 2, transpose3D:bool = False) -> tuple:
103
+ """Automatically converts audio from path or any format to [[...],[...]] array. Returns (audio, samplerate) tuple."""
104
+ # path
105
+ if isinstance(audio, str): return(open_audio(path=audio, lib=lib))
106
+ # array
107
+ if _iterable(audio):
108
+ if isinstance(audio, main.song):
109
+ if sr is None: sr = audio.sr
110
+ audio = audio.audio
111
+ # sr is provided in a tuple
112
+ if sr is None and len(audio) == 2:
113
+ if not _iterable(audio[0]):
114
+ sr = audio[0]
115
+ audio = audio[1]
116
+ elif not _iterable(audio[1]):
117
+ sr = audio[1]
118
+ audio = audio[0]
119
+ if not isinstance(audio, np.ndarray): audio = np.array(audio, copy=False)
120
+ sr = _sr(sr)
121
+ if _iterable(audio[0]):
122
+ # image
123
+ if _iterable(audio[0][0]):
124
+ audio2 = []
125
+ if transpose3D is True: audio = audio.T
126
+ for i in audio:
127
+ audio2.extend(_load(audio=i, sr=sr, lib=lib, channels=channels, transpose3D=transpose3D)[0])
128
+ return audio2, sr
129
+ # transposed
130
+ if len(audio) > 16:
131
+ audio = audio.T
132
+ return _load(audio=audio, sr=sr, lib=lib, channels=channels, transpose3D=transpose3D)
133
+ # multi channel
134
+ elif isinstance(channels, int):
135
+ if len(audio) >= channels:
136
+ return audio[:channels], sr
137
+ # masked mono
138
+ else: return np.array([audio[0] for _ in range(channels)], copy=False), sr
139
+ else: return audio, sr
140
+ else:
141
+ # mono
142
+ return (np.array([audio for _ in range(channels)], copy=False) if channels is not None else audio), sr
143
+ # unknown
144
+ else: assert False, f"Audio should be either a string with path, an array/iterable object, or a song object, but it is {type(audio)}"
145
+
146
+ def _tosong(audio, sr=None):
147
+ if isinstance(audio, main.song): return audio
148
+ else:
149
+ audio, sr = _load(audio = audio, sr = sr)
150
+ return main.song(audio=audio, sr = sr)
151
+
152
+ def _outputfilename(path:str = None, filename:str = None, suffix:str = None, ext:str = None):
153
+ """If path has file extension, returns `path + suffix + ext`. Else returns `path + filename + suffix + .ext`. If nothing is specified, returns `output.mp3`"""
154
+ if ext is not None:
155
+ if not ext.startswith('.'): ext = '.'+ext
156
+ if path is None: path = ''
157
+ if path.endswith('/') or path.endswith('\\'): path=path[:-1]
158
+ if '.' in path:
159
+ path = path.split('.')
160
+ if path[-1].lower() in ['mp3', 'wav', 'flac', 'ogg', 'wma', 'aac', 'ac3', 'aiff']:
161
+ if ext is not None:
162
+ path[-1] = ext
163
+ if suffix is not None: path[len(path)-2]+=suffix
164
+ return ''.join(path)
165
+ else: path = ''.join(path)
166
+ if filename is not None:
167
+ filename = filename.replace('\\','/').split('/')[-1]
168
+ if '.' in filename:
169
+ filename = filename.split('.')
170
+ if filename[-1].lower() in ['mp3', 'wav', 'flac', 'ogg', 'wma', 'aac', 'ac3', 'aiff']:
171
+ if ext is not None:
172
+ filename[-1] = ext
173
+ if suffix is not None: filename.insert(len(filename)-1, suffix)
174
+ else: filename += [ext]
175
+ filename = ''.join(filename)
176
+ return f'{path}/{filename}' if path != '' else filename
177
+ return f'{(path + "/") * (path != "")}{filename}{suffix if suffix is not None else ""}.{ext if ext is not None else "mp3"}'
178
+ else: return f'{path}/output.mp3'
beat_manipulator/main.py CHANGED
@@ -1,846 +1,516 @@
1
- import numpy
2
- numpy.set_printoptions(suppress=True)
3
- from .beatmap import beatmap, hitmap
4
- from .image import spectogram, beat_image
5
-
6
- def _safer_eval(string:str) -> float:
7
- if isinstance(string, str):
8
- #print(''.join([i for i in string if i.isdecimal() or i in '.+-*/']))
9
- string = eval(''.join([i for i in string if i.isdecimal() or i in '.+-*/']))
10
- return string
11
-
12
- def open_audio(filename=None, lib='auto') -> numpy.ndarray:
13
- """Opens audio from path, returns (audio, samplerate) tuple.
14
-
15
- Audio is returned as an array with normal volume range between -1, 1.
16
-
17
- Example of returned audio:
18
-
19
- [
20
- [0.35, -0.25, ... -0.15, -0.15],
21
-
22
- [0.31, -0.21, ... -0.11, -0.07]
23
- ]"""
24
- if filename is None:
25
- from tkinter.filedialog import askopenfilename
26
- filename = askopenfilename(title='select song', filetypes=[("mp3", ".mp3"),("wav", ".wav"),("flac", ".flac"),("ogg", ".ogg"),("wma", ".wma")])
27
- filename=filename.replace('\\', '/')
28
- if lib=='pedalboard.io':
29
- import pedalboard.io
30
- with pedalboard.io.AudioFile(filename) as f:
31
- audio = f.read(f.frames)
32
- samplerate = f.samplerate
33
- elif lib=='librosa':
34
- import librosa
35
- audio, samplerate = librosa.load(filename, sr=None, mono=False)
36
- elif lib=='soundfile':
37
- import soundfile
38
- audio, samplerate = soundfile.read(filename)
39
- audio=audio.T
40
- elif lib=='madmom':
41
- import madmom
42
- audio, samplerate = madmom.io.audio.load_audio_file(filename, dtype=float)
43
- audio=audio.T
44
- # elif lib=='pydub':
45
- # from pydub import AudioSegment
46
- # song=AudioSegment.from_file(filename)
47
- # audio = song.get_array_of_samples()
48
- # samplerate=song.frame_rate
49
- # print(audio)
50
- # print(filename)
51
- elif lib=='auto':
52
- for i in ('madmom', 'soundfile', 'librosa', 'pedalboard.io'):
53
- try:
54
- audio,samplerate=open_audio(filename, i)
55
- break
56
- except Exception as e:
57
- print(f'open_audio with {i}: {e}')
58
- if len(audio)<2: audio=[audio]
59
- return audio,samplerate
60
-
61
-
62
- def _outputfilename(output, filename, suffix=' (beatswap)', ext='mp3'):
63
- if not (output.lower().endswith('.mp3') or output.lower().endswith('.wav') or output.lower().endswith('.flac') or output.lower().endswith('.ogg') or
64
- output.lower().endswith('.aac') or output.lower().endswith('.ac3') or output.lower().endswith('.aiff') or output.lower().endswith('.wma')):
65
- return output+'.'.join(''.join(filename.split('/')[-1]).split('.')[:-1])+suffix+'.'+ext
66
-
67
- class song:
68
- def __init__(self, path:str=None, audio:numpy.array=None, samplerate:int=None, bmap:list=None, caching=True, filename=None, copied=False, log=True):
69
- """song can be loaded from path to an audio file, or from a list/numpy array and samplerate. Audio array should have values from -1 to 1, multiple channels should be stacked vertically. Optionally you can provide your own beat map.
70
-
71
- Song object has the following attributes:
72
 
73
- path - file system path to load the audio file from. Can be absolute or relative.
74
-
75
- audio - either a numpy array with shape=(channels, values) or a list with two lists. Audio is converted to list for certain operations to improve performance.
76
-
77
- samplerate - integer, for example 44100. Determined automatically when audio is loaded from a path.
78
 
79
- bmap - list of integers, with positions of each beat in samples.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
- caching = True - if True, generated beatmaps will be saved to SavedBeatmaps folder and loaded when the same audio file is opened again, instead of generating beatmap each time.
82
 
83
- log = True - if True, minimal info about all operations will be printed.
84
- """
85
- assert not (audio is not None and samplerate is None), 'If audio is provided, samplerate should be provided as well, for example samplerate=44100'
86
-
87
- self.audio=audio
88
- self.samplerate=samplerate
89
-
90
- # ask for a path if audio isn't specified
91
- if path is None and filename is None:
92
- if audio is None:
93
- from tkinter.filedialog import askopenfilename
94
- self.path = askopenfilename(title='select song')
95
- else:
96
- # generate unique identifier for storing beatmap cache
97
- audio_id = numpy.sum(audio[0][1000:2000]) if len(audio<2000) else numpy.sum(audio[1000:2000])
98
- self.filename = 'unknown ' + str(hex(int(audio_id))) + ' ' + str(hex(int((audio_id%1)*(10**18))))
99
- self.path = self.filename
100
- print(self.filename)
101
- else:
102
- if path is None: self.path=filename
103
- else: self.path=path
104
-
105
- # load from zip
106
- if self.path.lower().endswith('.zip'):
107
- import shutil,os
108
- if os.path.exists('BeatManipulator_TEMP'): shutil.rmtree('BeatManipulator_TEMP')
109
- os.mkdir('BeatManipulator_TEMP')
110
- shutil.unpack_archive(self.path, 'BeatManipulator_TEMP')
111
- for root,dirs,files in os.walk('BeatManipulator_TEMP'):
112
- for fname in files:
113
- if fname.lower().endswith('.mp3') or fname.lower().endswith('.wav') or fname.lower().endswith('.ogg') or fname.lower().endswith('.flac'):
114
- self.audio, self.samplerate=open_audio(root.replace('\\','/')+'/'+fname)
115
- stop=True
116
- break
117
- if stop is True: break
118
- shutil.rmtree('BeatManipulator_TEMP')
119
-
120
- # open audio from path
121
- if self.audio is None or self.samplerate is None:
122
- self.audio, self.samplerate=open_audio(self.path)
123
-
124
- # mono to stereo
125
- if len(self.audio)>16:
126
- self.audio=numpy.asarray((self.audio,self.audio))
127
-
128
- # stuff
129
- self.path=self.path.replace('\\', '/')
130
- if filename is None: self.filename=self.path.split('/')[-1]
131
- else: self.filename=filename.replace('\\', '/').split('/')[-1]
132
- self.samplerate=int(self.samplerate)
133
-
134
- # artist, title
135
- if ' - ' in self.path.split('/')[-1]:
136
- self.artist = self.path.split('/')[-1].split(' - ')[0]
137
- self.title= '.'.join(self.path.split('/')[-1].split(' - ')[1].split('.')[:-1])
138
- elif path is not None or filename is not None:
139
- self.title=''.join(self.path.split('/')[-1].split('.')[:-1])
140
- self.artist=None
141
- else:
142
- self.title = None
143
- self.artist = None
144
- self.caching=caching
145
- self.log=log
146
- if copied is False and self.log is True:
147
- if self.artist is not None or self.title is not None: print(f'Loaded {self.artist} - {self.title}; ')
148
- elif filename is not None: print(f'Loaded {self.filename}; ')
149
- elif path is not None: print(f'Loaded {self.path}; ')
150
- else: print(f'Loaded audio file; ')
151
- self.audio_isarray = True
152
-
153
- if isinstance(bmap, beatmap): self.beatmap=bmap
154
- else: self.beatmap = beatmap(beatmap = bmap, audio= self.audio, samplerate=self.samplerate, filename=self.filename, caching = caching, log=log, path=self.path, artist=self.artist, title=self.title)
155
- self.hitmap = hitmap(audio= self.audio, samplerate=self.samplerate, filename=self.filename, caching = caching, log=log, path=self.path, artist=self.artist, title=self.title)
156
- self.spectogram = spectogram(audio=self.audio, samplerate=self.samplerate, beatmap=self.beatmap, log=self.log)
157
- self.beat_image = beat_image(audio=self.audio, samplerate=self.samplerate, beatmap=self.beatmap, log=self.log)
158
-
159
- @property
160
- def bm(self):
161
- return self.beatmap.beatmap
162
-
163
- @property
164
- def hm(self):
165
- return self.hitmap.beatmap
166
-
167
- def _printlog(self, string, end=None, force = False, forcei = False):
168
- if (self.log is True or force is True) and forcei is False:
169
- if end is None: print(string)
170
- else:print(string,end=end)
171
-
172
- def _audio_tolist(self, force = True):
173
- if self.audio_isarray:
174
- self.audio = self.audio.tolist()
175
- self.audio_isarray = False
176
- elif force is True:
177
- self.audio = self.audio.tolist()
178
- self.audio_isarray = False
179
-
180
- def _audio_toarray(self, force = True):
181
- if not self.audio_isarray:
182
- self.audio = numpy.asarray(self.audio)
183
- self.audio_isarray = True
184
- elif force is True:
185
- self.audio = numpy.asarray(self.audio)
186
- self.audio_isarray = True
187
 
188
- def _update(self):
189
- self.beatmap.audio = self.audio
190
- self.hitmap.audio = self.audio
191
- self.spectogram.audio = self.audio
192
- self.beat_image.audio = self.audio
193
- self.beat_image.beatmap = self.bm
194
-
195
- def write(self, output:str, lib:str='auto', libs=('pedalboard.io', 'soundfile')):
196
- """"writes audio to path specified by output. Path should end with file extension, for example `folder/audio.mp3`"""
197
- self._audio_toarray()
198
- if lib!='auto': self._printlog(f'writing {output} with {lib}')
199
- if lib=='pedalboard.io':
200
- #print(audio)
201
- import pedalboard.io
202
- with pedalboard.io.AudioFile(output, 'w', self.samplerate, self.audio.shape[0]) as f:
203
- f.write(self.audio)
204
- elif lib=='soundfile':
205
- audio=self.audio.T
206
- import soundfile
207
- soundfile.write(output, audio, self.samplerate)
208
- del audio
209
- elif lib=='auto':
210
- for i in libs:
211
- try:
212
- self.write(output, i)
213
- break
214
- except Exception as e:
215
- print(e)
216
-
217
- # elif lib=='pydub':
218
- # from pydub import AudioSegment
219
- # song = AudioSegment(self.audio.tobytes(), frame_rate=self.samplerate, sample_width=2, channels=2)
220
- # format = output.split('.')[-1]
221
- # if len(format) > 4:
222
- # format='mp3'
223
- # output = output + '.' + format
224
- # song.export(output, format=format)
225
-
226
- # def generate_beatmap(self, lib='madmom.BeatDetectionProcessor', split=None):
227
- # self.beatmap = beatmap(beatmap=None, samplerate=self.samplerate, length=len(self.audio[0]),caching=self.caching,log=self.log)
228
- # self.beatmap.generate(audio=self.audio, samplerate=self.samplerate, lib=lib, caching=self.caching, split=split, filename=self.filename)
229
-
230
- # def generate_hitmap(self, lib='madmom.BeatDetectionProcessor'):
231
- # self.hitmap=hitmap(beatmap=None, samplerate=self.samplerate, length = len(self.audio), caching=self.caching, log=self.log)
232
- # self.hitmap.generate(audio=self.audio, samplerate=self.samplerate, lib=lib, caching=self.caching, filename=self.filename)
233
-
234
- def generate_osu_beatmap(self, difficulties = [0.2, 0.1, 0.08, 0.06, 0.04, 0.02, 0.01, 0.005]):
235
- self.hitmap.osu(difficulties = difficulties)
236
- import shutil, os
237
- if self.path is not None:
238
- shutil.copyfile(self.path, 'BeatManipulator_TEMP/'+self.path.split('/')[-1])
239
- else: self.write('BeatManipulator_TEMP/audio.mp3')
240
- shutil.make_archive('BeatManipulator_TEMP', 'zip', 'BeatManipulator_TEMP')
241
- outputname = _outputfilename('', self.path, '_'+self.hitmap.hitlib, 'osz')
242
- if not os.path.exists(outputname):
243
- os.rename('BeatManipulator_TEMP.zip', outputname)
244
- else: print(f'{outputname} already exists!')
245
- shutil.rmtree('BeatManipulator_TEMP')
246
- self._printlog(f'Wrote {outputname}')
247
-
248
- def autotrim(self):
249
- self._printlog(f'autotrimming; ')
250
- n=0
251
- for i in self.audio[0]:
252
- if i>=0.0001:break
253
- n+=1
254
- if type(self.audio) is tuple or list: self.audio = numpy.asarray(self.audio)
255
- self.audio = numpy.asarray([self.audio[0,n:], self.audio[1,n:]])
256
- self.beatmap._toarray()
257
- if self.bm is not None:
258
- self.beatmap.beatmap=numpy.absolute(self.beatmap.beatmap-n)
259
- if self.hm is not None:
260
- print(self.hm)
261
- self.hitmap.beatmap=numpy.absolute(self.hitmap.beatmap-n)
262
- self._update()
263
-
264
- def beatswap(self, pattern: str, sep=',', smoothing=40, smoothing_mode='replace'):
265
- import math, numpy
266
- # get pattern size
267
- size=0
268
- #cut processing??? not worth it, it is really fast anyways
269
- if sep != ' ':
270
- if sep not in pattern: pattern=pattern.replace(' ', sep) # separator not in patterm, e.g. forgot commas
271
- while f'{sep}{sep}' in pattern: pattern = pattern.replace(f'{sep}{sep}', sep) # double separator
272
- pattern=pattern.replace(' ', '').split(sep)
273
- else:
274
- while ' ' in pattern: pattern = pattern.relace(' ', ' ')
275
- pattern=pattern.split(sep)
276
- self._printlog(f"beatswapping with {' '.join(pattern)}; ")
277
- prev,prevb = None,None
278
- for j in pattern:
279
- s=''
280
- if '?' not in j:
281
- for i in j:
282
- #get the math expression
283
- #print(f'j = {j}, s = {s}, i = {i}, size = {size}, prev = {prev}, prevb = {prevb}')
284
- if i.isdecimal() or i=='.' or i=='-' or i=='/' or i=='+' or i=='%': s=str(s)+str(i)
285
- #if got :, write it to size
286
- elif i==':':
287
- if s=='': s='0'
288
- size=max(math.ceil(float(_safer_eval(s))), size)
289
- s=''
290
- #if got ;, save the number and then add it
291
- elif i=='>':
292
- if s=='': s='0'
293
- size=max(math.ceil(float(_safer_eval(s))), size)
294
- prev = _safer_eval(s)-1
295
- s=''
296
- elif i=='<':
297
- if s=='': s='0'
298
- size=max(math.ceil(float(_safer_eval(s))), size)
299
- prevb = _safer_eval(s)
300
- s=''
301
- # if prev is defined, add it to s (a>b to a+b)
302
- elif prev is not None:
303
- if s=='': s='0'
304
- #print(1, _safer_eval(s), prev, float(_safer_eval(s))+float(prev))
305
- size=max(math.ceil(float(_safer_eval(s))+float(prev)), size)
306
- prev=None
307
- break
308
- #prevb : a<b to a-b
309
- elif prevb is not None:
310
- if s=='': s='0'
311
- #print(2, _safer_eval(s), prevb, float(_safer_eval(s))+float(prevb))
312
- size=max(math.ceil(float(_safer_eval(s))-float(prevb)), size)
313
- prevb=None
314
- break
315
- # i isn't digit or any of the symbols, so stop parsing
316
- elif s!='': break
317
- #print(f'end: j = {j}, s = {s}, i = {i}, size = {size}, prev = {prev}, prevb = {prevb}')
318
- if s=='': s='0'
319
- if s=='': s='0'
320
- size=max(math.ceil(float(_safer_eval(s))), size)
321
- if prev is not None:
322
- size=max(math.ceil(float(_safer_eval(s))+float(prev)), size)
323
- prev=None
324
- if prevb is not None:
325
- size=max(math.ceil(float(_safer_eval(s))-float(prevb)), size)
326
- prev=None
327
-
328
- self._audio_tolist()
329
- self.beatmap._toarray()
330
- # turns audio into a tuple with L and R channels
331
- self.audio=(self.audio[0], self.audio[1])
332
-
333
- # adds the part before the first beat
334
- result=(self.audio[0][:self.beatmap[0]],self.audio[1][:self.beatmap[0]])
335
- beat=numpy.asarray([[],[]])
336
-
337
- # size, iterations are integers
338
- size=int(max(size//1, 1))
339
-
340
- self.beatmap._add_beat_to_end()
341
-
342
- iterations=int(len(self.beatmap)//size)
343
 
344
- if 'random' in pattern[0].lower():
345
- import random
346
- for i in range(len(self.beatmap)):
347
 
348
- choice=random.randint(1,len(self.beatmap)-1)
349
- for a in range(len(self.audio)):
350
- try:
351
- beat=self.audio[a][self.beatmap[choice-1]:self.beatmap[choice]-smoothing]
352
- if smoothing>0: result[a].extend(numpy.linspace(result[a][-1],beat[0],smoothing))
353
- result[a].extend(beat)
354
- except IndexError: pass
355
- self.audio = result
356
- return
357
-
358
- if 'reverse' in pattern[0].lower():
359
- for a in range(len(self.audio)):
360
- for i in list(reversed(range(len(self.beatmap))))[:-1]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361
  try:
362
- beat=self.audio[a][self.beatmap[i-1]:self.beatmap[i]-smoothing]
363
- #print(self.beatmap[i-1],self.beatmap[i])
364
- #print(result[a][-1], beat[0])
365
- if smoothing>0: result[a].extend(numpy.linspace(result[a][-1],beat[0],smoothing))
366
- result[a].extend(beat)
367
- except IndexError: pass
368
-
369
- self.audio = result
370
- return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
371
 
372
- #print(len(result[0]))
373
- def beatswap_getnum(i: str, c: str):
374
- if c in i:
375
- try:
376
- x=i.index(c)+1
377
- z=''
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
378
  try:
379
- while i[x].isdecimal() or i[x]=='.' or i[x]=='-' or i[x]=='/' or i[x]=='+' or i[x]=='%':
380
- z+=i[x]
381
- x+=1
382
- return z
383
- except IndexError:
384
- return z
385
- except ValueError: return None
386
-
387
- #print(len(self.beatmap), size, iterations)
388
- # processing
389
- for j in range(iterations+1):
390
- for i in pattern:
391
- if '!' not in i:
392
- n,s,st,reverse,z, is_c, is_cr=0,'',None,False,None,False,False
393
- for c in i:
394
- n+=1
395
- #print('c =', s, ', st =', st, ', s =', s, ', n =,',n)
396
-
397
- # Get the character
398
- if c.isdecimal() or c=='.' or c=='-' or c=='/' or c=='+' or c=='%':
399
- s=str(s)+str(c)
400
-
401
- # If character is : - get start
402
- elif s!='' and (c==':' or c=='>' or c=='<'):
403
- #print ('Beat start:',s,'=', _safer_eval(s),'=',int(_safer_eval(s)//1), '+',j,'*',size,' =',int(_safer_eval(s)//1)+j*size, ', mod=',_safer_eval(s)%1)
404
- try:
405
- sti = _safer_eval(s)
406
- if c=='>': sti-=1
407
- st=self.beatmap[int(sti//1)+j*size ] + sti%1* (self.beatmap[int(sti//1)+j*size +1] - self.beatmap[int(sti//1)+j*size])
408
- if c == '>': is_c = True
409
- elif c=='<': is_cr = True
410
- else:
411
- is_c = False
412
- is_cr = False
413
- except IndexError: break
414
- s=''
415
-
416
- # create a beat
417
- if s!='' and (n==len(i) or not(c.isdecimal() or c=='.' or c=='-' or c=='/' or c=='+' or c=='%')):
418
-
419
- # start already exists, e.g. : or >
420
- if st is not None:
421
- #print ('Beat end: ',s,'=', _safer_eval(s),'=',int(_safer_eval(s)//1), '+',j,'*',size,' =',int(_safer_eval(s)//1)+j*size, ', mod=',_safer_eval(s)%1)
422
- try:
423
- #print(1, is_c, s, st)
424
- if is_c is False and is_cr is False:
425
- si = _safer_eval(s)
426
- s=self.beatmap[int(si//1)+j*size ] + si%1* (self.beatmap[int(si//1)+j*size +1] - self.beatmap[int(si//1)+j*size])
427
- elif is_c is True:
428
- si=sti+_safer_eval(s)
429
- s=(self.beatmap[int(si//1)+j*size ] + si%1* (self.beatmap[int(si//1)+j*size +1] - self.beatmap[int(si//1)+j*size]))
430
- is_c = False
431
- elif is_cr is True:
432
- si=sti-_safer_eval(s)
433
- s=(self.beatmap[int(si//1)+j*size ] + si%1* (self.beatmap[int(si//1)+j*size +1] - self.beatmap[int(si//1)+j*size]))
434
- #print(si, sti, st, s)
435
- st, s = s, st
436
- is_cr = False
437
- #print(2, is_c, s, st)
438
- except IndexError: break
439
- else:
440
- # start doesn't exist
441
- #print ('Beat start:',s,'=', _safer_eval(s),'=',int(_safer_eval(s)//1), '+',j,'*',size,'- 1 =',int(_safer_eval(s)//1)+j*size, ', mod=',_safer_eval(s)%1)
442
- #print ('Beat end: ',s,'=', _safer_eval(s),'=',int(_safer_eval(s)//1), '+',j,'*',size,' =',int(_safer_eval(s)//1)+j*size+1, ', mod=',_safer_eval(s)%1)
443
- try:
444
- si = _safer_eval(s)
445
- st=self.beatmap[int(si//1)+j*size-1 ] + si%1* (self.beatmap[int(si//1)+j*size +1] - self.beatmap[int(si//1)+j*size])
446
- s=self.beatmap[int(si//1)+j*size ] + si%1* (self.beatmap[int(si//1)+j*size +1] - self.beatmap[int(si//1)+j*size])
447
- except IndexError: break
448
-
449
- if st>s:
450
- s, st=st, s
451
- reverse=True
452
- if st<0: st=0
453
- if s<0 or st==s: continue
454
-
455
- # create the beat
456
- if len(self.audio)>1:
457
- if smoothing_mode=='add': beat=numpy.asarray([self.audio[0][int(st):int(s)],self.audio[1][int(st):int(s)]])
458
- else: beat=numpy.asarray([self.audio[0][int(st):int(s)-smoothing],self.audio[1][int(st):int(s)-smoothing]])
459
- else:
460
- if smoothing_mode=='add': beat=numpy.asarray([self.audio[0][int(st):int(s)]])
461
- else: beat=numpy.asarray([self.audio[0][int(st):int(s)-smoothing]])
462
-
463
- # process the beat
464
- # channels
465
- z=beatswap_getnum(i,'c')
466
- if z is not None:
467
- if z=='': beat[0],beat[1]=beat[1],beat[0]
468
- elif _safer_eval(z)==0:beat[0]*=0
469
- else:beat[1]*=0
470
-
471
- # volume
472
- z=beatswap_getnum(i,'v')
473
- if z is not None:
474
- if z=='': z='0'
475
- beat*=_safer_eval(z)
476
-
477
- z=beatswap_getnum(i,'t')
478
- if z is not None:
479
- if z=='': z='2'
480
- beat**=1/_safer_eval(z)
481
-
482
- # speed
483
- z=beatswap_getnum(i,'s')
484
- if z is not None:
485
- if z=='': z='2'
486
- z=_safer_eval(z)
487
- if z<1:
488
- beat=numpy.asarray((numpy.repeat(beat[0],int(1//z)),numpy.repeat(beat[1],int(1//z))))
489
- else:
490
- beat=numpy.asarray((beat[0,::int(z)],beat[1,::int(z)]))
491
-
492
- # bitcrush
493
- z=beatswap_getnum(i,'b')
494
- if z is not None:
495
- if z=='': z='3'
496
- z=1/_safer_eval(z)
497
- if z<1: beat=beat*z
498
- beat=numpy.around(beat, max(int(z), 1))
499
- if z<1: beat=beat/z
500
-
501
- # downsample
502
- z=beatswap_getnum(i,'d')
503
- if z is not None:
504
- if z=='': z='3'
505
- z=int(_safer_eval(z))
506
- beat=numpy.asarray((numpy.repeat(beat[0,::z],z),numpy.repeat(beat[1,::z],z)))
507
-
508
- # convert to list
509
- beat=beat.tolist()
510
-
511
- # effects with list
512
- # reverse
513
- if ('r' in i and reverse is False) or (reverse is True and 'r' not in i):
514
- beat=(beat[0][::-1],beat[1][::-1] )
515
-
516
- # add beat to the result
517
- for a in range(len(self.audio)):
518
- #print('Adding beat... a, s, st:', a, s, st, sep=', ')
519
- #print(result[a][-1])
520
- #print(beat[a][0])
521
- try:
522
- if smoothing>0: result[a].extend(numpy.linspace(result[a][-1],beat[a][0],smoothing))
523
- result[a].extend(beat[a])
524
- except IndexError: pass
525
- #print(len(result[0]))
526
-
527
- #
528
- break
529
-
530
- self.audio = result
531
- self._update()
532
-
533
- def beatsample(self, audio2, shift=0):
534
- self._printlog(f'beatsample; ')
535
- try: l=len(audio2[0])
536
- except (TypeError, IndexError):
537
- l=len(audio2)
538
- audio2=numpy.vstack((audio2,audio2))
539
- for i in range(len(self.beatmap)):
540
- #print(self.beatmap[i])
541
- try: self.audio[:,int(self.beatmap[i]) + int(float(shift) * (int(self.beatmap[i+1])-int(self.beatmap[i]))) : int(self.beatmap[i])+int(float(shift) * (int(self.beatmap[i+1])-int(self.beatmap[i])))+int(l)]+=audio2
542
- except (IndexError, ValueError): pass
543
- self._update()
544
-
545
- def hitsample(self, audio2=None):
546
- self._printlog(f'hitsample; ')
547
- from . import generate
548
- if audio2 is None:audio2=generate.saw(0.05, 1000, self.samplerate)
549
- try: l=len(audio2[0])
550
- except (TypeError, IndexError):
551
- l=len(audio2)
552
- audio2=numpy.vstack((audio2,audio2))
553
- #print(self.audio)
554
- self.audio=numpy.array(self.audio).copy()
555
- #print(self.audio)
556
- for i in range(len(self.hitmap)):
557
- try:
558
- #print('before', self.audio[:,int(self.hitmap[i])])
559
- self.audio[:,int(self.hitmap[i]) : int(self.hitmap[i]+l)]+=audio2
560
- #print('after ', self.audio[:,int(self.hitmap[i])])
561
- #print(self.hitmap[i])
562
- except (IndexError, ValueError): pass
563
- self._update()
564
-
565
- def sidechain(self, audio2, shift=0, smoothing=40):
566
- self._printlog(f'sidechain; ')
567
- try: l=len(audio2[0])
568
- except (TypeError, IndexError):
569
- l=len(audio2)
570
- audio2=numpy.vstack((audio2,audio2))
571
- for i in range(len(self.beatmap)):
572
- try: self.audio[:,int(self.beatmap[i])-smoothing + int(float(shift) * (int(self.beatmap[i+1])-int(self.beatmap[i]))) : int(self.beatmap[i])-smoothing+int(float(shift) * (int(self.beatmap[i+1])-int(self.beatmap[i])))+int(l)]*=audio2
573
- except (IndexError, ValueError): break
574
- self._update()
575
-
576
- def quick_beatswap(self, output:str='', pattern:str=None, scale:float=1, shift:float=0, start:float=0, end:float=None, autotrim:bool=True, autoscale:bool=False, autoinsert:bool=False, suffix:str=' (beatswap)', lib:str='madmom.BeatDetectionProcessor', log = True):
577
- """Generates beatmap if it isn't generated, applies beatswapping to the song and writes the processed song it next to the .py file. If you don't want to write the file, set output=None
578
-
579
- output: can be a relative or an absolute path to a folder or to a file. Filename will be created from the original filename + a suffix to avoid overwriting. If path already contains a filename which ends with audio file extension, such as .mp3, that filename will be used.
580
-
581
- pattern: the beatswapping pattern.
582
-
583
- scale: scales the beatmap, for example if generated beatmap is two times faster than the song you can slow it down by putting 0.5.
584
-
585
- shift: shifts the beatmap by this amount of unscaled beats
586
-
587
- start: position in seconds, beats before the position will not be manipulated
588
-
589
- end: position in seconds, same. Set to None by default.
590
-
591
- autotrim: trims silence in the beginning for better beat detection, True by default
592
-
593
- autoscale: scales beats so that they are between 10000 and 20000 samples long. Useful when you are processing a lot of files with similar BPMs, False by default.
594
-
595
- autoinsert: uses distance between beats and inserts beats at the beginning at that distance if possible. Set to False by default, sometimes it can fix shifted beatmaps and sometimes can add unwanted shift.
596
-
597
- suffix: suffix that will be appended to the filename
598
-
599
- lib: beat detection library"""
600
- if log is False and self.log is True:
601
- self.log = False
602
- self.beatmap.log=False
603
- log_disabled = True
604
- else: log_disabled = False
605
- self._printlog('___')
606
- scale = _safer_eval(scale)
607
- shift = _safer_eval(shift)
608
- if self.bm is None: self.beatmap.generate(lib=lib)
609
- if autotrim is True: self.autotrim()
610
- save=self.beatmap.beatmap.copy()
611
- if autoscale is True: self.beatmap.autoscale()
612
- if shift!=0: self.beatmap.shift(shift)
613
- if scale!=1: self.beatmap.scale(scale)
614
- if autoinsert is True: self.beatmap.autoinsert()
615
- if start!=0 or end is not None: self.beatmap.cut(start, end)
616
- self._printlog(f'pattern = {pattern}')
617
- if 'test' in pattern.lower():
618
- self.audio*=0.7
619
- self.beatmap.beatmap=save.copy()
620
- if autoinsert is True: self.beatmap.autoinsert()
621
- if start!=0 or end is not None: self.beatmap.cut(start, end)
622
- audio2, samplerate2=open_audio('samples/cowbell.flac')
623
- song.quick_beatsample(self, output=None, audio2=list(i[::3] for i in audio2), scale=8*scale, shift=0+shift, log=log)
624
- song.quick_beatsample(self, output=None, audio2=list(i[::2] for i in audio2), scale=8*scale, shift=1*scale+shift, log=log)
625
- song.quick_beatsample(self, output=None, audio2=audio2, scale=8*scale, shift=2*scale+shift, log=log)
626
- song.quick_beatsample(self, output=None, audio2=numpy.repeat(audio2,2,axis=1), scale=8*scale, shift=3*scale+shift, log=log)
627
- song.quick_beatsample(self, output=None, audio2=numpy.repeat(audio2,3,axis=1), scale=8*scale, shift=4*scale+shift, log=log)
628
- song.quick_beatsample(self, output=None, audio2=numpy.repeat(audio2,2,axis=1), scale=8*scale, shift=5*scale+shift, log=log)
629
- song.quick_beatsample(self, output=None, audio2=audio2, scale=8*scale, shift=6*scale+shift, log=log)
630
- song.quick_beatsample(self, output=None, audio2=list(i[::2] for i in audio2), scale=8*scale, shift=7*scale+shift, log=log)
631
-
632
- else: self.beatswap(pattern)
633
-
634
- if output is not None:
635
- if not (output.lower().endswith('.mp3') or output.lower().endswith('.wav') or output.lower().endswith('.flac') or output.lower().endswith('.ogg') or
636
- output.lower().endswith('.aac') or output.lower().endswith('.ac3') or output.lower().endswith('.aiff') or output.lower().endswith('.wma')):
637
- output=output+'.'.join(''.join(self.path.split('/')[-1]).split('.')[:-1])+suffix+'.mp3'
638
- self.write(output)
639
-
640
- self.beatmap.beatmap=save.copy()
641
- if log_disabled is True:
642
- self.log = True
643
- self.beatmap.log=True
644
-
645
-
646
- def quick_sidechain(self, output:str='', audio2:numpy.array=None, scale:float=1, shift:float=0, start:float=0, end:float=None, autotrim:bool=True, autoscale:bool=False, autoinsert:bool=False, filename2:str=None, suffix:str=' (sidechain)', lib:str='madmom.BeatDetectionProcessor', log=True):
647
- """Generates beatmap if it isn't generated, applies fake sidechain on each beat to the song and writes the processed song it next to the .py file. If you don't want to write the file, set output=None
648
-
649
- output: can be a relative or an absolute path to a folder or to a file. Filename will be created from the original filename + a suffix to avoid overwriting. If path already contains a filename which ends with audio file extension, such as .mp3, that filename will be used.
650
-
651
- audio2: sidechain impulse, basically a curve that the volume will be multiplied by. By default one will be generated with generate_sidechain()
652
-
653
- scale: scales the beatmap, for example if generated beatmap is two times faster than the song you can slow it down by putting 0.5.
654
-
655
- shift: shifts the beatmap by this amount of unscaled beats
656
-
657
- start: position in seconds, beats before the position will not be manipulated
658
-
659
- end: position in seconds, same. Set to None by default.
660
-
661
- autotrim: trims silence in the beginning for better beat detection, True by default
662
-
663
- autoscale: scales beats so that they are between 10000 and 20000 samples long. Useful when you are processing a lot of files with similar BPMs, False by default.
664
-
665
- autoinsert: uses distance between beats and inserts beats at the beginning at that distance if possible. Set to False by default, sometimes it can fix shifted beatmaps and sometimes can add unwanted shift.
666
-
667
- filename2: loads sidechain impulse from the file if audio2 if not specified
668
-
669
- suffix: suffix that will be appended to the filename
670
-
671
- lib: beat detection library"""
672
- if log is False and self.log is True:
673
- self.log = False
674
- log_disabled = True
675
- else: log_disabled = False
676
- self._printlog('___')
677
- scale = _safer_eval(scale)
678
- shift = _safer_eval(shift)
679
- if filename2 is None and audio2 is None:
680
- from . import generate
681
- audio2=generate.sidechain()
682
-
683
- if audio2 is None:
684
- audio2, samplerate2=open_audio(filename2)
685
-
686
- if self.bm is None: self.beatmap.generate(lib=lib)
687
- if autotrim is True: self.autotrim()
688
- save=self.beatmap.beatmap.copy()
689
- if autoscale is True: self.beatmap.autoscale()
690
- if shift!=0: self.beatmap.shift(shift)
691
- if scale!=1: self.beatmap.scale(scale)
692
- if autoinsert is True: self.beatmap.autoinsert()
693
- if start!=0 or end is not None: self.beatmap.cut(start, end)
694
- self.sidechain(audio2)
695
-
696
- if output is not None:
697
- if not (output.lower().endswith('.mp3') or output.lower().endswith('.wav') or output.lower().endswith('.flac') or output.lower().endswith('.ogg') or
698
- output.lower().endswith('.aac') or output.lower().endswith('.ac3') or output.lower().endswith('.aiff') or output.lower().endswith('.wma')):
699
- output=output+'.'.join(''.join(self.path.split('/')[-1]).split('.')[:-1])+suffix+'.mp3'
700
- self.write(output)
701
-
702
- self.beatmap.beatmap=save.copy()
703
- if log_disabled is True: self.log = True
704
-
705
- def quick_beatsample(self, output:str='', filename2:str=None, scale:float=1, shift:float=0, start:float=0, end:float=None, autotrim:bool=True, autoscale:bool=False, autoinsert:bool=False, audio2:numpy.array=None, suffix:str=' (BeatSample)', lib:str='madmom.BeatDetectionProcessor', log=True):
706
- """Generates beatmap if it isn't generated, adds chosen sample to each beat of the song and writes the processed song it next to the .py file. If you don't want to write the file, set output=None
707
-
708
- output: can be a relative or an absolute path to a folder or to a file. Filename will be created from the original filename + a suffix to avoid overwriting. If path already contains a filename which ends with audio file extension, such as .mp3, that filename will be used.
709
-
710
- filename2: path to the sample.
711
-
712
- scale: scales the beatmap, for example if generated beatmap is two times faster than the song you can slow it down by putting 0.5.
713
-
714
- shift: shifts the beatmap by this amount of unscaled beats
715
-
716
- start: position in seconds, beats before the position will not be manipulated
717
-
718
- end: position in seconds, same. Set to None by default.
719
-
720
- autotrim: trims silence in the beginning for better beat detection, True by default
721
-
722
- autoscale: scales beats so that they are between 10000 and 20000 samples long. Useful when you are processing a lot of files with similar BPMs, False by default.
723
-
724
- autoinsert: uses distance between beats and inserts beats at the beginning at that distance if possible. Set to False by default, sometimes it can fix shifted beatmaps and sometimes can add unwanted shift.
725
-
726
- suffix: suffix that will be appended to the filename
727
-
728
- lib: beat detection library"""
729
- if log is False and self.log is True:
730
- self.log = False
731
- log_disabled = True
732
- else: log_disabled = False
733
- self._printlog('___')
734
- scale = _safer_eval(scale)
735
- shift = _safer_eval(shift)
736
- if filename2 is None and audio2 is None:
737
- from tkinter.filedialog import askopenfilename
738
- filename2 = askopenfilename(title='select sidechain impulse', filetypes=[("mp3", ".mp3"),("wav", ".wav"),("flac", ".flac"),("ogg", ".ogg"),("wma", ".wma")])
739
-
740
- if audio2 is None:
741
- audio2, samplerate2=open_audio(filename2)
742
-
743
- if self.bm is None: self.beatmap.generate(lib=lib)
744
- if autotrim is True: self.autotrim()
745
- save=self.beatmap.beatmap.copy()
746
- if autoscale is True: self.beatmap.autoscale()
747
- if shift!=0: self.beatmap.shift(shift)
748
- if scale!=1: self.beatmap.scale(scale)
749
- if autoinsert is True: self.beatmap.autoinsert()
750
- if start!=0 or end is not None: self.beatmap.cut(start, end)
751
- self.beatsample(audio2)
752
-
753
- if output is not None:
754
- if not (output.lower().endswith('.mp3') or output.lower().endswith('.wav') or output.lower().endswith('.flac') or output.lower().endswith('.ogg') or
755
- output.lower().endswith('.aac') or output.lower().endswith('.ac3') or output.lower().endswith('.aiff') or output.lower().endswith('.wma')):
756
- output=output+'.'.join(''.join(self.path.split('/')[-1]).split('.')[:-1])+suffix+'.mp3'
757
- self.write(output)
758
- self.beatmap.beatmap=save.copy()
759
- if log_disabled is True: self.log = True
760
-
761
- def spectogram_to_audio(self):
762
- self.audio = self.spectogram.toaudio()
763
-
764
- def beat_image_to_audio(self):
765
- self.audio = self.beat_image.toaudio()
766
-
767
-
768
- def fix_beatmap(filename, lib='madmom.BeatDetectionProcessor', scale=1, shift=0):
769
- if scale==1 and shift==0:
770
- print('scale = 1, shift = 0: no changes have been made.')
771
- return
772
- track=song(filename)
773
- audio_id=hex(len(track.audio[0]))
774
- cacheDir="SavedBeatmaps/" + ''.join(track.filename.split('/')[-1]) + "_"+lib+"_"+audio_id+'.txt'
775
- import os
776
- if not os.path.exists(cacheDir):
777
- print(f"beatmap isn't generated: {filename}")
778
- return
779
- track.beatmap.generate(lib=lib)
780
- track.beatmap.shift(shift)
781
- track.beatmap.scale(scale)
782
- if not os.path.exists('SavedBeatmaps'):
783
- os.mkdir('SavedBeatmaps')
784
- a=input(f'Are you sure you want to overwrite {cacheDir} using scale = {scale}; shift = {shift}? ("y" to continue): ')
785
- if 'n' in a.lower() or not 'y' in a.lower():
786
- print('Operation canceled.')
787
- return
788
- else:
789
- track.beatmap._toarray()
790
- numpy.savetxt(cacheDir, track.bm.astype(int), fmt='%d')
791
- print('Beatmap overwritten.')
792
-
793
- def delete_beatmap(filename, lib='madmom.BeatDetectionProcessor'):
794
- track=song(filename)
795
- audio_id=hex(len(track.audio[0]))
796
- import os
797
- if not os.path.exists('SavedBeatmaps'):
798
- os.mkdir('SavedBeatmaps')
799
- cacheDir="SavedBeatmaps/" + ''.join(track.filename.split('/')[-1]) + "_"+lib+"_"+audio_id+'.txt'
800
- if not os.path.exists(cacheDir):
801
- print(f"beatmap doesn't exist: {filename}")
802
- return
803
- a=input(f'Are you sure you want to delete {cacheDir}? ("y" to continue): ')
804
- if 'n' in a.lower() or not 'y' in a.lower():
805
- print('Operation canceled.')
806
- return
807
- else:
808
- os.remove(cacheDir)
809
- print('Beatmap deleted.')
810
-
811
-
812
- def _tosong(audio=None, bmap=None, samplerate=None, log=True):
813
- from .wrapper import _song_copy
814
- if isinstance(audio, str) or audio is None: audio = song(audio, bmap=bmap, log = log)
815
- elif isinstance(audio, list) or isinstance(audio, numpy.ndarray) or isinstance(audio, tuple):
816
- assert samplerate is not None, "If audio is an array, samplerate must be provided"
817
- if len(audio)>16 and isinstance(audio[0], list) or isinstance(audio[0], numpy.ndarray) or isinstance(audio[0], tuple):
818
- audio = numpy.asarray(audio).T
819
- audio = song(audio=audio, samplerate=samplerate, bmap=bmap, log = log)
820
- elif isinstance(audio, song):
821
- audio = _song_copy(audio)
822
- audio.log, audio.beatmap.log, audio.beat_image.log = log, log, log
823
- else: assert False, f"Audio should be either a path to a file, a list/array/tuple, a beat_manipulator.song object, or None for a pick file dialogue, but it is {type(audio)}"
824
- return audio
825
-
826
- def beatswap(pattern: str, audio = None, scale: float = 1, shift: float = 0, output='', samplerate = None, bmap = None, log = True, suffix=' (beatswap)'):
827
- audio = _tosong(audio=audio, bmap=bmap, samplerate=samplerate, log=log)
828
- output = _outputfilename(output=output, filename=audio.path, suffix=suffix)
829
- audio.quick_beatswap(pattern = pattern, scale=scale, shift=shift, output=output)
830
- return audio.path
831
-
832
- def generate_beat_image(audio = None, scale: float = 1, shift: float = 0, output='', samplerate = None, bmap = None, log = True, ext='png', maximum=4096):
833
- audio = _tosong(audio=audio, bmap=bmap, samplerate=samplerate, log=log)
834
- output = _outputfilename(output=output, filename=audio.path, ext=ext, suffix = '')
835
- audio.beatmap.generate()
836
- audio.beatmap.scale(scale)
837
- audio.beatmap.shift(shift)
838
- audio.beat_image.generate()
839
- audio.beat_image.write(output=output, maximum = maximum)
840
- return output
841
-
842
- def generate_osu_map(audio = None, samplerate = None, log = True, difficulties = [0.2, 0.1, 0.08, 0.06, 0.04, 0.02, 0.01, 0.005]):
843
- audio = _tosong(audio=audio, samplerate=samplerate, log=log)
844
- audio.hitmap.generate()
845
- audio.generate_osu_beatmap(difficulties=difficulties)
846
- return audio.path
 
1
+ import numpy as np, scipy.interpolate
2
+ from . import io, utils
3
+ from .effects import BM_EFFECTS
4
+ from .metrics import BM_METRICS
5
+ from .presets import BM_SAMPLES
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
 
 
 
 
 
7
 
8
+ class song:
9
+ def __init__(self, audio = None, sr:int=None, log=True):
10
+ if audio is None:
11
+ from tkinter import filedialog
12
+ audio = filedialog.askopenfilename()
13
+
14
+ if isinstance(audio, song): self.path = audio.path
15
+ self.audio, self.sr = io._load(audio=audio, sr=sr)
16
+
17
+ # unique filename is needed to generate/compare filenames for cached beatmaps
18
+ if isinstance(audio, str):
19
+ self.path = audio
20
+ elif not isinstance(audio, song):
21
+ self.path = 'unknown_' + str(hex(int(np.sum(self.audio)*(10**18))))
22
+
23
+ self.log = log
24
+ self.beatmap = None
25
+ self.normalized = None
26
+
27
+ def _slice(self, a):
28
+ if a is None: return None
29
+ elif isinstance(a, float):
30
+ if (a_dec:=a%1) != 0:
31
+ a_int = int(int(a)//1)
32
+ start = self.beatmap[a_int]
33
+ return int(start + a_dec * (self.beatmap[a_int+1] - start))
34
+ else:
35
+ return self.beatmap[int(a)]
36
+ elif isinstance(a, int): return self.beatmap[a]
37
+ else: raise TypeError(f'slice indices must be int, float, or None, not {type(a)}. Indice is {a}')
38
+
39
+ def __getitem__(self, s):
40
+ if isinstance(s, slice):
41
+ start = s.start
42
+ stop = s.stop
43
+ step = s.step
44
+ if start is not None and stop is not None:
45
+ if start > stop:
46
+ is_reversed = -1
47
+ start, stop = stop, start
48
+ else: is_reversed = None
49
+ if step is None or step == 1:
50
+ start = self._slice(start)
51
+ stop = self._slice(stop)
52
+ if isinstance(self.audio, list): return [self.audio[0][start:stop:is_reversed],self.audio[1][start:stop:is_reversed]]
53
+ else: return self.audio[:,start:stop:is_reversed]
54
+ else:
55
+ i = s.start if s.start is not None else 0
56
+ end = s.stop if s.stop is not None else len(self.beatmap)
57
+ if i > end:
58
+ step = -step
59
+ if step > 0: i, end = end-2, i
60
+ elif step < 0: i, end = end-2, i
61
+ if step < 0:
62
+ is_reversed = True
63
+ end -= 1
64
+ else: is_reversed = False
65
+ pattern = ''
66
+ while ((i > end) if is_reversed else (i < end)):
67
+ pattern+=f'{i},'
68
+ i+=step
69
+ song_copy = song(audio = self.audio, sr = self.sr, log = False)
70
+ song_copy.beatmap = self.beatmap.copy()
71
+ song_copy.beatmap = np.insert(song_copy.beatmap, 0, 0)
72
+ result = song_copy.beatswap(pattern = pattern, return_audio = True)
73
+ if isinstance(self.audio, np.ndarray): return result
74
+ else: return result.tolist()
75
+
76
+ elif isinstance(s, float):
77
+ start = self._slice(s-1)
78
+ stop = self._slice(s)
79
+ if isinstance(self.audio, list): return [self.audio[0][start:stop],self.audio[1][start:stop]]
80
+ else: return self.audio[:,start:stop]
81
+ elif isinstance(s, int):
82
+ start = self.beatmap[s-1]
83
+ stop = self.beatmap[s]
84
+ if isinstance(self.audio, list): return [self.audio[0][start:stop],self.audio[1][start:stop]]
85
+ else: return self.audio[:,start:stop]
86
+ elif isinstance(s, tuple):
87
+ start = self._slice(s[0])
88
+ stop = self._slice(s[0] + s[1])
89
+ if stop<0:
90
+ start -= stop
91
+ stop = -stop
92
+ step = -1
93
+ else: step = None
94
+ if isinstance(self.audio, list): return [self.audio[0][start:stop:step],self.audio[1][start:stop:step]]
95
+ else: return self.audio[:,start:stop:step]
96
+ elif isinstance(s, list):
97
+ start = s[0]
98
+ stop = s[1] if len(s) > 1 else None
99
+ if start > stop:
100
+ step = -1
101
+ start, stop = stop, start
102
+ else: step = None
103
+ start = self._slice(start)
104
+ stop = self._slice(stop)
105
+ if step is not None and stop is None: stop = self._slice(start + s.step)
106
+ if isinstance(self.audio, list): return [self.audio[0][start:stop:step],self.audio[1][start:stop:step]]
107
+ else: return self.audio[:,start:stop:step]
108
+ elif isinstance(s, str):
109
+ return self.beatswap(pattern = s, return_audio = True)
110
+
111
+
112
+ else: raise TypeError(f'list indices must be int/float/slice/tuple, not {type(s)}; perhaps you missed a comma? Slice is `{s}`')
113
+
114
+
115
+ def _print(self, *args, end=None, sep=None):
116
+ if self.log: print(*args, end=end, sep=sep)
117
+
118
+
119
+ def write(self, output='', ext='mp3', suffix=' (beatswap)', literal_output=False):
120
+ """writes"""
121
+ if literal_output is False: output = io._outputfilename(output, filename=self.path, suffix=suffix, ext=ext)
122
+ io.write_audio(audio=self.audio, sr=self.sr, output=output, log=self.log)
123
+ return output
124
+
125
+
126
+ def beatmap_generate(self, lib='madmom.BeatDetectionProcessor', caching = True, load_settings = True):
127
+ """Find beat positions"""
128
+ from . import beatmap
129
+ self.beatmap = beatmap.generate(audio = self.audio, sr = self.sr, lib=lib, caching=caching, filename = self.path, log = self.log, load_settings = load_settings)
130
+ if load_settings is True:
131
+ audio_id=hex(len(self.audio[0]))
132
+ settingsDir="beat_manipulator/beatmaps/" + ''.join(self.path.split('/')[-1]) + "_"+lib+"_"+audio_id+'_settings.txt'
133
+ import os
134
+ if os.path.exists(settingsDir):
135
+ with open(settingsDir, 'r') as f:
136
+ settings = f.read().split(',')
137
+ if settings[3] != None: self.normalized = settings[3]
138
+ self.beatmap_default = self.beatmap.copy()
139
+ self.lib = lib
140
+
141
+ def beatmap_scale(self, scale:float):
142
+ from . import beatmap
143
+ self.beatmap = beatmap.scale(beatmap = self.beatmap, scale = scale, log = self.log)
144
+
145
+ def beatmap_shift(self, shift:float, mode = 1):
146
+ from . import beatmap
147
+ self.beatmap = beatmap.shift(beatmap = self.beatmap, shift = shift, log = self.log, mode = mode)
148
+
149
+ def beatmap_reset(self):
150
+ self.beatmap = self.beatmap_default.copy()
151
+
152
+ def beatmap_adjust(self, adjust = 500):
153
+ self.beatmap = np.append(np.sort(np.absolute(self.beatmap - adjust)), len(self.audio[0]))
154
+
155
+ def beatmap_save_settings(self, scale: float = None, shift: float = None, adjust: int = None, normalized = None, overwrite = 'ask'):
156
+ from . import beatmap
157
+ if self.beatmap is None: self.beatmap_generate()
158
+ beatmap.save_settings(audio = self.audio, filename = self.path, scale = scale, shift = shift,adjust = adjust, normalized = normalized, log=self.log, overwrite=overwrite, lib = self.lib)
159
+
160
+ def beatswap(self, pattern = '1;"cowbell"s3v2, 2;"cowbell"s2, 3;"cowbell", 4;"cowbell"s0.5, 5;"cowbell"s0.25, 6;"cowbell"s0.4, 7;"cowbell"s0.8, 8;"cowbell"s1.6',
161
+ scale:float = 1, shift:float = 0, length = None, samples:dict = BM_SAMPLES, effects:dict = BM_EFFECTS, metrics:dict = BM_METRICS, smoothing: int = 100, adjust=500, return_audio = False, normalize = False):
162
+
163
+ if normalize is True:
164
+ self.normalize_beats()
165
+ if self.beatmap is None: self.beatmap_generate()
166
+ beatmap_default = self.beatmap.copy()
167
+ self.beatmap = np.append(np.sort(np.absolute(self.beatmap - adjust)), len(self.audio[0]))
168
+ self.beatmap_shift(shift)
169
+ self.beatmap_scale(scale)
170
+
171
+ # baked in presets
172
+ #reverse
173
+ if pattern.lower() == 'reverse':
174
+ if return_audio is False:
175
+ self.audio = self[::-1]
176
+ self.beatmap = beatmap_default.copy()
177
+ return
178
+ else:
179
+ result = self[::-1]
180
+ self.beatmap = beatmap_default.copy()
181
+ return result
182
+ # shuffle
183
+ elif pattern.lower() == 'shuffle':
184
+ import random
185
+ beats = list(range(len(self.beatmap)))
186
+ random.shuffle(beats)
187
+ beats = ','.join(list(str(i) for i in beats))
188
+ if return_audio is False:
189
+ self.beatswap(beats)
190
+ self.beatmap = beatmap_default.copy()
191
+ return
192
+ else:
193
+ result = self.beatswap(beats, return_audio = True)
194
+ self.beatmap = beatmap_default.copy()
195
+ return result
196
+ # test
197
+ elif pattern.lower() == 'test':
198
+ if return_audio is False:
199
+ self.beatswap('1;"cowbell"s3v2, 2;"cowbell"s2, 3;"cowbell", 4;"cowbell"s0.5, 5;"cowbell"s0.25, 6;"cowbell"s0.4, 7;"cowbell"s0.8, 8;"cowbell"s1.6')
200
+ self.beatmap = beatmap_default.copy()
201
+ return
202
+ else:
203
+ result = self.beatswap('1;"cowbell"s3v2, 2;"cowbell"s2, 3;"cowbell", 4;"cowbell"s0.5, 5;"cowbell"s0.25, 6;"cowbell"s0.4, 7;"cowbell"s0.8, 8;"cowbell"s1.6', return_audio = True)
204
+ self.beatmap = beatmap_default.copy()
205
+ return result
206
+ # random
207
+ elif pattern.lower() == 'random':
208
+ import random,math
209
+ pattern = ''
210
+ rand_length=0
211
+ while True:
212
+ rand_num = int(math.floor(random.triangular(1, 16, rand_length-1)))
213
+ if random.uniform(0, rand_num)>rand_length: rand_num = rand_length+1
214
+ rand_slice = random.choices(['','>0.5','>0.25', '<0.5', '<0.25', '<1/3', '<2/3', '>1/3', '>2/3', '<0.75', '>0.75',
215
+ f'>{random.uniform(0.01,2)}', f'<{random.uniform(0.01,2)}'], weights = [13,1,1,1,1,1,1,1,1,1,1,1,1], k=1)[0]
216
+
217
+ rand_effect = random.choices(['', 's0.5', 's2', f's{random.triangular(0.1,1,4)}', 'r','v0.5', 'v2', 'v0',
218
+ f'd{int(random.triangular(1,8,16))}', 'g', 'c', 'c0', 'c1', f'b{int(random.triangular(1,8,4))}'],
219
+ weights=[30, 2, 2, 2, 2, 1, 1, 2, 2, 1, 2, 2, 2, 1], k=1)[0]
220
+
221
+ rand_join = random.choices([', ', ';'], weights = [5, 1], k=1)[0]
222
+ pattern += f'{rand_num}{rand_slice}{rand_effect}{rand_join}'
223
+ if rand_join == ',': rand_length+=1
224
+ if rand_length in [4, 8, 16]:
225
+ if random.uniform(rand_num,16)>14: break
226
+ else:
227
+ if random.uniform(rand_num,16)>15.5: break
228
+ pattern_length = 4
229
+ if rand_length > 6: pattern_length = 8
230
+ if rand_length > 12: pattern_length = 16
231
+ if rand_length > 24: pattern_length = 32
232
+
233
+
234
+
235
+ from . import parse
236
+ pattern, operators, pattern_length, shuffle_groups, shuffle_beats, c_slice, c_misc, c_join = parse.parse(pattern = pattern, samples = samples, pattern_length = length, log = self.log)
237
+
238
+ #print(f'pattern length = {pattern_length}')
239
+
240
+ # beatswap
241
+ n=-1
242
+ tries = 0
243
+ metric = None
244
+ result=[self.audio[:,:self.beatmap[0]]]
245
+ #for i in pattern: print(i)
246
 
 
247
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
249
 
250
+ # loop over pattern until it reaches the last beat
251
+ while n*pattern_length <= len(self.beatmap):
252
+ n+=1
253
 
254
+ # Every time pattern loops, shuffles beats with #
255
+ if len(shuffle_beats) > 0:
256
+ pattern = parse._shuffle(pattern, shuffle_beats, shuffle_groups)
257
+
258
+ # Loops over all beats in pattern
259
+ for num, b in enumerate(pattern):
260
+ if len(b) == 4: beat = b[3] # Sample has length 4
261
+ else: beat = b[0] # Else take the beat
262
+
263
+ if beat is not None:
264
+ beat_as_string = ''.join(beat) if isinstance(beat, list) else beat
265
+ # Skips `!` beats
266
+ if c_misc[9] in beat_as_string: continue
267
+
268
+ # Audio is a sample or a song
269
+ if len(b) == 4:
270
+ audio = b[0]
271
+
272
+ # Audio is a song
273
+ if b[2] == c_misc[10]:
274
+ try:
275
+
276
+ # Song slice is a single beat, takes it
277
+ if isinstance(beat, str):
278
+ # random beat if `@` in beat (`_` is separator)
279
+ if c_misc[4] in beat: beat = parse._random(beat, rchar = c_misc[4], schar = c_misc[5], length = pattern_length)
280
+ beat = utils._safer_eval(beat) + pattern_length*n
281
+ while beat > len(audio.beatmap)-1: beat = 1 + beat - len(audio.beatmap)
282
+ beat = audio[beat]
283
+
284
+ # Song slice is a range of beats, takes the beats
285
+ elif isinstance(beat, list):
286
+ beat = beat.copy()
287
+ for i in range(len(beat)-1): # no separator
288
+ if c_misc[4] in beat[i]: beat[i] = parse._random(beat[i], rchar = c_misc[4], schar = c_misc[5], length = pattern_length)
289
+ beat[i] = utils._safer_eval(beat[i])
290
+ while beat[i] + pattern_length*n > len(audio.beatmap)-1: beat[i] = 1 + beat[i] - len(audio.beatmap)
291
+ if beat[2] == c_slice[0]: beat = audio[beat[0] + pattern_length*n : beat[1] + pattern_length*n]
292
+ elif beat[2] == c_slice[1]: beat = audio[beat[0] - 1 + pattern_length*n: beat[0] - 1 + beat[1] + pattern_length*n]
293
+ elif beat[2] == c_slice[2]: beat = audio[beat[0] - beat[1] + pattern_length*n : beat[0] + pattern_length*n]
294
+
295
+ # No Song slice, take whole song
296
+ elif beat is None: beat = audio.audio
297
+
298
+ except IndexError as e:
299
+ print(e)
300
+ tries += 1
301
+ if tries > 30: break
302
+ continue
303
+
304
+ # Audio is an audio file
305
+ else:
306
+ # No audio slice, takes whole audio
307
+ if beat is None: beat = audio
308
+
309
+ # Audio slice, takes part of the audio
310
+ elif isinstance(beat, list):
311
+ audio_length = len(audio[0])
312
+ beat = [min(int(utils._safer_eval(beat[0])*audio_length), audio_length-1), min(int(utils._safer_eval(beat[1])*audio_length), audio_length-1)]
313
+ if beat[0] > beat[1]:
314
+ beat[0], beat[1] = beat[1], beat[0]
315
+ step = -1
316
+ else: step = None
317
+ beat = audio[:, beat[0] : beat[1] : step]
318
+
319
+ # Audio is a beat
320
+ else:
321
  try:
322
+ beat_str = beat if isinstance(beat, str) else ''.join(beat)
323
+ # Takes a single beat
324
+ if isinstance(beat, str):
325
+ if c_misc[4] in beat: beat = parse._random(beat, rchar = c_misc[4], schar = c_misc[5], length = pattern_length)
326
+ beat = self[utils._safer_eval(beat) + pattern_length*n]
327
+
328
+ # Takes a range of beats
329
+ elif isinstance(beat, list):
330
+ beat = beat.copy()
331
+ for i in range(len(beat)-1): # no separator
332
+ if c_misc[4] in beat[i]: beat[i] = parse._random(beat[i], rchar = c_misc[4], schar = c_misc[5], length = pattern_length)
333
+ beat[i] = utils._safer_eval(beat[i])
334
+ if beat[2] == c_slice[0]: beat = self[beat[0] + pattern_length*n : beat[1] + pattern_length*n]
335
+ elif beat[2] == c_slice[1]: beat = self[beat[0] - 1 + pattern_length*n: beat[0] - 1 + beat[1] + pattern_length*n]
336
+ elif beat[2] == c_slice[2]: beat = self[beat[0] - beat[1] + pattern_length*n : beat[0] + pattern_length*n]
337
+
338
+ # create a variable if `%` in beat
339
+ if c_misc[7] in beat_str: metric = parse._metric_get(beat_str, beat, metrics, c_misc[7])
340
+
341
+ except IndexError:
342
+ tries += 1
343
+ if tries > 30: break
344
+ continue
345
+
346
+ if len(beat[0])<1: continue #Ignores empty beats
347
+
348
+ # Applies effects
349
+ effect = b[1]
350
+ for e in effect:
351
+ if e[0] in effects:
352
+ v = e[1]
353
+ e = effects[e[0]]
354
+ # parse effect value
355
+ if isinstance(v, str):
356
+ if metric is not None: v = parse._metric_replace(v, metric, c_misc[7])
357
+ v = utils._safer_eval(v)
358
+
359
+ # effects
360
+ if e == 'volume':
361
+ if v is None: v = 0
362
+ beat = beat * v
363
+ elif e == 'downsample':
364
+ if v is None: v = 8
365
+ beat = np.repeat(beat[:,::v], v, axis=1)
366
+ elif e == 'gradient':
367
+ beat = np.gradient(beat, axis=1)
368
+ elif e == 'reverse':
369
+ beat = beat[:,::-1]
370
+ else:
371
+ beat = e(beat, v)
372
+
373
+ beat = np.clip(beat, -1, 1)
374
+
375
+ # Adds the processed beat to list of beats.
376
+ # Separator is `,`
377
+ if operators[num] == c_join[0]:
378
+ result.append(beat)
379
+
380
+ # Makes sure beat doesn't get added on top of previous beat multiple times when pattern is out of range of song beats, to avoid distorted end.
381
+ elif tries<2:
382
+
383
+ # Separator is `;` - always use first beat length, normalizes volume to 1.5
384
+ if operators[num] == c_join[1]:
385
+ length = len(beat[0])
386
+ prev_length = len(result[-1][0])
387
+ if length > prev_length:
388
+ result[-1] += beat[:,:prev_length]
389
+ else:
390
+ result[-1][:,:length] += beat
391
+ limit = np.max(result[-1])
392
+ if limit > 1.5:
393
+ result[-1] /= limit*0.75
394
 
395
+ # Separator is `~` - cuts to shortest
396
+ elif operators[num] == c_join[2]:
397
+ minimum = min(len(beat[0]), len(result[-1][0]))
398
+ result[-1] = beat[:,:minimum-1] + result[-1][:,:minimum-1]
399
+
400
+ # Separator is `&` - extends to longest
401
+ elif operators[num] == c_join[3]:
402
+ length = len(beat[0])
403
+ prev_length = len(result[-1][0])
404
+ if length > prev_length:
405
+ beat[:,:prev_length] += result[-1]
406
+ result[-1] = beat
407
+ else:
408
+ result[-1][:,:length] += beat
409
+
410
+ # Separator is `^` - uses first beat length and multiplies beats, used for sidechain
411
+ elif operators[num] == c_join[4]:
412
+ length = len(beat[0])
413
+ prev_length = len(result[-1][0])
414
+ if length > prev_length:
415
+ result[-1] *= beat[:,:prev_length]
416
+ else:
417
+ result[-1][:,:length] *= beat
418
+
419
+
420
+ # Separator is `$` - always use first beat length, additionally sidechains first beat by second
421
+ elif operators[num] == c_join[5]:
422
+ from . import effects
423
+ length = len(beat[0])
424
+ prev_length = len(result[-1][0])
425
+ if length > prev_length:
426
+ result[-1] *= effects.to_sidechain(beat[:,:prev_length])
427
+ result[-1] += beat[:,:prev_length]
428
+ else:
429
+ result[-1][:,:length] *= effects.to_sidechain(beat)
430
+ result[-1][:,:length] += beat
431
+
432
+ # Separator is `}` - always use first beat length
433
+ elif operators[num] == c_join[6]:
434
+ length = len(beat[0])
435
+ prev_length = len(result[-1][0])
436
+ if length > prev_length:
437
+ result[-1] += beat[:,:prev_length]
438
+ else:
439
+ result[-1][:,:length] += beat
440
+
441
+
442
+ # smoothing
443
+ for i in range(len(result)-1):
444
+ current1 = result[i][0][-2]
445
+ current2 = result[i][0][-1]
446
+ following1 = result[i+1][0][0]
447
+ following2 = result[i+1][0][1]
448
+ num = (abs(following1 - (current2 + (current2 - current1))) + abs(current2 - (following1 + (following1 - following2))))/2
449
+ if num > 0.0:
450
+ num = int(smoothing*num)
451
+ if num>3:
452
  try:
453
+ line = scipy.interpolate.CubicSpline([0, num+1], [0, following1], bc_type='clamped')(np.arange(0, num, 1))
454
+ #print(line)
455
+ line2 = np.linspace(1, 0, num)**0.5
456
+ result[i][0][-num:] *= line2
457
+ result[i][1][-num:] *= line2
458
+ result[i][0][-num:] += line
459
+ result[i][1][-num:] += line
460
+ except (IndexError, ValueError): pass
461
+
462
+ self.beatmap = beatmap_default.copy()
463
+ # Beats are conjoined into a song
464
+ import functools
465
+ import operator
466
+ # Makes a [l, r, l, r, ...] list of beats (left and right channels)
467
+ result = functools.reduce(operator.iconcat, result, [])
468
+
469
+ # Every first beat is conjoined into left channel, every second beat is conjoined into right channel
470
+ if return_audio is False: self.audio = np.array([functools.reduce(operator.iconcat, result[::2], []), functools.reduce(operator.iconcat, result[1:][::2], [])])
471
+ else: return np.array([functools.reduce(operator.iconcat, result[::2], []), functools.reduce(operator.iconcat, result[1:][::2], [])])
472
+
473
+ def normalize_beats(self):
474
+ if self.normalized is not None:
475
+ if ',' in self.normalized:
476
+ self.beatswap(pattern = self.normalized)
477
+ else:
478
+ from . import presets
479
+ self.beatswap(*presets.get(self.normalized))
480
+
481
+ def image_generate(self, scale=1, shift=0, mode = 'median'):
482
+ if self.beatmap is None: self.beatmap_generate()
483
+ beatmap_default = self.beatmap.copy()
484
+ self.beatmap_shift(shift)
485
+ self.beatmap_scale(scale)
486
+ from .image import generate as image_generate
487
+ self.image = image_generate(song = self, mode = mode, log = self.log)
488
+ self.beatmap = beatmap_default.copy()
489
+
490
+ def image_write(self, output='', mode = 'color', max_size = 4096, ext = 'png', rotate=True, suffix = ''):
491
+ from .image import write as image_write
492
+ output = io._outputfilename(output, self.path, ext=ext, suffix = suffix)
493
+ image_write(self.image, output = output, mode = mode, max_size = max_size , rotate = rotate)
494
+ return output
495
+
496
+
497
+
498
+ def beatswap(audio = None, pattern = 'test', scale = 1, shift = 0, length = None, sr = None, output = '', log = True, suffix = ' (beatswap)', copy = True):
499
+ if not isinstance(audio, song): audio = song(audio = audio, sr = sr, log = log)
500
+ elif copy is True:
501
+ beatmap = audio.beatmap
502
+ path = audio.path
503
+ audio = song(audio = audio.audio, sr = audio.sr)
504
+ audio.beatmap = beatmap
505
+ audio.path = path
506
+ audio.beatswap(pattern = pattern, scale = scale, shift = shift, length = length)
507
+ if output is not None:
508
+ return audio.write(output = output, suffix = suffix)
509
+ else: return audio
510
+
511
+ def image(audio, scale = 1, shift = 0, sr = None, output = '', log = True, suffix = '', max_size = 4096):
512
+ if not isinstance(audio, song): audio = song(audio = audio, sr = sr, log = log)
513
+ audio.image_generate(scale = scale, shift = shift)
514
+ if output is not None:
515
+ return audio.image_write(output = output, max_size=max_size, suffix=suffix)
516
+ else: return audio.image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beat_manipulator/metrics.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from . import effects
3
+
4
+ def volume(audio: np.ndarray) -> float:
5
+ return np.average(np.abs(audio))
6
+
7
+ def volume_gradient(audio: np.ndarray, number:int = 1) -> float:
8
+ audio = effects.gradient(audio, number = number)
9
+ return np.average(np.abs(audio))
10
+
11
+ def maximum_high(audio: np.ndarray, number:int = 1) -> float:
12
+ audio = effects.gradient(audio, number = number)
13
+ return np.max(np.abs(audio))
14
+
15
+ def locate_1st_hit(audio: np.ndarray, number: int = 1):
16
+ audio = effects.gradient(audio, number = number)
17
+ return np.argmax(audio, axis=1) / len(audio[0])
18
+
19
+ def is_hit(audio: np.ndarray, threshold: float = 0.5, number:int = 1) -> int:
20
+ return 1 if maximum_high(audio, number=number) > threshold else 0
21
+
22
+ def hit_at_start(audio: np.ndarray, diff = 0.1) -> int:
23
+ return is_hit(audio) * (locate_1st_hit(audio) <= diff)
24
+
25
+ def hit_in_middle(audio: np.ndarray, diff = 0.1) -> int:
26
+ return is_hit(audio) * ((0.5 - diff) <= locate_1st_hit(audio) <= (0.5 + diff))
27
+
28
+ def hit_at_end(audio: np.ndarray, diff = 0.1) -> int:
29
+ return is_hit(audio) * (locate_1st_hit(audio) >= (1-diff))
30
+
31
+ BM_METRICS = {
32
+ "v": volume,
33
+ "g": volume_gradient,
34
+ "m": maximum_high,
35
+ "l": locate_1st_hit,
36
+ "h": is_hit,
37
+ "s": hit_at_start,
38
+ "a": hit_in_middle,
39
+ "e": hit_at_end,
40
+ }
beat_manipulator/mix.py DELETED
@@ -1,44 +0,0 @@
1
- import numpy
2
- from . import main as bm
3
- def mix_shuffle_approx_random(audio1, audio2, iterations, minlength=0, maxlength=None, bias=0):
4
- import random
5
- if isinstance(audio1, bm.song):
6
- minlength*=audio1.samplerate
7
- if maxlength is not None: maxlength*=audio1.samplerate
8
- audio1=audio1.audio
9
- else:
10
- minlength*=44100
11
- if maxlength is not None: maxlength*=44100
12
- if isinstance(audio2, bm.song): audio2=audio2.audio
13
- if len(audio1)>16: audio1=numpy.asarray([audio1,audio1])
14
- if len(audio2)>16: audio1=numpy.asarray([audio2,audio2])
15
- shape2=len(audio2)
16
- mono1=numpy.abs(numpy.gradient(audio1[0]))
17
- mono2=numpy.abs(numpy.gradient(audio2[0]))
18
- length1=len(mono1)
19
- length2=len(mono2)
20
- result=numpy.zeros(shape=(shape2, length2))
21
- result_diff=numpy.zeros(shape=length2)
22
- old_difference=numpy.sum(mono2)
23
- random_result=result_diff.copy()
24
- for i in range(iterations):
25
- rstart=random.randint(0, length1)
26
- if maxlength is not None:
27
- rlength=random.randint(minlength, min(length1-rstart, maxlength))
28
- else: rlength=random.randint(minlength, minlength+length1-rstart)
29
- rplace=random.randint(0, length2-rlength)
30
- random_result=numpy.array(result_diff, copy=True)
31
- random_result[rplace:rplace + rlength] = mono1[rstart:rstart + rlength]
32
- difference = numpy.sum(numpy.abs(mono2 - random_result))
33
- if difference<old_difference-bias:
34
- print(i, difference)
35
- result[:, rplace:rplace + rlength] = audio1[:, rstart:rstart + rlength]
36
- result_diff=random_result
37
- old_difference = difference
38
- return result
39
- # 10 5 4 1
40
- # 10 0 0 0
41
- # 0 5 4 1 10
42
- # 10 5 4 1
43
- # 10 5 4 1
44
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beat_manipulator/osu.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import main
2
+ import numpy as np
3
+
4
+ # L L L L L L L L L
5
+ def generate(song, difficulties = [0.2, 0.1, 0.05, 0.025, 0.01, 0.0075, 0.005, 0.0025], lib='madmom.MultiModelSelectionProcessor', caching=True, log = True, output = '', add_peaks = True):
6
+ # for i in difficulties:
7
+ # if i<0.005: print(f'Difficulties < 0.005 may result in broken beatmaps, found difficulty = {i}')
8
+ if lib.lower == 'stunlocked': add_peaks = False
9
+
10
+ if not isinstance(song, main.song): song = main.song(song)
11
+ if log is True: print(f'Using {lib}; ', end='')
12
+
13
+ filename = song.path.replace('\\', '/').split('/')[-1]
14
+ if ' - ' in filename and len(filename.split(' - '))>1:
15
+ artist = filename.split(' - ')[0]
16
+ title = ' - '.join(filename.split(' - ')[1:])
17
+ else:
18
+ artist = ''
19
+ title = filename
20
+
21
+ if caching is True:
22
+ audio_id=hex(len(song.audio[0]))
23
+ import os
24
+ if not os.path.exists('beat_manipulator/beatmaps'):
25
+ os.mkdir('beat_manipulator/beatmaps')
26
+ cacheDir="beat_manipulator/beatmaps/" + filename + "_"+lib+"_"+audio_id+'.txt'
27
+ try:
28
+ beatmap=np.loadtxt(cacheDir)
29
+ if log is True: print('loaded cached beatmap.')
30
+ except OSError:
31
+ if log is True:print("beatmap hasn't been generated yet. Generating...")
32
+ beatmap = None
33
+
34
+ if beatmap is None:
35
+ if 'madmom' in lib.lower():
36
+ from collections.abc import MutableMapping, MutableSequence
37
+ import madmom
38
+ assert len(song.audio[0])>song.sr*2, f'Audio file is too short, len={len(song.audio[0])} samples, or {len(song.audio[0])/song.sr} seconds. Minimum length is 2 seconds, audio below that breaks madmom processors.'
39
+ if lib=='madmom.RNNBeatProcessor':
40
+ proc = madmom.features.beats.RNNBeatProcessor()
41
+ beatmap = proc(madmom.audio.signal.Signal(song.audio.T, song.sr))
42
+ elif lib=='madmom.MultiModelSelectionProcessor':
43
+ proc = madmom.features.beats.RNNBeatProcessor(post_processor=None)
44
+ predictions = proc(madmom.audio.signal.Signal(song.audio.T, song.sr))
45
+ mm_proc = madmom.features.beats.MultiModelSelectionProcessor(num_ref_predictions=None)
46
+ beatmap= mm_proc(predictions)*song.sr
47
+ beatmap/= np.max(beatmap)
48
+ elif lib=='stunlocked':
49
+ spikes = np.abs(np.gradient(np.clip(song.audio[0], -1, 1)))[:int(len(song.audio[0]) - (len(song.audio[0])%int(song.sr/100)))]
50
+ spikes = spikes.reshape(-1, (int(song.sr/100)))
51
+ spikes = np.asarray(list(np.max(i) for i in spikes))
52
+ if len(beatmap) > len(spikes): beatmap = beatmap[:len(spikes)]
53
+ elif len(spikes) > len(beatmap): spikes = spikes[:len(beatmap)]
54
+ zeroing = 0
55
+ for i in range(len(spikes)):
56
+ if zeroing > 0:
57
+ if spikes[i] <= 0.1: zeroing -=1
58
+ spikes[i] = 0
59
+ elif spikes[i] >= 0.1:
60
+ spikes[i] = 1
61
+ zeroing = 7
62
+ if spikes[i] <= 0.1: spikes[i] = 0
63
+ beatmap = spikes
64
+
65
+ if caching is True: np.savetxt(cacheDir, beatmap)
66
+
67
+ if add_peaks is True:
68
+ spikes = np.abs(np.gradient(np.clip(song.audio[0], -1, 1)))[:int(len(song.audio[0]) - (len(song.audio[0])%int(song.sr/100)))]
69
+ spikes = spikes.reshape(-1, (int(song.sr/100)))
70
+ spikes = np.asarray(list(np.max(i) for i in spikes))
71
+ if len(beatmap) > len(spikes): beatmap = beatmap[:len(spikes)]
72
+ elif len(spikes) > len(beatmap): spikes = spikes[:len(beatmap)]
73
+ zeroing = 0
74
+ for i in range(len(spikes)):
75
+ if zeroing > 0:
76
+ if spikes[i] <= 0.1: zeroing -=1
77
+ spikes[i] = 0
78
+ elif spikes[i] >= 0.1:
79
+ spikes[i] = 1
80
+ zeroing = 7
81
+ if spikes[i] <= 0.1: spikes[i] = 0
82
+ else: spikes = None
83
+
84
+ def _process(song: main.song, beatmap, spikes, threshold):
85
+ '''ඞ'''
86
+ if add_peaks is True: beatmap += spikes
87
+ hitmap=[]
88
+ actual_samplerate=int(song.sr/100)
89
+ beat_middle=int(actual_samplerate/2)
90
+ for i in range(len(beatmap)):
91
+ if beatmap[i]>threshold: hitmap.append(i*actual_samplerate + beat_middle)
92
+ hitmap=np.asarray(hitmap)
93
+ clump=[]
94
+ for i in range(len(hitmap)-1):
95
+ #print(i, abs(song.beatmap[i]-song.beatmap[i+1]), clump)
96
+ if abs(hitmap[i] - hitmap[i+1]) < song.sr/16 and i != len(hitmap)-2: clump.append(i)
97
+ elif clump!=[]:
98
+ clump.append(i)
99
+ actual_time=hitmap[clump[0]]
100
+ hitmap[np.array(clump)]=0
101
+ #print(song.beatmap)
102
+ hitmap[clump[0]]=actual_time
103
+ clump=[]
104
+
105
+ hitmap=hitmap[hitmap!=0]
106
+ return hitmap
107
+
108
+ osufile=lambda title,artist,version: ("osu file format v14\n"
109
+ "\n"
110
+ "[General]\n"
111
+ f"AudioFilename: {song.path.split('/')[-1]}\n"
112
+ "AudioLeadIn: 0\n"
113
+ "PreviewTime: -1\n"
114
+ "Countdown: 0\n"
115
+ "SampleSet: Normal\n"
116
+ "StackLeniency: 0.5\n"
117
+ "Mode: 0\n"
118
+ "LetterboxInBreaks: 0\n"
119
+ "WidescreenStoryboard: 0\n"
120
+ "\n"
121
+ "[Editor]\n"
122
+ "DistanceSpacing: 1.1\n"
123
+ "BeatDivisor: 4\n"
124
+ "GridSize: 8\n"
125
+ "TimelineZoom: 1.6\n"
126
+ "\n"
127
+ "[Metadata]\n"
128
+ f"Title:{title}\n"
129
+ f"TitleUnicode:{title}\n"
130
+ f"Artist:{artist}\n"
131
+ f"ArtistUnicode:{artist}\n"
132
+ f'Creator:{lib} + BeatManipulator\n'
133
+ f'Version:{version} {lib}\n'
134
+ 'Source:\n'
135
+ 'Tags:BeatManipulator\n'
136
+ 'BeatmapID:0\n'
137
+ 'BeatmapSetID:-1\n'
138
+ '\n'
139
+ '[Difficulty]\n'
140
+ 'HPDrainRate:4\n'
141
+ 'CircleSize:4\n'
142
+ 'OverallDifficulty:5\n'
143
+ 'ApproachRate:10\n'
144
+ 'SliderMultiplier:3.3\n'
145
+ 'SliderTickRate:1\n'
146
+ '\n'
147
+ '[Events]\n'
148
+ '//Background and Video events\n'
149
+ '//Break Periods\n'
150
+ '//Storyboard Layer 0 (Background)\n'
151
+ '//Storyboard Layer 1 (Fail)\n'
152
+ '//Storyboard Layer 2 (Pass)\n'
153
+ '//Storyboard Layer 3 (Foreground)\n'
154
+ '//Storyboard Layer 4 (Overlay)\n'
155
+ '//Storyboard Sound Samples\n'
156
+ '\n'
157
+ '[TimingPoints]\n'
158
+ '0,140.0,4,1,0,100,1,0\n'
159
+ '\n'
160
+ '\n'
161
+ '[HitObjects]\n')
162
+ # remove the clumps
163
+ #print(self.beatmap)
164
+
165
+ #print(self.beatmap)
166
+
167
+
168
+ #print(len(osumap))
169
+ #input('banana')
170
+ import shutil, os
171
+ if os.path.exists('beat_manipulator/temp'): shutil.rmtree('beat_manipulator/temp')
172
+ os.mkdir('beat_manipulator/temp')
173
+ hitmap=[]
174
+ import random
175
+ for difficulty in difficulties:
176
+ for i in range(4):
177
+ #print(i)
178
+ this_difficulty=_process(song, beatmap, spikes, difficulty)
179
+ hitmap.append(this_difficulty)
180
+
181
+ for k in range(len(hitmap)):
182
+ osumap=np.vstack((hitmap[k],np.zeros(len(hitmap[k])),np.zeros(len(hitmap[k])))).T
183
+ difficulty= difficulties[k]
184
+ for i in range(len(osumap)-1):
185
+ if i==0:continue
186
+ dist=(osumap[i,0]-osumap[i-1,0])*(1-(difficulty**0.3))
187
+ if dist<1000: dist=0.005
188
+ elif dist<2000: dist=0.01
189
+ elif dist<3000: dist=0.015
190
+ elif dist<4000: dist=0.02
191
+ elif dist<5000: dist=0.25
192
+ elif dist<6000: dist=0.35
193
+ elif dist<7000: dist=0.45
194
+ elif dist<8000: dist=0.55
195
+ elif dist<9000: dist=0.65
196
+ elif dist<10000: dist=0.75
197
+ elif dist<12500: dist=0.85
198
+ elif dist<15000: dist=0.95
199
+ elif dist<20000: dist=1
200
+ #elif dist<30000: dist=0.8
201
+ prev_x=osumap[i-1,1]
202
+ prev_y=osumap[i-1,2]
203
+ if prev_x>0: prev_x=prev_x-dist*0.1
204
+ elif prev_x<0: prev_x=prev_x+dist*0.1
205
+ if prev_y>0: prev_y=prev_y-dist*0.1
206
+ elif prev_y<0: prev_y=prev_y+dist*0.1
207
+ dirx=random.uniform(-dist,dist)
208
+ diry=dist-abs(dirx)*random.choice([-1, 1])
209
+ if abs(prev_x+dirx)>1: dirx=-dirx
210
+ if abs(prev_y+diry)>1: diry=-diry
211
+ x=prev_x+dirx
212
+ y=prev_y+diry
213
+ #print(dirx,diry,x,y)
214
+ #print(x>1, x<1, y>1, y<1)
215
+ if x>1: x=0.8
216
+ if x<-1: x=-0.8
217
+ if y>1: y=0.8
218
+ if y<-1: y=-0.8
219
+ #print(dirx,diry,x,y)
220
+ osumap[i,1]=x
221
+ osumap[i,2]=y
222
+
223
+ osumap[:,1]*=300
224
+ osumap[:,1]+=300
225
+ osumap[:,2]*=180
226
+ osumap[:,2]+=220
227
+
228
+ file=osufile(artist, title, difficulty)
229
+ for j in osumap:
230
+ #print('285,70,'+str(int(int(i)*1000/self.samplerate))+',1,0')
231
+ file+=f'{int(j[1])},{int(j[2])},{str(int(int(j[0])*1000/song.sr))},1,0\n'
232
+ with open(f'beat_manipulator/temp/{artist} - {title} (BeatManipulator {difficulty} {lib}].osu', 'x', encoding="utf-8") as f:
233
+ f.write(file)
234
+ from . import io
235
+ import shutil, os
236
+ shutil.copyfile(song.path, 'beat_manipulator/temp/'+filename)
237
+ shutil.make_archive('beat_manipulator_osz', 'zip', 'beat_manipulator/temp')
238
+ outputname = io._outputfilename(path = output, filename = song.path, suffix = ' ('+lib + ')', ext = 'osz')
239
+ if not os.path.exists(outputname):
240
+ os.rename('beat_manipulator_osz.zip', outputname)
241
+ if log is True: print(f'Created `{outputname}`')
242
+ else: print(f'{outputname} already exists!')
243
+ shutil.rmtree('beat_manipulator/temp')
244
+ return outputname
beat_manipulator/parse.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .utils import C_SLICE, C_JOIN, C_MISC, C_MATH
2
+ import numpy as np
3
+ from . import io, utils, main
4
+ def _getnum(pattern, cur, symbols = '+-*/'):
5
+ number = ''
6
+ while pattern[cur].isdecimal() or pattern[cur] in symbols:
7
+ number+=pattern[cur]
8
+ cur+=1
9
+ return number, cur-1
10
+
11
+ def parse(pattern:str, samples:dict, pattern_length:int = None,
12
+ c_slice:str = C_SLICE,
13
+ c_join:str = C_JOIN,
14
+ c_misc:str = C_MISC,
15
+ log = True,
16
+ simple_mode = False):
17
+ """Returns (beats, operators, pattern_length, c_slice, c_misc, c_join)"""
18
+ if log is True: print(f'Beatswapping with `{pattern}`')
19
+
20
+ #load samples:
21
+ if isinstance(samples, str): samples = (samples,)
22
+ if not isinstance(samples, dict):
23
+ samples = {str(i+1):samples[i] for i in range(len(samples))}
24
+
25
+ #preprocess pattern
26
+ separator = c_join[0]
27
+ #forgot separator
28
+ if simple_mode is True:
29
+ if c_join[0] not in pattern and c_join[1] not in pattern and c_join[2] not in pattern and c_join[3] not in pattern: pattern = pattern.replace(' ', separator)
30
+ if ' ' not in c_join: pattern = pattern.replace(' ', '') # ignore spaces
31
+ for i in c_join:
32
+ while i+i in pattern: pattern = pattern.replace(i+i, i) #double separator
33
+ while pattern.startswith(i): pattern = pattern[1:]
34
+ while pattern.endswith(i): pattern = pattern[:-1]
35
+
36
+ # Creates a list of beat strings so that I can later see if there is a `!` in the string
37
+ separated = pattern
38
+ for i in c_join:
39
+ separated = separated.replace(i, c_join[0])
40
+ separated = separated.split(c_join[0])
41
+ pattern = pattern.replace(c_misc[6], '')
42
+
43
+ # parsing
44
+ length = 0
45
+ num = ''
46
+ cur = 0
47
+ beats = []
48
+ operators = [separator]
49
+ shuffle_beats = []
50
+ shuffle_groups = []
51
+ current_beat = 0
52
+ effect = None
53
+ pattern += ' '
54
+ sample_toadd = None
55
+
56
+ # Loops over all characters
57
+ while cur < len(pattern):
58
+ char = pattern[cur]
59
+ #print(f'char = {char}, cur = {cur}, num = {num}, current_beat = {current_beat}, effect = {effect}, len(beats) = {len(beats)}, length = {length}')
60
+ if char == c_misc[3]: char = str(current_beat+1) # Replaces `i` with current number
61
+
62
+ # If character is `", ', `, or [`: searches for closing quote and gets the sample rate,
63
+ # moves cursor to the character after last quote/bracket, creates a sample_toadd variable with the sample.
64
+ elif char in c_misc[0:3]+c_misc[10:12]:
65
+ quote = char
66
+ if quote == c_misc[10]: quote = c_misc[11] # `[` is replaced with `]`
67
+ cur += 1
68
+ sample = ''
69
+
70
+ # Gets sample name between quote characters, moves cursor to the ending quote.
71
+ while pattern[cur] != quote:
72
+ sample += pattern[cur]
73
+ cur += 1
74
+ assert sample in samples, f"No sample named `{sample}` found in samples. Available samples: {samples.keys()}"
75
+
76
+ # If sample is a song, it will be converted to a song if needed, and beatmap will be generated
77
+ if quote == c_misc[11]:
78
+ if not isinstance(samples[sample], main.song): samples[sample] = main.song(samples[sample])
79
+ if samples[sample].beatmap is None:
80
+ samples[sample].beatmap_generate()
81
+ samples[sample].beatmap_adjust()
82
+
83
+ # Else sample is a sound file
84
+ elif not isinstance(samples[sample], np.ndarray): samples[sample] = io._load(samples[sample])[0]
85
+
86
+ sample_toadd = [samples[sample], [], quote, None] # Creates the sample_toadd variable
87
+ cur += 1
88
+ char = pattern[cur]
89
+
90
+ # If character is a math character, a slice character, or `@_?!%` - random, not count, skip, create variable -
91
+ # - it gets added to `num`, and the loop repeats.
92
+ # _safer_eval only takes part of the expression to the left of special characters (@%#), so it won't affect length calculation
93
+ if char.isdecimal() or char in (C_MATH + c_slice + c_misc[4:8] + c_misc[9]):
94
+ num += char
95
+ #print(f'char = {char}, added it to num: num = {num}')
96
+
97
+ # If character is `%` and beat hasn't been created yet, it takes the next character as well
98
+ if char == c_misc[7] and len(beats) == current_beat:
99
+ cur += 1
100
+ char = pattern[cur]
101
+ num += char
102
+
103
+ # If character is a shuffle character `#` + math expression, beat number gets added to `shuffle_beats`,
104
+ # beat shuffle group gets added to `shuffle_groups`, cursor is moved to the character after the math expression, and loop repeats.
105
+ # That means operations after this will only execute once character is not a math character.
106
+ elif char == c_misc[8]:
107
+ cur+=1
108
+ number, cur = _getnum(pattern, cur)
109
+ char = pattern[cur]
110
+ shuffle_beats.append(current_beat)
111
+ shuffle_groups.append(number)
112
+
113
+ # If character is not math/shuffle, that means math expression has ended. Now it tries to figure out where the expression belongs,
114
+ # and parses the further characters
115
+ else:
116
+
117
+ # If the beat has not been added, it adds the beat. Also figures out pattern length.
118
+ if len(beats) == current_beat and len(num) > 0:
119
+ # Checks all slice characters in the beat expression. If slice character is found, splits the slice and breaks.
120
+ for c in c_slice:
121
+ if c in num:
122
+ num = num.split(c)[:2] + [c]
123
+ #print(f'slice: split num by `{c}`, num = {num}, whole beat is {separated[current_beat]}')
124
+ if pattern_length is None and c_misc[6] not in separated[current_beat]:
125
+ num0, num1 = utils._safer_eval(num[0]), utils._safer_eval(num[1])
126
+ if c == c_slice[0]: length = max(num0, num1, length)
127
+ if c == c_slice[1]: length = max(num0-1, num0+num1-1, length)
128
+ if c == c_slice[2]: length = max(num0-num1, num0, length)
129
+ break
130
+ # If it didn't break, the expression is not a slice, so it pattern length is just compared with the beat number.
131
+ else:
132
+ #print(f'single beat: {num}. Whole beat is {separated[current_beat]}')
133
+ if c_misc[6] not in separated[current_beat]: length = max(utils._safer_eval(num), length)
134
+
135
+ # If there no sample saved in `sample_toadd`, adds the beat to list of beats.
136
+ if sample_toadd is None: beats.append([num, []])
137
+ # If `sample_toadd` is not None, beat is a sample/song. Adds the beat and sets sample_toadd to None
138
+ else:
139
+ sample_toadd[3] = num
140
+ beats.append(sample_toadd)
141
+ sample_toadd = None
142
+ #print(f'char = {char}, got num = {num}, appended beat {len(beats)}')
143
+
144
+ # Sample might not have a `num` with a slice, this adds the sample without a slice
145
+ elif len(beats) == current_beat and len(num) == 0 and sample_toadd is not None:
146
+ beats.append(sample_toadd)
147
+ sample_toadd = None
148
+
149
+ # If beat has been added, it now parses beats.
150
+ if len(beats) == current_beat+1:
151
+ #print(f'char = {char}, parsing effects:')
152
+
153
+ # If there is an effect and current character is not a math character, effect and value are added to current beat, and effect is set to None
154
+ if effect is not None:
155
+ #print(f'char = {char}, adding effect: type = {effect}, value = {num}')
156
+ beats[current_beat][1].append([effect, num if num!='' else None])
157
+ effect = None
158
+
159
+ # If current character is a letter, it sets that letter to `effect` variable.
160
+ # Since loop repeats after that, that while current character is a math character, it gets added to `num`.
161
+ if char.isalpha() and effect is None:
162
+ #print(f'char = {char}, effect type is {effect}')
163
+ effect = char
164
+
165
+ # If character is a beat separator, it starts parsing the next beat in the next loop.
166
+ if char in c_join and len(beats) == current_beat + 1:
167
+ #print(f'char = {char}, parsing next beat')
168
+ current_beat += 1
169
+ effect = None
170
+ operators.append(char)
171
+
172
+ num = '' # `num` is set to empty string. btw `num` is only used in this loop so it needs to be here
173
+
174
+ cur += 1 # cursor goes to the next character
175
+
176
+
177
+ #for i in beats: print(i)
178
+ import math
179
+ if pattern_length is None: pattern_length = int(math.ceil(length))
180
+
181
+ return beats, operators, pattern_length, shuffle_groups, shuffle_beats, c_slice, c_misc, c_join
182
+
183
+ # I can't be bothered to annotate this one. It just works, okay?
184
+ def _random(beat:str, length:int, rchar = C_MISC[4], schar = C_MISC[5]) -> str:
185
+ """Takes a string and replaces stuff like `@1_4_0.5` with randomly generated number where 1 - start, 4 - stop, 0.5 - step. Returns string."""
186
+ import random
187
+ beat+=' '
188
+ while rchar in beat:
189
+ rand_index = beat.find(rchar)+1
190
+ char = beat[rand_index]
191
+ number = ''
192
+ while char.isdecimal() or char in '.+-*/':
193
+ number += char
194
+ rand_index+=1
195
+ char = beat[rand_index]
196
+ if number != '': start = utils._safer_eval(number)
197
+ else: start = 0
198
+ if char == schar:
199
+ rand_index+=1
200
+ char = beat[rand_index]
201
+ number = ''
202
+ while char.isdecimal() or char in '.+-*/':
203
+ number += char
204
+ rand_index+=1
205
+ char = beat[rand_index]
206
+ if number != '': stop = utils._safer_eval(number)
207
+ else: stop = length
208
+ if char == schar:
209
+ rand_index+=1
210
+ char = beat[rand_index]
211
+ number = ''
212
+ while char.isdecimal() or char in '.+-*/':
213
+ number += char
214
+ rand_index+=1
215
+ char = beat[rand_index]
216
+ if number != '': step = utils._safer_eval(number)
217
+ else: step = length
218
+ choices = []
219
+ while start <= stop:
220
+ choices.append(start)
221
+ start+=step
222
+ beat = list(beat)
223
+ beat[beat.index(rchar):rand_index] = list(str(random.choice(choices)))
224
+ beat = ''.join(beat)
225
+ return beat
226
+
227
+ def _shuffle(pattern: list, shuffle_beats: list, shuffle_groups: list) -> list:
228
+ """Shuffles pattern according to shuffle_beats and shuffle_groups"""
229
+ import random
230
+ done = []
231
+ result = pattern.copy()
232
+ for group in shuffle_groups:
233
+ if group not in done:
234
+ shuffled = [i for n, i in enumerate(shuffle_beats) if shuffle_groups[n] == group]
235
+ unshuffled = shuffled.copy()
236
+ random.shuffle(shuffled)
237
+ for i in range(len(shuffled)):
238
+ result[unshuffled[i]] = pattern[shuffled[i]]
239
+ done.append(group)
240
+ return result
241
+
242
+ def _metric_get(v, beat, metrics, c_misc7 = C_MISC[7]):
243
+ assert v[v.find(c_misc7)+1] in metrics, f'`%{v[v.find(c_misc7)+1]}`: No metric called `{v[v.find(c_misc7)+1]}` found in metrics. Available metrics: {metrics.keys()}'
244
+ metric = metrics[v[v.find(c_misc7)+1]](beat)
245
+ return metric
246
+
247
+
248
+ def _metric_replace(v, metric, c_misc7 = C_MISC[7]):
249
+ for _ in range(v.count(c_misc7)):
250
+ v= v[:v.find(c_misc7)] + str(metric) + v[v.find(c_misc7)+2:]
251
+ return v
beat_manipulator/presets.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import main, utils
2
+ BM_SAMPLES = {'cowbell' : 'beat_manipulator/samples/cowbell.flac',
3
+ }
4
+
5
+ presets = {}
6
+
7
+ def presets_load(path, mode = 'add'):
8
+ global presets
9
+ import yaml
10
+ with open(path, 'r') as f:
11
+ yaml_presets = yaml.safe_load(f.read())
12
+
13
+ if mode.lower() == 'add':
14
+ presets = presets | yaml_presets
15
+ elif mode.lower() == 'replace':
16
+ presets = yaml_presets
17
+
18
+ presets_load('beat_manipulator/presets.yaml')
19
+
20
+ def _beatswap(song, pattern, pattern_name, scale = 1, shift = 0, output = '', modify = False):
21
+ if isinstance(scale, str):
22
+ if ',' in scale: scale = scale.replace(' ', '').split(',')
23
+ elif not isinstance(scale, list): scale = [scale]
24
+ if modify is False:
25
+ for i in scale:
26
+ main.beatswap(song, pattern = pattern, scale = i, shift = shift, output=output, suffix = f' ({pattern_name}{(" x"+str(round(utils._safer_eval(i), 4))) * (len(scale)>1)})', copy = True)
27
+ else:
28
+ assert isinstance(song, main.song), f"In order to modify a song, it needs to be of a main.song type, but it is {type(song)}"
29
+ song.beatswap(pattern, scale = scale[0], shift = shift)
30
+ return song
31
+
32
+ def get(preset):
33
+ """returns (pattern, scale, shift)"""
34
+ global presets
35
+ assert preset in presets, f"{preset} not found in presets."
36
+ preset = presets[preset]
37
+ return preset['pattern'], preset['scale'] if 'scale' in preset else 1, preset['shift'] if 'shift' in preset else 0
38
+
39
+ def use(song, preset, output = '', scale = 1, shift = 0):
40
+ global presets
41
+ assert preset in presets, f"{preset} not found in presets."
42
+ preset_name = preset
43
+ preset = presets[preset]
44
+ if not isinstance(song, main.song): song = main.song(song)
45
+ if isinstance(list(preset.values())[0], dict):
46
+ for i in preset.values():
47
+ if 'sample' in i:
48
+ pass
49
+ elif 'sidechain' in i:
50
+ pass
51
+ else:
52
+ song = _beatswap(song, pattern = i['pattern'], scale = scale*(i['scale'] if 'scale' in i else 1), shift = shift*(i['shift'] if 'shift' in i else 0), output = output, modify = True, pattern_name = preset_name)
53
+ song.write(output, suffix = f' ({preset})')
54
+ else:
55
+ if 'sample' in preset:
56
+ pass
57
+ elif 'sidechain' in preset:
58
+ pass
59
+ else:
60
+ _beatswap(song, pattern = preset['pattern'], scale = scale*(preset['scale'] if 'scale' in preset else 1), shift = shift*(preset['shift'] if 'shift' in preset else 0), output = output, modify = False, pattern_name = preset_name)
61
+
62
+ def use_all(song, output = ''):
63
+ if not isinstance(song, main.song): song = main.song(song)
64
+ for key in presets.keys():
65
+ print(f'__ {key} __')
66
+ use(song, key, output = output)
67
+ print()
68
+
69
+ def test(song, scale = 1, shift = 0, adjust = 0, output = '', load_settings = False):
70
+ song = main.song(song)
71
+ song.beatmap_generate(load_settings = load_settings)
72
+ song.beatswap('test', scale = scale, shift = shift, adjust = 500+adjust)
73
+ song.write(output = output, suffix = ' (test)')
74
+
75
+ def save(song, scale = 1, shift = 0, adjust = 0):
76
+ song = main.song(song)
77
+ song.beatmap_save_settings(scale = scale, shift = shift, adjust = adjust)
78
+
79
+ def savetest(song, scale = 1, shift = 0, adjust = 0, output = '', load_settings = False):
80
+ song = main.song(song)
81
+ song.beatmap_generate(load_settings = load_settings)
82
+ song.beatswap('test', scale = scale, shift = shift, adjust = 500+adjust)
83
+ song.write(output = output, suffix = ' (test)')
84
+ song.beatmap_save_settings(scale = scale, shift = shift, adjust = adjust)
beat_manipulator/presets.yaml ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Presets. `Scales` can be a list of all scales that the pattern works with.
2
+ # ________________ BASIC ________________
3
+ 2x speed:
4
+ pattern: 1>0.5
5
+ scale: 1, 0.5, 1/3, 0.25
6
+
7
+ 3x speed:
8
+ pattern: 1>1/3
9
+ scale: 1, 0.5
10
+
11
+ 4x speed:
12
+ pattern: 1>0.25
13
+ scale: 1, 0.5
14
+
15
+ 6x speed:
16
+ pattern: 1>1/6
17
+ scale: 1, 0.5
18
+
19
+ 8x speed:
20
+ pattern: 1>0.125
21
+ scale: 1, 0.5
22
+
23
+ 1.33x faster:
24
+ pattern: 1>0.75
25
+ scale: 1, 2/3, 0.5, 1/3, 0.25
26
+
27
+ 1.5x faster:
28
+ pattern: 1>2/3
29
+ scale: 1, 2/3
30
+
31
+ 1.5x slower:
32
+ pattern: 1>0.5, 1<0.5r, 1<0.5
33
+ scale: 2, 1, 0.75, 0.5
34
+
35
+ 1.33x slower:
36
+ pattern: 1>2/3, 1<1/3r, 1<1/3
37
+ scale: 2, 1
38
+
39
+ reverse:
40
+ pattern: reverse
41
+ scale: 8, 4, 2, 1, 0.5, 1/3, 0.25, 0.2, 1/7, 0.125
42
+
43
+ reverse 8 beats:
44
+ pattern: 8, 7, 6, 5, 4, 3, 2, 1
45
+ scale: 1, 0.5
46
+
47
+ shuffle:
48
+ pattern: shuffle
49
+
50
+ shuffle 3 beats:
51
+ pattern: 1#1, 2#1, 3#1
52
+ scale: 2, 1, 0.75, 0.5, 0.25, 0.2, 0.125
53
+
54
+ shuffle 4 beats:
55
+ pattern: 1#1, 2#1, 3#1, 4#1
56
+ scale: 2, 1, 0.75, 0.5, 0.25, 0.125
57
+
58
+ shuffle 8 beats:
59
+ pattern: 1#1, 2#1, 3#1, 4#1, 5#1, 6#1, 7#1, 8#1
60
+ scale: 2, 1, 0.75, 0.5, 0.25
61
+
62
+ shuffle alternate:
63
+ pattern: 1#1, 2#2, 3#1, 4#2, 5#1, 6#2, 7#1, 8#2
64
+ scale: 1, 0.125
65
+
66
+ shuffle mix:
67
+ pattern: i#1, i#2, i#3, i#4, i#1, i#2, i#3, i#4, i#1, i#2, i#3, i#4, i#1, i#2, i#3, i#4
68
+ scale: 1, 0.5
69
+
70
+ 3 bars mix:
71
+ pattern: i, i+4?, i+8?, 3!
72
+ scale: 1, 0.5, 1/3
73
+
74
+ 4 bars mix:
75
+ pattern: i, i+4?, i+8?, i+12?, 4!
76
+ scale: 1, 0.5
77
+
78
+ 6 bars mix:
79
+ pattern: i, i+4?, i+8?, i+12?, i+16?, i+20?, 6!
80
+ scale: 1, 0.5
81
+
82
+ 8 bars mix:
83
+ pattern: i, i+4?, i+8?, i+12?, i+16?, i+20?, i+24?, i+28?, 8!
84
+ scale: 1, 0.5
85
+
86
+ 2 in 1:
87
+ pattern: 1; 2
88
+ scale: 8, 6, 4, 3, 2, 1, 0.5, 0.25
89
+
90
+ 3 in 1:
91
+ pattern: 1; 2; 3
92
+ scale: 4, 3, 1
93
+
94
+ 4 in 1:
95
+ pattern: 1; 2; 3; 4
96
+ scale: 4, 1
97
+
98
+ 5 in 1:
99
+ pattern: 1;2;3;4;5
100
+ scale: 2, 1
101
+
102
+ 2 in 1 reverse:
103
+ pattern: 1;2r?
104
+ scale: 8, 3, 1, 0.75, 0.5, 0.25, 0.125
105
+
106
+ reverse mix:
107
+ pattern: 1;1r
108
+ scale: 4, 1, 0.75, 0.5
109
+
110
+ random:
111
+ pattern: random
112
+ scale: 2, 1, 0.5, 0.25, 0.125
113
+ description: generates a new random pattern each time
114
+
115
+ kicks only:
116
+ pattern: 1>0.5
117
+ scale: 2
118
+ description: plays only kicks
119
+
120
+ kicks only double-time:
121
+ pattern: 1>0.25
122
+ scale: 2
123
+ description: plays only kicks
124
+
125
+ snares only:
126
+ pattern: 1<0.5
127
+ scale: 2
128
+ description: plays only snares
129
+
130
+ no main drums:
131
+ pattern: 1<0.5
132
+ scale: 1, 0.5, 0.25, 0.125
133
+ description: skips kicks and snares
134
+
135
+ # ________________ STRUCTURES ________________
136
+ half-time:
137
+ pattern: 1,2,4,5, | 3,6,8,7, | 9,11,12,13, | 15,13,14,16
138
+ scale: 1, 0.5 #0.25
139
+ description: halves the BPM
140
+
141
+ quarter-time 1:
142
+ pattern: 1,2,4,5,|6,8,9,10,|11,12,13,14,|16,14,15,16
143
+ scale: 0.5
144
+ description: 4 times lower BPM
145
+
146
+ quarter-time 2:
147
+ pattern: 1,2,4,5, | 6,8,10,12, | 11,10,12,13, | 9,13,14,16
148
+ scale: 0.5 #0.25
149
+ description: 4 times lower BPM, with a syncopated structure
150
+
151
+ dotted snares 1:
152
+ pattern: 1, 2>0.5, 3, 4>0.5, 5, 6>0.5, 3, 4>0.5, 7, 8
153
+ scale: 2, 1
154
+ description: Plays 5 snares in a 4/3 syncopation, a rhythm commonly used in drum&bass
155
+
156
+ dotted snares 2:
157
+ pattern: 1, 2, 3 , 4, | 5, 7 , 6, 8, | 11 , 10, 9, 11 , | 13, 14, 15 , 16
158
+ scale: 0.5 #0.25
159
+ description: Plays 5 snares in a 4/3 syncopation, a rhythm commonly used in drum&bass. This one only swaps snares and preserves the original rhythm better.
160
+
161
+ dotted snares 2 long:
162
+ pattern: 1, 2, 3 , 4, | 5, 7 , 6, 8, | 11 , 10, 9, 11 , | 13, 14, 15 , 16, | 17, 19 , 18, 20, | 23 , 22, 21, 23 , | 25, 26, 27 , 28, | 29, 31 , 30, 32
163
+ scale: 0.5 #0.25
164
+ description: Plays 10 snares in a long 4/3 syncopation, a rhythm commonly used in drum&bass/darkstep.
165
+
166
+ dotted snares 2 longer:
167
+ pattern: 1, 2, 3 , 4, | 5, 7 , 6, 8, | 11 , 10, 9, 11 , | 13, 14, 15 , 16, | 17, 19 , 18, 20, | 23 , 22, 21, 23 , | 25, 26, 27 , 28, | 29, 31 , 30, 32
168
+ scale: 0.5 #0.25
169
+ description: Plays 20 snares in a very long 4/3 syncopation to create a rolling, jazzy feel.
170
+
171
+ dotted snares fast 1:
172
+ pattern: 1, 2, 3, 5>0.5, 7, 5>0.5, 11, 5>0.5, 7, 5>0.5, 11, 9>0.5, 7, 9>0.5, 11, 9>0.5, 7, 9>0.5, 11, 16
173
+ scale: 0.5
174
+ description: Plays 10 snares in a fast 4/3 syncopation, a rhythm commonly used in drum&bass
175
+
176
+ dotted snares fast 2:
177
+ pattern: 1, 2>0.75, 2>0.25, 1.25:1.75;3, 4>0.75, 4>0.75, 4>0.75, 4>0.25, 3.25:3.75;5, 6>0.75, 6>0.75;7, 8>0.75, 6>0.25;8<0.25
178
+ scale: 1
179
+ description: Plays 10 snares in a fast 4/3 syncopation, a rhythm commonly used in drum&bass
180
+
181
+ dotted kicks:
182
+ pattern: 1>0.75, 1>0.25, 2>0.5, 1>0.75, 1>0.75, 4>0.75, 1>0.75, 1>0.5, 6>0.25, 1>0.75, 1>0.75, 1>0.25, 8>0.5, 1>0.5
183
+ scale: 1
184
+ description: Plays the first beat in a 4/3 syncopation while preserving snare beats.
185
+
186
+ dotted kicks 2:
187
+ pattern: 0:0.75, 0.75:1.5;0:0.75, 1.5:2.25;0:0.75, 2.25:3;0:0.75, 3:3.75;0:0.75, 3.75:4.5;0:0.75, 4.5:5.25;0:0.75, 5.25:6;0:0.75, 6:6.75;0:0.75, 6.75:7.5;0:0.75, 7.5:8;0:0.5
188
+ scale: 1
189
+ description: Plays a 4/3 syncopated first beat on top of normal beats.
190
+
191
+ tripple dotted: #try shifts
192
+ pattern: 1>0.375, 1>0.375, 1>0.25
193
+ scale: 8, 4, 2, 1, 0.5
194
+ description: Each beat turns into three 4/3 syncopated notes. Can be somewhat similar to footwork.
195
+
196
+ tripple dotted snares:
197
+ pattern: 1>0.375, 1>0.375, 1>0.25
198
+ scale: 8, 4, 2
199
+ shift: 1
200
+ description: plays only the snare beats in three 4/3 syncopated notes, a rhythm used in drum&bass/jungle.
201
+
202
+ dotted structure:
203
+ pattern: 1>0.75, 2>0.75, 4>0.5
204
+ scale: 4, 2, 1 #0.5
205
+ description: plays the significant drum beats as three 4/3 syncopated notes. Similar to moombahton but without the second kick.
206
+
207
+ dotted chaos 1:
208
+ pattern: 1>1/3
209
+ scale: 0.75
210
+
211
+ dotted chaos 2:
212
+ pattern: 1>1/6
213
+ scale: 0.75
214
+
215
+ dotted pattern 1:
216
+ pattern: 1, 2>0.75, 2>0.25, 1.25:1.75;3, 2>0.75, 2>0.75, 2>0.75, 2>0.25, 1.25:1.75;5, 2>0.75, 2>0.75;7, 2>0.75, 2>0.25;8<0.25
217
+ scale: 0.5
218
+ description: plays part between first kick and snare in a 4/3 syncopation, with original drums on top.
219
+
220
+ dotted pattern 2:
221
+ pattern: 1, 2>0.75, 2>0.25, 1.25:1.75;3, 4>0.75, 4>0.75, 4>0.75, 4>0.25, 3.25:3.75;5, 6>0.75, 6>0.75;7, 8>0.75, 6>0.25;8<0.25
222
+ scale: 0.5
223
+ description: plays parts between each kick and snare in a 4/3 syncopation, with original drums on top.
224
+
225
+ # ________________ TIME SIGNATURES ________________
226
+ 4-3:
227
+ pattern: 1>2/3, 2>2/3, 2>2/3
228
+ scale: 2, 1, 0.5
229
+ description: 4/3 time signature, preserves length
230
+
231
+ 3-4:
232
+ pattern: 1>0.75
233
+ scale: 8, 4, 3, 2
234
+ description: plays 3 beats out of each 4, creating 3/4 time signature
235
+
236
+ 4-7 1:
237
+ pattern: 1, 2, 3, 4>0.5
238
+ scale: 2, 1, 0.5, 0.25, 0.125
239
+ description: cuts 4th beat in half, creating 4/7 time signature
240
+
241
+ 4-7 2:
242
+ pattern: 1, 2, 3, 4>0.25, 3.75:4, 5,6>0.5, 7, 8
243
+ scale: 2, 1, 0.5, 0.25, 0.125
244
+ description: alternates between cutting 2nd and 4th beats in half, creating a natural 4/7 time signature
245
+
246
+ 4-13:
247
+ pattern: 1, 2, 3, 4>0.25
248
+ scale: 4, 2, 1, 0.5
249
+ description: abruptly stops on quarter of the 4th beat, creating 4/13 time signature
250
+
251
+ # ________________ GENRES ________________
252
+ moombahton:
253
+ pattern: 1>0.75, 2>0.25, 1>0.5, 4>0.5
254
+ scale: 3, 2, 1
255
+ description: a distinct popular moombathon/dutch house rhythm.
256
+
257
+ four-on-the-floor 1:
258
+ pattern: 1, 2, 1, 4, 1, 6, 1, 8, 1, 10, 1, 12, 1, 14, 1, 16
259
+ scale: 0.5
260
+ description: replaces snares with kicks
261
+
262
+ four-on-the-floor 1 double-time:
263
+ pattern: 1, 2, 1, 4, 1, 6, 1, 8, 1, 10, 1, 12, 1, 14, 1, 16, 1, 18, 1, 20, 1, 22, 1, 24, 1, 26, 1, 28, 1, 30, 1, 32
264
+ scale: 0.25
265
+ description: replaces snares with kicks
266
+
267
+ house 1:
268
+ pattern: 1, 2, 3, 4, 1, 6, 7, 8, 1, 10, 11, 12, 1, 14, 15, 16
269
+ scale: 0.5
270
+
271
+ house 1 double-time:
272
+ pattern: 1, 2, 5, 4, 1, 6, 5, 8, 1, 10, 13, 12, 1, 14, 13, 16, 1, 18, 21, 20, 1, 22, 21, 24, 1, 26, 29, 28, 1, 30, 29, 32
273
+ scale: 0.25
274
+
275
+ house 2:
276
+ pattern: 1>0.5
277
+ scale: 4
278
+
279
+ house 2 double-time:
280
+ pattern: 1>0.25
281
+ scale: 4
282
+
283
+ drill:
284
+ pattern: 1>0.75, 2>0.75, 2>0.5, 3>0.75, 4>0.75, 4>0.5, 5>0.75, 6>0.75, 6>0.5, 6, 7>0.75, 8<0.25
285
+ scale: 1, 0.5, 0.25 #2
286
+ description: distinct drill rhythm with 4/3 syncopatied notes and a shifted second snare.
287
+
288
+ jungle 1:
289
+ pattern: 1, 2, 3, 4, 5, 7, 6, 8, | 11, 10, 11, 12, 13, 15, 14, 16, | 19, 18, 19, 20, 21, 23, 22, 24, | 27, 26, 27, 28, 29, 31, 30, 32
290
+ scale: 1.5, 0.75, 0.5
291
+ description: Rhythm commonly used in jungle, otherwise sounds like a buildup snare pattern.
292
+
293
+ jungle 2:
294
+ pattern: 1, 2, 1, 2, | 3>0.5, 3>0.5, 1>0.5, 7>0.5, | 7>0.5, 7>0.5, 5>0.5, 11>0.5, | 11>0.5, 7>0.5, 0>0.5, 11>0.5, | 14>0.5, 11>0.5, 13>0.5, 15>0.5, 16!
295
+ scale: 0.5
296
+ description: 4/3 syncopated snares with additional snare-rolls
297
+
298
+ drumfunk:
299
+ pattern: 1, 2, 3 , 4, | 3 , 4, 9, 7 , | 8, 10, 11 , 0>0.5, 11>0.5 , | 0>0.5, 15>0.5, 14, 15 , 16
300
+ scale: 1, 0.5
301
+ description: pattern commonly used in drumfunk
302
+
303
+ jazzy:
304
+ pattern: 1, 2>0.5, 3, 4>0.5, 5, 6>0.5, 3, 4>0.5, 7, 8
305
+ scale: 0.5, 0.25
306
+ description: seamlessly adds a 4/3 syncopation without disrupting the original rhythm
307
+
308
+ darkstep:
309
+ pattern: 1,1,3,1, | 1,7,1,1, | 11,9,9,11, | 9,9,15,16
310
+ scale: 1, 0.5
311
+
312
+ darkstep long:
313
+ pattern: 1,1,3,1, | 1,7,1,1, | 11,9,9,11, | 9,9,15,9, | 17,19,17,17, | 19,17,17,23, | 25,25,27,25, | 25,31,25,32
314
+ scale: 0.5
315
+
316
+ darkstep fast:
317
+ pattern: 1,1,5,1, | 1,13,1,1, | 21,17,17,21, | 17,17,29,32
318
+ scale: 0.25
319
+
320
+ # ________________ EFFECTS ________________
321
+ staccato reverese:
322
+ pattern: 1>0.5, 0.5:0.8r, 0.5:0.8, 0.5:0.8r, 0.5:0.8, 0.5:0.8r, 3>0.6, 0.5:0.8r, 0.5:0.8, 0.5:0.8r, 0.5:0.8, 0.5:0.7r, 5>0.5, 0.5:0.8r, 0.5:0.8, 0.5:0.8r, 0.5:0.8, 0.5:0.8r, 7>0.6, 0.5:0.8r, 0.5:0.8, 0.5:0.8r, 7.6:7.9, 7.0>0
323
+ scale: 0.5, 0.25
324
+
325
+ staccato reverese syncopated 1:
326
+ pattern: 1, 2>0.5, 2.5:4r, 2.5:4, 2.5:4r, 2.5:4, 2.5:3r, | 9, 10.5:12, 10.5:12r, 10.5:12, 10.5:12r, 10.5:11.5, | 16:16.5, 18.5:20r, 18.5:20, 18.5:20r, 18.5:20, 18.5:20r, | 25, 25:25.5, 26.5:28r, 26.5:28, 26.5:28r, 26.5:28, 31.5:32
327
+ scale: 1/8, 1/16
328
+
329
+ staccato reverese syncopated 2:
330
+ pattern: 1, 2>0.5, 2.5:4r, 2.5:4, 2.5:4r, 2.5:4, 2.5:3r, | 9, 2.5:4, 2.5:4r, 2.5:4, 2.5:4r, 2.5:3.5, | 16:16.5, 2.5:4r, 2.5:4, 2.5:4r, 2.5:4, 2.5:4r, | 25, 25:25.5, 2.5:4r, 2.5:4, 2.5:4r, 2.5:4, 31.5:32
331
+ scale: 1/8, 1/16
332
+
333
+ staccato reverese syncopated 3:
334
+ pattern: 1, 2>0.5, 2.5:4s2,2.5:4s2r, 2.5:4, 2.5:4r, 2.5:4s2,2.5:4s2r, 2.5:3, | 9, 2.5:4r, 2.5:4s2,2.5:4s2r, 2.5:4, 2.5:4r, 2.5:4s2,2.5:4s2r, | 16:17.5, 2.5:4r, 2.5:4s2,2.5:4s2r, 2.5:4, 2.5:4r, | 24:25.5, 2.5:4, 2.5:4r, 2.5:4s2,2.5:4s2r, 2.5:4, 31.5:32r
335
+ scale: 1/8, 1/16
336
+
337
+ # ________________ SONGS ________________
338
+ BS6:
339
+ pattern: 1, 1, | 3>1.5, 3>1.5, 3>1.5, 3>1.5, | 9, 9>0.5 | 14.5>1.5, 14.5>1.5, 14.5>1.5, 14.5>1.5, 14.5>0.5, 16!
340
+ scale: 1, 0.5
341
+ description: Hyroglifics & Sinistarr - BS6
342
+
343
+ Poison:
344
+ pattern: 0:1/3, 0:1/3, 1:4/3, 1:4/3, 2:7/3, 2:7/3, 3:10/3, 3:10/3, 1/3:2/3, 4/3:5/3, 10/3:4
345
+ scale: 1
346
+ description: Stray & Halogenix - Poison
347
+
348
+ Szamar Madar:
349
+ pattern: 1, 2, 3, 4, 4, 1, 2, 3, 1, 1v0, 1v0, 1, 7, 8,|9, 10, 11, 12, 13, 14, 15, 16, 15, 10, 10, 10, 11, 16,|17, 18, 19, 20, 20, 17, 18, 19, 20, 20, 17, 17v0, 23, 24,|25, 25:25.5, 24:24.5, 27, 25, 28, 25, 31, 24:24.5, 27.5:28, 24:24.5, 27.5:28, 25, 25, 25, 31, 32
350
+ scale: 0.5
351
+ description: Venetian Snares - Szamár Madár (11/4)
352
+
353
+ Conceivability:
354
+ pattern: 1, 2, 3, 4, 9, 10, 11, 12, 13, 14, 16<0.5, 16>0.5, | 17, 18, 19>0.5, 20, 21, 21<0.5, 22, 23, 23<0.5, 24, 30, 31, 32>0.5
355
+ scale: 1
356
+
357
+ Rhythm Era:
358
+ pattern: 1, 2>0.75, 2>0.75, 2>0.75, 2>0.25, | 5, 6>0.75, 8>0.75, 6>0.75, 8>0.25, | 9, 10>0.75, 10>0.75, 10>0.75, 10>0.25, | 13, 14>0.75v0.6; 16>0.75v0.6, 14>0.75, 14>0.5, 14>0.5v0.6; 16>0.5v0.6
359
+ scale: 1
360
+ description: stunlocked - Rhythm Era (7/4)
361
+
362
+ # ________________ OTHER ________________
363
+ test:
364
+ pattern: test
365
+ description: puts cowbells on beats
{samples → beat_manipulator/samples}/cowbell.flac RENAMED
File without changes
beat_manipulator/samples/oh_live.ogg ADDED
Binary file (60.1 kB). View file
 
beat_manipulator/tests.py DELETED
@@ -1,121 +0,0 @@
1
- from . import main as bm
2
- audio=list(i/100 for i in range(-100,100,1))
3
- beatmap=list(range(0,100,10))+list(range(100,201,20))
4
-
5
- def printb(text):
6
- print(f'\033[1m{text}\033[0m')
7
- def printe(text):
8
- print(f'\x1b[0;31;40m{text}\x1b[0m')
9
-
10
- # audio:
11
- # [-1.0, -0.99, -0.98, -0.97, -0.96, -0.95, -0.94, -0.93, -0.92, -0.91, -0.9, -0.89, -0.88, -0.87, -0.86, -0.85, -0.84, -0.83, -0.82, -0.81, -0.8, -0.79, -0.78, -0.77, -0.76, -0.75, -0.74, -0.73, -0.72, -0.71, -0.7, -0.69, -0.68, -0.67, -0.66, -0.65, -0.64, -0.63, -0.62, -0.61, -0.6, -0.59, -0.58, -0.57, -0.56, -0.55, -0.54, -0.53, -0.52, -0.51, -0.5, -0.49, -0.48, -0.47, -0.46, -0.45, -0.44, -0.43, -0.42, -0.41, -0.4, -0.39, -0.38, -0.37, -0.36, -0.35, -0.34, -0.33, -0.32, -0.31, -0.3, -0.29, -0.28, -0.27, -0.26, -0.25, -0.24, -0.23, -0.22, -0.21, -0.2, -0.19, -0.18, -0.17, -0.16, -0.15, -0.14, -0.13, -0.12, -0.11, -0.1, -0.09, -0.08, -0.07, -0.06, -0.05, -0.04, -0.03, -0.02, -0.01, 0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.2, 0.21, 0.22, 0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.3, 0.31, 0.32, 0.33, 0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.4, 0.41, 0.42, 0.43, 0.44, 0.45, 0.46, 0.47, 0.48, 0.49, 0.5, 0.51, 0.52, 0.53, 0.54, 0.55, 0.56, 0.57, 0.58, 0.59, 0.6, 0.61, 0.62, 0.63, 0.64, 0.65, 0.66, 0.67, 0.68, 0.69, 0.7, 0.71, 0.72, 0.73, 0.74, 0.75, 0.76, 0.77, 0.78, 0.79, 0.8, 0.81, 0.82, 0.83, 0.84, 0.85, 0.86, 0.87, 0.88, 0.89, 0.9, 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99]
12
- # audio at beatmap:
13
- # [-1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
14
-
15
- test=bm.song(audio=audio, samplerate=2, bmap=beatmap, filename='test.mp3', log=False)
16
- if list(test.bm) == beatmap: printb('beatmap assignment passed')
17
- else: printe(f'''beatmap assignment error.
18
- {beatmap}
19
- {test.beatmap}''')
20
-
21
- test.beatmap.shift(2)
22
- if list(test.bm) == beatmap[2:]: printb('beatmap_shift(2) passed')
23
- else: printe(f'''beatmap_shift(2) error, 1st line is the expected result:
24
- {[0, 1, 2] + beatmap[1:]}
25
- {test.beatmap}''')
26
-
27
- test.beatmap.beatmap = beatmap.copy()
28
- test.beatmap.shift(-2)
29
- if list(test.bm) == list([0, 1, 2] + beatmap[1:]): printb ('beatmap_shift(-2) passed')
30
- else:printe(f'''beatmap_shift(-2) error, 1st line is the expected result:
31
- {beatmap[2:]}
32
- {test.beatmap}''')
33
-
34
- test.beatmap.beatmap = beatmap.copy()
35
- should=[5, 15, 25, 35, 45, 55, 65, 75, 85, 95, 110, 130, 150, 170, 190, 200]
36
- test.beatmap.shift(0.5)
37
- if list(test.bm) == should: printb('beatmap_shift(0.5) passed')
38
- else:printe(f'''beatmap_shift(0.5) error, 1st line is the expected result:
39
- {should}
40
- {test.beatmap}''')
41
-
42
- test.beatmap.beatmap = beatmap.copy()
43
- should=[0, 5, 15, 25, 35, 45, 55, 65, 75, 85, 95, 110, 130, 150, 170, 190]
44
- test.beatmap.shift(-0.5)
45
- if list(test.bm) == should: printb('beatmap_shift(-0.5) passed')
46
- else:printe(f'''beatmap_shift(-0.5) error, 1st line is the expected result:
47
- {should}
48
- {test.beatmap}''')
49
-
50
- test.beatmap.beatmap = beatmap.copy()
51
- should=[25, 35, 45, 55, 65, 75, 85, 95, 110, 130, 150, 170, 190, 200]
52
- test.beatmap.shift(2.5)
53
- if list(test.bm) == should: printb('beatmap_shift(2.5) passed')
54
- else:printe(f'''beatmap_shift(2.5) error, 1st line is the expected result:
55
- {should}
56
- {list(test.beatmap)}''')
57
-
58
- test.beatmap.beatmap = beatmap.copy()
59
- should=[1, 2, 3, 5, 15, 25, 35, 45, 55, 65, 75, 85, 95, 110, 130, 150, 170, 190]
60
- test.beatmap.shift(-2.5)
61
- if list(test.bm) == should: printb('beatmap_shift(-2.5) passed')
62
- else:printe(f'''beatmap_shift(-2.5) error, 1st line is the expected result:
63
- {should}
64
- {list(test.beatmap)}''')
65
-
66
- test.beatmap.beatmap = beatmap.copy()
67
- should=[0, 20, 40, 60, 80, 100, 140, 180]
68
- test.beatmap.scale(2)
69
- if list(test.bm) == should: printb('beatmap_scale(2) passed')
70
- else:printe(f'''beatmap_scale(2) error, 1st line is the expected result:
71
- {should}
72
- {list(test.beatmap)}''')
73
-
74
- test.beatmap.beatmap = beatmap.copy()
75
- should=[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190]
76
- test.beatmap.scale(0.5)
77
- if list(test.bm) == should: printb('beatmap_scale(2) passed')
78
- else:printe(f'''beatmap_scale(2) error, 1st line is the expected result:
79
- {should}
80
- {list(test.beatmap)}''')
81
-
82
- test.beatmap.beatmap = beatmap.copy()
83
- test.beatswap("1, 3, 2, 4", smoothing=0)
84
- should=[[-1.0, -0.99, -0.98, -0.97, -0.96, -0.95, -0.94, -0.93, -0.92, -0.91, -0.8, -0.79, -0.78, -0.77, -0.76, -0.75, -0.74, -0.73, -0.72, -0.71, -0.9, -0.89, -0.88, -0.87, -0.86, -0.85, -0.84, -0.83, -0.82, -0.81, -0.7, -0.69, -0.68, -0.67, -0.66, -0.65, -0.64, -0.63, -0.62, -0.61, -0.6, -0.59, -0.58, -0.57, -0.56, -0.55, -0.54, -0.53, -0.52, -0.51, -0.4, -0.39, -0.38, -0.37, -0.36, -0.35, -0.34, -0.33, -0.32, -0.31, -0.5, -0.49, -0.48, -0.47, -0.46, -0.45, -0.44, -0.43, -0.42, -0.41, -0.3, -0.29, -0.28, -0.27, -0.26, -0.25, -0.24, -0.23, -0.22, -0.21, -0.2, -0.19, -0.18, -0.17, -0.16, -0.15, -0.14, -0.13, -0.12, -0.11, 0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, -0.1, -0.09, -0.08, -0.07, -0.06, -0.05, -0.04, -0.03, -0.02, -0.01, 0.2, 0.21, 0.22, 0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.3, 0.31, 0.32, 0.33, 0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.4, 0.41, 0.42, 0.43, 0.44, 0.45, 0.46, 0.47, 0.48, 0.49, 0.5, 0.51, 0.52, 0.53, 0.54, 0.55, 0.56, 0.57, 0.58, 0.59, 0.8, 0.81, 0.82, 0.83, 0.84, 0.85, 0.86, 0.87, 0.88, 0.89, 0.9, 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 0.6, 0.61, 0.62, 0.63, 0.64, 0.65, 0.66, 0.67, 0.68, 0.69, 0.7, 0.71, 0.72, 0.73, 0.74, 0.75, 0.76, 0.77, 0.78, 0.79], [-1.0, -0.99, -0.98, -0.97, -0.96, -0.95, -0.94, -0.93, -0.92, -0.91, -0.8, -0.79, -0.78, -0.77, -0.76, -0.75, -0.74, -0.73, -0.72, -0.71, -0.9, -0.89, -0.88, -0.87, -0.86, -0.85, -0.84, -0.83, -0.82, -0.81, -0.7, -0.69, -0.68, -0.67, -0.66, -0.65, -0.64, -0.63, -0.62, -0.61, -0.6, -0.59, -0.58, -0.57, -0.56, -0.55, -0.54, -0.53, -0.52, -0.51, -0.4, -0.39, -0.38, -0.37, -0.36, -0.35, -0.34, -0.33, -0.32, -0.31, -0.5, -0.49, -0.48, -0.47, -0.46, -0.45, -0.44, -0.43, -0.42, -0.41, -0.3, -0.29, -0.28, -0.27, -0.26, -0.25, -0.24, -0.23, -0.22, -0.21, -0.2, -0.19, -0.18, -0.17, -0.16, -0.15, -0.14, -0.13, -0.12, -0.11, 0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, -0.1, -0.09, -0.08, -0.07, -0.06, -0.05, -0.04, -0.03, -0.02, -0.01, 0.2, 0.21, 0.22, 0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.3, 0.31, 0.32, 0.33, 0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.4, 0.41, 0.42, 0.43, 0.44, 0.45, 0.46, 0.47, 0.48, 0.49, 0.5, 0.51, 0.52, 0.53, 0.54, 0.55, 0.56, 0.57, 0.58, 0.59, 0.8, 0.81, 0.82, 0.83, 0.84, 0.85, 0.86, 0.87, 0.88, 0.89, 0.9, 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 0.6, 0.61, 0.62, 0.63, 0.64, 0.65, 0.66, 0.67, 0.68, 0.69, 0.7, 0.71, 0.72, 0.73, 0.74, 0.75, 0.76, 0.77, 0.78, 0.79]]
85
- if list(test.audio) == should: printb('beatswap("1, 3, 2, 4") passed')
86
- else:printe(f'''beatswap("1, 3, 2, 4") error, 1st line is the expected result:
87
- {should}
88
- {list(test.audio)}''')
89
-
90
- # [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 120, 140, 160, 180, 200]
91
-
92
- def import_test():
93
- audio2=list(i/100000 for i in range(-100000,100000,1))
94
- beatmap2=list(range(0,100000,10))+list(range(100,200001,20))
95
- test2=bm.song(audio=audio2, samplerate=2, bmap=beatmap2, filename='test2.mp3', log=False)
96
-
97
- def shift_test(number, shift):
98
- audio2=list(i/number for i in range(-number,number,1))
99
- beatmap2=list(range(0,number,10))+list(range(100,number*2+1,20))
100
- test2=bm.song(audio=audio2, samplerate=2, bmap=beatmap2, filename='test2.mp3', log=False)
101
- test2.beatmap.shift(shift)
102
-
103
- def scale_test(number, scale):
104
- audio2=list(i/number for i in range(-number,number,1))
105
- beatmap2=list(range(0,number,10))+list(range(100,number*2+1,20))
106
- test2=bm.song(audio=audio2, samplerate=2, bmap=beatmap2, filename='test2.mp3',log=False)
107
- test2.beatmap.scale(0.5)
108
-
109
- def beatswap_test(number, pattern):
110
- audio2=list((i/number)*100 for i in range(-number,number,1))
111
- beatmap2=list(range(0,number*100,1000))+list(range(10000,number*200+1,2000))
112
- test2=bm.song(audio=audio2, samplerate=2, bmap=beatmap2, filename='test2.mp3',log=False)
113
- test2.beatswap(pattern)
114
-
115
- input('run time tests?')
116
- import timeit
117
- printb(f'beatmap_shift(-2.5) for 1000 beats takes {timeit.timeit(lambda: shift_test(1000,shift=-2.5), number=1)}') #0.0028216999489814043
118
- printb(f'beatmap_shift(-2.5) for 20000 beats takes {timeit.timeit(lambda: shift_test(20000,shift=-2.5), number=1)}') #0.6304191001690924
119
- printb(f'beatmap_scale(0.5) for 20000 beats takes {timeit.timeit(lambda: scale_test(20000,scale=0.5), number=1)}') #0.10623739985749125
120
- printb(f'test2.beatswap("1,3,2,4") for 20000 beats takes {timeit.timeit(lambda: beatswap_test(20000,pattern="1,3,2,4"), number=1)}') #0.406920799985528
121
- printb(f'test2.beatswap("1v2, 0:0.5b5, 1:1.5r, 3c, 4:3") for 20000 beats takes {timeit.timeit(lambda: beatswap_test(20000,pattern="1v2, 0:0.5b5, 1:1.5r, 3c, 4:3"), number=1)}') #0.5667359000071883
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beat_manipulator/utils.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ C_SLICE = ":><" # 0 - range, 1 - first, 2 - last
2
+ C_JOIN = ",;~&^$}" # 0 - append, 1 - first length, 2 - cut, 3 - maximum, 4 - sidechain
3
+ C_MISC = "'\"`i@_?%#![]"
4
+ # 0 ',1 " - sample, 2 ` - sample uncut, 3 i - current, 4 @ - random,
5
+ # # 5 _ - random sep, 6 ? - not count, 7 % - create variable, 8 # - shuffle, 9 ! skip
6
+ # 10, 11 [] - song
7
+ C_MATH = '+-*/.'
8
+ C_MATH_STRICT = '.+-*/'
9
+
10
+ def _safer_eval(string:str) -> float:
11
+ if isinstance(string, str):
12
+ try:
13
+ for i in (C_MISC[4], C_MISC[7], C_MISC[8]):
14
+ if i in string: string = string[:string.find(i)]
15
+ string = string.replace('{', '<').replace('}', '>')
16
+ string = eval(''.join([i for i in string if i.isdecimal() or i in C_MATH]))
17
+ except (NameError, SyntaxError): string = 1
18
+ return string
19
+
20
+ def _safer_eval_strict(string:str) -> float:
21
+ if isinstance(string, str):
22
+ for n, v in enumerate(string):
23
+ assert v in C_MATH_STRICT or v == ' ' or v.isdecimal, f"_safer_eval_strict error: {string}[{n}] = {v}, which isn't a decimal, isn't in {C_MATH_STRICT} and isn't a space"
24
+ string = eval(''.join([i for i in string if i.isdecimal() or i in C_MATH_STRICT]))
25
+ return string
beat_manipulator/wrapper.py DELETED
@@ -1,209 +0,0 @@
1
- from . import main as bm
2
- from .main import _outputfilename
3
- import json
4
- def _safer_eval(string:str) -> float:
5
- if isinstance(string, str):
6
- #print(''.join([i for i in string if i.isdecimal() or i in '.+-*/']))
7
- string = eval(''.join([i for i in string if i.isdecimal() or i in '.+-*/']))
8
- return string
9
-
10
- with open("presets.json", "r") as f:
11
- presets=f.read()
12
-
13
- presets=json.loads(presets)
14
-
15
- def _song_copy(audio:bm.song):
16
- return bm.song(path=audio.path, audio=audio.audio, samplerate=audio.samplerate, bmap=audio.beatmap, caching=audio.caching, filename=audio.filename, copied=True)
17
-
18
- def _normalize(song: bm.song, beat, pattern=None, scale=None, shift=None):
19
- beat=beat.lower()
20
- if pattern is not None:
21
- if scale is None: scale=1
22
- if shift is None: shift=0
23
- song.quick_beatswap(output=None, pattern=pattern, scale=scale,shift=shift)
24
- elif beat=='normal' or beat is None: pass
25
- elif beat=='shifted': song.quick_beatswap(output=None, pattern='1,2,3,4,5,7,6,8', scale=0.5)
26
- elif beat=='shifted2': song.quick_beatswap(output=None, pattern='1,2,3,4,5,6,8,7', scale=0.5)
27
- else: print(f"'{beat}' is not a valid beat")
28
- return song
29
-
30
- def lib_test(filename,output='', samplerate=44100, lib='madmom.BeatDetectionProcessor', scale=1, shift=0,beat='normal', log=False):
31
- '''basically a way to quickly test scale and offset'''
32
- if type(filename)==str :
33
- song=bm.song(filename)
34
- samplerate=song.samplerate
35
- else:
36
- song=filename
37
- if beat!='normal' and beat is not None: song=_normalize(song=song, beat=beat, scale=scale, shift=shift)
38
- song.quick_beatswap(output=None, pattern='test', scale=scale, shift=shift, log=log)
39
- if beat!='normal' and beat is not None: song=_normalize(song=song, beat=beat, scale=scale, shift=shift)
40
- song.write_audio(output=bm.outputfilename('', song.filename, f' ({lib} x{scale} {shift})'))
41
-
42
- def lib_test_full(filename,samplerate, log):
43
- '''A way to test all beat detection modules to see which one performs better.'''
44
- print(filename)
45
- lib_test(filename, samplerate,'madmom.BeatDetectionProcessor', log=log)
46
- lib_test(filename, samplerate,'madmom.BeatDetectionProcessor.consistent', log=log)
47
- #lib_test(filename, samplerate,'madmom.BeatTrackingProcessor') # better for live performances with variable BPM
48
- #lib_test(filename, samplerate,'madmom.BeatTrackingProcessor.constant') # results identical to madmom.BeatDetectionProcessor
49
- lib_test(filename, samplerate,'madmom.BeatTrackingProcessor.consistent', log=log)
50
- lib_test(filename, samplerate,'madmom.CRFBeatDetectionProcessor', log=log)
51
- lib_test(filename, samplerate,'madmom.CRFBeatDetectionProcessor.constant',log=log)
52
- #lib_test(filename, samplerate,'madmom.DBNBeatTrackingProcessor') # better for live performances with variable BPM
53
- lib_test(filename, samplerate,'madmom.DBNBeatTrackingProcessor.1000',log=log)
54
- lib_test(filename, samplerate,'madmom.DBNDownBeatTrackingProcessor',log=log)
55
- import gc
56
- gc.collect()
57
-
58
- def _process_list(something)-> list:
59
- if isinstance(something, int) or isinstance(something, float): something=(something,)
60
- elif isinstance(something,list): False if isinstance(something[0],int) or isinstance(something[0],float) else list(_safer_eval(i) for i in something)
61
- else: something=list(_safer_eval(i) for i in something.split(','))
62
- return something
63
-
64
- def _process(song:bm.song, preset: str, scale:float, shift:float, random=False, every=False, log=True)->bm.song:
65
- #print(preset)
66
- if 'pattern' in preset:
67
- shift=shift+(preset['shift'] if 'shift' in preset else 0)
68
- # Scale can be a list and we either take one value or all of them
69
- if 'scale' in preset: pscale=_process_list(preset['scale'])
70
- else: pscale=(1,)
71
- #input(pscale)
72
- if random is True:
73
- import random
74
- pscale=random.choice(pscale)
75
- elif every is True:
76
- songs=[]
77
- for i in pscale:
78
- song2=_song_copy(song)
79
- song2.quick_beatswap(output=None, pattern=preset['pattern'], scale=scale*i, shift=shift, log = log)
80
- songs.append((song2, i))
81
- return songs
82
- else: pscale=preset['scale_d'] if 'scale_d' in preset else pscale[0]
83
- if every is False: song.quick_beatswap(output=None, pattern=preset['pattern'], scale=scale*pscale, shift=shift, log = log)
84
- elif preset['type'] =='sidechain':
85
- length=preset['sc length'] if 'sc length' in preset else 0.5
86
- curve=preset['sc curve'] if 'sc curve' in preset else 2
87
- vol0=preset['sc vol0'] if 'sc vol0' in preset else 0
88
- vol1=preset['sc vol1'] if 'sc vol1' in preset else 1
89
- from . import generate
90
- sidechain=bm.open_audio(preset['sc impulse'])[0] if 'sc impulse' in preset else generate.sidechain(samplerate=song.samplerate, length=length, curve=curve, vol0=vol0, vol1=vol1, smoothing=40)
91
- scale=scale*(preset['scale'] if 'scale' in preset else 1)
92
- shift=shift+(preset['shift'] if 'shift' in preset else 0)
93
- song.quick_sidechain(output=None, audio2=sidechain, scale=scale, shift=shift)
94
- elif preset['type'] =='beatsample':
95
- sample=preset['filename']
96
- scale=scale*(preset['scale'] if 'scale' in preset else 1)
97
- shift=shift+(preset['shift'] if 'shift' in preset else 0)
98
- song.quick_beatsample(output=None, filename2=sample, scale=scale, shift=shift)
99
- return song
100
-
101
-
102
- def use_preset(output:str,song: str, preset: str, presets=presets, scale=1, shift=0, beat:str='normal', test=False, _normalize=True, random=False, every=False, log = True):
103
- if not isinstance(song, bm.song):
104
- song=bm.song(song)
105
- else: song = _song_copy(song)
106
- #print(song.samplerate)
107
- if preset is None:
108
- weights=[]
109
- for i in presets.items():
110
- weights.append(i[1]['weight'])
111
- import random
112
- preset = random.choices(population=list(presets), weights=weights, k=1)[0]
113
- name=preset
114
- if isinstance(preset, str): preset=presets[preset]
115
- if test is True:
116
- testsong=_song_copy(song)
117
- lib_test(testsong, output, samplerate=testsong.samplerate, log = log)
118
- del testsong
119
- #print(name, preset)
120
- if _normalize is True and beat!='normal' and beat is not None:
121
- if '_normalize' in preset:
122
- if preset['_normalize'] is True:
123
- song=_normalize(song, beat)
124
- if '1' in preset:
125
- for i in preset:
126
- if type(preset[i])==dict:song=_process(song, preset[i], scale=scale, shift=shift, log=log)
127
- else: song=_process(song, preset,scale=scale,shift=shift,random=random, every=every, log=log)
128
- if isinstance(song, list):
129
- for i in song:
130
- i[0].write(output=_outputfilename(output, i[0].filename, suffix=f' ({name}{(" x"+str(round(i[1], 3)))*(len(song)>1)})'))
131
- else:
132
- out_folder = _outputfilename(output, song.filename, suffix=' ('+name+')')
133
- song.write(output=out_folder)
134
- return out_folder
135
-
136
- def all(output:str,filename: str, presets:dict=presets, scale=1, shift=0, beat='normal', test=True, boring=False, effects=False, variations=False, log = False):
137
- if boring is False:
138
- for i in ['2x faster','3x faster','4x faster','8x faster','1.33x faster','1.5x faster','1.5x slower','reverse','random', 'syncopated effect']:
139
- if i in presets:
140
- #print(i)
141
- presets.pop(i)
142
- if not isinstance(filename, bm.song): song=bm.song(filename)
143
- else: song=filename
144
- song__normalized=_normalize(_song_copy(song), beat)
145
- if test is True:
146
- testsong=_song_copy(song)
147
- lib_test(testsong, output, samplerate=testsong.samplerate, log = log)
148
- del testsong
149
- for key, i in presets.items():
150
- #print(key, i)
151
- if 'scale' in i:
152
- #print(i['scale'])
153
- if isinstance(i['scale'], int) or isinstance(i['scale'], float):
154
- if i['scale']<0.01:
155
- continue
156
- if effects is False:
157
- if 'effect - ' in key: continue
158
- if '_normalize' in i:
159
- if i['_normalize'] is True:
160
- song2=_song_copy(song__normalized)
161
- else: song2=_song_copy(song)
162
- else: song2=_song_copy(song)
163
- use_preset(output, song2, preset=key, presets=presets, scale=scale, shift=shift, beat=beat, test=False, _normalize=False, every=variations, log = log)
164
-
165
-
166
-
167
- # ___ my stuff ___
168
-
169
- # ___ get song ___
170
- #filename='F:/Stuff/Music/Tracks/Poseidon & Leon Ross - Parallax.mp3'
171
- #filename = 'F:/Stuff/Music/Tracks/'+random.choice(os.listdir("F:\Stuff\Music\Tracks"))
172
- # print(filename)
173
-
174
- # ___ analyze+fix ___
175
- #scale, shift = 1,0
176
- #lib_test(filename, scale=scale, shift=shift)
177
- #bm.fix_beatmap(filename, scale=scale, shift=shift)
178
-
179
- # ___ presets ___
180
- #use_preset ('', filename, 'dotted kicks', scale=1, shift=0, beat='normal', test=False)
181
- #use_preset ('', filename, None, scale=scale, shift=shift, test=False)
182
- #all('', filename, scale=1, shift=0, beat='normal', test=False)
183
-
184
- # ___ beat swap __
185
- #song=bm.song(filename)
186
- #song.quick_beatswap(output='', pattern='test', scale=1, shift=0)
187
-
188
- # ___ osu ___
189
- #song=bm.song()
190
- #song.generate_hitmap()
191
- #song.osu()
192
- #song.hitsample()
193
-
194
- # ___ saber2osu ___
195
- #import Saber2Osu as s2o
196
- #osu=s2o.osu_map(threshold=0.3, declumping=100)
197
-
198
- # ___ song to image ___
199
- #song.write_image()
200
-
201
- # ___ randoms ___
202
- # while True:
203
- # filename = 'F:/Stuff/Music/Tracks/'+random.choice(os.listdir("F:\Stuff\Music\Tracks"))
204
- # use_preset ('', filename, None, scale=scale, shift=shift, test=False)
205
-
206
- # ___ effects ___
207
- #song = bm.song(filename)
208
- #song.audio=bm.pitchB(song.audio, 2, 100)
209
- #song.write_audio(bm.outputfilename('',filename, ' (pitch)'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
examples.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import beat_manipulator as bm, os, random
2
+
3
+ path = 'F:/Stuff/Music/Tracks/'
4
+ song = 'Phonetick - You.mp3'
5
+ song = path + song
6
+
7
+ #bm.presets.savetest(song, scale = 1, shift = 0)
8
+
9
+ bm.beatswap(song, 'random', scale = 1, shift = 0)
10
+
11
+ #bm.presets.use(song = song, preset = 'dotted snares fast 1', scale = 1)
jupiter.ipynb ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "attachments": {},
5
+ "cell_type": "markdown",
6
+ "metadata": {},
7
+ "source": [
8
+ "<h1><b><center>Beat Manipulator</center></b></h1>"
9
+ ]
10
+ },
11
+ {
12
+ "attachments": {},
13
+ "cell_type": "markdown",
14
+ "metadata": {},
15
+ "source": [
16
+ "Simply put your pattern in the cell below and run it as many times as you wish. Pattern syntax, scale and shift are explained here https://github.com/stunlocked1/BeatManipulator\n",
17
+ "\n",
18
+ "A file selection dialog will open. Note: you might need to Alt+Tab to it due to how Jupiter works (press Alt+Tab and select file selection dialog). Alternatively you can add `audio=\"path/to/audio\"` attribute into bm.beatswap to load a specified audio file.\n",
19
+ "\n",
20
+ "Choose any audio file, and the beatswapped version will be displayed, as well as saved next to this Jupiter Notebook file.\n",
21
+ "\n",
22
+ "Analyzing beats for the first time will take some time, but if you open the same file for the second time, it will load a saved beat map."
23
+ ]
24
+ },
25
+ {
26
+ "cell_type": "code",
27
+ "execution_count": null,
28
+ "metadata": {},
29
+ "outputs": [],
30
+ "source": [
31
+ "pattern = '1, 4' # Replace this with your pattern. You can write \"test\" as a pattern to test where each beat is.\n",
32
+ "scale = 1\n",
33
+ "shift = 0\n",
34
+ "audio = None # If you want to skip select file dialog, replace None with a path to your audio file\n",
35
+ "\n",
36
+ "pattern_length = None # Length of the pattern. If None, this will be inferred from the highest number in the pattern\n",
37
+ "\n",
38
+ "\n",
39
+ "import beat_manipulator as bm, IPython\n",
40
+ "print(\"Press alt+tab if file selection dialog didn't show\")\n",
41
+ "path = bm.beatswap(audio=audio, pattern = pattern, scale = scale, shift = shift, length = pattern_length)\n",
42
+ "IPython.display.Audio(path)"
43
+ ]
44
+ },
45
+ {
46
+ "attachments": {},
47
+ "cell_type": "markdown",
48
+ "metadata": {},
49
+ "source": [
50
+ "***\n",
51
+ "## Other stuff\n",
52
+ "Those operate the same as the above cell"
53
+ ]
54
+ },
55
+ {
56
+ "attachments": {},
57
+ "cell_type": "markdown",
58
+ "metadata": {},
59
+ "source": [
60
+ "**Song to image**\n",
61
+ "\n",
62
+ "creates an image based on beat positions, so each song will generate a unique image."
63
+ ]
64
+ },
65
+ {
66
+ "cell_type": "code",
67
+ "execution_count": null,
68
+ "metadata": {},
69
+ "outputs": [],
70
+ "source": [
71
+ "image_size = 512 # image will be a square with this size in pixels\n",
72
+ "audio = None # If you want to skip select file dialog, replace None with a path to your audio file\n",
73
+ "\n",
74
+ "\n",
75
+ "import beat_manipulator as bm, IPython\n",
76
+ "print(\"Press alt+tab if file selection dialog didn't show\")\n",
77
+ "path = bm.image(audio=audio, max_size = image_size)\n",
78
+ "IPython.display.Image(path)"
79
+ ]
80
+ },
81
+ {
82
+ "attachments": {},
83
+ "cell_type": "markdown",
84
+ "metadata": {},
85
+ "source": [
86
+ "***\n",
87
+ "**osu! beatmap generator**\n",
88
+ "\n",
89
+ "generates an osu! beatmap from your song. This generates a hitmap, probabilities of hits at each sample, picks all ones above a threshold, and turns them into osu circles, trying to emulate actual osu beatmap. This doesn't generate sliders, however, because no known science has been able to comprehend the complexity of those.\n",
90
+ "\n",
91
+ "The .osz file will be generated next to this notebook, open it with osu! to install it as any other beatmap."
92
+ ]
93
+ },
94
+ {
95
+ "cell_type": "code",
96
+ "execution_count": null,
97
+ "metadata": {},
98
+ "outputs": [],
99
+ "source": [
100
+ "difficulties = [0.2, 0.1, 0.05, 0.025, 0.01, 0.0075, 0.005, 0.0025, 0.0001] # all difficulties will be embedded in one beatmap, lower = harder.\n",
101
+ "audio = None # If you want to skip select file dialog, replace None with a path to your audio file\n",
102
+ "\n",
103
+ "\n",
104
+ "import beat_manipulator.osu\n",
105
+ "print(\"Press alt+tab if file selection dialog didn't show\")\n",
106
+ "beat_manipulator.osu.generate(song=audio, difficulties = difficulties)"
107
+ ]
108
+ }
109
+ ],
110
+ "metadata": {
111
+ "kernelspec": {
112
+ "display_name": "audio310",
113
+ "language": "python",
114
+ "name": "python3"
115
+ },
116
+ "language_info": {
117
+ "codemirror_mode": {
118
+ "name": "ipython",
119
+ "version": 3
120
+ },
121
+ "file_extension": ".py",
122
+ "mimetype": "text/x-python",
123
+ "name": "python",
124
+ "nbconvert_exporter": "python",
125
+ "pygments_lexer": "ipython3",
126
+ "version": "3.10.9"
127
+ },
128
+ "orig_nbformat": 4,
129
+ "vscode": {
130
+ "interpreter": {
131
+ "hash": "f56da36b984886453ea677d340712034d0bd218b2dc7a53ab7c38da0c6f67f35"
132
+ }
133
+ }
134
+ },
135
+ "nbformat": 4,
136
+ "nbformat_minor": 2
137
+ }
packages.txt DELETED
@@ -1,3 +0,0 @@
1
- ffmpeg
2
- cython
3
- python3-opencv
 
 
 
 
presets.json DELETED
@@ -1,316 +0,0 @@
1
- {
2
- "2x faster": {
3
- "pattern": "0:0.5",
4
- "scale": "8/3, 2, 4/3, 1, 0.5, 1/3, 0.25",
5
- "scale_d": 1,
6
- "weight": 2.5
7
- },
8
- "3x faster": {
9
- "pattern": "0:1/3",
10
- "scale": "8, 4, 2, 1, 0.5, 1/3",
11
- "scale_d": 1,
12
- "weight": 2.5
13
- },
14
- "4x faster": {
15
- "pattern": "0:0.25",
16
- "scale": "2, 1, 0.5, 1/3",
17
- "scale_d": 1,
18
- "weight": 1.25
19
- },
20
- "8x faster": {
21
- "pattern": "0:0.125",
22
- "scale": "2, 1, 0.5",
23
- "scale_d": 1,
24
- "weight": 0.75
25
- },
26
- "1.33x faster": {
27
- "pattern": "0:0.75",
28
- "scale": "16, 8, 4, 2, 1, 0.5, 1/3, 0.25, 0.2",
29
- "scale_d": 1,
30
- "weight": 5
31
- },
32
- "1.5x faster": {
33
- "pattern": "0:2/3",
34
- "scale": "16, 8, 4, 2, 1, 0.5, 1/3",
35
- "scale_d": 1,
36
- "weight": 5
37
- },
38
- "1.5x slower": {
39
- "pattern": "0:0.5, 0.5:1r, 0.5:1",
40
- "scale": "1, 0.5, 1/3, 0.25, 0.2, 1/7, 0.125",
41
- "weight": 4
42
- },
43
- "reverse": {
44
- "pattern": "reverse",
45
- "scale": "1, 0.5, 1/3, 0.25, 0.2",
46
- "weight": 5
47
- },
48
- "random": {
49
- "pattern": "random",
50
- "scale": "1, 0.5, 1/3",
51
- "weight": 0.000000001
52
- },
53
- "half-time A": {
54
- "pattern": "1,2,4,5, | 3,6,8,7, | 9,11,12,13, | 15,13,14,16",
55
- "scale": 0.5,
56
- "normalize": true,
57
- "weight": 10
58
- },
59
- "half-time B": {
60
- "pattern": "1,2,2r,4,3,6r,6,8",
61
- "scale": 0.5,
62
- "normalize": true,
63
- "weight": 5
64
- },
65
- "half-time C": {
66
- "pattern": "1,2,4,5,3,8,6,8, | 9,10,12,13,15,16,14,16",
67
- "scale": 0.5,
68
- "normalize": true,
69
- "weight": 10
70
- },
71
- "quarter-time A": {
72
- "pattern": "1,2,4,5,|6,8,9,10,|11,12,13,14,|16,14,15,16",
73
- "scale": 0.5,
74
- "normalize": true,
75
- "weight": 10
76
- },
77
- "quarter-time B": {
78
- "pattern": "1,2,2,4, | 5,6r,6,8, | 11,10,10r,12, | 13,14r,14r,16",
79
- "scale": 0.5,
80
- "normalize": true,
81
- "weight": 5
82
- },
83
- "quarter-time C": {
84
- "pattern": "1,2,4,5, | 6,8,10,12, | 11,10,12,13, | 9,13,14,16",
85
- "scale": 0.5,
86
- "normalize": true,
87
- "weight": 10
88
- },
89
- "dotted snares A": {
90
- "pattern": "1, 1:1.5, 3, 3:3.5, 5, 5:5.5, 3, 3:3.5, 7, 8",
91
- "normalize": true,
92
- "weight": 10
93
- },
94
- "dotted snares B": {
95
- "pattern": "1, 2, 3 , 4, | 5, 7 , 6, 8, | 11 , 10, 9, 11 , | 13, 14, 15 , 16",
96
- "scale": 0.5,
97
- "normalize": true,
98
- "weight": 10
99
- },
100
- "dotted snares B 4": {
101
- "pattern": "1, 2, 3 , 4, | 5, 7 , 6, 8, | 11 , 10, 9, 11 , | 13, 14, 15 , 16, | 17, 19 , 18, 20, | 23 , 22, 21, 23 , | 25, 26, 27 , 28, | 29, 31 , 30, 32, | 35 , 34, 33, 35 , | 37, 38, 39 , 40, | 41, 43 , 42, 44, | 47 , 46, 45, 47 , | 49, 50, 51 , 52, | 53, 55 , 54, 56, | 59 , 58, 57, 59 , | 61, 62, 63 , 64",
102
- "scale": 0.5,
103
- "normalize": true,
104
- "weight": 10
105
- },
106
- "dotted snares 0.5 A": {
107
- "pattern": "0:3, 4:4.5,7, 4:4.5,11, 4:4.5,7, 4:4.5,11, 8:8.5,7, 8:8.5,11, 8:8.5,7, 8:8.5,11, 16",
108
- "scale": 0.5,
109
- "normalize": true,
110
- "weight": 10
111
- },
112
- "dotted kicks": {
113
- "pattern": "0:0.75, 0:0.25, 1:1.5, 0:0.75, 0:0.75, 3:3.75, 0:0.75, 0:0.5, 5:5.25, 0:0.75, 0:0.75, 0:0.25, 7:7.5, 0:0.5",
114
- "scale": 1,
115
- "normalize": true,
116
- "weight": 10
117
- },
118
- "dotted kicks B": {
119
- "pattern": "1, 2, 3, 1, |5, 6, 1, 8, 9, 1, 11, 12, |13, 14, 15, 1, 17, 18, 1, 20, |21, 1, 23, 24, 1, 26, 27, 1, |29, 30, 1, 32",
120
- "scale": 0.25,
121
- "normalize": true,
122
- "weight": 10
123
- },
124
- "drum&bass": {
125
- "pattern": "1, 2, 3, 4, 5, 7, 6, 8",
126
- "scale": 0.5,
127
- "weight": 2
128
- },
129
- "tripple dotted": {
130
- "pattern": "0:0.375, 0:0.375, 0:0.25",
131
- "scale": "8, 4, 2, 1, 0.5",
132
- "scale_d": 1,
133
- "weight": 5
134
- },
135
- "tripple dotted snares": {
136
- "pattern": "0:0.375, 0:0.375, 0:0.25",
137
- "scale": 2,
138
- "shift": 1,
139
- "normalize": true,
140
- "weight": 5
141
- },
142
- "dotted structure": {
143
- "pattern": "0:0.75, 1:1.75, 3:3.5",
144
- "scale": "4, 2, 1, 1/3, 0.25, 0.2",
145
- "scale_d": 1,
146
- "weight": 10
147
- },
148
- "moombahton": {
149
- "pattern": "0:0.75, 1:1.25, 0:0.5, 3:3.5",
150
- "weight": 10
151
- },
152
- "four-on-the-floor": {
153
- "pattern": "1, 0:0.5, 1.5:2, 0:0.5, 2.5:3, 0:0.5, 3.5:4, 0:0.5, 4.5:5, 0:0.5, 5.5:6, 0:0.5, 6.5:7, 0:0.5, 7.5:8",
154
- "weight": 10
155
- },
156
- "four-on-the-floor 0.5": {
157
- "pattern": "1, 2, 1, 4, 1, 6, 1, 8, 1, 10, 1, 12, 1, 14, 1, 16, 1, 18, 1, 20, 1, 22, 1, 24, 1, 26, 1, 28, 1, 30, 1, 32",
158
- "scale": 0.25,
159
- "weight": 10
160
- },
161
- "house": {
162
- "pattern": "1, 2, 0:0.5, 2.5:3, 1:1.5, 3.5:4, 0:0.5, 4.5:5, 3:3.5, 5.5:6, 0:0.5, 6.5:7, 3:3.5, 7.5:8",
163
- "weight": 10
164
- },
165
- "house 0.5": {
166
- "pattern": "1, 2, 5, 4, 1, 6, 5, 8, 1, 10, 13, 12, 1, 14, 13, 16, 1, 18, 21, 20, 1, 22, 21, 24, 1, 26, 29, 28, 1, 30, 29, 32",
167
- "scale": 0.25,
168
- "weight": 10
169
- },
170
- "drill": {
171
- "pattern": "0:0.75,1:1.75,1:1.5, 2:2.75,3:3.75,3:3.5, 4:4.75,5:5.75,5:5.5, 6, 6:6.75, 7.75:8",
172
- "scale": 0.5,
173
- "weight": 10
174
- },
175
- "jungle A": {
176
- "pattern": "1, 2, 3, 4, 5, 7, 6, 8, | 11, 10, 11, 12, 13, 15, 14, 16, | 19, 18, 19, 20, 21, 23, 22, 24, | 27, 26, 27, 28, 29, 31, 30, 32",
177
- "scale": 0.5,
178
- "normalize": true,
179
- "weight": 10
180
- },
181
- "jungle B": {
182
- "pattern": "1, 2, 1, 2, | 2:3.5, 2:2.5, 0:0.5, 6:6.5, | 6:7.5, 6:6.5, 4:4.5, 10:10.5, | 10:11.5, 6:6.5, 8:8.5, 10:10.5, | 14:15.5, 10:10.5, 12:12.5, 14:14.5, 16!",
183
- "scale": 0.5,
184
- "normalize": true,
185
- "weight": 10
186
- },
187
- "drumfunk": {
188
- "pattern": "1, 2, 3 , 4, | 3 , 4, 9, 7 , | 8, 10, 11 , 8:8.5, 10:10.5 , | 8:8.5, 14:14.5, 14, 15 , 16",
189
- "scale": 0.5,
190
- "normalize": true,
191
- "weight": 10
192
- },
193
- "neuro-hop": {
194
- "pattern": "1, 1:1.5, 3, 3:3.5, 5, 5:5.5, 3, 3:3.5, 7, 8",
195
- "scale": "0.5, 0.25",
196
- "weight": 10
197
- },
198
- "BS6": {
199
- "pattern": "1, 1, | 2:3.5, 2:3.5, 2:3.5, 2:3.5, 8!",
200
- "scale": 0.5,
201
- "normalize": true,
202
- "weight": 10
203
- },
204
- "staccato reverese": {
205
- "pattern": "0:0.5, 0.5:0.8r, 0.5:0.8, 0.5:0.8r, 0.5:0.8, 0.5:0.8r, 2:2.6, 0.5:0.8r, 0.5:0.8, 0.5:0.8r, 0.5:0.8, 0.5:0.7r, 4:4.5, 0.5:0.8r, 0.5:0.8, 0.5:0.8r, 0.5:0.8, 0.5:0.8r, 6:6.6, 0.5:0.8r, 0.5:0.8, 0.5:0.8r, 7.6:7.9, 7.8:8",
206
- "scale": "0.5, 0.25",
207
- "weight": 2
208
- },
209
- "staccato reverese syncopated": {
210
- "pattern": "1, 1:1.5, 2.5:4r, 2.5:4, 2.5:4r, 2.5:4, 2.5:3r, | 9, 10.5:12, 10.5:12r, 10.5:12, 10.5:12r, 10.5:11.5, | 16:16.5, 18.5:20r, 18.5:20, 18.5:20r, 18.5:20, 18.5:20r, | 25, 25:25.5, 26.5:28r, 26.5:28, 26.5:28r, 26.5:28, 31.5:32",
211
- "scale": "1/8, 1/16",
212
- "scale_d": 0.125,
213
- "weight": 2
214
- },
215
- "staccato reverese syncopated B": {
216
- "pattern": "1, 1:1.5, 2.5:4r, 2.5:4, 2.5:4r, 2.5:4, 2.5:3r, | 9, 2.5:4, 2.5:4r, 2.5:4, 2.5:4r, 2.5:3.5, | 16:16.5, 2.5:4r, 2.5:4, 2.5:4r, 2.5:4, 2.5:4r, | 25, 25:25.5, 2.5:4r, 2.5:4, 2.5:4r, 2.5:4, 31.5:32",
217
- "scale": "1/8, 1/16",
218
- "scale_d": 0.125,
219
- "weight": 2
220
- },
221
- "staccato reverese syncopated C": {
222
- "pattern": "1, 1:1.5, 2.5:4s2,2.5:4s2r, 2.5:4, 2.5:4r, 2.5:4s2,2.5:4s2r, 2.5:3, | 9, 2.5:4r, 2.5:4s2,2.5:4s2r, 2.5:4, 2.5:4r, 2.5:4s2,2.5:4s2r, | 16:17.5, 2.5:4r, 2.5:4s2,2.5:4s2r, 2.5:4, 2.5:4r, | 24:25.5, 2.5:4, 2.5:4r, 2.5:4s2,2.5:4s2r, 2.5:4, 31.5:32r",
223
- "scale": "1/8, 1/16",
224
- "scale_d": 0.125,
225
- "weight": 2
226
- },
227
- "syncopated effect": {
228
- "pattern": "1s2, 1s2r, 2, 3, 4",
229
- "scale": 0.375,
230
- "weight": 1
231
- },
232
- "darkstep": {
233
- "pattern": "1,1,3,1, | 1,7,1,1, | 11,9,9,11, | 9,9,15,16",
234
- "scale": 0.5,
235
- "normalize": true,
236
- "weight": 4
237
- },
238
- "darkstep long": {
239
- "pattern": "1,1,3,1, | 1,7,1,1, | 11,9,9,11, | 9,9,15,9, | 17,19,17,17, | 19,17,17,23, | 25,25,27,25, | 25,31,25,32",
240
- "scale": 0.5,
241
- "normalize": true,
242
- "weight": 4
243
- },
244
- "darkstep fast": {
245
- "pattern": "1,1,5,1, | 1,13,1,1, | 21,17,17,21, | 17,17,29,32",
246
- "scale": 0.25,
247
- "normalize": true,
248
- "weight": 4
249
- },
250
- "4-3 time": {
251
- "pattern": "0:2/3, 1:5/3, 1:5/3",
252
- "scale": "2, 1, 0.5, 0.25",
253
- "scale_d": 0.5,
254
- "weight": 4
255
- },
256
- "4-7 time A": {
257
- "pattern": "1, 2, 3, 3:3.5",
258
- "scale": "2, 1, 0.5",
259
- "scale_d": 1,
260
- "weight": 6
261
- },
262
- "4-7 time B": {
263
- "pattern": "1, 2, 3, 3:3.25, 3.75:4, 5,5:5.5, 7, 8",
264
- "scale": "2, 1, 0.5",
265
- "scale_d": 1,
266
- "weight": 6
267
- },
268
- "Stray & Halogenix - Poison": {
269
- "pattern": "0:1/3, 0:1/3, 1:4/3, 1:4/3, 2:7/3, 2:7/3, 3:10/3, 3:10/3, 1/3:2/3, 4/3:5/3, 10/3:4",
270
- "scale": "1",
271
- "normalize": true,
272
- "scale_d": 1,
273
- "weight": 5
274
- },
275
- "Venetian Snares - Szamar Madar": {
276
- "pattern": "1, 2, 3, 4, 4, 1, 2, 3, 1, 1v0, 1v0, 1, 7, 8,|9, 10, 11, 12, 13, 14, 15, 16, 15, 10, 10, 10, 11, 16,|17, 18, 19, 20, 20, 17, 18, 19, 20, 20, 17, 17v0, 23, 24,|25, 25:25.5, 24:24.5, 27, 25, 28, 25, 31, 24:24.5, 27.5:28, 24:24.5, 27.5:28, 25, 25, 25, 31, 32",
277
- "scale": "0.5",
278
- "scale_d": 0.5,
279
- "weight": 5
280
- },
281
- "effect - octave up": {
282
- "pattern": "1s2,1s2",
283
- "scale": 0.01,
284
- "weight": 0.000000001
285
- },
286
- "effect - octave down": {
287
- "pattern": "0:0.5s0.5",
288
- "scale": 0.01,
289
- "weight": 0.000000001
290
- },
291
- "effect - speed 2x": {
292
- "pattern": "1,2!",
293
- "scale": 0.01,
294
- "weight": 0.000000001
295
- },
296
- "effect - speed 0.5x": {
297
- "pattern": "1,1",
298
- "scale": 0.01,
299
- "weight": 0.000000001
300
- },
301
- "effect - robot": {
302
- "pattern": "1,1,1,1,1,1,1,1,8!",
303
- "scale": 0.01,
304
- "weight": 0.000000001
305
- },
306
- "hardcore": {
307
- "1": {
308
- "type": "sidechain"
309
- },
310
- "2": {
311
- "type": "beatsample",
312
- "filename": "samples/cowbell.mp3"
313
- },
314
- "weight": 0.000000001
315
- }
316
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt DELETED
@@ -1,12 +0,0 @@
1
- cython
2
- mido
3
- numpy
4
- scipy
5
- pytest
6
- pyfftw
7
- soundfile
8
- ffmpeg-python
9
- librosa
10
- pedalboard
11
- opencv-python
12
- git+https://github.com/CPJKU/madmom