const fastify = require('fastify')({ bodyLimit: 25 * 1024 * 1024, logger: { level: 'info', transport: { target: 'pino-pretty', options: { translateTime: 'HH:MM:ss Z', ignore: 'pid,hostname', }, }, }, }) const cors = require('@fastify/cors') const { v4: uuidv4 } = require('uuid') const wav = require('node-wav') const fs = require('fs').promises const { exec } = require('child_process') const util = require('util') const path = require('path') const execPromise = util.promisify(exec) // Constants const MODEL_ID = 'Qwen/Qwen3-ForcedAligner-0.6B' const CLEANUP_INTERVAL = 5 const JOB_TTL_SECONDS = 300 const AVG_ALIGN_SECONDS = 30.0 const MIN_AUDIO_SECONDS = 0.3 const MAX_AUDIO_SECONDS = 180.0 const ROLLING_AVG_WINDOW = 10 // Job status enum const JobStatus = { QUEUED: 'queued', RUNNING: 'running', COMPLETED: 'completed', FAILED: 'failed', ABANDONED: 'abandoned', } const TERMINAL_STATUSES = new Set([ JobStatus.COMPLETED, JobStatus.FAILED, JobStatus.ABANDONED, ]) // In-memory state const state = { jobs: new Map(), metrics: { totalSubmitted: 0, totalCompleted: 0, totalFailed: 0, totalAbandoned: 0, totalCancelled: 0, startTime: new Date(), }, recentDurations: [], workerReady: false, } // Register CORS fastify.register(cors, { origin: '*', methods: ['GET', 'POST', 'OPTIONS'], }) // JSON schema for align request const alignSchema = { body: { type: 'object', required: ['audio_base64', 'text'], properties: { audio_base64: { type: 'string' }, text: { type: 'string' }, language: { type: 'string', default: 'English' }, pass_number: { type: 'integer', default: 1 }, client_id: { type: 'string', nullable: true }, }, }, } const cancelSchema = { params: { type: 'object', required: ['id'], properties: { id: { type: 'string' }, }, }, body: { type: 'object', properties: { client_id: { type: 'string', nullable: true }, }, }, } // Helper functions function avgAlignS() { if (state.recentDurations.length === 0) { return AVG_ALIGN_SECONDS } const sum = state.recentDurations.reduce((a, b) => a + b, 0) return Math.round((sum / state.recentDurations.length) * 10) / 10 } function cleanText(text) { // Curly quotes to straight text = text.replace(/\u2018|\u2019/g, "'") text = text.replace(/\u201c|\u201d/g, '"') // Dashes to space text = text.replace(/\u2014|\u2013/g, ' ') // Ellipsis to space text = text.replace(/\u2026/g, ' ') // Newlines to space text = text.replace(/[\n\r]/g, ' ') // Collapse whitespace text = text.replace(/\s+/g, ' ').trim() return text } async function validateAudio(audioBase64) { // Decode base64 let raw try { raw = Buffer.from(audioBase64, 'base64') } catch (err) { throw { statusCode: 400, error: 'Invalid audio', error_code: 'AUDIO_DECODE_ERROR', detail: 'audio_base64 is not valid base64.', } } // Parse WAV let wavData try { wavData = wav.decode(raw) } catch (err) { throw { statusCode: 400, error: 'Invalid audio', error_code: 'AUDIO_PARSE_ERROR', detail: `Could not parse as WAV: ${err.message}`, } } const { sampleRate, channelData, bitDepth } = wavData // Only reject if bitDepth is explicitly reported and unsupported if (bitDepth !== undefined && bitDepth !== 16 && bitDepth !== 32) { throw { statusCode: 400, error: 'Unsupported audio format', error_code: 'AUDIO_FORMAT_ERROR', detail: `Only 16-bit PCM or 32-bit float WAV supported (got ${bitDepth}-bit).`, } } if (sampleRate < 8000) { throw { statusCode: 400, error: 'Unsupported audio format', error_code: 'AUDIO_RATE_ERROR', detail: `Sample rate too low: ${sampleRate} Hz (minimum 8000 Hz).`, } } const numFrames = channelData[0].length const duration = numFrames / sampleRate if (duration < MIN_AUDIO_SECONDS) { throw { statusCode: 400, error: 'Audio too short', error_code: 'AUDIO_TOO_SHORT', detail: `Audio is ${duration.toFixed(2)}s — minimum is ${MIN_AUDIO_SECONDS}s.`, } } if (duration > MAX_AUDIO_SECONDS) { throw { statusCode: 400, error: 'Audio too long', error_code: 'AUDIO_TOO_LONG', detail: `Audio is ${duration.toFixed(1)}s — maximum is ${MAX_AUDIO_SECONDS}s.`, } } // Normalize to mono 16-bit const normalized = await normalizeWAV(raw, wavData) return { normalized, duration } } async function normalizeWAV(raw, wavData) { const { sampleRate, channelData, bitDepth } = wavData // Already mono 16-bit — return as-is if (channelData.length === 1 && bitDepth === 16) { return raw } // Mix down to mono let monoData if (channelData.length > 1) { monoData = new Float32Array(channelData[0].length) for (let i = 0; i < monoData.length; i++) { let sum = 0 for (let ch = 0; ch < channelData.length; ch++) sum += channelData[ch][i] monoData[i] = sum / channelData.length } } else { monoData = channelData[0] } // Encode back to WAV using node-wav (no extra dependencies needed) return Buffer.from(wav.encode([monoData], { sampleRate, float: false, bitDepth: 16 })) } function jobView(job, slim = false) { const base = { job_id: job.id, status: job.status, created_at: job.createdAt.toISOString(), } switch (job.status) { case JobStatus.QUEUED: base.queue_position = 1 base.estimated_wait_s = avgAlignS() base.message = 'Queued at position 1. Poll /job/{id} every 2 s.' break case JobStatus.RUNNING: if (job.startedAt) { const elapsed = (Date.now() - job.startedAt.getTime()) / 1000 const estimatedRemaining = Math.max(0, avgAlignS() - elapsed) base.started_at = job.startedAt.toISOString() base.elapsed_s = Math.round(elapsed * 10) / 10 base.estimated_remaining_s = Math.round(estimatedRemaining * 10) / 10 base.message = 'Running.' } break case JobStatus.COMPLETED: base.total_words = job.result.length base.language = job.request.language base.pass_number = job.request.pass_number base.model = MODEL_ID base.fine_tuned = false if (job.startedAt) { base.started_at = job.startedAt.toISOString() } if (job.terminalAt) { base.completed_at = job.terminalAt.toISOString() } if (job.startedAt && job.terminalAt) { const duration = (job.terminalAt - job.startedAt) / 1000 base.duration_s = Math.round(duration * 100) / 100 } if (!slim) { base.word_timestamps = job.result } break case JobStatus.FAILED: case JobStatus.ABANDONED: if (job.error) { base.error = job.error } if (job.terminalAt) { base.completed_at = job.terminalAt.toISOString() } break } return base } function promoteQueued() { // Check if any running job exists for (const job of state.jobs.values()) { if (job.status === JobStatus.RUNNING) { return } } // Find oldest queued job let oldestQueued = null let oldestId = null for (const [id, job] of state.jobs.entries()) { if (job.status === JobStatus.QUEUED) { if (!oldestQueued || job.createdAt < oldestQueued.createdAt) { oldestQueued = job oldestId = id } } } if (oldestQueued) { oldestQueued.status = JobStatus.RUNNING oldestQueued.startedAt = new Date() fastify.log.info(`Promoted queued job ${oldestId} → RUNNING`) // Start alignment runAlignment(oldestId) } } async function runAlignment(jobId) { fastify.log.info(`[${jobId}] Starting alignment`) const job = state.jobs.get(jobId) if (!job || job.status !== JobStatus.RUNNING) return const tempPath = path.join('/tmp', `${jobId}.wav`) try { // Write temp file await fs.writeFile(tempPath, job.wavBytes) const start = Date.now() // Call Python worker const { stdout, stderr } = await execPromise( `python3 worker.py ${tempPath} "${job.request.text}" "${job.request.language}"` ) const duration = (Date.now() - start) / 1000 // Parse result let timestamps try { timestamps = JSON.parse(stdout) } catch (err) { throw new Error(`Failed to parse alignment result: ${err.message}`) } fastify.log.info(`[${jobId}] Done — ${timestamps.length} words in ${duration.toFixed(2)}s`) // Update job const currentJob = state.jobs.get(jobId) if (currentJob && currentJob.status === JobStatus.RUNNING) { currentJob.status = JobStatus.COMPLETED currentJob.result = timestamps currentJob.terminalAt = new Date() state.metrics.totalCompleted++ state.recentDurations.push(duration) if (state.recentDurations.length > ROLLING_AVG_WINDOW) { state.recentDurations.shift() } } } catch (err) { fastify.log.error(`[${jobId}] Alignment failed: ${err.message}`) const currentJob = state.jobs.get(jobId) if (currentJob && currentJob.status === JobStatus.RUNNING) { currentJob.status = JobStatus.FAILED currentJob.error = err.message currentJob.terminalAt = new Date() state.metrics.totalFailed++ } } finally { // Clean up temp file try { await fs.unlink(tempPath) } catch (err) { // Ignore cleanup errors } promoteQueued() } } // Cleanup loop async function cleanupLoop() { setInterval(() => { const now = new Date() const cutoff = new Date(now - JOB_TTL_SECONDS * 1000) for (const [id, job] of state.jobs.entries()) { if (TERMINAL_STATUSES.has(job.status)) { if (job.terminalAt && job.terminalAt < cutoff) { state.jobs.delete(id) fastify.log.info(`Purged TTL-expired job ${id}`) } } } promoteQueued() }, CLEANUP_INTERVAL * 1000) } // Routes fastify.get('/', async () => { return { name: 'Qwen3-ForcedAligner Service', version: '1.5.0', status: 'ready', model: MODEL_ID, endpoints: { 'POST /align': 'Submit alignment job', 'GET /job/{id}': 'Unified status + result [preferred]', 'GET /job/{id}?slim=true': 'Status only — omits word_timestamps (use while polling)', 'GET /result/{id}': 'Legacy result poll [compat]', 'GET /queue/status': 'Queue availability', 'POST /cancel/{id}': 'Explicit job cancellation', 'GET /health': 'Service health + job counts', 'GET /metrics': 'Aggregate metrics', }, } }) fastify.get('/health', async () => { const counts = { queued: 0, running: 0, completed: 0, failed: 0, abandoned: 0, } for (const job of state.jobs.values()) { counts[job.status]++ } const overall = state.workerReady ? 'healthy' : 'degraded' return { status: overall, worker_alive: state.workerReady, worker_ready: state.workerReady, worker_restarting: false, model: MODEL_ID, shm_free_mb: null, shm_ok: true, avg_align_s: avgAlignS(), job_counts: counts, total_jobs: state.jobs.size, } }) fastify.get('/metrics', async () => { const total = state.metrics.totalCompleted + state.metrics.totalFailed + state.metrics.totalAbandoned const successRate = total > 0 ? Math.round((state.metrics.totalCompleted / total) * 1000) / 1000 : null const uptime = (Date.now() - state.metrics.startTime) / 1000 return { uptime_s: Math.round(uptime), total_submitted: state.metrics.totalSubmitted, total_completed: state.metrics.totalCompleted, total_failed: state.metrics.totalFailed, total_abandoned: state.metrics.totalAbandoned, total_cancelled: state.metrics.totalCancelled, success_rate: successRate, worker_restarts: 0, avg_align_s: avgAlignS(), recent_durations: state.recentDurations, } }) fastify.get('/queue/status', async () => { let runningJobId = null let queuedJobId = null for (const [id, job] of state.jobs.entries()) { if (job.status === JobStatus.RUNNING) runningJobId = id if (job.status === JobStatus.QUEUED) queuedJobId = id } const runningCount = runningJobId ? 1 : 0 const waitingCount = queuedJobId ? 1 : 0 return { // NEW: integer counts the controller reads running: runningCount, waiting: waitingCount, // Existing fields kept for backwards compat can_submit: runningCount === 0 && waitingCount === 0, slot_available: runningCount === 0, queue_full: runningCount === 1 && waitingCount === 1, running_job_id: runningJobId, queued_job_id: queuedJobId, worker_ready: state.workerReady, estimated_wait_s: runningJobId ? avgAlignS() : 0, } }) fastify.post('/align', { schema: alignSchema }, async (request, reply) => { const req = request.body // Set defaults req.language = req.language || 'English' req.pass_number = req.pass_number || 1 // 1. Model check if (!state.workerReady) { return reply.code(503).send({ error: 'Worker unavailable', error_code: 'WORKER_DOWN', detail: 'Model is still loading. Retry in a few seconds.', }) } // 2. Text validation const cleanedText = cleanText(req.text) if (!cleanedText) { return reply.code(400).send({ error: 'Invalid text', error_code: 'TEXT_EMPTY', detail: 'Text is empty after normalisation.', }) } req.text = cleanedText // 3. Audio validation let wavNormalized, audioDuration try { const result = await validateAudio(req.audio_base64) wavNormalized = result.normalized audioDuration = result.duration } catch (err) { return reply.code(err.statusCode || 400).send(err) } const runningExists = Array.from(state.jobs.values()).some( (j) => j.status === JobStatus.RUNNING ) const queuedExists = Array.from(state.jobs.values()).some( (j) => j.status === JobStatus.QUEUED ) // 4. Queue full check if (runningExists && queuedExists) { const wait = avgAlignS() return reply.code(503).send({ error: 'Service busy', error_code: 'QUEUE_FULL', detail: 'One job running, one already queued. Retry after current jobs finish.', retry_after: wait, }) } // 5. Duplicate client check let duplicateWarning = null if (req.client_id) { for (const [id, job] of state.jobs.entries()) { if ( job.client_id === req.client_id && (job.status === JobStatus.RUNNING || job.status === JobStatus.QUEUED) ) { duplicateWarning = { message: 'You already have an active job.', existing_job_id: id, existing_status: job.status, } break } } } // 6. Create job const status = runningExists ? JobStatus.QUEUED : JobStatus.RUNNING const jobId = uuidv4().split('-')[0] const now = new Date() const job = { id: jobId, request: req, status, createdAt: now, startedAt: status === JobStatus.RUNNING ? now : null, terminalAt: null, result: null, error: null, client_id: req.client_id, audioDuration: Math.round(audioDuration * 100) / 100, wavBytes: wavNormalized, } state.jobs.set(jobId, job) state.metrics.totalSubmitted++ fastify.log.info( `Job ${jobId} created — status=${status}, duration=${audioDuration.toFixed(1)}s, client=${req.client_id}` ) if (status === JobStatus.RUNNING) { runAlignment(jobId) } const response = { job_id: jobId, status, queue_position: status === JobStatus.QUEUED ? 1 : 0, poll_url: `/job/${jobId}`, estimated_wait_s: status === JobStatus.RUNNING ? 0 : avgAlignS(), audio_duration_s: Math.round(audioDuration * 100) / 100, message: status === JobStatus.RUNNING ? `Job started. Poll GET /job/${jobId}.` : `Job queued at position 1. Poll GET /job/${jobId} every 2 s.`, } if (duplicateWarning) { response.duplicate_warning = duplicateWarning } return response }) fastify.get('/job/:id', async (request) => { const { id } = request.params const slim = request.query.slim === 'true' const job = state.jobs.get(id) if (!job) { throw { statusCode: 404, error: 'Job not found', error_code: 'JOB_NOT_FOUND', detail: 'Job may have been purged (TTL=5 min) or never existed.', } } return jobView(job, slim) }) fastify.get('/result/:id', async (request) => { const { id } = request.params const job = state.jobs.get(id) if (!job) { throw { statusCode: 404, error: 'Job not found', error_code: 'JOB_NOT_FOUND', } } return jobView(job, false) }) fastify.post('/cancel/:id', { schema: cancelSchema }, async (request, reply) => { const { id } = request.params const { client_id } = request.body const job = state.jobs.get(id) if (!job) { throw { statusCode: 404, error: 'Job not found', error_code: 'JOB_NOT_FOUND', } } // Client ID check if (job.client_id) { if (!client_id || client_id !== job.client_id) { throw { statusCode: 403, error: 'Client ID mismatch', error_code: 'FORBIDDEN', detail: 'You are not the owner of this job.', } } } if (TERMINAL_STATUSES.has(job.status)) { return { cancelled: false, status: job.status, message: `Job was already ${job.status} — nothing to cancel.`, } } const wasRunning = job.status === JobStatus.RUNNING job.status = JobStatus.ABANDONED job.error = 'Cancelled by client' job.terminalAt = new Date() state.metrics.totalCancelled++ fastify.log.info(`Job ${id} cancelled (${wasRunning ? 'RUNNING' : 'QUEUED'})`) promoteQueued() return { cancelled: true, job_id: id, restarting: false, message: 'Job cancelled.', } }) fastify.post('/benchmark', async (request) => { const req = request.body if (!state.workerReady) { throw { statusCode: 503, error: 'Model not loaded yet', } } const cleanedText = cleanText(req.text) if (!cleanedText) { throw { statusCode: 400, error: 'Empty text', } } let wavNormalized, audioDuration try { const result = await validateAudio(req.audio_base64) wavNormalized = result.normalized audioDuration = result.duration } catch (err) { throw err } const wordCount = cleanedText.split(/\s+/).length const tempPath = path.join('/tmp', `benchmark_${uuidv4()}.wav`) try { await fs.writeFile(tempPath, wavNormalized) const start = Date.now() const { stdout } = await execPromise( `python3 worker.py ${tempPath} "${req.text}" "${req.language || 'English'}"` ) const actualDuration = (Date.now() - start) / 1000 const timestamps = JSON.parse(stdout) return { audio_duration_s: Math.round(audioDuration * 1000) / 1000, word_count: wordCount, actual_align_s: Math.round(actualDuration * 1000) / 1000, realtime_factor: Math.round((actualDuration / audioDuration) * 1000) / 1000, ms_per_word: wordCount > 0 ? Math.round((actualDuration / wordCount) * 1000 * 10) / 10 : null, words_aligned: timestamps.length, language: req.language || 'English', timestamp: new Date().toISOString(), } } finally { try { await fs.unlink(tempPath) } catch (err) { // Ignore cleanup errors } } }) // Error handler fastify.setErrorHandler((error, request, reply) => { fastify.log.error(error) if (error.statusCode) { reply.code(error.statusCode).send(error) } else { reply.code(500).send({ error: 'Internal server error', error_code: 'INTERNAL_ERROR', detail: error.message, }) } }) // Start server const start = async () => { try { // Start cleanup loop cleanupLoop() // Simulate Python worker starting setTimeout(() => { state.workerReady = true fastify.log.info('Python worker ready') }, 10000) await fastify.listen({ port: 7860, host: '0.0.0.0' }) fastify.log.info('Qwen3-ForcedAligner Service v1.5.0 ready') } catch (err) { fastify.log.error(err) process.exit(1) } } start()