Spaces:
Sleeping

olokaflow / apps /server /src /services /voiceService.ts
phucsd's picture
feat(enterprise): add Batch URL/CSV Video Factory, Zero-Shot Voice Cloning Studio & Auth Login Gate
8d2c959 verified
Raw History Blame Contribute Delete
19.9 kB
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { db, AUDIO_CACHE_DIR, logUsage } from '../db/database.js';
import { resolveTargetsForRole, normalizeBaseUrl } from './aiProfileService.js';
import { probeMediaDurationSec } from './assetAnalysisService.js';
import type { WordTimestamp } from '@olokaflow/shared';
const execFileAsync = promisify(execFile);
export interface VoiceCatalogItem {
id: string;
name: string;
voiceId: string;
gender: string;
region: string;
description: string;
lang: string;
provider: 'olokatts' | 'openai' | 'cloned';
isEditorsPick?: boolean;
previewUrl?: string;
refText?: string;
sampleAudioPath?: string;
fallbackVoiceId?: string;
}
export interface SynthesizedSceneVoice {
audioUrl: string;
audioDurationSec: number;
sceneDurationSec: number;
words: WordTimestamp[];
fromCache: boolean;
}
const OLOKATTS_BASE_URL = 'https://tts.oloka.net';
export const STATIC_FALLBACK_VOICES: VoiceCatalogItem[] = [
{
id: 'vp_haidang',
name: 'Hải Đăng (Nam • Miền Nam)',
voiceId: 'Hải Đăng',
gender: 'Nam',
region: 'Nam',
description: 'Trẻ trung, hiện đại, phong cách tự nhiên (Mặc định)',
lang: 'Tiếng Việt',
provider: 'olokatts',
isEditorsPick: true,
previewUrl: `${OLOKATTS_BASE_URL}/static/samples/presets/vp_haidang.wav`,
},
{
id: 'vp_trucly',
name: 'Trúc Ly (Nữ • Miền Bắc)',
voiceId: 'Trúc Ly',
gender: 'Nữ',
region: 'Bắc',
description: 'Trong trẻo, lôi cuốn, phong cách tự nhiên',
lang: 'Tiếng Việt',
provider: 'olokatts',
isEditorsPick: true,
previewUrl: `${OLOKATTS_BASE_URL}/static/samples/presets/vp_trucly.wav`,
},
{
id: 'vp_anhkhoi',
name: 'Anh Khôi (Nam • Miền Bắc)',
voiceId: 'Anh Khôi',
gender: 'Nam',
region: 'Bắc',
description: 'Trầm ấm, truyền cảm, phong cách kể chuyện',
lang: 'Tiếng Việt',
provider: 'olokatts',
isEditorsPick: true,
previewUrl: `${OLOKATTS_BASE_URL}/static/samples/presets/vp_anhkhoi.wav`,
},
{
id: 'vp_maianh',
name: 'Mai Anh (Nữ • Miền Bắc)',
voiceId: 'Mai Anh',
gender: 'Nữ',
region: 'Bắc',
description: 'Dịu dàng, chuẩn phát thanh, phong cách tin tức',
lang: 'Tiếng Việt',
provider: 'olokatts',
isEditorsPick: true,
previewUrl: `${OLOKATTS_BASE_URL}/static/samples/presets/vp_maianh.wav`,
},
{
id: 'vp_adambua',
name: 'Adam Bựa (Nam • Hài hước)',
voiceId: 'Adam bựa',
gender: 'Nam',
region: 'Bắc',
description: 'Hài hước, dí dỏm, độc đáo cho TikTok/Reels',
lang: 'Tiếng Việt',
provider: 'olokatts',
isEditorsPick: true,
previewUrl: `${OLOKATTS_BASE_URL}/static/samples/presets/vp_adambua.wav`,
},
{
id: 'nova',
name: 'Nova (OpenAI • Nữ năng lượng)',
voiceId: 'nova',
gender: 'Nữ',
region: 'Quốc tế / Đa ngôn ngữ',
description: 'Giọng nữ hiện đại, giàu năng lượng chuẩn OpenAI',
lang: 'Multi / VI',
provider: 'openai',
},
{
id: 'alloy',
name: 'Alloy (OpenAI • Trung tính)',
voiceId: 'alloy',
gender: 'Trung tính',
region: 'Quốc tế / Đa ngôn ngữ',
description: 'Giọng thuyết minh cân bằng, chuyên nghiệp',
lang: 'Multi / VI',
provider: 'openai',
},
{
id: 'onyx',
name: 'Onyx (OpenAI • Nam trầm ấm)',
voiceId: 'onyx',
gender: 'Nam',
region: 'Quốc tế / Đa ngôn ngữ',
description: 'Giọng nam sâu, uy tín cho giới thiệu doanh nghiệp',
lang: 'Multi / VI',
provider: 'openai',
},
{
id: 'shimmer',
name: 'Shimmer (OpenAI • Nữ dịu dàng)',
voiceId: 'shimmer',
gender: 'Nữ',
region: 'Quốc tế / Đa ngôn ngữ',
description: 'Giọng nữ nhẹ nhàng cho lifestyle & kể chuyện',
lang: 'Multi / VI',
provider: 'openai',
},
];
let cachedLiveVoices: VoiceCatalogItem[] | null = null;
let cachedVoicesTimestamp = 0;
export function listCustomClonedVoices(): VoiceCatalogItem[] {
try {
const rows = db
.prepare('SELECT * FROM custom_voices ORDER BY created_at DESC')
.all() as any[];
return rows.map((r) => ({
id: r.id,
name: `${r.name} (Clone • ${r.gender})`,
voiceId: r.voice_id || r.id,
gender: r.gender || 'Nam',
region: r.region || 'Việt Nam',
description:
r.description || 'Giọng đọc Clone cá nhân hóa (Zero-Shot Voice Clone)',
lang: 'Tiếng Việt',
provider: 'cloned' as const,
isEditorsPick: true,
previewUrl: r.sample_public_url || '',
refText: r.ref_text || '',
sampleAudioPath: r.sample_audio_path || '',
fallbackVoiceId: r.fallback_voice_id || 'Hải Đăng',
}));
} catch {
return [];
}
}
export function createCustomClonedVoice(params: {
name: string;
gender: string;
region: string;
description?: string;
refText?: string;
sampleAudioPath: string;
samplePublicUrl: string;
fallbackVoiceId?: string;
}): VoiceCatalogItem {
const id = `vc-clone-${crypto.randomUUID().slice(0, 8)}`;
const now = new Date().toISOString();
const cleanName = params.name.trim() || 'Giọng Clone Mới';
const fallbackVoice =
params.fallbackVoiceId || (params.gender === 'Nữ' ? 'Trúc Ly' : 'Hải Đăng');
db.prepare(`
INSERT INTO custom_voices (
id, name, voice_id, gender, region, description, ref_text,
sample_audio_path, sample_public_url, fallback_voice_id, created_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
id,
cleanName,
id,
params.gender || 'Nam',
params.region || 'Việt Nam',
params.description || 'Giọng đọc Clone cá nhân hóa từ file mẫu',
params.refText || '',
params.sampleAudioPath,
params.samplePublicUrl,
fallbackVoice,
now
);
cachedLiveVoices = null;
return listCustomClonedVoices().find((v) => v.id === id)!;
}
export function deleteCustomClonedVoice(id: string): void {
db.prepare('DELETE FROM custom_voices WHERE id = ?').run(id);
cachedLiveVoices = null;
}
/**
* Fetches the live 25 Vietnamese voices from https://tts.oloka.net/v1/voices
* and merges with custom cloned voices + OpenAI standard voices.
*/
export async function listAvailableVoices(): Promise<VoiceCatalogItem[]> {
const customClones = listCustomClonedVoices();
if (cachedLiveVoices && Date.now() - cachedVoicesTimestamp < 5 * 60 * 1000) {
return [...customClones, ...cachedLiveVoices];
}
try {
const resp = await fetch(`${OLOKATTS_BASE_URL}/v1/voices`, {
signal: AbortSignal.timeout(8000),
});
if (resp.ok) {
const payload = (await resp.json()) as any[];
if (Array.isArray(payload) && payload.length > 0) {
const olokaVoices: VoiceCatalogItem[] = payload
.map((row) => {
const voiceId = String(row.voice_id || row.name || '').trim();
if (!voiceId) return null;
const preview = String(row.preview_audio_url || '');
const previewUrl = preview.startsWith('/')
? `${OLOKATTS_BASE_URL}${preview}`
: preview.startsWith('http')
? preview
: '';
const gender = String(row.gender || 'Nam');
const region = String(row.region || 'Việt Nam');
return {
id: String(row.id || voiceId),
name: `${row.name || voiceId} (${gender} • Miền ${region})`,
voiceId,
gender,
region,
description: String(row.description || 'Giọng đọc AI tiếng Việt tự nhiên').slice(0, 160),
lang: 'Tiếng Việt',
provider: 'olokatts' as const,
isEditorsPick: Boolean(row.is_editors_pick),
previewUrl,
};
})
.filter(Boolean) as VoiceCatalogItem[];
const openaiExtras = STATIC_FALLBACK_VOICES.filter((v) => v.provider === 'openai');
cachedLiveVoices = [...olokaVoices, ...openaiExtras];
cachedVoicesTimestamp = Date.now();
return [...customClones, ...cachedLiveVoices];
}
}
} catch (err: any) {
console.warn(`[VoiceService] Live OlokaTTS catalog fetch note: ${err.message}`);
}
return [...customClones, ...STATIC_FALLBACK_VOICES];
}
export const AVAILABLE_VOICES = STATIC_FALLBACK_VOICES;
const VI_DIGITS = ['không', 'một', 'hai', 'ba', 'bốn', 'năm', 'sáu', 'bảy', 'tám', 'chín'];
function readTwoDigitsVi(n: number): string {
if (n < 10) return VI_DIGITS[n];
const tens = Math.floor(n / 10);
const ones = n % 10;
const tensText = tens === 1 ? 'mười' : `${VI_DIGITS[tens]} mươi`;
if (ones === 0) return tensText;
if (ones === 1 && tens > 1) return `${tensText} mốt`;
if (ones === 5) return `${tensText} lăm`;
return `${tensText} ${VI_DIGITS[ones]}`;
}
function numberToViWords(numStr: string): string {
const n = Number.parseInt(numStr, 10);
if (!Number.isFinite(n) || n < 0 || n > 9999) return numStr;
if (n < 100) return readTwoDigitsVi(n);
if (n < 1000) {
const hundreds = Math.floor(n / 100);
const rem = n % 100;
if (rem === 0) return `${VI_DIGITS[hundreds]} trăm`;
if (rem < 10) return `${VI_DIGITS[hundreds]} trăm lẻ ${VI_DIGITS[rem]}`;
return `${VI_DIGITS[hundreds]} trăm ${readTwoDigitsVi(rem)}`;
}
return numStr;
}
/**
* Normalizes Vietnamese narration text for clean TTS pronunciation:
* - Strips markdown/stage directions in brackets
* - Expands percentages & small integers for natural Vietnamese TTS reading
*/
export function normalizeVietnameseTtsText(rawText: string): string {
return (rawText || '')
.replace(/\[(?:scene|cảnh|visual|sfx|bgm)[^\]]*\]/gi, ' ')
.replace(/(\d+)\s*%/g, (_, d) => `${numberToViWords(d)} phần trăm`)
.replace(/\s+/g, ' ')
.trim();
}
/**
* Generates proportional word-level timestamps weighted by character/syllable length
* when ASR endpoint is not configured or as a fast deterministic sync rail.
*/
export function buildSyllableWeightedWordTimestamps(
text: string,
audioDurationSec: number
): WordTimestamp[] {
const cleanTokens = (text || '')
.replace(/\s+/g, ' ')
.trim()
.split(' ')
.filter(Boolean);
if (cleanTokens.length === 0) return [];
const usableDuration = Math.max(1.2, audioDurationSec - 0.15);
const weights = cleanTokens.map((w) => {
const base = Math.max(2, w.length);
const pauseBonus = /[.,;!?]$/.test(w) ? 2.2 : 0;
return base + pauseBonus;
});
const totalWeight = weights.reduce((a, b) => a + b, 0) || 1;
let cursor = 0.08;
return cleanTokens.map((word, idx) => {
const span = (weights[idx] / totalWeight) * usableDuration;
const start = Number(cursor.toFixed(3));
const end = Number(Math.min(audioDurationSec, cursor + span).toFixed(3));
cursor += span;
return { word, start, end };
});
}
async function masterVoiceAudioToMp3(inputPath: string, outputMp3Path: string): Promise<boolean> {
const isWin = process.platform === 'win32';
const ffmpegCmd = isWin ? 'ffmpeg.exe' : 'ffmpeg';
try {
await execFileAsync(
ffmpegCmd,
[
'-y',
'-i',
inputPath,
'-af',
'highpass=f=90,equalizer=f=3200:t=q:w=1.2:g=2.0,acompressor=threshold=-18dB:ratio=2.5:attack=15:release=180,loudnorm=I=-12.5:TP=-1.5:LRA=5',
'-ar',
'44100',
'-ac',
'1',
'-c:a',
'libmp3lame',
'-b:a',
'192k',
outputMp3Path,
],
{ timeout: 25000 }
);
return fs.existsSync(outputMp3Path) && fs.statSync(outputMp3Path).size > 256;
} catch {
return false;
}
}
export async function synthesizeSceneVoice(params: {
projectId: string;
sceneIndex: number;
text: string;
voiceId: string;
speed?: number;
}): Promise<SynthesizedSceneVoice> {
const cleanText = normalizeVietnameseTtsText(params.text || '');
const speed = Math.max(0.5, Math.min(2.0, Number(params.speed || 1.0)));
// Resolve voiceId against live catalog if an id like 'vp_haidang' or a cloned voice was passed
const catalog = await listAvailableVoices();
const matchedVoice = catalog.find(
(v) => v.id === params.voiceId || v.voiceId === params.voiceId
);
const isClonedVoice = matchedVoice?.provider === 'cloned';
const resolvedVoiceName = isClonedVoice
? matchedVoice.fallbackVoiceId || 'Hải Đăng'
: matchedVoice
? matchedVoice.voiceId
: params.voiceId || 'Hải Đăng';
let clonedAudioB64 = '';
if (
isClonedVoice &&
matchedVoice?.sampleAudioPath &&
fs.existsSync(matchedVoice.sampleAudioPath)
) {
try {
clonedAudioB64 = fs
.readFileSync(matchedVoice.sampleAudioPath)
.toString('base64');
} catch {}
}
const hash = crypto
.createHash('sha256')
.update(`${matchedVoice?.id || resolvedVoiceName}:${speed}:${cleanText}`)
.digest('hex')
.slice(0, 16);
const mp3FileName = `vo-${hash}.mp3`;
const wordsFileName = `vo-${hash}.words.json`;
const mp3Path = path.join(AUDIO_CACHE_DIR, mp3FileName);
const wordsPath = path.join(AUDIO_CACHE_DIR, wordsFileName);
// 1. Check SHA-256 Scene TTS Cache first!
if (fs.existsSync(mp3Path) && fs.existsSync(wordsPath)) {
try {
const cached = JSON.parse(fs.readFileSync(wordsPath, 'utf8'));
return {
audioUrl: `/media/audio_cache/${mp3FileName}`,
audioDurationSec: cached.audioDurationSec,
sceneDurationSec: cached.sceneDurationSec,
words: cached.words,
fromCache: true,
};
} catch {}
}
// Estimate speaking duration from Vietnamese word count (~2.9 words/sec at 1.0x)
const wordCount = cleanText.split(/\s+/).filter(Boolean).length;
const estimatedAudioDurationSec = Number(
Math.max(2.6, wordCount / (2.9 * speed)).toFixed(2)
);
// 2. Try calling configured OpenAI-compatible / OlokaTTS endpoint
const ttsTargets = resolveTargetsForRole('voice_tts');
for (const target of ttsTargets) {
const { profile, modelId } = target;
if (!profile.baseUrl || !profile.apiKey) continue;
const baseUrl = normalizeBaseUrl(profile.baseUrl, profile.protocol);
const isOlokaTts = baseUrl.includes('tts.oloka.net');
const speechEndpoint = baseUrl.endsWith('/v1')
? `${baseUrl}/audio/speech`
: baseUrl.includes('tts.oloka.net')
? `${baseUrl}/v1/audio/speech`
: `${baseUrl}/audio/speech`;
const startTime = Date.now();
try {
const requestBody: Record<string, any> = isOlokaTts
? {
model: modelId || 'olokatts-v3-turbo',
voice: resolvedVoiceName,
input: cleanText,
speed,
...(clonedAudioB64
? {
reference_audio_b64: clonedAudioB64,
ref_text: matchedVoice?.refText || undefined,
}
: {}),
}
: {
model: modelId || 'tts-1-hd',
voice: resolvedVoiceName,
input: cleanText,
speed,
response_format: 'mp3',
...(clonedAudioB64
? {
reference_audio_b64: clonedAudioB64,
ref_text: matchedVoice?.refText || undefined,
}
: {}),
};
const resp = await fetch(speechEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${profile.apiKey}`,
...(isOlokaTts ? { Accept: 'audio/wav' } : {}),
...profile.customHeaders,
},
body: JSON.stringify(requestBody),
signal: AbortSignal.timeout(profile.timeoutMs || 120000),
});
if (!resp.ok) {
const errBody = await resp.text().catch(() => '');
throw new Error(`TTS HTTP ${resp.status}: ${errBody.slice(0, 160)}`);
}
const audioBuffer = Buffer.from(await resp.arrayBuffer());
const rawTempPath = path.join(AUDIO_CACHE_DIR, `raw-${hash}.bin`);
fs.writeFileSync(rawTempPath, audioBuffer);
// Master audio to -12.5 LUFS MP3 if FFmpeg is installed, else save directly
const mastered = await masterVoiceAudioToMp3(rawTempPath, mp3Path);
if (!mastered) {
fs.copyFileSync(rawTempPath, mp3Path);
}
try {
fs.unlinkSync(rawTempPath);
} catch {}
const measuredDuration = await probeMediaDurationSec(
mp3Path,
estimatedAudioDurationSec
);
const sceneDurationSec = Number(
Math.max(3.2, Math.ceil((measuredDuration + 0.45) * 10) / 10).toFixed(2)
);
// Try Whisper word-level ASR if configured
let words = await tryTranscribeWordTimestamps(mp3Path, measuredDuration);
if (!words || words.length === 0) {
words = buildSyllableWeightedWordTimestamps(params.text || cleanText, measuredDuration);
}
fs.writeFileSync(
wordsPath,
JSON.stringify({ audioDurationSec: measuredDuration, sceneDurationSec, words }, null, 2),
'utf8'
);
logUsage({
projectId: params.projectId,
profileId: profile.id,
modelId: requestBody.model,
role: 'voice_tts',
ttsChars: cleanText.length,
durationMs: Date.now() - startTime,
});
return {
audioUrl: `/media/audio_cache/${mp3FileName}`,
audioDurationSec: measuredDuration,
sceneDurationSec,
words,
fromCache: false,
};
} catch (err: any) {
console.warn(`[VoiceService] TTS profile "${profile.name}" failed: ${err.message}`);
}
}
// 3. Fallback when TTS API key is not yet entered: compute accurate word timing rail
const sceneDurationSec = Number(
Math.max(3.5, Math.ceil((estimatedAudioDurationSec + 0.45) * 10) / 10).toFixed(2)
);
const words = buildSyllableWeightedWordTimestamps(
params.text || cleanText,
estimatedAudioDurationSec
);
return {
audioUrl: '',
audioDurationSec: estimatedAudioDurationSec,
sceneDurationSec,
words,
fromCache: false,
};
}
async function tryTranscribeWordTimestamps(
mp3Path: string,
fallbackDurationSec: number
): Promise<WordTimestamp[] | null> {
const asrTargets = resolveTargetsForRole('voice_asr');
for (const target of asrTargets) {
const { profile, modelId } = target;
if (!profile.baseUrl || !profile.apiKey) continue;
try {
const baseUrl = normalizeBaseUrl(profile.baseUrl, profile.protocol);
const fileBuf = fs.readFileSync(mp3Path);
const formData = new FormData();
formData.append('file', new Blob([fileBuf], { type: 'audio/mpeg' }), path.basename(mp3Path));
formData.append('model', modelId || 'whisper-1');
formData.append('response_format', 'verbose_json');
formData.append('timestamp_granularities[]', 'word');
const resp = await fetch(`${baseUrl}/audio/transcriptions`, {
method: 'POST',
headers: {
Authorization: `Bearer ${profile.apiKey}`,
...profile.customHeaders,
},
body: formData,
signal: AbortSignal.timeout(30000),
});
if (!resp.ok) continue;
const data = (await resp.json()) as any;
if (Array.isArray(data?.words) && data.words.length > 0) {
return data.words.map((w: any) => ({
word: String(w.word || '').trim(),
start: Number(w.start || 0),
end: Number(w.end || fallbackDurationSec),
}));
}
} catch {
// fallback to syllable timing
}
}
return null;
}