-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathtest-single.js
More file actions
181 lines (145 loc) · 5.22 KB
/
test-single.js
File metadata and controls
181 lines (145 loc) · 5.22 KB
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
#!/usr/bin/env node
/**
* Test script - generate audio for a single file
*/
import { GoogleGenerativeAI } from '@google/generative-ai';
import { readFileSync, writeFileSync, mkdirSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const DOCS_DIR = join(__dirname, '../website/docs');
const AUDIO_OUTPUT_DIR = join(__dirname, '../website/static/audio');
const TTS_MODEL = 'gemini-2.5-flash-preview-tts';
const DIALOGUE_MODEL = 'gemini-2.5-flash';
const API_KEY = process.env.GOOGLE_API_KEY || process.env.GEMINI_API_KEY || process.env.GCP_API_KEY;
if (!API_KEY) {
console.error('❌ Error: No API key found');
process.exit(1);
}
const genAI = new GoogleGenerativeAI(API_KEY);
function createWavHeader(pcmDataLength) {
const header = Buffer.alloc(44);
header.write('RIFF', 0);
header.writeUInt32LE(36 + pcmDataLength, 4);
header.write('WAVE', 8);
header.write('fmt ', 12);
header.writeUInt32LE(16, 16);
header.writeUInt16LE(1, 20);
header.writeUInt16LE(1, 22);
header.writeUInt32LE(24000, 24);
header.writeUInt32LE(24000 * 1 * 2, 28);
header.writeUInt16LE(1 * 2, 32);
header.writeUInt16LE(16, 34);
header.write('data', 36);
header.writeUInt32LE(pcmDataLength, 40);
return header;
}
async function retryWithBackoff(fn, maxAttempts = 4) {
let lastError;
for (let attempt = 0; attempt < maxAttempts; attempt++) {
try {
return await fn();
} catch (error) {
lastError = error;
const isRetryable =
error.message?.includes('fetch failed') ||
error.message?.includes('ECONNRESET') ||
error.message?.includes('ETIMEDOUT') ||
error.message?.includes('ENOTFOUND') ||
error.status === 429 ||
error.status === 500 ||
error.status === 503 ||
error.status === 504;
const isPermanent =
error.status === 400 ||
error.status === 401 ||
error.status === 403 ||
error.status === 404;
if (isPermanent) {
throw error;
}
if (!isRetryable || attempt === maxAttempts - 1) {
throw lastError;
}
const delay = Math.pow(2, attempt) * 1000;
console.log(`⏳ Retry ${attempt + 1}/${maxAttempts} after ${delay}ms (${error.message})`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
throw lastError;
}
async function generateAudio(dialogue, outputPath) {
console.log(`🎙️ Synthesizing audio...`);
const result = await retryWithBackoff(async () => {
const model = genAI.getGenerativeModel({ model: TTS_MODEL });
const response = await model.generateContent({
contents: [{
role: 'user',
parts: [{ text: dialogue }]
}],
generationConfig: {
responseModalities: ['AUDIO'],
speechConfig: {
multiSpeakerVoiceConfig: {
speakerVoiceConfigs: [
{
speaker: 'Alex',
voiceConfig: {
prebuiltVoiceConfig: { voiceName: 'Kore' }
}
},
{
speaker: 'Sam',
voiceConfig: {
prebuiltVoiceConfig: { voiceName: 'Charon' }
}
}
]
}
}
}
});
if (!response?.response?.candidates?.[0]?.content?.parts?.[0]?.inlineData?.data) {
throw new Error('TTS API returned malformed response - missing inlineData.data');
}
return response;
});
const audioData = result.response.candidates[0].content.parts[0].inlineData;
const pcmBuffer = Buffer.from(audioData.data, 'base64');
const wavHeader = createWavHeader(pcmBuffer.length);
const wavBuffer = Buffer.concat([wavHeader, pcmBuffer]);
mkdirSync(dirname(outputPath), { recursive: true });
writeFileSync(outputPath, wavBuffer);
console.log(`✅ Audio synthesized successfully`);
return { size: wavBuffer.length, pcmSize: pcmBuffer.length };
}
// Test with a simple dialogue
const testDialogue = `Alex: Welcome to our AI Coding Course!
Sam: Thanks for having me! I'm excited to learn about AI-driven development.
Alex: Great! Let's dive into how AI agents can help senior engineers work more efficiently.
Sam: That sounds really practical. I'm ready when you are.`;
const outputPath = join(AUDIO_OUTPUT_DIR, 'test-output.wav');
console.log('🧪 Testing WAV generation...\n');
console.log('Input dialogue:');
console.log(testDialogue);
console.log('\n' + '='.repeat(60) + '\n');
try {
const result = await generateAudio(testDialogue, outputPath);
console.log(`\n✅ Success!`);
console.log(` Output: ${outputPath}`);
console.log(` PCM size: ${(result.pcmSize / 1024).toFixed(2)} KB`);
console.log(` WAV size: ${(result.size / 1024).toFixed(2)} KB (with header)`);
console.log('\nVerifying file...');
// Verify the file
const testBuffer = readFileSync(outputPath);
const header = testBuffer.slice(0, 12).toString();
if (header.startsWith('RIFF') && header.includes('WAVE')) {
console.log('✅ Valid WAV file structure detected!');
} else {
console.log('❌ Invalid WAV header');
}
} catch (error) {
console.error('❌ Error:', error.message);
process.exit(1);
}