/
index.html
543 lines (437 loc) · 15.9 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Musicgen</title>
<style>
:root{
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color: #213547;
background-color: #fff;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
}
*{
box-sizing:border-box;
}
body{
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
background-color: rgb(243 244 246);
padding:2rem;
display:flex;
align-items:center;
justify-content:center;
height:100vh;
width:100vw;
}
h1{
color: rgb(31,41,55);
font-weight: 600;
text-align: center;
}
h2{
font-weight:500;
font-size: 1rem;
line-height: 1.5rem;
text-align: center;
}
label{
font-size: .875rem;
line-height: 1.25rem;
}
textarea{
border: 1px solid rgb(209,213,219);
width:100%;
border-radius: .375rem;
resize: vertical;
font-family: inherit;
font-feature-settings: inherit;
font-variation-settings: inherit;
font-size: 100%;
font-weight: inherit;
line-height: inherit;
color: inherit;
}
input[type="range"]{
flex-grow:1;
}
#centered{
max-width: 36rem;
max-height:100vh;
padding: 2rem;
border-radius: .5rem;
overflow:auto;
background-color:white;
--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);
--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);
box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);
}
#downloading-model,
#progress-bar{
display:none;
}
#progress-bar{
width:300px;
padding:2rem 1rem;
}
#progress-bar:before{
content:'Generating audio...';
display:inline-block;
position:relative;
top:-.6rem;
}
#prompt{
width:100%;
height:100px;
padding:.5rem;
box-sizing:border-box;
}
.setting{
justify-content:space-between;
border-bottom:1px solid rgba(0, 0, 0, .1);
margin:.8rem 0;
padding:.3rem 0;
width:300px;
}
.flex{
display:flex;
}
.column{
flex-direction:column;
}
button{
padding:.5rem 1rem;
border-radius:.375rem;
cursor:pointer;
border:none;
background-color: rgb(59,130,246);
color:white;
font-size: 100%;
}
button:hover{
background-color: rgb(37,99,235);
}
audio{
margin-top:1rem;
}
.button-container{
width:100%;
padding:1rem;
text-align: center;
}
#download_container_el{
display:flex;
flex-direction:column;
}
#download_container_el progress{
width:100%;
}
#download_container_el:not(:empty):before{
content:"Downloading";
display:block;
}
</style>
</head>
<body>
<div id="centered">
<h1>🎸 🎺 🥁 MusicGen 🎶 🎵 🎶 </h1>
<h2 class="text-base font-medium text-gray-700 mb-2 text-center">Made with <a href="https://huggingface.co/docs/transformers.js">🤗 Transformers.js</a></h2>
<p>This AI will generate a 30 second music clip tailored to your wishes. It's 100% privacy friendly, as the AI runs completely on your own computer, and not 'in the cloud'.</p>
<p>After the AI model is downloaded to your computer, which may take a few minutes, generating the audio can easily take another few minutes. In other words: please be patient.<p>
<p>You can find this demo <a href="https://github.com/flatsiedatsie/transformers_js_musicgen">on Github</a>.</p>
<br/>
<label for="prompt" class="block text-sm font-medium text-gray-600">Prompt</label><br/>
<textarea id="prompt">80s pop track with bassy drums and synth</textarea><br/>
<div class="flex column setting">
<label>Duration</label>
<div class="flex">
10 <input id="duration" type="range" min="10" max="30" step="1" value="30"/> 30
</div>
</div>
<!--
<div class="flex setting"><label>Do Sample</label>
<input id="do-sample" type="checkbox" checked/>
</div>
-->
<div class="flex column setting">
<label>Creativity</label>
<div class="flex">
0.1 <input id="temperature" type="range" min="0.1" max="2" step=".1" value="1"/> 2
</div>
</div>
<div class="flex column setting">
<label>Guidance scale</label>
<div class="flex">
fast <input id="guidance-scale" type="range" min="0" max="10" step="1" value="3"/> quality
</div>
</div>
<br/>
<div class="button-container">
<button id="submit-button">Generate</button>
</div>
<div id="status"></div>
<div id="download-container"></div>
<div id="downloading-model"></div>
<progress id="progress-bar" aria-label="Generating…"></progress>
<div id="output-container"></div>
</div>
<script type="module">
//import { AutoTokenizer, MusicgenForConditionalGeneration } from './js/transformers.js';
import { AutoTokenizer, MusicgenForConditionalGeneration, BaseStreamer } from './js/transformers.js';
const downloading_model_el = document.getElementById('downloading-model');
const download_container_el = document.getElementById('download-container');
const progress_bar_el = document.getElementById('progress-bar');
const duration_el = document.getElementById('duration');
const do_sample_el = document.getElementById('do-sample');
const temperature_el = document.getElementById('temperature');
const guidance_scale_el = document.getElementById('guidance-scale');
const output_container_el = document.getElementById('output-container');
const status_el = document.getElementById('status');
// Hacky way of getting progress updates
/*
var logOfConsole = [];
console.warn = function() {
logOfConsole.push({method: 'warn', arguments: arguments});
//return _warn.apply(console, arguments);
console.log("logOfConsole.length (of 511): ", logOfConsole.length, arguments);
progress_bar_el.value = (1/1510) * logOfConsole.length; // The 1510 hardcoded value is the maximum I've seen. Lowest was 511, It increases with the guidance scale value.
progress_bar_el.style.display = 'block';
downloading_model_el.style.display = 'none';
};
*/
// Library for turning audio data array into a WAV file
function minFramesForTargetMS(targetDuration, frameSamples, sr = 16e3) {
return Math.ceil(targetDuration * sr / 1e3 / frameSamples);
}
function arrayBufferToBase64(buffer) {
var binary = "";
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
function encodeWAV(samples, format = 3, sampleRate = 16e3, numChannels = 1, bitDepth = 32) {
var bytesPerSample = bitDepth / 8;
var blockAlign = numChannels * bytesPerSample;
var buffer = new ArrayBuffer(44 + samples.length * bytesPerSample);
var view = new DataView(buffer);
writeString(view, 0, "RIFF");
view.setUint32(4, 36 + samples.length * bytesPerSample, true);
writeString(view, 8, "WAVE");
writeString(view, 12, "fmt ");
view.setUint32(16, 16, true);
view.setUint16(20, format, true);
view.setUint16(22, numChannels, true);
view.setUint32(24, sampleRate, true);
view.setUint32(28, sampleRate * blockAlign, true);
view.setUint16(32, blockAlign, true);
view.setUint16(34, bitDepth, true);
writeString(view, 36, "data");
view.setUint32(40, samples.length * bytesPerSample, true);
if (format === 1) {
floatTo16BitPCM(view, 44, samples);
} else {
writeFloat32(view, 44, samples);
}
return buffer;
}
function writeFloat32(output, offset, input) {
for (var i = 0; i < input.length; i++, offset += 4) {
output.setFloat32(offset, input[i], true);
}
}
function floatTo16BitPCM(output, offset, input) {
for (var i = 0; i < input.length; i++, offset += 2) {
var s = Math.max(-1, Math.min(1, input[i]));
output.setInt16(offset, s < 0 ? s * 32768 : s * 32767, true);
}
}
function writeString(view, offset, string) {
for (let i = 0; i < string.length; ++i) {
view.setUint8(offset + i, string.charCodeAt(i))
}
}
// Submit button
const submit_button = document.getElementById('submit-button');
submit_button.addEventListener('click', () => {
console.log("making that funky music");
make_funky_music();
});
function setStatusText(text){
console.log("in setStatusText. text: ", text);
status_el.textContent = text;
}
function setProgress(progress){
console.log("in setProgress. Progress: ", progress);
progress_bar_el.style.display = 'block';
progress_bar_el.value = progress;
}
class CallbackStreamer extends BaseStreamer {
constructor(callback_fn) {
super();
this.callback_fn = callback_fn;
}
put(value) {
return this.callback_fn(value);
}
end() {
return this.callback_fn();
}
}
// Main function that starts the (download and) music generation process
async function make_funky_music(){
submit_button.style.display = 'none';
downloading_model_el.style.display = 'block';
progress_bar_el.value = 0;
//logOfConsole = [];
// Load tokenizer and model
const tokenizer = await AutoTokenizer.from_pretrained('Xenova/musicgen-small');
// The comments below are valid on 12 april 2024
/*
const model = await MusicgenForConditionalGeneration.from_pretrained('Xenova/musicgen-small', {
dtype: {
text_encoder: 'q8', // or 'fp32'. Both seem to work well, but q8 provides 4x memory reduction.
decoder_model_merged: 'q8', // IMPORTANT: otherwise, you'll get out-of-memory issues
encodec_decode: 'fp32', // IMPORTANT: If not full-precision, quality won't be very good.
},
device: {
text_encoder: 'webgpu', // much faster :)
decoder_model_merged: 'wasm', // webgpu is slower at the moment due to inefficient buffer reuse. Will fix.
encodec_decode: 'wasm', // webgpu is currently broken (known upstream bug in onnxruntime-web). Will be fixed soon.
},
});
*/
const model = await MusicgenForConditionalGeneration.from_pretrained('Xenova/musicgen-small', {
progress_callback: (data) => {
console.log("progress_callback: data: ", data);
if (data.status !== 'progress') return;
//setLoadProgress(prev => ({ ...prev, [data.file]: data }))
setLoadProgress(data);
},
dtype: {
text_encoder: 'q8',
decoder_model_merged: 'q8',
encodec_decode: 'fp32',
},
device: 'wasm',
});
function setLoadProgress(loadProgress){
console.log("in setLoadProgress. loadProgress: ", typeof loadProgress, loadProgress);
if(typeof loadProgress.file == 'string' && typeof loadProgress.progress == 'number'){
let download_progress_el_id = loadProgress.file.substr(loadProgress.file.indexOf('/'));
let download_progress_el = document.getElementById(download_progress_el_id);
if(download_progress_el == null){
download_progress_el = document.createElement('progress');
download_progress_el.setAttribute('id',download_progress_el_id);
download_container_el.appendChild(download_progress_el);
}
download_progress_el.value = loadProgress.progress/100;
if(loadProgress.progress == 100){
download_progress_el.remove();
}
}
/*
const items = Object.values(loadProgress);
console.log("items: ", items);
if (items.length !== 5) return; // 5 files to load
let loaded = 0;
let total = 0;
for (const data of Object.values(loadProgress)) {
loaded += data.loaded;
total += data.total;
}
const progress = loaded / total;
console.log("progress: ", progress);
setProgress(progress);
setStatusText(progress === 1
? 'Ready!'
: `Loading model (${(progress * 100).toFixed()}% of 656MB)...`
);
*/
}
const temperature = temperature_el.value;
// Prepare text input
const prompt = document.getElementById('prompt').value; //'80s pop track with bassy drums and synth';
const inputs = tokenizer(prompt);
const duration = duration_el.value;
const max_length = Math.min(
Math.max(Math.floor(duration * 50), 1) + 4,
model.generation_config.max_length ?? 1500,
);
const streamer = new CallbackStreamer((value) => {
console.log("in streamer. value: ", value);
const percent = value === undefined ? 1 : value[0].length / max_length;
console.log("streamer: percent: ", percent);
setStatusText(`Generating (${(percent * 100).toFixed()}%)...`);
setProgress(percent * 100);
});
let guidance_scale = guidance_scale_el.value;
if(guidance_scale == 0){guidance_scale = null} // default is 3. Null disables it. Greatly increases memory usage.
console.log("duration: ", duration);
console.log("max_length: ", max_length);
//console.log("do_sample: ", do_sample_el.checked);
console.log("temperature: ", temperature);
console.log("guidance_scale: ", guidance_scale);
// Generate audio
const audio_values = await model.generate({
// Inputs
...inputs,
// Generation parameters
max_length, // duration, as number of tokens. 10 seconds equals to approximatately 1500 tokens
guidance_scale,
temperature,
// Outputs
streamer,
});
console.log("audio_values: ", audio_values);
console.log("audio_values: ", audio_values.data);
console.log("audio_values.ort_tensor: ", audio_values.ort_tensor);
console.log("audio_values.ort_tensor.cpuData: ", audio_values.ort_tensor.cpuData);
// turn array into a WAV file
let wav = encodeWAV(audio_values.ort_tensor.cpuData, 3, 32000, 1, 32); // The MusicGen model outputs at a samplerate of 32000, 1 channel (mono), 32 bit data,
let wav_blob = new Blob([wav], { type: 'audio/wav' });
const audio_el = document.createElement('audio');
audio_el.setAttribute('controls', true);
audio_el.src = window.URL.createObjectURL(wav_blob);
output_container_el.appendChild(audio_el);
submit_button.style.display = 'block';
progress_bar_el.style.display = 'none';
/*
// The code below instantly plays the music after it has been created // At the moment it plays it at a wrong speed on my device, since audio is generated at 32000 framerate, and my audiodevice is 44000 framerate, so it sounds sped-up.
// Stereo
var channels = 1;
// Create an empty two second stereo buffer at the
// sample rate of the AudioContext
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var frameCount = audioCtx.sampleRate * 10.0;
var myArrayBuffer = audioCtx.createBuffer(channels, frameCount, audioCtx.sampleRate);
for (var channel = 0; channel < channels; channel++) {
var nowBuffering = myArrayBuffer.getChannelData(channel);
for (var i = 0; i < frameCount; i++) {
nowBuffering[i] = audio_values.ort_tensor.cpuData[i];
}
}
// Get an AudioBufferSourceNode.
// This is the AudioNode to use when we want to play an AudioBuffer
var source = audioCtx.createBufferSource();
// set the buffer in the AudioBufferSourceNode
source.buffer = myArrayBuffer;
// connect the AudioBufferSourceNode to the
// destination so we can hear the sound
source.connect(audioCtx.destination);
// start the source playing
source.start();
*/
} // end of make_funky_music()
</script>
</body>
</html>