File size: 14,559 Bytes
3fde5f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const API_BASE_URL = window.location.origin;
const recorder = new AudioRecorder();

// Audio context and buffers
let audioContext = null;
let audioBuffers = [];
let pendingAudioPaths = new Set();
let currentAudioPath = null;
let ws = null;

// DOM Elements
const startRecordingBtn = document.getElementById('startRecording');
const stopRecordingBtn = document.getElementById('stopRecording');
const transcriptionArea = document.getElementById('transcription');
const asrStatus = document.getElementById('asrStatus');
const ttsInput = document.getElementById('ttsInput');
const generateSpeechBtn = document.getElementById('generateSpeech');
const ttsStatus = document.getElementById('ttsStatus');
const audioPlayer = document.getElementById('audioPlayer');
const downloadAudioBtn = document.getElementById('downloadAudio');
const audioFileInput = document.getElementById('audioFileInput');
const uploadAudioBtn = document.getElementById('uploadAudio');

// File upload handler with format conversion
uploadAudioBtn.addEventListener('click', async () => {
    const file = audioFileInput.files[0];
    if (!file) {
        asrStatus.textContent = 'Please select an audio file';
        asrStatus.className = 'status error';
        return;
    }

    try {
        asrStatus.textContent = 'Processing audio file...';
        asrStatus.className = 'status';

        // Convert audio to WAV format
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        const arrayBuffer = await file.arrayBuffer();
        const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
        
        // Create WAV file
        const wavBuffer = await audioBufferToWav(audioBuffer);
        const wavBlob = new Blob([wavBuffer], { type: 'audio/wav' });

        const formData = new FormData();
        formData.append('file', wavBlob, 'recording.wav');

        const response = await fetch(`${API_BASE_URL}/asr`, {
            method: 'POST',
            body: formData
        });

        if (!response.ok) throw new Error('ASR request failed');

        const data = await response.json();
        transcriptionArea.value = data.text;
        asrStatus.textContent = 'Transcription complete!';
        asrStatus.className = 'status success';
        
        // Clean up
        audioContext.close();
    } catch (error) {
        asrStatus.textContent = 'Error: ' + error.message;
        asrStatus.className = 'status error';
    }
});

// Recording handlers
startRecordingBtn.addEventListener('click', async () => {
    try {
        asrStatus.textContent = 'Starting recording...';
        asrStatus.className = 'status';
        await recorder.start();
        startRecordingBtn.disabled = true;
        stopRecordingBtn.disabled = false;
        asrStatus.textContent = 'Recording...';
    } catch (error) {
        asrStatus.textContent = 'Error starting recording: ' + error.message;
        asrStatus.className = 'status error';
    }
});

stopRecordingBtn.addEventListener('click', async () => {
    try {
        const audioBlob = await recorder.stop();
        startRecordingBtn.disabled = false;
        stopRecordingBtn.disabled = true;
        asrStatus.textContent = 'Processing audio...';

        // Send to ASR endpoint
        const formData = new FormData();
        formData.append('file', audioBlob);

        const response = await fetch(`${API_BASE_URL}/asr`, {
            method: 'POST',
            body: formData
        });

        if (!response.ok) throw new Error('ASR request failed');

        const data = await response.json();
        transcriptionArea.value = data.text;
        asrStatus.textContent = 'Transcription complete!';
        asrStatus.className = 'status success';
    } catch (error) {
        asrStatus.textContent = 'Error: ' + error.message;
        asrStatus.className = 'status error';
        startRecordingBtn.disabled = false;
        stopRecordingBtn.disabled = true;
    }
});

// TTS handlers
function connectWebSocket() {
    const wsProtocol = window.location.protocol === 'https:' ? 'wss' : 'ws';
    ws = new WebSocket(`${wsProtocol}://${window.location.host}/tts-ws`);
    
    ws.onopen = () => {
        console.log('WebSocket connected');
        generateSpeechBtn.disabled = false;
        ttsStatus.textContent = 'Connected to TTS service';
        ttsStatus.className = 'status success';
        
        // Initialize AudioContext if needed
        if (!audioContext) {
            audioContext = new (window.AudioContext || window.webkitAudioContext)();
        } else if (audioContext.state === 'suspended') {
            audioContext.resume();
        }
    };

    ws.onmessage = async (event) => {
        const response = JSON.parse(event.data);
        
        if (response.status === 'partial') {
            ttsStatus.textContent = 'Generating audio...';
            ttsStatus.className = 'status';
            
            try {
                const audioPath = response.audioPath.split('/').pop();
                pendingAudioPaths.add(audioPath);
                
                if (audioContext.state === 'suspended') {
                    await audioContext.resume();
                }
                
                // Use retry mechanism for fetching audio
                const audioResponse = await fetchWithRetry(`${API_BASE_URL}/cache/${audioPath}`);
                const arrayBuffer = await audioResponse.arrayBuffer();
                
                if (arrayBuffer.byteLength === 0) {
                    throw new Error('Empty audio data received');
                }
                
                const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
                audioBuffers.push(audioBuffer);
                pendingAudioPaths.delete(audioPath);
            } catch (error) {
                console.error('Error loading audio:', error);
                ttsStatus.textContent = 'Error loading audio: ' + error.message;
                ttsStatus.className = 'status error';
                pendingAudioPaths.clear();
            }
        } else if (response.status === 'complete') {
            // Wait for any pending audio loads to complete
            if (pendingAudioPaths.size > 0) {
                ttsStatus.textContent = 'Finalizing audio...';
                await new Promise(resolve => setTimeout(resolve, 500));
            }

            try {
                // Combine all audio buffers
                const targetSampleRate = 16000;
                const totalLength = audioBuffers.reduce((acc, buffer) => {
                    // Calculate resampled length if needed
                    const ratio = targetSampleRate / buffer.sampleRate;
                    return acc + Math.ceil(buffer.length * ratio);
                }, 0);
                
                const combinedBuffer = audioContext.createBuffer(
                    1,  // mono
                    totalLength,
                    targetSampleRate
                );
                
                let offset = 0;
                for (const buffer of audioBuffers) {
                    // Resample if needed
                    let channelData = buffer.getChannelData(0);
                    if (buffer.sampleRate !== targetSampleRate) {
                        channelData = await resampleAudio(channelData, buffer.sampleRate, targetSampleRate);
                    }
                    combinedBuffer.copyToChannel(channelData, 0, offset);
                    offset += channelData.length;
                }
                
                // Convert to WAV for download
                const wavBlob = new Blob([await audioBufferToWav(combinedBuffer)], { type: 'audio/wav' });
                const audioUrl = URL.createObjectURL(wavBlob);
                
                // Update audio player
                audioPlayer.src = audioUrl;
                audioPlayer.load();
                downloadAudioBtn.disabled = false;
                
                // Store for download
                currentAudioPath = audioUrl;
                
                ttsStatus.textContent = 'Audio generated successfully!';
                ttsStatus.className = 'status success';
            } catch (error) {
                console.error('Error combining audio:', error);
                ttsStatus.textContent = 'Error combining audio: ' + error.message;
                ttsStatus.className = 'status error';
            } finally {
                // Clear buffers
                audioBuffers = [];
                pendingAudioPaths.clear();
            }
        } else if (response.status === 'error') {
            ttsStatus.textContent = 'Error: ' + response.message;
            ttsStatus.className = 'status error';
            audioBuffers = [];
            pendingAudioPaths.clear();
        }
    };

    ws.onclose = () => {
        console.log('WebSocket disconnected');
        generateSpeechBtn.disabled = true;
        ttsStatus.textContent = 'Disconnected. Trying to reconnect...';
        ttsStatus.className = 'status error';
        
        // Clean up any pending audio resources
        audioBuffers = [];
        pendingAudioPaths.clear();
        if (currentAudioPath) {
            URL.revokeObjectURL(currentAudioPath);
            currentAudioPath = null;
        }
        
        setTimeout(connectWebSocket, 5000);
    };

    ws.onerror = (error) => {
        console.error('WebSocket error:', error);
        ttsStatus.textContent = 'Connection error. Retrying...';
        ttsStatus.className = 'status error';
        
        // Clean up audio resources on error
        audioBuffers = [];
        pendingAudioPaths.clear();
        if (currentAudioPath) {
            URL.revokeObjectURL(currentAudioPath);
            currentAudioPath = null;
        }
    };
}

// Convert AudioBuffer to WAV with specific format requirements
async function audioBufferToWav(buffer) {
    // Resample to 16kHz if needed
    let audioData = buffer.getChannelData(0);
    if (buffer.sampleRate !== 16000) {
        audioData = await resampleAudio(audioData, buffer.sampleRate, 16000);
    }
    
    const numChannels = 1; // Mono
    const sampleRate = 16000;
    const format = 1; // PCM
    const bitDepth = 16;
    
    const dataLength = audioData.length * (bitDepth / 8);
    const headerLength = 44;
    const totalLength = headerLength + dataLength;
    
    const arrayBuffer = new ArrayBuffer(totalLength);
    const view = new DataView(arrayBuffer);
    
    // Write WAV header
    writeString(view, 0, 'RIFF');
    view.setUint32(4, totalLength - 8, 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 * numChannels * (bitDepth / 8), true);
    view.setUint16(32, numChannels * (bitDepth / 8), true);
    view.setUint16(34, bitDepth, true);
    writeString(view, 36, 'data');
    view.setUint32(40, dataLength, true);
    
    // Write audio data
    floatTo16BitPCM(view, 44, audioData);
    
    return arrayBuffer;
}

function resampleAudio(audioData, originalSampleRate, targetSampleRate) {
    const ratio = targetSampleRate / originalSampleRate;
    const newLength = Math.round(audioData.length * ratio);
    const result = new Float32Array(newLength);
    
    for (let i = 0; i < newLength; i++) {
        const position = i / ratio;
        const index = Math.floor(position);
        const fraction = position - index;
        
        if (index + 1 < audioData.length) {
            result[i] = audioData[index] * (1 - fraction) + audioData[index + 1] * fraction;
        } else {
            result[i] = audioData[index];
        }
    }
    
    return result;
}

function writeString(view, offset, string) {
    for (let i = 0; i < string.length; i++) {
        view.setUint8(offset + i, string.charCodeAt(i));
    }
}

function floatTo16BitPCM(view, offset, input) {
    for (let i = 0; i < input.length; i++, offset += 2) {
        const s = Math.max(-1, Math.min(1, input[i]));
        view.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);
    }
}

generateSpeechBtn.addEventListener('click', () => {
    const text = ttsInput.value.trim();
    if (!text) {
        ttsStatus.textContent = 'Please enter some text';
        ttsStatus.className = 'status error';
        return;
    }

    if (ws && ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({ text }));
        ttsStatus.textContent = 'Generating audio...';
        ttsStatus.className = 'status';
    } else {
        ttsStatus.textContent = 'Connection lost. Reconnecting...';
        ttsStatus.className = 'status error';
        connectWebSocket();
    }
});

downloadAudioBtn.addEventListener('click', () => {
    if (currentAudioPath) {
        const link = document.createElement('a');
        link.href = currentAudioPath;
        link.download = `combined_audio_${Date.now()}.wav`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
});

// Clean up resources when leaving the page
window.addEventListener('beforeunload', () => {
    if (audioContext) {
        audioContext.close();
    }
    if (ws) {
        ws.close();
    }
    // Clean up any blob URLs
    if (currentAudioPath) {
        URL.revokeObjectURL(currentAudioPath);
    }
    // Clear any pending audio buffers
    audioBuffers = [];
    pendingAudioPaths.clear();
});

// Initialize WebSocket connection
connectWebSocket();

async function fetchWithRetry(url, maxRetries = 3, retryDelay = 1000) {
    for (let i = 0; i < maxRetries; i++) {
        try {
            const response = await fetch(url);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response;
        } catch (error) {
            if (i === maxRetries - 1) throw error;
            await new Promise(resolve => setTimeout(resolve, retryDelay));
        }
    }
}