Add TTS model and voice discovery with caching

This commit is contained in:
OpenCode committed 2025-12-15 17:43:05 +00:00
1 parent 722c62f61e
commit 406ff8fd4a
5 files changed
+421 -31

No files matched your search

+205
View File
@@ -9,7 +9,9 @@ import { logger } from '../utils/logger'
import { getWorkspacePath } from '@opencode-manager/shared'
const TTS_CACHE_DIR = join(getWorkspacePath(), 'cache', 'tts')
const DISCOVERY_CACHE_DIR = join(getWorkspacePath(), 'cache', 'discovery')
const CACHE_TTL_MS = 24 * 60 * 60 * 1000
const DISCOVERY_CACHE_TTL_MS = 60 * 60 * 1000 // 1 hour for discovery cache
const TTSRequestSchema = z.object({
text: z.string().min(1).max(4096),
@@ -25,6 +27,10 @@ async function ensureCacheDir(): Promise<void> {
await mkdir(TTS_CACHE_DIR, { recursive: true })
}
async function ensureDiscoveryCacheDir(): Promise<void> {
await mkdir(DISCOVERY_CACHE_DIR, { recursive: true })
}
async function getCachedAudio(cacheKey: string): Promise<Buffer | null> {
try {
const filePath = join(TTS_CACHE_DIR, `${cacheKey}.mp3`)
@@ -46,6 +52,127 @@ async function cacheAudio(cacheKey: string, audioData: Buffer): Promise<void> {
await writeFile(filePath, audioData)
}
async function getCachedDiscovery(cacheKey: string): Promise<string[] | null> {
try {
const filePath = join(DISCOVERY_CACHE_DIR, `${cacheKey}.json`)
const fileStat = await stat(filePath)
if (Date.now() - fileStat.mtimeMs > DISCOVERY_CACHE_TTL_MS) {
await unlink(filePath)
return null
}
const content = await readFile(filePath, 'utf-8')
return JSON.parse(content)
} catch {
return null
}
}
async function cacheDiscovery(cacheKey: string, data: string[]): Promise<void> {
try {
const filePath = join(DISCOVERY_CACHE_DIR, `${cacheKey}.json`)
await writeFile(filePath, JSON.stringify(data))
} catch (error) {
logger.error(`Failed to cache discovery data for ${cacheKey}:`, error)
}
}
function generateDiscoveryCacheKey(endpoint: string, apiKey: string, type: 'models' | 'voices'): string {
const hash = createHash('sha256')
hash.update(`${endpoint}|${apiKey.substring(0, 8)}|${type}`)
return hash.digest('hex')
}
async function fetchAvailableModels(endpoint: string, apiKey: string): Promise<string[]> {
// Try different endpoint formats for models
const endpointVariations = [
`${endpoint.replace(/\/audio\/speech$/, '')}/v1/models`,
`${endpoint.replace(/\/audio\/speech$/, '')}/models`,
`${endpoint.replace(/\/v1\/audio\/speech$/, '')}/v1/models`,
]
for (const modelEndpoint of endpointVariations) {
try {
const response = await fetch(modelEndpoint, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
})
if (response.ok) {
const data = await response.json() as { data?: { id?: string }[] } | unknown[]
// Handle different response formats
if ('data' in data && Array.isArray(data.data)) {
// OpenAI format: { data: [{ id: "gpt-4" }, ...] }
return data.data
.filter((model) => model.id && typeof model.id === 'string')
.filter((model) =>
model.id!.toLowerCase().includes('tts') ||
model.id!.toLowerCase().includes('audio') ||
model.id!.toLowerCase().includes('speech')
)
.map((model) => model.id!)
} else if (Array.isArray(data)) {
return data.filter((item): item is string => typeof item === 'string')
}
}
} catch (error) {
logger.debug(`Failed to fetch models from ${modelEndpoint}:`, error)
continue
}
}
return ['tts-1', 'tts-1-hd']
}
async function fetchAvailableVoices(endpoint: string, apiKey: string): Promise<string[]> {
// Try different endpoint formats for voices
const endpointVariations = [
`${endpoint.replace(/\/audio\/speech$/, '')}/v1/audio/voices`,
`${endpoint.replace(/\/audio\/speech$/, '')}/voices`,
`${endpoint.replace(/\/v1\/audio\/speech$/, '')}/v1/audio/voices`,
`${endpoint.replace(/\/v1\/audio\/speech$/, '')}/audio/voices`,
]
for (const voiceEndpoint of endpointVariations) {
try {
const response = await fetch(voiceEndpoint, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
})
if (response.ok) {
type VoiceItem = { id?: string; name?: string; voice?: string }
const data = await response.json() as { data?: VoiceItem[] } | (string | VoiceItem)[]
// Handle different response formats
if ('data' in data && Array.isArray(data.data)) {
// OpenAI-style format: { data: [{ name: "alloy" }, ...] }
return data.data
.filter((voice) => voice.id || voice.name)
.map((voice) => (voice.id || voice.name)!)
} else if (Array.isArray(data)) {
// Simple array format: ["alloy", "echo", ...] or [{ voice: "alloy" }, ...]
return data.map((item) => {
if (typeof item === 'string') return item
return item.name || item.voice || item.id
}).filter((v): v is string => typeof v === 'string')
}
}
} catch (error) {
logger.debug(`Failed to fetch voices from ${voiceEndpoint}:`, error)
continue
}
}
return ['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer']
}
export async function cleanupExpiredCache(): Promise<number> {
try {
await ensureCacheDir()
@@ -159,6 +286,84 @@ export function createTTSRoutes(db: Database) {
}
})
app.get('/models', async (c) => {
try {
const userId = c.req.query('userId') || 'default'
const forceRefresh = c.req.query('refresh') === 'true'
const settingsService = new SettingsService(db)
const settings = settingsService.getSettings(userId)
const ttsConfig = settings.preferences.tts
if (!ttsConfig?.apiKey || !ttsConfig?.endpoint) {
return c.json({ error: 'TTS not configured' }, 400)
}
const cacheKey = generateDiscoveryCacheKey(ttsConfig.endpoint, ttsConfig.apiKey, 'models')
// Check cache first (unless force refresh)
if (!forceRefresh) {
const cachedModels = await getCachedDiscovery(cacheKey)
if (cachedModels) {
logger.info(`Models cache hit for user ${userId}`)
return c.json({ models: cachedModels, cached: true })
}
}
// Fetch from API
await ensureDiscoveryCacheDir()
logger.info(`Fetching TTS models for user ${userId}`)
const models = await fetchAvailableModels(ttsConfig.endpoint, ttsConfig.apiKey)
await cacheDiscovery(cacheKey, models)
logger.info(`Fetched ${models.length} TTS models`)
return c.json({ models, cached: false })
} catch (error) {
logger.error('Failed to fetch TTS models:', error)
return c.json({ error: 'Failed to fetch models' }, 500)
}
})
app.get('/voices', async (c) => {
try {
const userId = c.req.query('userId') || 'default'
const forceRefresh = c.req.query('refresh') === 'true'
const settingsService = new SettingsService(db)
const settings = settingsService.getSettings(userId)
const ttsConfig = settings.preferences.tts
if (!ttsConfig?.apiKey || !ttsConfig?.endpoint) {
return c.json({ error: 'TTS not configured' }, 400)
}
const cacheKey = generateDiscoveryCacheKey(ttsConfig.endpoint, ttsConfig.apiKey, 'voices')
// Check cache first (unless force refresh)
if (!forceRefresh) {
const cachedVoices = await getCachedDiscovery(cacheKey)
if (cachedVoices) {
logger.info(`Voices cache hit for user ${userId}`)
return c.json({ voices: cachedVoices, cached: true })
}
}
// Fetch from API
await ensureDiscoveryCacheDir()
logger.info(`Fetching TTS voices for user ${userId}`)
const voices = await fetchAvailableVoices(ttsConfig.endpoint, ttsConfig.apiKey)
await cacheDiscovery(cacheKey, voices)
logger.info(`Fetched ${voices.length} TTS voices`)
return c.json({ voices, cached: false })
} catch (error) {
logger.error('Failed to fetch TTS voices:', error)
return c.json({ error: 'Failed to fetch voices' }, 500)
}
})
app.get('/status', async (c) => {
const userId = c.req.query('userId') || 'default'
const settingsService = new SettingsService(db)