Spaces:
Running

axeronis commited on
Commit
50876ef
·
1 Parent(s): ba4f3b1

feat: Static voice demo files with API fallback

Browse files

VOICE SETTINGS:
- Add demoAudioUrl to VOICE_OPTIONS pointing to /voice-demos/[id].mp3
- playDemoVoice now tries static file first, API fallback second
- Removed voiceCache - static files are always available
- Add voice-demos folder with README for manual generation

SCRIPT:
- Add generate_voice_demos.py for batch generation (requires auth)

NOTE: Static MP3 files need to be generated manually - see README

frontend/app/settings/voice/page.tsx CHANGED
@@ -30,6 +30,7 @@ const VOICE_OPTIONS = [
30
  gradient: 'from-indigo-500 to-blue-600',
31
  bgGradient: 'from-indigo-500/20 to-blue-600/10',
32
  demoText: 'Здравствуйте! Я ваш менеджер. Готов помочь найти решение для бизнеса.',
 
33
  traits: ['Уверенный', 'Деловой', 'Авторитетный']
34
  },
35
  {
@@ -41,6 +42,7 @@ const VOICE_OPTIONS = [
41
  gradient: 'from-emerald-500 to-teal-600',
42
  bgGradient: 'from-emerald-500/20 to-teal-600/10',
43
  demoText: 'Привет! Рад что написали. Давайте разберёмся что вам нужно!',
 
44
  traits: ['Тёплый', 'Располагающий', 'Дружелюбный']
45
  },
46
  {
@@ -52,6 +54,7 @@ const VOICE_OPTIONS = [
52
  gradient: 'from-purple-500 to-pink-600',
53
  bgGradient: 'from-purple-500/20 to-pink-600/10',
54
  demoText: 'Добрый день! Спасибо за интерес. Расскажу подробнее.',
 
55
  traits: ['Элегантный', 'Приятный', 'Доверительный']
56
  }
57
  ]
@@ -72,8 +75,6 @@ export default function VoiceSettingsPage() {
72
  const [generatingVoice, setGeneratingVoice] = useState<string | null>(null)
73
  const [isServiceAvailable] = useState<boolean>(true)
74
  const audioRef = React.useRef<HTMLAudioElement | null>(null)
75
- // Cache for generated voice samples to avoid regeneration
76
- const [voiceCache, setVoiceCache] = useState<Record<string, string>>({})
77
 
78
  // React Query for voice settings - cached!
79
  const { data: tenantData, isLoading: loading } = useQuery({
@@ -99,7 +100,7 @@ export default function VoiceSettingsPage() {
99
  }
100
  }, [tenantData])
101
 
102
- const playDemoVoice = async (voiceId: string, text: string) => {
103
  // Stop current playback
104
  if (audioRef.current) {
105
  audioRef.current.pause()
@@ -113,24 +114,32 @@ export default function VoiceSettingsPage() {
113
 
114
  setPlayingVoice(voiceId)
115
 
116
- // Check cache first - use cached audio if available
117
- if (voiceCache[voiceId]) {
118
- audioRef.current = new Audio(voiceCache[voiceId])
119
- audioRef.current.onended = () => setPlayingVoice(null)
120
- audioRef.current.onerror = () => {
121
- setPlayingVoice(null)
122
- // Clear bad cache entry
123
- setVoiceCache(prev => {
124
- const newCache = { ...prev }
125
- delete newCache[voiceId]
126
- return newCache
127
- })
 
 
 
128
  }
129
- audioRef.current.play()
130
- return
131
  }
132
 
133
- // Generate new audio and cache it
 
 
 
 
 
 
 
134
  setGeneratingVoice(voiceId)
135
  try {
136
  const response = await api.post('/api/v1/voice/synthesize', {
@@ -144,11 +153,11 @@ export default function VoiceSettingsPage() {
144
  const audioBlob = new Blob([response.data], { type: 'audio/mpeg' })
145
  const audioUrl = URL.createObjectURL(audioBlob)
146
 
147
- // Cache the URL for future use
148
- setVoiceCache(prev => ({ ...prev, [voiceId]: audioUrl }))
149
-
150
  audioRef.current = new Audio(audioUrl)
151
- audioRef.current.onended = () => setPlayingVoice(null)
 
 
 
152
  audioRef.current.onerror = () => {
153
  setPlayingVoice(null)
154
  toast.error(t('voice.playbackError'))
@@ -156,13 +165,8 @@ export default function VoiceSettingsPage() {
156
  audioRef.current.play()
157
  } catch (error) {
158
  console.error('Failed to generate demo voice:', error)
159
- // Fallback to browser TTS
160
- const utterance = new SpeechSynthesisUtterance(text)
161
- utterance.lang = 'ru-RU'
162
- utterance.rate = 0.9
163
- utterance.onend = () => setPlayingVoice(null)
164
- utterance.onerror = () => setPlayingVoice(null)
165
- window.speechSynthesis.speak(utterance)
166
  } finally {
167
  setGeneratingVoice(null)
168
  }
@@ -346,7 +350,6 @@ export default function VoiceSettingsPage() {
346
  const isSelected = settings.voice_id === voice.id
347
  const isPlaying = playingVoice === voice.id
348
  const isGenerating = generatingVoice === voice.id
349
- const isCached = !!voiceCache[voice.id]
350
  const IconComponent = voice.icon
351
 
352
  return (
@@ -408,7 +411,7 @@ export default function VoiceSettingsPage() {
408
  <button
409
  onClick={(e) => {
410
  e.stopPropagation()
411
- playDemoVoice(voice.id, voice.demoText)
412
  }}
413
  disabled={isGenerating}
414
  className={cn(
@@ -426,7 +429,7 @@ export default function VoiceSettingsPage() {
426
  ) : isPlaying ? (
427
  <><Square className="w-4 h-4" /> {t('voice.stop')}</>
428
  ) : (
429
- <><Play className="w-4 h-4" /> {isCached ? '▶ Воспроизвести' : t('voice.listenDemo')}</>
430
  )}
431
  </button>
432
  </motion.div>
 
30
  gradient: 'from-indigo-500 to-blue-600',
31
  bgGradient: 'from-indigo-500/20 to-blue-600/10',
32
  demoText: 'Здравствуйте! Я ваш менеджер. Готов помочь найти решение для бизнеса.',
33
+ demoAudioUrl: '/voice-demos/professional_male.mp3',
34
  traits: ['Уверенный', 'Деловой', 'Авторитетный']
35
  },
36
  {
 
42
  gradient: 'from-emerald-500 to-teal-600',
43
  bgGradient: 'from-emerald-500/20 to-teal-600/10',
44
  demoText: 'Привет! Рад что написали. Давайте разберёмся что вам нужно!',
45
+ demoAudioUrl: '/voice-demos/friendly_male.mp3',
46
  traits: ['Тёплый', 'Располагающий', 'Дружелюбный']
47
  },
48
  {
 
54
  gradient: 'from-purple-500 to-pink-600',
55
  bgGradient: 'from-purple-500/20 to-pink-600/10',
56
  demoText: 'Добрый день! Спасибо за интерес. Расскажу подробнее.',
57
+ demoAudioUrl: '/voice-demos/professional_female.mp3',
58
  traits: ['Элегантный', 'Приятный', 'Доверительный']
59
  }
60
  ]
 
75
  const [generatingVoice, setGeneratingVoice] = useState<string | null>(null)
76
  const [isServiceAvailable] = useState<boolean>(true)
77
  const audioRef = React.useRef<HTMLAudioElement | null>(null)
 
 
78
 
79
  // React Query for voice settings - cached!
80
  const { data: tenantData, isLoading: loading } = useQuery({
 
100
  }
101
  }, [tenantData])
102
 
103
+ const playDemoVoice = async (voiceId: string, demoAudioUrl?: string) => {
104
  // Stop current playback
105
  if (audioRef.current) {
106
  audioRef.current.pause()
 
114
 
115
  setPlayingVoice(voiceId)
116
 
117
+ // Use static demo audio file first (pre-generated, instant playback)
118
+ if (demoAudioUrl) {
119
+ try {
120
+ audioRef.current = new Audio(demoAudioUrl)
121
+ audioRef.current.onended = () => setPlayingVoice(null)
122
+ audioRef.current.onerror = async () => {
123
+ // Static file failed, try API fallback
124
+ console.warn('Static demo audio failed, trying API...')
125
+ await playFromAPI(voiceId)
126
+ }
127
+ await audioRef.current.play()
128
+ return
129
+ } catch (error) {
130
+ console.warn('Failed to play static audio:', error)
131
+ // Fall through to API
132
  }
 
 
133
  }
134
 
135
+ // Fallback: Generate from API
136
+ await playFromAPI(voiceId)
137
+ }
138
+
139
+ const playFromAPI = async (voiceId: string) => {
140
+ const voice = VOICE_OPTIONS.find(v => v.id === voiceId)
141
+ const text = voice?.demoText || 'Здравствуйте! Это демонстрация голоса.'
142
+
143
  setGeneratingVoice(voiceId)
144
  try {
145
  const response = await api.post('/api/v1/voice/synthesize', {
 
153
  const audioBlob = new Blob([response.data], { type: 'audio/mpeg' })
154
  const audioUrl = URL.createObjectURL(audioBlob)
155
 
 
 
 
156
  audioRef.current = new Audio(audioUrl)
157
+ audioRef.current.onended = () => {
158
+ setPlayingVoice(null)
159
+ URL.revokeObjectURL(audioUrl)
160
+ }
161
  audioRef.current.onerror = () => {
162
  setPlayingVoice(null)
163
  toast.error(t('voice.playbackError'))
 
165
  audioRef.current.play()
166
  } catch (error) {
167
  console.error('Failed to generate demo voice:', error)
168
+ setPlayingVoice(null)
169
+ toast.error('Не удалось воспроизвести демо')
 
 
 
 
 
170
  } finally {
171
  setGeneratingVoice(null)
172
  }
 
350
  const isSelected = settings.voice_id === voice.id
351
  const isPlaying = playingVoice === voice.id
352
  const isGenerating = generatingVoice === voice.id
 
353
  const IconComponent = voice.icon
354
 
355
  return (
 
411
  <button
412
  onClick={(e) => {
413
  e.stopPropagation()
414
+ playDemoVoice(voice.id, voice.demoAudioUrl)
415
  }}
416
  disabled={isGenerating}
417
  className={cn(
 
429
  ) : isPlaying ? (
430
  <><Square className="w-4 h-4" /> {t('voice.stop')}</>
431
  ) : (
432
+ <><Play className="w-4 h-4" /> {t('voice.listenDemo')}</>
433
  )}
434
  </button>
435
  </motion.div>
frontend/public/voice-demos/README.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Voice Demo Files
2
+
3
+ This folder should contain pre-generated voice demo MP3 files.
4
+
5
+ ## Required Files
6
+
7
+ - `professional_male.mp3` - Text: "Здравствуйте! Я ваш менеджер. Готов помочь найти решение для бизнеса."
8
+ - `friendly_male.mp3` - Text: "Привет! Рад что написали. Давайте разберёмся что вам нужно!"
9
+ - `professional_female.mp3` - Text: "Добрый день! Спасибо за интерес. Расскажу подробнее."
10
+
11
+ ## How to Generate
12
+
13
+ ### Option 1: Use ElevenLabs directly
14
+ 1. Go to https://elevenlabs.io/
15
+ 2. Use voices: George (male), Daniel (male), Charlotte (female)
16
+ 3. Generate each text and download as MP3
17
+ 4. Place files in this folder
18
+
19
+ ### Option 2: Use Backend API (requires auth)
20
+ ```bash
21
+ cd d:\MicroFunnel Studio
22
+ # Edit scripts/generate_voice_demos.py to add auth token
23
+ python scripts/generate_voice_demos.py
24
+ ```
25
+
26
+ ### Option 3: Browser Network Tab
27
+ 1. Go to Settings → Voice
28
+ 2. Click play for each voice
29
+ 3. In DevTools Network tab, find the audio response
30
+ 4. Right-click → Save as .mp3
31
+
32
+ ## Fallback Behavior
33
+
34
+ If static files are not present, the frontend will fallback to:
35
+ 1. Backend API synthesis (requires login)
36
+ 2. Error message if that fails
37
+
38
+ Static files provide instant playback without API latency.
scripts/generate_voice_demos.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Generate voice demo MP3 files for the 3 voice options.
4
+ Run this script once to create static demo files.
5
+ """
6
+
7
+ import requests
8
+ import os
9
+
10
+ API_URL = "https://api.microfunnel.online/api/v1/voice/synthesize"
11
+ OUTPUT_DIR = r"d:\MicroFunnel Studio\frontend\public\voice-demos"
12
+
13
+ VOICES = [
14
+ {
15
+ "id": "professional_male",
16
+ "text": "Здравствуйте! Я ваш менеджер. Готов помочь найти решение для бизнеса."
17
+ },
18
+ {
19
+ "id": "friendly_male",
20
+ "text": "Привет! Рад что написали. Давайте разберёмся что вам нужно!"
21
+ },
22
+ {
23
+ "id": "professional_female",
24
+ "text": "Добрый день! Спасибо за интерес. Расскажу подробнее."
25
+ }
26
+ ]
27
+
28
+ def main():
29
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
30
+
31
+ for voice in VOICES:
32
+ print(f"Generating {voice['id']}...")
33
+
34
+ try:
35
+ response = requests.post(
36
+ API_URL,
37
+ json={
38
+ "text": voice["text"],
39
+ "voice": voice["id"]
40
+ },
41
+ timeout=60
42
+ )
43
+
44
+ if response.status_code == 200:
45
+ output_path = os.path.join(OUTPUT_DIR, f"{voice['id']}.mp3")
46
+ with open(output_path, "wb") as f:
47
+ f.write(response.content)
48
+ print(f" OK: Saved to {output_path}")
49
+ else:
50
+ print(f" ERROR: {response.status_code}")
51
+ except Exception as e:
52
+ print(f" EXCEPTION: {e}")
53
+
54
+ if __name__ == "__main__":
55
+ main()