forked from facebookresearch/audiocraft
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcommentedout.js
406 lines (345 loc) · 13.8 KB
/
commentedout.js
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
const Max = require('max-api');
const fs = require('fs');
const io = require('socket.io-client');
const socket = io('http://localhost:8000', {
// our backend url
// const socket = io('https://g4l.thecollabagepatch.com', {
transports: ['websocket'], // Force WebSocket usage
reconnection: true, // Enable auto-reconnection
reconnectionAttempts: Infinity, // Unlimited reconnection attempts
reconnectionDelay: 1000, // Wait 1 second before attempting to reconnect
reconnectionDelayMax: 5000, // Maximum delay between reconnections
randomizationFactor: 0.5,
timeout: 300000, // Connection timeout in milliseconds
pingTimeout: 240000, // How many ms without a pong packet to consider the connection closed
pingInterval: 120000 // How many ms before sending a new ping packet
});
const path = require('path');
let modelPath = 'thepatch/vanya_ai_dnb_0.1'; // Default model path
let sessionID = null; // Variable to store the session ID
let isProcessing = false;
let promptDuration = 6; // Default prompt duration
let tameTheGaryEnabled = false; // New state variable for the toggle
let variationName = 'accordion_folk'; // Default variation
let isBackendConnected = false;
// Add handler for variation text input
Max.addHandler('set_variation', (newVariation) => {
if (typeof newVariation === 'string') {
variationName = newVariation.trim();
Max.post(`Variation updated to: ${variationName}`);
}
});
// Update transform handler to use the variationName variable
Max.addHandler('transform', () => {
if (!isProcessing) {
isProcessing = true;
const audioPath = sessionID ? 'C:/g4l/myOutput.wav' : 'C:/g4l/myBuffer.wav';
fs.readFile(audioPath, (err, data) => {
if (err) {
Max.post(`Error reading audio file: ${err}`);
isProcessing = false;
return;
}
const audioData_base64 = data.toString('base64');
const request = {
audio_data: audioData_base64,
variation: variationName, // Use the stored variation name
session_id: sessionID
};
socket.emit('transform_audio_request', request);
});
setTimeout(() => {
isProcessing = false;
}, timeoutDuration);
} else {
Max.post('Processing already in progress.');
}
});
// Add handler for undo button
Max.addHandler('undo_transform', () => {
if (!isProcessing && sessionID) {
isProcessing = true;
const request = {
session_id: sessionID
};
socket.emit('undo_transform_request', request);
setTimeout(() => {
isProcessing = false;
}, timeoutDuration);
} else {
Max.post('Either processing in progress or no session available for undo.');
}
});
Max.addHandler('tame_gary', (value) => {
tameTheGaryEnabled = value === 1;
Max.post(`Tame the Gary ${tameTheGaryEnabled ? 'enabled' : 'disabled'}`);
});
// Timeout duration in milliseconds
const timeoutDuration = 500; // .5 seconds
// Initialize WebSocket connection and setup event listeners
function initSocketConnection() {
socket.on('connect', () => {
isBackendConnected = true;
Max.post('Connected to WebSocket server.');
Max.outlet('backend_connection', true);
if (sessionID) {
socket.emit('verify_session', { session_id: sessionID });
}
});
socket.on('reconnect_attempt', () => {
Max.post('Attempting to reconnect to WebSocket server...');
});
Max.addHandler('reconnect', () => {
// Only send the connection status
Max.outlet('backend_connection', true);
// Reset any error states if needed
Max.post('Reconnected and reset states');
});
socket.on('reconnect_error', (error) => {
Max.post('Reconnection error: ' + error.message);
});
socket.on('reconnect_failed', () => {
Max.post('Failed to reconnect to WebSocket server.');
});
socket.on('connect_error', (error) => {
isBackendConnected = false;
Max.post('Connection error: ' + error.message);
Max.outlet('backend_connection', false); // Inform about lost backend connection
});
socket.on('disconnect', (reason) => {
isBackendConnected = false;
Max.post('Disconnected from WebSocket server: ' + reason);
Max.outlet('backend_connection', false); // Inform about lost backend connection
if (reason === 'io server disconnect') {
socket.connect();
}
});
socket.on('audio_processed', (data) => {
isProcessing = false; // Reset flag when audio processing is complete
Max.post('Audio processing successful.');
sessionID = data.session_id; // Store the session ID
const outputBuffer = Buffer.from(data.audio_data, 'base64');
fs.writeFileSync('C:/g4l/myOutput.wav', outputBuffer);
Max.outlet('audio_processed');
Max.outlet('progress_update', 100);
});
socket.on('music_continued', (data) => {
isProcessing = false; // Reset flag when audio processing is complete
Max.post('Music continuation successful.');
sessionID = data.session_id; // Update the session ID
const outputBuffer = Buffer.from(data.audio_data, 'base64');
fs.writeFileSync('C:/g4l/myOutput.wav', outputBuffer);
Max.outlet('music_continued');
Max.outlet('progress_update', 100); // Force the progress to 100% on completion
});
socket.on('music_retried', (data) => {
isProcessing = false; // Reset flag when audio processing is complete
Max.post('Music retry successful.');
const outputBuffer = Buffer.from(data.audio_data, 'base64');
fs.writeFileSync('C:/g4l/myOutput.wav', outputBuffer);
Max.outlet('music_retried');
Max.outlet('progress_update', 100); // Force the progress to 100% on completion
});
socket.on('progress_update', (data) => {
Max.post(`progress update: ${data.progress}%`);
Max.outlet('progress_update', data.progress);
});
socket.on('error', (data) => {
isProcessing = false;
Max.post('Error from WebSocket server: ' + data.message);
// Check if the error message includes the specific connection error
if (data.message.includes('Connection refused') ||
data.message.includes('Failed to establish a new connection')) {
Max.outlet('error_message', 'transform|terry is asleep right now. he uses alot of gpu ram. you can learn how to spin up your own terry container by bugging kevin in the discord tho: https://discord.gg/VECkyXEnAd');
} else {
Max.outlet('error', data.message);
}
});
socket.on('update_cropped_audio_complete', (data) => {
sessionID = data.session_id; // Update the session ID
Max.post('Cropped audio updated successfully.');
});
// Add new socket listener for transform response
socket.on('audio_transformed', (data) => {
isProcessing = false;
Max.post('Audio transformation successful.');
sessionID = data.session_id; // Update session ID
const outputBuffer = Buffer.from(data.audio_data, 'base64');
fs.writeFileSync('C:/g4l/myOutput.wav', outputBuffer);
Max.outlet('audio_transformed');
// Max.outlet('progress_update', 100);
});
// Add socket listener for undo response
socket.on('transform_undone', (data) => {
isProcessing = false;
Max.post('Transform undo successful.');
sessionID = data.session_id;
const outputBuffer = Buffer.from(data.audio_data, 'base64');
fs.writeFileSync('C:/g4l/myOutput.wav', outputBuffer);
Max.outlet('transform_undone');
});
}
// Function to handle 'bang' message from Max
Max.addHandler('bang', () => {
if (!isProcessing) {
isProcessing = true;
// Optional: Send a cleanup request if sessionID exists
if (sessionID) {
socket.emit('cleanup_session_request', { session_id: sessionID });
}
Max.post('Sending audio processing request to WebSocket server with a new session.');
processAudio('C:/g4l/myBuffer.wav');
sessionID = null; // Reset the session ID after sending the cleanup request
// Add timeout to reset isProcessing
setTimeout(() => {
isProcessing = false;
}, timeoutDuration);
} else {
Max.post('Processing already in progress.');
}
});
// Function to handle 'continue' message from Max
Max.addHandler('continue', () => {
if (isProcessing) {
Max.outlet('error_message', 'processing', 'Still processing previous request, wait a sec...');
Max.post('Processing already in progress.');
return;
}
if (!sessionID) {
// Let's try concatenating the type and message with a delimiter
Max.outlet('error_message', 'no_session|no audio in the session to continue yet, homie. press bang first.');
Max.post('No session available - need to press bang first.');
return;
}
isProcessing = true;
continueMusic();
setTimeout(() => {
isProcessing = false;
}, timeoutDuration);
});
// Function to handle 'retry' message from Max
Max.addHandler('retry', () => {
if (isProcessing) {
Max.outlet('error_message', 'processing|Still processing previous request, wait a sec...');
Max.post('Processing already in progress.');
return;
}
if (!sessionID) {
// Using the same delimiter format as continue
Max.outlet('error_message', 'no_continuation|no continued audio to retry bro. press continue first.');
Max.post('No continued audio available - need to press continue first.');
return;
}
isProcessing = true;
const request = {
session_id: sessionID,
model_name: modelPath,
prompt_duration: promptDuration
};
// Add Gary-taming parameters if enabled
if (tameTheGaryEnabled) {
request.top_k = 150;
request.cfg_coef = 5;
request.description = "drums, percussion";
}
socket.emit('retry_music_request', request);
setTimeout(() => {
isProcessing = false;
}, timeoutDuration);
});
// This handler will directly update the model path when text changes
Max.addHandler('text', (newModelPath) => {
if (typeof newModelPath === 'string') {
modelPath = newModelPath.trim(); // Ensure to trim any extra whitespace
Max.post(`Model path updated directly to: ${modelPath}`);
}
});
// Handler for receiving the prompt duration value
Max.addHandler('prompt_duration', (value) => {
if (typeof value === 'number' && value >= 1 && value <= 15) {
promptDuration = value;
Max.post(`Prompt duration set to: ${promptDuration}`);
} else {
Max.post('Invalid prompt duration value. It should be between 1 and 15.');
}
});
// Handler for the 'crop_audio' event
Max.addHandler('crop_audio', () => {
const outputAudioPath = 'C:/g4l/myOutput.wav';
fs.readFile(outputAudioPath, (err, data) => {
if (err) {
Max.post(`Error reading output file for cropping: ${err}`);
return;
}
const audioData_base64 = data.toString('base64');
socket.emit('update_cropped_audio', { session_id: sessionID, audio_data: audioData_base64 });
Max.post('Sent cropped audio data to backend');
});
});
// Add handler for reset_transform
Max.addHandler('reset_transform', () => {
Max.post('[commentedout] Reset transform handler triggered');
// If we have an active session, clean it up
if (sessionID) {
Max.post('[commentedout] Cleaning up session: ' + sessionID);
socket.emit('cleanup_session_request', { session_id: sessionID });
sessionID = null;
} else {
Max.post('[commentedout] No active session to clean up');
}
Max.post('[commentedout] Reset complete');
});
// Function to process audio
function processAudio(inputAudioPath) {
fs.readFile(inputAudioPath, (err, data) => {
if (err) {
Max.post(`Error reading audio file: ${err}`);
isProcessing = false;
Max.outlet('error', err.toString());
return;
}
const audioData_base64 = data.toString('base64');
// Base request object
const request = {
audio_data: audioData_base64,
model_name: modelPath,
prompt_duration: promptDuration
};
// Add Gary-taming parameters if enabled
if (tameTheGaryEnabled) {
request.top_k = 100;
request.cfg_coef = 5;
request.description = "drums, percussion";
}
socket.emit('process_audio_request', request);
});
}
// Function to continue music
function continueMusic() {
const outputAudioPath = 'C:/g4l/myOutput.wav';
fs.readFile(outputAudioPath, (err, data) => {
if (err) {
Max.post(`Error reading output file: ${err}`);
isProcessing = false;
Max.outlet('error', err.toString());
return;
}
const audioData_base64 = data.toString('base64');
// Base request object
const request = {
audio_data: audioData_base64,
model_name: modelPath,
session_id: sessionID,
prompt_duration: promptDuration
};
// Add Gary-taming parameters if enabled
if (tameTheGaryEnabled) {
request.top_k = 150;
request.cfg_coef = 5;
request.description = "drums, percussion";
}
socket.emit('continue_music_request', request);
});
}
// Start the WebSocket connection
initSocketConnection();