From c3075b3a5277f762579c473d7c1a8553cd17e088 Mon Sep 17 00:00:00 2001 From: rouges78 Date: Tue, 24 Nov 2026 03:49:58 +0100 Subject: [PATCH] Move OpenAI text-to-speech to the Realtime API before tts-1 shuts down OpenAI shuts down tts-1, tts-1-hd and gpt-4o-mini-tts on 6 January 2027. The named replacement, gpt-realtime-2.1-mini, does not work on /v1/audio/speech and only runs through the Realtime API. - Add lib/voice/openai-realtime-tts.ts: mints an ephemeral key with the user's key, opens the Realtime WebSocket with it, sends the text, and wraps the returned PCM16 24 kHz audio in a WAV blob. - Use it in voice-clone.ts (tts-1-hd), tts-preview.tsx and voice-translator.tsx (tts-1). The local XTTS clone path is unchanged. - Replace the tts-1-only voices (fable, nova, onyx) with Realtime voices in the pickers; saved settings that still hold them are mapped to verse, coral and ash. - Clamp speed to the Realtime range (0.25-1.5); duration matching with OpenAI voices now tops out at 1.5x. - Allow wss://api.openai.com in the Tauri and production CSP. Reported in a GitHub issue. Not yet tested against the live API. Co-Authored-By: Claude Opus 5.5 --- .../voice/voice-translator-pipeline.test.tsx | 22 ++- .../lib/voice/openai-realtime-tts.test.ts | 170 ++++++++++++++++ __tests__/lib/voice/voice-clone-keys.test.ts | 14 +- app/dubbing/page.tsx | 8 +- components/tools/voice-clone-studio.tsx | 2 +- components/translator/tts-preview.tsx | 33 +--- components/voice/voice-translator.tsx | 82 ++++---- lib/i18n/locales/de.json | 6 +- lib/i18n/locales/el.json | 6 +- lib/i18n/locales/en.json | 6 +- lib/i18n/locales/es.json | 6 +- lib/i18n/locales/fr.json | 6 +- lib/i18n/locales/it.json | 6 +- lib/i18n/locales/ja.json | 6 +- lib/i18n/locales/ko.json | 6 +- lib/i18n/locales/pl.json | 6 +- lib/i18n/locales/pt.json | 6 +- lib/i18n/locales/ru.json | 6 +- lib/i18n/locales/zh.json | 6 +- lib/voice/openai-realtime-tts.ts | 185 ++++++++++++++++++ lib/voice/voice-clone.ts | 35 ++-- middleware.ts | 2 +- src-tauri/tauri.conf.json | 2 +- 23 files changed, 478 insertions(+), 149 deletions(-) create mode 100644 __tests__/lib/voice/openai-realtime-tts.test.ts create mode 100644 lib/voice/openai-realtime-tts.ts diff --git a/__tests__/components/voice/voice-translator-pipeline.test.tsx b/__tests__/components/voice/voice-translator-pipeline.test.tsx index b55cc5aeb..de4486de5 100644 --- a/__tests__/components/voice/voice-translator-pipeline.test.tsx +++ b/__tests__/components/voice/voice-translator-pipeline.test.tsx @@ -10,6 +10,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { render, screen, fireEvent, waitFor } from '@testing-library/react'; const translateMock = vi.fn(); +const synthMock = vi.fn(); vi.mock('@/lib/i18n', () => ({ useTranslation: () => ({ t: (k: string) => k, language: 'it' }), @@ -20,6 +21,11 @@ vi.mock('@/lib/ai/ai-translate-direct', () => ({ translateWithFallback: (...args: unknown[]) => translateMock(...args), })); +vi.mock('@/lib/voice/openai-realtime-tts', () => ({ + OPENAI_TTS_MAX_SPEED: 1.5, + synthesizeOpenAISpeech: (...args: unknown[]) => synthMock(...args), +})); + vi.mock('@/lib/client-logger', () => ({ clientLogger: { debug: vi.fn(), warn: vi.fn(), error: vi.fn(), info: vi.fn() }, })); @@ -27,7 +33,6 @@ vi.mock('@/lib/client-logger', () => ({ import { VoiceTranslator } from '@/components/voice/voice-translator'; const WHISPER_URL = 'https://api.openai.com/v1/audio/transcriptions'; -const TTS_URL = 'https://api.openai.com/v1/audio/speech'; const fetchMock = vi.fn(); @@ -49,6 +54,8 @@ function callsTo(url: string) { beforeEach(() => { translateMock.mockReset(); + synthMock.mockReset(); + synthMock.mockResolvedValue(new Blob(['wav'], { type: 'audio/wav' })); fetchMock.mockReset(); vi.stubGlobal('fetch', fetchMock); URL.createObjectURL = vi.fn(() => 'blob:x'); // jsdom non lo implementa @@ -62,16 +69,15 @@ afterEach(() => { describe('VoiceTranslator — pipeline completa', () => { it('trascrive, traduce e genera l audio passando i risultati da un passo all altro', async () => { fetchMock.mockImplementation(async (url: string) => - url === WHISPER_URL ? whisperOk('Hello') : new Response(new Blob(['mp3']), { status: 200 })); + url === WHISPER_URL ? whisperOk('Hello') : new Response('{}', { status: 404 })); translateMock.mockResolvedValue({ translations: ['Ciao'], provider: 'gemini', success: true }); await loadAudioAndRunPipeline(); - await waitFor(() => expect(callsTo(TTS_URL)).toHaveLength(1)); + await waitFor(() => expect(synthMock).toHaveBeenCalledTimes(1)); expect(callsTo(WHISPER_URL)).toHaveLength(1); expect(translateMock).toHaveBeenCalledWith(expect.objectContaining({ texts: ['Hello'], targetLanguage: 'it' })); - const ttsBody = JSON.parse((callsTo(TTS_URL)[0][1] as RequestInit).body as string); - expect(ttsBody.input).toBe('Ciao'); + expect(synthMock).toHaveBeenCalledWith(expect.objectContaining({ apiKey: 'sk-test', text: 'Ciao' })); }); it('si ferma se la trascrizione fallisce', async () => { @@ -81,18 +87,18 @@ describe('VoiceTranslator — pipeline completa', () => { expect(await screen.findByText('quota')).toBeInTheDocument(); expect(translateMock).not.toHaveBeenCalled(); - expect(callsTo(TTS_URL)).toHaveLength(0); + expect(synthMock).not.toHaveBeenCalled(); }); it('si ferma se nessun provider traduce, invece di leggere il testo originale come tradotto', async () => { fetchMock.mockImplementation(async (url: string) => - url === WHISPER_URL ? whisperOk('Hello') : new Response(new Blob(['mp3']), { status: 200 })); + url === WHISPER_URL ? whisperOk('Hello') : new Response('{}', { status: 404 })); translateMock.mockResolvedValue({ translations: ['Hello'], provider: 'none', success: false }); await loadAudioAndRunPipeline(); expect(await screen.findByText('voiceTranslator.translationError')).toBeInTheDocument(); - expect(callsTo(TTS_URL)).toHaveLength(0); + expect(synthMock).not.toHaveBeenCalled(); }); it('nessun parlato riconosciuto: lo dice e non traduce', async () => { diff --git a/__tests__/lib/voice/openai-realtime-tts.test.ts b/__tests__/lib/voice/openai-realtime-tts.test.ts new file mode 100644 index 000000000..10b018bba --- /dev/null +++ b/__tests__/lib/voice/openai-realtime-tts.test.ts @@ -0,0 +1,170 @@ +/** + * Sintesi vocale OpenAI via Realtime API (lib/voice/openai-realtime-tts.ts). + * + * tts-1 e tts-1-hd si spengono il 6 gennaio 2027; il sostituto + * gpt-realtime-2.1-mini funziona solo via Realtime. Qui si simula il server: + * chiave effimera via fetch, poi gli eventi WebSocket. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { synthesizeOpenAISpeech, toRealtimeVoice, OPENAI_TTS_MODEL } from '@/lib/voice/openai-realtime-tts'; + +class FakeWebSocket { + static last: FakeWebSocket | null = null; + sent: Array> = []; + closed = false; + onmessage: ((e: { data: string }) => void) | null = null; + onerror: (() => void) | null = null; + onclose: (() => void) | null = null; + + constructor(public url: string, public protocols: string[]) { + FakeWebSocket.last = this; + } + send(data: string) { + this.sent.push(JSON.parse(data)); + } + close() { + this.closed = true; + } + /** Evento dal server. */ + emit(event: object) { + this.onmessage?.({ data: JSON.stringify(event) }); + } +} + +const fetchMock = vi.fn(); + +function secretOk(value = 'ek_test') { + return new Response(JSON.stringify({ value, expires_at: 0 }), { status: 200 }); +} + +/** Attende che il WebSocket venga aperto (dopo la fetch della chiave effimera). */ +async function socket(): Promise { + await vi.waitFor(() => expect(FakeWebSocket.last).not.toBeNull()); + return FakeWebSocket.last!; +} + +/** jsdom non implementa Blob.arrayBuffer(). */ +function readBlob(blob: Blob): Promise { + return new Promise((resolve) => { + const reader = new FileReader(); + reader.onload = () => resolve(reader.result as ArrayBuffer); + reader.readAsArrayBuffer(blob); + }); +} + +const pcmBase64 = (bytes: number[]) => btoa(String.fromCharCode(...bytes)); + +beforeEach(() => { + FakeWebSocket.last = null; + fetchMock.mockReset(); + vi.stubGlobal('fetch', fetchMock); + vi.stubGlobal('WebSocket', FakeWebSocket); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('synthesizeOpenAISpeech', () => { + it('chiede la chiave effimera con la sessione configurata e non usa più /v1/audio/speech', async () => { + fetchMock.mockImplementation(async () => secretOk()); + const promise = synthesizeOpenAISpeech({ apiKey: 'sk-user', text: 'Ciao', voice: 'nova', speed: 3 }); + const ws = await socket(); + ws.emit({ type: 'session.created' }); + ws.emit({ type: 'response.output_audio.delta', delta: pcmBase64([1, 0]) }); + ws.emit({ type: 'response.done', response: { status: 'completed' } }); + await promise; + + const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]; + expect(url).toBe('https://api.openai.com/v1/realtime/client_secrets'); + expect((init.headers as Record).Authorization).toBe('Bearer sk-user'); + const { session } = JSON.parse(init.body as string); + expect(session.model).toBe(OPENAI_TTS_MODEL); + expect(session.output_modalities).toEqual(['audio']); + expect(session.audio.input.turn_detection).toBeNull(); + expect(session.audio.output.voice).toBe('coral'); // nova non esiste in Realtime + expect(session.audio.output.speed).toBe(1.5); // limite Realtime + }); + + it('apre il WebSocket con la chiave effimera, mai con quella dell utente', async () => { + fetchMock.mockImplementation(async () => secretOk('ek_abc')); + const promise = synthesizeOpenAISpeech({ apiKey: 'sk-user', text: 'Ciao', voice: 'alloy' }); + const ws = await socket(); + + expect(ws.url).toBe(`wss://api.openai.com/v1/realtime?model=${OPENAI_TTS_MODEL}`); + expect(ws.protocols).toEqual(['realtime', 'openai-insecure-api-key.ek_abc']); + expect(ws.protocols.join()).not.toContain('sk-user'); + + ws.emit({ type: 'error', error: { message: 'stop' } }); + await expect(promise).rejects.toThrow('stop'); + }); + + it('invia il testo dopo session.created e restituisce un WAV con tutto l audio ricevuto', async () => { + fetchMock.mockImplementation(async () => secretOk()); + const promise = synthesizeOpenAISpeech({ apiKey: 'sk-user', text: 'Ciao mondo', voice: 'marin' }); + const ws = await socket(); + + expect(ws.sent).toHaveLength(0); + ws.emit({ type: 'session.created' }); + expect(ws.sent[0]).toEqual({ + type: 'conversation.item.create', + item: { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'Ciao mondo' }] }, + }); + expect(ws.sent[1].type).toBe('response.create'); + + ws.emit({ type: 'response.output_audio.delta', delta: pcmBase64([1, 2, 3, 4]) }); + ws.emit({ type: 'response.output_audio.delta', delta: pcmBase64([5, 6]) }); + ws.emit({ type: 'response.done', response: { status: 'completed' } }); + + const blob = await promise; + expect(blob.type).toBe('audio/wav'); + const bytes = new Uint8Array(await readBlob(blob)); + const view = new DataView(bytes.buffer); + expect(String.fromCharCode(...bytes.slice(0, 4))).toBe('RIFF'); + expect(String.fromCharCode(...bytes.slice(8, 12))).toBe('WAVE'); + expect(view.getUint32(24, true)).toBe(24000); + expect(view.getUint32(40, true)).toBe(6); + expect([...bytes.slice(44)]).toEqual([1, 2, 3, 4, 5, 6]); + expect(ws.closed).toBe(true); + }); + + it('fallisce con il messaggio di OpenAI se la chiave effimera viene rifiutata', async () => { + fetchMock.mockResolvedValue(new Response(JSON.stringify({ error: { message: 'Incorrect API key' } }), { status: 401 })); + + await expect(synthesizeOpenAISpeech({ apiKey: 'sk-bad', text: 'Ciao', voice: 'alloy' })) + .rejects.toThrow('Incorrect API key'); + expect(FakeWebSocket.last).toBeNull(); + }); + + it('fallisce se la risposta non è completata o non contiene audio', async () => { + fetchMock.mockImplementation(async () => secretOk()); + const failed = synthesizeOpenAISpeech({ apiKey: 'sk-user', text: 'Ciao', voice: 'alloy' }); + const ws1 = await socket(); + ws1.emit({ type: 'response.done', response: { status: 'failed', status_details: { error: { message: 'quota' } } } }); + await expect(failed).rejects.toThrow('quota'); + + FakeWebSocket.last = null; + const empty = synthesizeOpenAISpeech({ apiKey: 'sk-user', text: 'Ciao', voice: 'alloy' }); + const ws2 = await socket(); + ws2.emit({ type: 'response.done', response: { status: 'completed' } }); + await expect(empty).rejects.toThrow(/nessun audio/); + }); + + it('fallisce se la connessione si chiude prima della fine', async () => { + fetchMock.mockImplementation(async () => secretOk()); + const promise = synthesizeOpenAISpeech({ apiKey: 'sk-user', text: 'Ciao', voice: 'alloy' }); + const ws = await socket(); + ws.onclose?.(); + await expect(promise).rejects.toThrow(/chiusa/); + }); +}); + +describe('toRealtimeVoice', () => { + it('porta le voci solo-tts-1 su voci Realtime e lascia le altre', () => { + expect(toRealtimeVoice('nova')).toBe('coral'); + expect(toRealtimeVoice('fable')).toBe('verse'); + expect(toRealtimeVoice('onyx')).toBe('ash'); + expect(toRealtimeVoice('alloy')).toBe('alloy'); + expect(toRealtimeVoice('marin')).toBe('marin'); + }); +}); diff --git a/__tests__/lib/voice/voice-clone-keys.test.ts b/__tests__/lib/voice/voice-clone-keys.test.ts index a3c7be22f..f49451905 100644 --- a/__tests__/lib/voice/voice-clone-keys.test.ts +++ b/__tests__/lib/voice/voice-clone-keys.test.ts @@ -11,6 +11,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; const getApiKeysMock = vi.fn(); const persistMock = vi.fn(); +const synthMock = vi.fn(); vi.mock('@/lib/ai/ai-translate-direct', () => ({ getApiKeys: () => getApiKeysMock(), @@ -20,6 +21,10 @@ vi.mock('@/lib/settings-persistence', () => ({ persistSettingsToDisk: () => persistMock(), })); +vi.mock('@/lib/voice/openai-realtime-tts', () => ({ + synthesizeOpenAISpeech: (...args: unknown[]) => synthMock(...args), +})); + vi.mock('@/lib/client-logger', () => ({ clientLogger: { debug: vi.fn(), warn: vi.fn(), error: vi.fn(), info: vi.fn() }, })); @@ -76,8 +81,7 @@ describe('voiceCloneService — chiavi dallo store centrale', () => { it('la sintesi OpenAI (usata da /dubbing) parte con la chiave delle Impostazioni', async () => { getApiKeysMock.mockReturnValue({ openai: 'sk-settings' }); - const fetchMock = vi.fn(async () => new Response(new Blob(['mp3']), { status: 200 })); - vi.stubGlobal('fetch', fetchMock); + synthMock.mockResolvedValue(new Blob(['wav'], { type: 'audio/wav' })); URL.createObjectURL = vi.fn(() => 'blob:x'); // jsdom non lo implementa const service = await freshService(); @@ -89,10 +93,8 @@ describe('voiceCloneService — chiavi dallo store centrale', () => { }, }); - expect(fetchMock).toHaveBeenCalledTimes(1); - const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]; - expect(url).toBe('https://api.openai.com/v1/audio/speech'); - expect((init.headers as Record).Authorization).toBe('Bearer sk-settings'); + expect(synthMock).toHaveBeenCalledTimes(1); + expect(synthMock).toHaveBeenCalledWith(expect.objectContaining({ apiKey: 'sk-settings', text: 'Ciao', voice: 'alloy' })); }); it('senza chiave da nessuna parte fallisce prima della rete', async () => { diff --git a/app/dubbing/page.tsx b/app/dubbing/page.tsx index e19e5a949..3d0614dbd 100644 --- a/app/dubbing/page.tsx +++ b/app/dubbing/page.tsx @@ -35,9 +35,11 @@ const LANGUAGES = [ const VOICES = [ { id: 'alloy', name: 'Alloy', desc: 'Neutro' }, { id: 'echo', name: 'Echo', desc: 'Maschile profondo' }, - { id: 'fable', name: 'Fable', desc: 'Narratore' }, - { id: 'onyx', name: 'Onyx', desc: 'Maschile autorevole' }, - { id: 'nova', name: 'Nova', desc: 'Femminile energico' }, + { id: 'verse', name: 'Verse', desc: 'Espressivo' }, + { id: 'ash', name: 'Ash', desc: 'Maschile chiaro' }, + { id: 'coral', name: 'Coral', desc: 'Femminile caldo' }, + { id: 'marin', name: 'Marin', desc: 'Femminile naturale' }, + { id: 'cedar', name: 'Cedar', desc: 'Maschile naturale' }, { id: 'shimmer', name: 'Shimmer', desc: 'Femminile caldo' }, ]; diff --git a/components/tools/voice-clone-studio.tsx b/components/tools/voice-clone-studio.tsx index 41f853fb2..ca0fe775c 100644 --- a/components/tools/voice-clone-studio.tsx +++ b/components/tools/voice-clone-studio.tsx @@ -41,7 +41,7 @@ export function VoiceCloneStudio() { const [inputText, setInputText] = useState(''); const [generatedAudio, setGeneratedAudio] = useState(null); const [selectedProvider, setSelectedProvider] = useState<'openai' | 'elevenlabs'>('openai'); - const [selectedVoice, setSelectedVoice] = useState('nova'); + const [selectedVoice, setSelectedVoice] = useState('marin'); // Voice settings const [stability, setStability] = useState(0.5); diff --git a/components/translator/tts-preview.tsx b/components/translator/tts-preview.tsx index ca06c2d0d..33f2b8afe 100644 --- a/components/translator/tts-preview.tsx +++ b/components/translator/tts-preview.tsx @@ -24,6 +24,7 @@ import { import { toast } from 'sonner'; import { useTranslation } from '@/lib/i18n'; import { clientLogger } from '@/lib/client-logger'; +import { synthesizeOpenAISpeech } from '@/lib/voice/openai-realtime-tts'; // Voci disponibili per la Web Speech API const BROWSER_VOICES = [ @@ -80,7 +81,7 @@ export function TTSPreview({ const [volume, setVolume] = useState(1); const [availableVoices, setAvailableVoices] = useState([]); const [useOpenAI, setUseOpenAI] = useState(false); - const [openAIVoice, setOpenAIVoice] = useState('nova'); + const [openAIVoice, setOpenAIVoice] = useState('coral'); const utteranceRef = useRef(null); const audioRef = useRef(null); @@ -182,7 +183,7 @@ export function TTSPreview({ setIsLoading(true); try { - // Chiamata diretta OpenAI TTS (no API routes Next.js) + // Chiamata diretta OpenAI (Realtime API, no API routes Next.js) let openaiKey = ''; try { const settings = JSON.parse(localStorage.getItem('gameStringerSettings') || '{}'); @@ -190,27 +191,7 @@ export function TTSPreview({ } catch {} if (!openaiKey) throw new Error('OpenAI API key non configurata'); - const response = await fetch('https://api.openai.com/v1/audio/speech', { - method: 'POST', - headers: { - 'Authorization': `Bearer ${openaiKey}`, - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - model: 'tts-1', - input: text, - voice: openAIVoice, - speed: rate, - response_format: 'mp3', - }), - }); - - if (!response.ok) { - const err = await response.json().catch(() => ({})); - throw new Error(err?.error?.message || 'Errore API TTS'); - } - - const audioBlob = await response.blob(); + const audioBlob = await synthesizeOpenAISpeech({ apiKey: openaiKey, text, voice: openAIVoice, speed: rate }); const audioUrl = URL.createObjectURL(audioBlob); if (audioRef.current) { @@ -371,11 +352,11 @@ export function TTSPreview({ - {t('ttsPreviewComp.novaFemminile')} + {t('ttsPreviewComp.coralFemminile')} {t('ttsPreviewComp.alloyNeutro')} {t('ttsPreviewComp.echoMaschile')} - {t('ttsPreviewComp.fableNarratore')} - {t('ttsPreviewComp.onyxProfondo')} + {t('ttsPreviewComp.verseNarratore')} + {t('ttsPreviewComp.ashProfondo')} {t('ttsPreviewComp.shimmerSoft')} diff --git a/components/voice/voice-translator.tsx b/components/voice/voice-translator.tsx index fd00e0932..90d401732 100644 --- a/components/voice/voice-translator.tsx +++ b/components/voice/voice-translator.tsx @@ -27,6 +27,7 @@ import { Label } from '@/components/ui/label'; import { useTranslation } from '@/lib/i18n'; import { translateWithFallback, getApiKeys } from '@/lib/ai/ai-translate-direct'; import { clientLogger } from '@/lib/client-logger'; +import { synthesizeOpenAISpeech, OPENAI_TTS_MAX_SPEED } from '@/lib/voice/openai-realtime-tts'; interface TranscriptionSegment { start: number; @@ -84,11 +85,13 @@ const LANGUAGES = [ ]; const TTS_VOICES = [ - { id: 'nova', name: 'Nova', description: 'Female, natural' }, + { id: 'marin', name: 'Marin', description: 'Female, natural' }, + { id: 'cedar', name: 'Cedar', description: 'Male, natural' }, + { id: 'coral', name: 'Coral', description: 'Female, warm' }, { id: 'alloy', name: 'Alloy', description: 'Neutral, versatile' }, { id: 'echo', name: 'Echo', description: 'Male, deep' }, - { id: 'fable', name: 'Fable', description: 'Narrative, expressive' }, - { id: 'onyx', name: 'Onyx', description: 'Male, authoritative' }, + { id: 'verse', name: 'Verse', description: 'Expressive' }, + { id: 'ash', name: 'Ash', description: 'Male, clear' }, { id: 'shimmer', name: 'Shimmer', description: 'Female, bright' }, { id: 'clone', name: '🎤 Voice Clone (Locale/XTTS)', description: 'Clona la voce originale (Richiede XTTS/AllTalk locale)' } ]; @@ -109,7 +112,7 @@ export function VoiceTranslator() { targetLanguage: 'it', isSynthesizing: false, synthesizedAudioUrl: null, - selectedVoice: 'nova', + selectedVoice: 'marin', speechSpeed: 1.0, durationMatchEnabled: false, originalDuration: 0, @@ -347,21 +350,11 @@ export function VoiceTranslator() { try { const { openai: openaiKey } = getApiKeys(); - - let ttsUrl = 'https://api.openai.com/v1/audio/speech'; + // Calculate speed: if duration matching is enabled, auto-calculate let effectiveSpeed = state.speechSpeed; - - let requestBody: Record = { - model: 'tts-1', - input: text, - voice: state.selectedVoice, - speed: effectiveSpeed, - response_format: 'mp3', - }; - const headers: Record = { - 'Content-Type': 'application/json', - }; + let maxSpeed = OPENAI_TTS_MAX_SPEED; + let synthesize: (speed: number) => Promise; // Se l'utente sceglie "clone", proviamo a usare un endpoint locale (es. AllTalk/XTTS) if (state.selectedVoice === 'clone') { @@ -378,9 +371,12 @@ export function VoiceTranslator() { // Configurazione per server locale XTTS/AllTalk (API compatibile o custom) const settings = JSON.parse(localStorage.getItem('gameStringerSettings') || '{}'); - ttsUrl = settings?.voice?.localTtsUrl || 'http://127.0.0.1:8000/v1/audio/speech'; - - requestBody = { + const ttsUrl = settings?.voice?.localTtsUrl || 'http://127.0.0.1:8000/v1/audio/speech'; + const headers: Record = { + 'Content-Type': 'application/json', + }; + + const requestBody = { model: 'xtts', input: text, voice: 'clone', @@ -398,25 +394,29 @@ export function VoiceTranslator() { } else { headers['Authorization'] = `Bearer ${openaiKey || 'local'}`; } + + maxSpeed = 2.0; + synthesize = async (speed) => { + const response = await fetch(ttsUrl, { + method: 'POST', + headers, + body: JSON.stringify({ ...requestBody, speed }) + }); + if (!response.ok) { + const err = await response.json().catch(() => ({})); + throw new Error(err?.error?.message || `TTS errore ${response.status}`); + } + return response.blob(); + }; } else { if (!openaiKey) { throw new Error('OpenAI API key non configurata. Vai nelle Impostazioni.'); } - headers['Authorization'] = `Bearer ${openaiKey}`; - } - - const response = await fetch(ttsUrl, { - method: 'POST', - headers, - body: JSON.stringify(requestBody) - }); - - if (!response.ok) { - const err = await response.json().catch(() => ({})); - throw new Error(err?.error?.message || `TTS errore ${response.status}`); + synthesize = (speed) => synthesizeOpenAISpeech({ apiKey: openaiKey, text, voice: state.selectedVoice, speed }); } - let audioBlob = await response.blob(); + effectiveSpeed = Math.min(maxSpeed, effectiveSpeed); + let audioBlob = await synthesize(effectiveSpeed); let synthDuration = await measureDuration(audioBlob); // Duration matching: if enabled and we have original duration, re-synthesize with adjusted speed @@ -426,24 +426,18 @@ export function VoiceTranslator() { if (diff > tolerance) { const speedRatio = synthDuration / state.originalDuration; - effectiveSpeed = Math.max(0.5, Math.min(2.0, state.speechSpeed * speedRatio)); + effectiveSpeed = Math.max(0.5, Math.min(maxSpeed, state.speechSpeed * speedRatio)); clientLogger.debug(`[DurationMatch] Original: ${state.originalDuration.toFixed(2)}s, Synthesized: ${synthDuration.toFixed(2)}s → Speed: ${effectiveSpeed.toFixed(2)}x`); // Re-synthesize with adjusted speed - requestBody.speed = effectiveSpeed; - const response2 = await fetch(ttsUrl, { - method: 'POST', - headers, - body: JSON.stringify(requestBody) - }); - if (response2.ok) { - audioBlob = await response2.blob(); + try { + audioBlob = await synthesize(effectiveSpeed); synthDuration = await measureDuration(audioBlob); - } else { + } catch (resynthError) { // Si tiene il primo audio: il badge non deve mostrare una velocità mai applicata. effectiveSpeed = state.speechSpeed; - clientLogger.warn(`[DurationMatch] Re-synthesis failed: ${response2.status}`); + clientLogger.warn(`[DurationMatch] Re-synthesis failed: ${resynthError instanceof Error ? resynthError.message : resynthError}`); } } } diff --git a/lib/i18n/locales/de.json b/lib/i18n/locales/de.json index b9ad64f43..98f3b5c8c 100644 --- a/lib/i18n/locales/de.json +++ b/lib/i18n/locales/de.json @@ -2240,11 +2240,11 @@ "texttospeechPreview": "Text-to-Speech-Vorschau", "impostazioniVoce": "Stimmeneinstellungen", "voceOpenai": "OpenAI-Stimme", - "novaFemminile": "Nova (weiblich)", + "coralFemminile": "Coral (weiblich)", "alloyNeutro": "Alloy (neutral)", "echoMaschile": "Echo (männlich)", - "fableNarratore": "Fable (Erzähler)", - "onyxProfondo": "Onyx (tief)", + "verseNarratore": "Verse (Erzähler)", + "ashProfondo": "Ash (tief)", "shimmerSoft": "Shimmer (sanft)", "lingua": "Sprache", "nessunTestoDaRiprodurre": "Kein Text zum Abspielen..." diff --git a/lib/i18n/locales/el.json b/lib/i18n/locales/el.json index af02533da..c949229d0 100644 --- a/lib/i18n/locales/el.json +++ b/lib/i18n/locales/el.json @@ -2373,11 +2373,11 @@ "texttospeechPreview": "Προεπισκόπηση Text-to-Speech", "impostazioniVoce": "Ρυθμίσεις φωνής", "voceOpenai": "Φωνή OpenAI", - "novaFemminile": "Nova (γυναικεία)", + "coralFemminile": "Coral (γυναικεία)", "alloyNeutro": "Alloy (ουδέτερη)", "echoMaschile": "Echo (ανδρική)", - "fableNarratore": "Fable (αφηγητής)", - "onyxProfondo": "Onyx (βαθιά)", + "verseNarratore": "Verse (αφηγητής)", + "ashProfondo": "Ash (βαθιά)", "shimmerSoft": "Shimmer (απαλή)", "lingua": "Γλώσσα", "nessunTestoDaRiprodurre": "Δεν υπάρχει κείμενο για αναπαραγωγή..." diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index 7fdffaf27..d74c63bc8 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -2328,11 +2328,11 @@ "texttospeechPreview": "Text-to-Speech Preview", "impostazioniVoce": "Voice Settings", "voceOpenai": "OpenAI Voice", - "novaFemminile": "Nova (female)", + "coralFemminile": "Coral (female)", "alloyNeutro": "Alloy (neutral)", "echoMaschile": "Echo (male)", - "fableNarratore": "Fable (narrator)", - "onyxProfondo": "Onyx (deep)", + "verseNarratore": "Verse (narrator)", + "ashProfondo": "Ash (deep)", "shimmerSoft": "Shimmer (soft)", "lingua": "Language", "nessunTestoDaRiprodurre": "No text to play..." diff --git a/lib/i18n/locales/es.json b/lib/i18n/locales/es.json index f32d3c03b..a483f9579 100644 --- a/lib/i18n/locales/es.json +++ b/lib/i18n/locales/es.json @@ -2240,11 +2240,11 @@ "texttospeechPreview": "Vista previa de texto a voz", "impostazioniVoce": "Ajustes de voz", "voceOpenai": "Voz OpenAI", - "novaFemminile": "Nova (femenina)", + "coralFemminile": "Coral (femenina)", "alloyNeutro": "Alloy (neutra)", "echoMaschile": "Echo (masculina)", - "fableNarratore": "Fable (narrador)", - "onyxProfondo": "Onyx (profunda)", + "verseNarratore": "Verse (narrador)", + "ashProfondo": "Ash (profunda)", "shimmerSoft": "Shimmer (suave)", "lingua": "Idioma", "nessunTestoDaRiprodurre": "No hay texto para reproducir..." diff --git a/lib/i18n/locales/fr.json b/lib/i18n/locales/fr.json index 2b66ea6a9..f5472e870 100644 --- a/lib/i18n/locales/fr.json +++ b/lib/i18n/locales/fr.json @@ -2240,11 +2240,11 @@ "texttospeechPreview": "Aperçu de synthèse vocale", "impostazioniVoce": "Paramètres de la voix", "voceOpenai": "Voix OpenAI", - "novaFemminile": "Nova (féminine)", + "coralFemminile": "Coral (féminine)", "alloyNeutro": "Alloy (neutre)", "echoMaschile": "Echo (masculine)", - "fableNarratore": "Fable (narrateur)", - "onyxProfondo": "Onyx (profonde)", + "verseNarratore": "Verse (narrateur)", + "ashProfondo": "Ash (profonde)", "shimmerSoft": "Shimmer (douce)", "lingua": "Langue", "nessunTestoDaRiprodurre": "Aucun texte à lire..." diff --git a/lib/i18n/locales/it.json b/lib/i18n/locales/it.json index af199dba7..324a156ef 100644 --- a/lib/i18n/locales/it.json +++ b/lib/i18n/locales/it.json @@ -2328,11 +2328,11 @@ "texttospeechPreview": "Anteprima text-to-speech", "impostazioniVoce": "Impostazioni Voce", "voceOpenai": "Voce OpenAI", - "novaFemminile": "Nova (femminile)", + "coralFemminile": "Coral (femminile)", "alloyNeutro": "Alloy (neutro)", "echoMaschile": "Echo (maschile)", - "fableNarratore": "Fable (narratore)", - "onyxProfondo": "Onyx (profondo)", + "verseNarratore": "Verse (narratore)", + "ashProfondo": "Ash (profondo)", "shimmerSoft": "Shimmer (morbida)", "lingua": "Lingua", "nessunTestoDaRiprodurre": "Nessun testo da riprodurre..." diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index c77231b23..e048407f4 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -2240,11 +2240,11 @@ "texttospeechPreview": "Text-to-Speechプレビュー", "impostazioniVoce": "音声設定", "voceOpenai": "OpenAIの音声", - "novaFemminile": "Nova(女性)", + "coralFemminile": "Coral(女性)", "alloyNeutro": "Alloy(中性)", "echoMaschile": "Echo(男性)", - "fableNarratore": "Fable(ナレーター)", - "onyxProfondo": "Onyx(低音)", + "verseNarratore": "Verse(ナレーター)", + "ashProfondo": "Ash(低音)", "shimmerSoft": "Shimmer(ソフト)", "lingua": "言語", "nessunTestoDaRiprodurre": "再生するテキストがありません..." diff --git a/lib/i18n/locales/ko.json b/lib/i18n/locales/ko.json index 44e2c49f1..bc7fe8f3d 100644 --- a/lib/i18n/locales/ko.json +++ b/lib/i18n/locales/ko.json @@ -2240,11 +2240,11 @@ "texttospeechPreview": "Text-to-Speech 미리듣기", "impostazioniVoce": "음성 설정", "voceOpenai": "OpenAI 음성", - "novaFemminile": "Nova (여성)", + "coralFemminile": "Coral (여성)", "alloyNeutro": "Alloy (중성)", "echoMaschile": "Echo (남성)", - "fableNarratore": "Fable (나레이터)", - "onyxProfondo": "Onyx (저음)", + "verseNarratore": "Verse (나레이터)", + "ashProfondo": "Ash (저음)", "shimmerSoft": "Shimmer (부드러움)", "lingua": "언어", "nessunTestoDaRiprodurre": "재생할 텍스트가 없습니다..." diff --git a/lib/i18n/locales/pl.json b/lib/i18n/locales/pl.json index cadd63647..cb3609ac2 100644 --- a/lib/i18n/locales/pl.json +++ b/lib/i18n/locales/pl.json @@ -2240,11 +2240,11 @@ "texttospeechPreview": "Podgląd Text-to-Speech", "impostazioniVoce": "Ustawienia głosu", "voceOpenai": "Głos OpenAI", - "novaFemminile": "Nova (żeński)", + "coralFemminile": "Coral (żeński)", "alloyNeutro": "Alloy (neutralny)", "echoMaschile": "Echo (męski)", - "fableNarratore": "Fable (narrator)", - "onyxProfondo": "Onyx (głęboki)", + "verseNarratore": "Verse (narrator)", + "ashProfondo": "Ash (głęboki)", "shimmerSoft": "Shimmer (miękki)", "lingua": "Język", "nessunTestoDaRiprodurre": "Brak tekstu do odtworzenia..." diff --git a/lib/i18n/locales/pt.json b/lib/i18n/locales/pt.json index 922fc1e02..365bff37e 100644 --- a/lib/i18n/locales/pt.json +++ b/lib/i18n/locales/pt.json @@ -2240,11 +2240,11 @@ "texttospeechPreview": "Pré-visualização Text-to-Speech", "impostazioniVoce": "Definições de Voz", "voceOpenai": "Voz OpenAI", - "novaFemminile": "Nova (feminina)", + "coralFemminile": "Coral (feminina)", "alloyNeutro": "Alloy (neutra)", "echoMaschile": "Echo (masculina)", - "fableNarratore": "Fable (narrador)", - "onyxProfondo": "Onyx (profunda)", + "verseNarratore": "Verse (narrador)", + "ashProfondo": "Ash (profunda)", "shimmerSoft": "Shimmer (suave)", "lingua": "Idioma", "nessunTestoDaRiprodurre": "Nenhum texto para reproduzir..." diff --git a/lib/i18n/locales/ru.json b/lib/i18n/locales/ru.json index 2a2d38f72..3d75943ca 100644 --- a/lib/i18n/locales/ru.json +++ b/lib/i18n/locales/ru.json @@ -2240,11 +2240,11 @@ "texttospeechPreview": "Предпросмотр Text-to-Speech", "impostazioniVoce": "Настройки голоса", "voceOpenai": "Голос OpenAI", - "novaFemminile": "Nova (женский)", + "coralFemminile": "Coral (женский)", "alloyNeutro": "Alloy (нейтральный)", "echoMaschile": "Echo (мужской)", - "fableNarratore": "Fable (рассказчик)", - "onyxProfondo": "Onyx (глубокий)", + "verseNarratore": "Verse (рассказчик)", + "ashProfondo": "Ash (глубокий)", "shimmerSoft": "Shimmer (мягкий)", "lingua": "Язык", "nessunTestoDaRiprodurre": "Нет текста для воспроизведения..." diff --git a/lib/i18n/locales/zh.json b/lib/i18n/locales/zh.json index 8e8938cba..1ff72e720 100644 --- a/lib/i18n/locales/zh.json +++ b/lib/i18n/locales/zh.json @@ -2240,11 +2240,11 @@ "texttospeechPreview": "Text-to-Speech 预览", "impostazioniVoce": "语音设置", "voceOpenai": "OpenAI 语音", - "novaFemminile": "Nova(女声)", + "coralFemminile": "Coral(女声)", "alloyNeutro": "Alloy(中性)", "echoMaschile": "Echo(男声)", - "fableNarratore": "Fable(旁白)", - "onyxProfondo": "Onyx(低沉)", + "verseNarratore": "Verse(旁白)", + "ashProfondo": "Ash(低沉)", "shimmerSoft": "Shimmer(柔和)", "lingua": "语言", "nessunTestoDaRiprodurre": "没有可播放的文本…" diff --git a/lib/voice/openai-realtime-tts.ts b/lib/voice/openai-realtime-tts.ts new file mode 100644 index 000000000..b0a2108dc --- /dev/null +++ b/lib/voice/openai-realtime-tts.ts @@ -0,0 +1,185 @@ +/** + * Sintesi vocale OpenAI tramite Realtime API. + * + * OpenAI spegne tts-1, tts-1-hd e gpt-4o-mini-tts il 6 gennaio 2027. Il + * sostituto indicato, gpt-realtime-2.1-mini, non funziona su /v1/audio/speech: + * va usato via Realtime. Flusso (guide OpenAI "Text to speech" e "Realtime + * WebSocket", 2026-11): + * 1. POST /v1/realtime/client_secrets con la chiave dell'utente → chiave + * effimera (`value`), con la sessione già configurata. + * 2. WebSocket wss://api.openai.com/v1/realtime con la chiave effimera nel + * sottoprotocollo `openai-insecure-api-key.`. + * 3. Dopo `session.created`: conversation.item.create (il testo) e + * response.create. L'audio arriva a pezzi in `response.output_audio.delta` + * (PCM16 mono 24 kHz in base64), la fine in `response.done`. + * Il PCM viene avvolto in un WAV, così chi chiama riceve un Blob riproducibile + * come prima. + */ + +export const OPENAI_TTS_MODEL = 'gpt-realtime-2.1-mini'; +/** Limiti di `audio.output.speed` nella Realtime API (prima, su tts-1: 0.25–4). */ +export const OPENAI_TTS_MIN_SPEED = 0.25; +export const OPENAI_TTS_MAX_SPEED = 1.5; + +const CLIENT_SECRETS_URL = 'https://api.openai.com/v1/realtime/client_secrets'; +const REALTIME_URL = `wss://api.openai.com/v1/realtime?model=${OPENAI_TTS_MODEL}`; +const SAMPLE_RATE = 24000; + +/** + * fable, nova e onyx esistevano solo per tts-1/tts-1-hd. Profili e + * impostazioni salvati possono ancora contenerli: li si porta sulla voce + * Realtime più vicina invece di far fallire la sintesi. + */ +const LEGACY_VOICES: Record = { nova: 'coral', fable: 'verse', onyx: 'ash' }; + +export function toRealtimeVoice(voice: string): string { + return LEGACY_VOICES[voice] ?? voice; +} + +// Il modello è conversazionale: senza istruzioni risponderebbe al testo invece di leggerlo. +const READ_ALOUD_INSTRUCTIONS = + "You are a text-to-speech engine. Read the user's message aloud exactly as written, word for word, " + + 'in the language it is written in. Do not answer it, translate it, comment on it, or add anything before or after it.'; + +/** I soli campi degli eventi server che servono qui. */ +interface RealtimeServerEvent { + type?: string; + delta?: string; + response?: { status?: string; status_details?: { error?: { message?: string } } }; + error?: { message?: string }; +} + +export interface OpenAISpeechRequest { + apiKey: string; + text: string; + voice: string; + speed?: number; + timeoutMs?: number; +} + +export async function synthesizeOpenAISpeech({ + apiKey, + text, + voice, + speed = 1, + timeoutMs = 60_000, +}: OpenAISpeechRequest): Promise { + const secretResponse = await fetch(CLIENT_SECRETS_URL, { + method: 'POST', + headers: { + Authorization: `Bearer ${apiKey}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + session: { + type: 'realtime', + model: OPENAI_TTS_MODEL, + instructions: READ_ALOUD_INSTRUCTIONS, + output_modalities: ['audio'], + audio: { + input: { turn_detection: null }, + output: { + voice: toRealtimeVoice(voice), + speed: Math.min(OPENAI_TTS_MAX_SPEED, Math.max(OPENAI_TTS_MIN_SPEED, speed)), + format: { type: 'audio/pcm', rate: SAMPLE_RATE }, + }, + }, + }, + }), + }); + + if (!secretResponse.ok) { + const err = await secretResponse.json().catch(() => ({})); + throw new Error(err?.error?.message || `Errore sintesi vocale OpenAI (${secretResponse.status})`); + } + const { value: ephemeralKey } = await secretResponse.json(); + if (!ephemeralKey) { + throw new Error('Errore sintesi vocale OpenAI: chiave di sessione mancante'); + } + + return new Promise((resolve, reject) => { + const ws = new WebSocket(REALTIME_URL, ['realtime', `openai-insecure-api-key.${ephemeralKey}`]); + const chunks: Uint8Array[] = []; + let settled = false; + + const finish = (error: Error | null, blob?: Blob) => { + if (settled) return; + settled = true; + clearTimeout(timer); + ws.close(); + if (error) reject(error); + else resolve(blob!); + }; + + const timer = setTimeout(() => finish(new Error('Sintesi vocale OpenAI: tempo scaduto')), timeoutMs); + + ws.onmessage = (event: MessageEvent) => { + let message: RealtimeServerEvent; + try { + message = JSON.parse(String(event.data)); + } catch { + return; + } + + switch (message.type) { + case 'session.created': + ws.send(JSON.stringify({ + type: 'conversation.item.create', + item: { type: 'message', role: 'user', content: [{ type: 'input_text', text }] }, + })); + ws.send(JSON.stringify({ type: 'response.create', response: { output_modalities: ['audio'] } })); + break; + case 'response.output_audio.delta': + if (message.delta) chunks.push(base64ToBytes(message.delta)); + break; + case 'response.done': { + const status = message.response?.status; + if (status !== 'completed') { + const reason = message.response?.status_details?.error?.message || status; + finish(new Error(`Sintesi vocale OpenAI non completata: ${reason}`)); + } else if (chunks.length === 0) { + finish(new Error('Sintesi vocale OpenAI: nessun audio ricevuto')); + } else { + finish(null, pcm16ToWav(chunks, SAMPLE_RATE)); + } + break; + } + case 'error': + finish(new Error(message.error?.message || 'Errore sintesi vocale OpenAI')); + break; + } + }; + ws.onerror = () => finish(new Error('Sintesi vocale OpenAI: connessione non riuscita')); + ws.onclose = () => finish(new Error('Sintesi vocale OpenAI: connessione chiusa prima della fine')); + }); +} + +function base64ToBytes(base64: string): Uint8Array { + const binary = atob(base64); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return bytes; +} + +/** PCM16 mono little-endian → WAV (intestazione RIFF di 44 byte). */ +function pcm16ToWav(chunks: Uint8Array[], sampleRate: number): Blob { + const dataLength = chunks.reduce((sum, c) => sum + c.length, 0); + const header = new DataView(new ArrayBuffer(44)); + const writeTag = (offset: number, tag: string) => { + for (let i = 0; i < 4; i++) header.setUint8(offset + i, tag.charCodeAt(i)); + }; + writeTag(0, 'RIFF'); + header.setUint32(4, 36 + dataLength, true); + writeTag(8, 'WAVE'); + writeTag(12, 'fmt '); + header.setUint32(16, 16, true); // dimensione blocco fmt + header.setUint16(20, 1, true); // PCM + header.setUint16(22, 1, true); // mono + header.setUint32(24, sampleRate, true); + header.setUint32(28, sampleRate * 2, true); // byte al secondo + header.setUint16(32, 2, true); // byte per campione + header.setUint16(34, 16, true); // bit per campione + writeTag(36, 'data'); + header.setUint32(40, dataLength, true); + return new Blob([header.buffer, ...chunks], { type: 'audio/wav' }); +} diff --git a/lib/voice/voice-clone.ts b/lib/voice/voice-clone.ts index af5c1d6ac..84208391d 100644 --- a/lib/voice/voice-clone.ts +++ b/lib/voice/voice-clone.ts @@ -6,6 +6,7 @@ import { clientLogger } from '@/lib/client-logger'; import { getApiKeys } from '@/lib/ai/ai-translate-direct'; import { persistSettingsToDisk } from '@/lib/settings-persistence'; +import { synthesizeOpenAISpeech } from '@/lib/voice/openai-realtime-tts'; /** * Le chiavi voce vivono nello store centrale delle Impostazioni @@ -110,9 +111,11 @@ export const VOICE_PRESETS: Record> = { export const OPENAI_VOICES = [ { id: 'alloy', name: 'Alloy', gender: 'neutral', style: 'balanced' }, { id: 'echo', name: 'Echo', gender: 'male', style: 'warm' }, - { id: 'fable', name: 'Fable', gender: 'neutral', style: 'expressive' }, - { id: 'onyx', name: 'Onyx', gender: 'male', style: 'deep' }, - { id: 'nova', name: 'Nova', gender: 'female', style: 'friendly' }, + { id: 'verse', name: 'Verse', gender: 'male', style: 'expressive' }, + { id: 'ash', name: 'Ash', gender: 'male', style: 'clear' }, + { id: 'coral', name: 'Coral', gender: 'female', style: 'warm' }, + { id: 'marin', name: 'Marin', gender: 'female', style: 'natural' }, + { id: 'cedar', name: 'Cedar', gender: 'male', style: 'natural' }, { id: 'shimmer', name: 'Shimmer', gender: 'female', style: 'clear' }, ]; @@ -360,27 +363,13 @@ class VoiceCloneService { throw new Error('API key OpenAI non configurata'); } - const response = await fetch('https://api.openai.com/v1/audio/speech', { - method: 'POST', - headers: { - 'Authorization': `Bearer ${apiKey}`, - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - model: 'tts-1-hd', - input: request.text, - voice: request.voiceProfile.voiceId, - response_format: request.outputFormat || 'mp3', - speed: request.voiceProfile.settings.speed || 1.0, - }), + // Realtime restituisce solo PCM, consegnato come WAV: outputFormat qui non si applica. + const audioBlob = await synthesizeOpenAISpeech({ + apiKey, + text: request.text, + voice: request.voiceProfile.voiceId, + speed: request.voiceProfile.settings.speed || 1.0, }); - - if (!response.ok) { - const error = await response.json(); - throw new Error(error.error?.message || 'Errore sintesi vocale OpenAI'); - } - - const audioBlob = await response.blob(); const audioUrl = URL.createObjectURL(audioBlob); return { diff --git a/middleware.ts b/middleware.ts index f078e7244..3f4d7365a 100644 --- a/middleware.ts +++ b/middleware.ts @@ -80,7 +80,7 @@ const CSP_POLICY = IS_DEV "script-src 'self' 'unsafe-inline' 'unsafe-eval'", "style-src 'self' 'unsafe-inline'", "img-src 'self' data: blob: https://*.akamaihd.net https://*.steamstatic.com https://*.steamgriddb.com https://media.steampowered.com https://store.steampowered.com https://avatars.githubusercontent.com", - "connect-src 'self' http://ipc.localhost https://*.supabase.co https://*.openai.com https://*.anthropic.com https://generativelanguage.googleapis.com https://*.deepseek.com https://*.mistral.ai https://openrouter.ai https://api.github.com https://*.nexusmods.com https://*.steampowered.com https://*.rawg.io https://*.igdb.com https://howlongtobeat.com https://*.steamgriddb.com https://*.gamestranslator.it https://api.allorigins.win https://corsproxy.io http://127.0.0.1:* http://localhost:* ws://127.0.0.1:* ws://localhost:*", + "connect-src 'self' http://ipc.localhost https://*.supabase.co https://*.openai.com wss://api.openai.com https://*.anthropic.com https://generativelanguage.googleapis.com https://*.deepseek.com https://*.mistral.ai https://openrouter.ai https://api.github.com https://*.nexusmods.com https://*.steampowered.com https://*.rawg.io https://*.igdb.com https://howlongtobeat.com https://*.steamgriddb.com https://*.gamestranslator.it https://api.allorigins.win https://corsproxy.io http://127.0.0.1:* http://localhost:* ws://127.0.0.1:* ws://localhost:*", "font-src 'self' data:", "media-src 'self' blob:", ].join('; '); diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index f73162b8a..0b69b30ef 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -43,7 +43,7 @@ } ], "security": { - "csp": "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https: https://steamcdn-a.akamaihd.net https://cdn.akamai.steamstatic.com https://shared.akamai.steamstatic.com https://cdn.steamgriddb.com https://cdn2.steamgriddb.com https://media.steampowered.com https://cdn.cloudflare.steamstatic.com https://store.steampowered.com https://avatars.githubusercontent.com; connect-src 'self' https://gamestringer.ai https://api.openai.com https://api.anthropic.com https://generativelanguage.googleapis.com https://api.deepseek.com https://api.mistral.ai https://openrouter.ai https://api.deepl.com https://api-free.deepl.com https://api.groq.com https://api.cerebras.ai https://api.cohere.com https://api.together.xyz https://api.fireworks.ai https://api-inference.huggingface.co https://api.cognitive.microsofttranslator.com https://api.mymemory.translated.net https://dashscope.aliyuncs.com https://api.elevenlabs.io https://libretranslate.de https://lingva.ml https://api.github.com https://api.nexusmods.com https://api.steampowered.com https://api.rawg.io https://api.igdb.com https://howlongtobeat.com https://www.steamgriddb.com https://*.supabase.co wss://*.supabase.co http://127.0.0.1:* http://localhost:*; font-src 'self' data:; media-src 'self' blob:", + "csp": "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https: https://steamcdn-a.akamaihd.net https://cdn.akamai.steamstatic.com https://shared.akamai.steamstatic.com https://cdn.steamgriddb.com https://cdn2.steamgriddb.com https://media.steampowered.com https://cdn.cloudflare.steamstatic.com https://store.steampowered.com https://avatars.githubusercontent.com; connect-src 'self' https://gamestringer.ai https://api.openai.com wss://api.openai.com https://api.anthropic.com https://generativelanguage.googleapis.com https://api.deepseek.com https://api.mistral.ai https://openrouter.ai https://api.deepl.com https://api-free.deepl.com https://api.groq.com https://api.cerebras.ai https://api.cohere.com https://api.together.xyz https://api.fireworks.ai https://api-inference.huggingface.co https://api.cognitive.microsofttranslator.com https://api.mymemory.translated.net https://dashscope.aliyuncs.com https://api.elevenlabs.io https://libretranslate.de https://lingva.ml https://api.github.com https://api.nexusmods.com https://api.steampowered.com https://api.rawg.io https://api.igdb.com https://howlongtobeat.com https://www.steamgriddb.com https://*.supabase.co wss://*.supabase.co http://127.0.0.1:* http://localhost:*; font-src 'self' data:; media-src 'self' blob:", "capabilities": [ "default", "app-events"