/** * AudioToText.com Speech-to-Text & Transcription Scraper * Engine: Audiototext.com Pipeline (AssemblyAI Engine) * Author: Vamz Spectre / VamxAPI * * Fitur: * 1. Transkripsi suara ke teks akurat dengan deteksi multi-speaker (SPK_1, SPK_2, dst). * 2. Timestamp per kata/kalimat (StartTime & EndTime dalam milidetik). * 3. Support input path file lokal (mp3, wav, ogg, m4a, webm, dll) atau direct URL audio. * 4. Tanpa perlu auth / akun (Bypass anonymous session). * * Penggunaan CLI: * curl -sL "https://code.vamxapi.my.id/snippet/raw/audiototext" -o audiototext.js * node audiototext.js "sample.mp3" * node audiototext.js "https://j.top4top.io/m_3648lcp5h0.mp3" */ const axios = require('axios'); const fs = require('fs'); const path = require('path'); const SUPABASE_BASE = 'https://pgxqjqkmvprwhsuuolda.supabase.co'; /** * Mendapatkan MIME type berdasarkan ekstensi file */ function getMimeType(filePath) { const ext = path.extname(filePath).toLowerCase(); const mimes = { '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.ogg': 'audio/ogg', '.m4a': 'audio/m4a', '.aac': 'audio/aac', '.flac': 'audio/flac', '.webm': 'audio/webm', '.mp4': 'video/mp4', '.mov': 'video/quicktime' }; return mimes[ext] || 'audio/mpeg'; } /** * Transkripsi audio file (Path lokal, URL, atau Buffer) * @param {string|Buffer} input - Path file audio, direct URL audio, atau Buffer * @param {object} options - Opsi tambahan (filename, locale, maxPollRetries) */ async function transcribeAudio(input, options = {}) { let fileBuffer; let filename = options.filename; let mimeType = options.mimeType; const locale = options.locale || 'auto'; const maxRetries = options.maxPollRetries || 60; // 1. Tangani input audio (URL, Path lokal, atau Buffer) if (Buffer.isBuffer(input)) { fileBuffer = input; if (!filename) filename = `audio_${Date.now()}.mp3`; if (!mimeType) mimeType = getMimeType(filename); } else if (typeof input === 'string') { if (input.startsWith('http://') || input.startsWith('https://')) { const parsedUrl = new URL(input); filename = filename || path.basename(parsedUrl.pathname) || `audio_${Date.now()}.mp3`; mimeType = mimeType || getMimeType(filename); const dl = await axios.get(input, { responseType: 'arraybuffer', timeout: 30000, headers: { 'User-Agent': 'Mozilla/5.0' } }); fileBuffer = Buffer.from(dl.data); } else { if (!fs.existsSync(input)) { throw new Error(`File audio tidak ditemukan: ${input}`); } filename = filename || path.basename(input); mimeType = mimeType || getMimeType(filename); fileBuffer = fs.readFileSync(input); } } else { throw new Error('Input wajib berupa file path, URL audio, atau Buffer.'); } // 2. Request S3 Pre-signed Upload URL ke Audiototext const uploadUrlRes = await axios.post( `${SUPABASE_BASE}/functions/v1/att-generate-upload-url`, { filename: filename, fileType: mimeType }, { headers: { 'Content-Type': 'application/json' }, timeout: 15000 } ); const { uploadUrl, filePath, storage } = uploadUrlRes.data; if (!uploadUrl || !filePath) { throw new Error('Gagal mendapatkan upload URL dari Audiototext.'); } // 3. Upload Audio ke S3 Storage await axios.put(uploadUrl, fileBuffer, { headers: { 'Content-Type': mimeType }, timeout: 60000, maxBodyLength: Infinity, maxContentLength: Infinity }); // 4. Inisiasi proses transkripsi const anonymousSessionId = `anon_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`; const initPayload = { filePath: filePath, isAssembly: true, anonymousSessionId: anonymousSessionId }; if (locale && locale !== 'auto') { initPayload.locale = locale; } const initRes = await axios.post( `${SUPABASE_BASE}/functions/v1/att-initiate-transcription`, initPayload, { headers: { 'Content-Type': 'application/json' }, timeout: 15000 } ); const orderId = initRes.data?.orderId; if (!orderId) { throw new Error('Gagal memulai antrean transkripsi.'); } // 5. Polling status transkripsi sampai selesai let result = null; for (let attempt = 1; attempt <= maxRetries; attempt++) { await new Promise(r => setTimeout(r, 3000)); const pollRes = await axios.post( `${SUPABASE_BASE}/functions/v1/get-att-transcription-order`, { orderId: orderId }, { headers: { 'Content-Type': 'application/json' }, timeout: 15000 } ); const data = pollRes.data; if (data.status === 'completed') { result = data; break; } else if (data.status === 'error' || data.success === false) { throw new Error(data.error || 'Proses transkripsi gagal.'); } } if (!result) { throw new Error(`Transkripsi timeout setelah polling ${maxRetries * 3} detik.`); } // 6. Format respon yang rapi & bersih const blocks = (result.blocks || []).map(b => ({ speaker: b.Speaker || 'SPK_1', text: (b.text || '').trim(), start_time_ms: b.StartTime, end_time_ms: b.EndTime })); const fullText = blocks.map(b => b.text).join(' ').trim(); const speakers = [...new Set(blocks.map(b => b.speaker))]; const totalDurationMs = blocks.length > 0 ? blocks[blocks.length - 1].end_time_ms : 0; return { status: true, order_id: result.order_id, filename: result.filename, speakers: speakers, duration_ms: totalDurationMs, full_text: fullText, blocks: blocks, playback_audio_url: result.audio_url || null }; } // Module Export module.exports = { transcribeAudio }; // CLI Runner if (require.main === module) { const arg = process.argv[2] || '/root/sample_test.mp3'; (async () => { try { const res = await transcribeAudio(arg); console.log(JSON.stringify(res, null, 2)); } catch (err) { console.error(JSON.stringify({ status: false, error: err.message }, null, 2)); process.exit(1); } })(); }