Spaces:
Running
Running
axeronis commited on
Commit ·
c222f07
1
Parent(s): 983490a
feat: TTS sanitizer - extract URLs/cards/emails and send as text after voice
Browse files- backend/app/api/voice.py +2 -2
- backend/app/api/webhook.py +28 -1
- backend/app/services/llm_client.py +2 -1
- backend/app/services/voice_service.py +106 -26
backend/app/api/voice.py
CHANGED
|
@@ -19,7 +19,7 @@ async def generate_speech(
|
|
| 19 |
Generate audio speech from text.
|
| 20 |
Returns an audio/mpeg stream.
|
| 21 |
"""
|
| 22 |
-
audio_content = await voice_service.generate_audio(request.text, request.voice)
|
| 23 |
|
| 24 |
return Response(
|
| 25 |
content=audio_content,
|
|
@@ -38,7 +38,7 @@ async def synthesize_voice(
|
|
| 38 |
Synthesize voice from text using Chatterbox TTS.
|
| 39 |
Alias for /speak endpoint used by frontend voice preview.
|
| 40 |
"""
|
| 41 |
-
audio_content = await voice_service.generate_audio(request.text, request.voice)
|
| 42 |
|
| 43 |
return Response(
|
| 44 |
content=audio_content,
|
|
|
|
| 19 |
Generate audio speech from text.
|
| 20 |
Returns an audio/mpeg stream.
|
| 21 |
"""
|
| 22 |
+
audio_content, _ = await voice_service.generate_audio(request.text, request.voice)
|
| 23 |
|
| 24 |
return Response(
|
| 25 |
content=audio_content,
|
|
|
|
| 38 |
Synthesize voice from text using Chatterbox TTS.
|
| 39 |
Alias for /speak endpoint used by frontend voice preview.
|
| 40 |
"""
|
| 41 |
+
audio_content, _ = await voice_service.generate_audio(request.text, request.voice)
|
| 42 |
|
| 43 |
return Response(
|
| 44 |
content=audio_content,
|
backend/app/api/webhook.py
CHANGED
|
@@ -1391,7 +1391,7 @@ Answer with ONE word:
|
|
| 1391 |
voice_id = getattr(tenant, 'voice_id', 'professional_male')
|
| 1392 |
custom_voice_url = getattr(tenant, 'voice_reference_url', None)
|
| 1393 |
logger.info(f"🎙️ Generating voice response (voice={voice_id})...")
|
| 1394 |
-
audio_bytes = await voice_service.generate_audio(
|
| 1395 |
text=ai_response["text"],
|
| 1396 |
voice=voice_id,
|
| 1397 |
custom_voice_url=custom_voice_url
|
|
@@ -1449,6 +1449,33 @@ Answer with ONE word:
|
|
| 1449 |
|
| 1450 |
if send_success:
|
| 1451 |
logger.info(f"🎤 Voice response sent to chat {chat_id}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1452 |
else:
|
| 1453 |
# Fallback to text if voice fails
|
| 1454 |
logger.warning("⚠️ Voice send failed, falling back to text")
|
|
|
|
| 1391 |
voice_id = getattr(tenant, 'voice_id', 'professional_male')
|
| 1392 |
custom_voice_url = getattr(tenant, 'voice_reference_url', None)
|
| 1393 |
logger.info(f"🎙️ Generating voice response (voice={voice_id})...")
|
| 1394 |
+
audio_bytes, extracted_items = await voice_service.generate_audio(
|
| 1395 |
text=ai_response["text"],
|
| 1396 |
voice=voice_id,
|
| 1397 |
custom_voice_url=custom_voice_url
|
|
|
|
| 1449 |
|
| 1450 |
if send_success:
|
| 1451 |
logger.info(f"🎤 Voice response sent to chat {chat_id}")
|
| 1452 |
+
|
| 1453 |
+
# 📝 SEND EXTRACTED SENSITIVE DATA AS SEPARATE TEXT MESSAGE
|
| 1454 |
+
if extracted_items:
|
| 1455 |
+
# Format extracted items for text message
|
| 1456 |
+
text_parts = []
|
| 1457 |
+
for item in extracted_items:
|
| 1458 |
+
item_type = item.get("type", "")
|
| 1459 |
+
value = item.get("value", "")
|
| 1460 |
+
if item_type == "link":
|
| 1461 |
+
text_parts.append(f"🔗 {value}")
|
| 1462 |
+
elif item_type == "card":
|
| 1463 |
+
text_parts.append(f"💳 {value}")
|
| 1464 |
+
elif item_type == "email":
|
| 1465 |
+
text_parts.append(f"📧 {value}")
|
| 1466 |
+
elif item_type == "iban":
|
| 1467 |
+
text_parts.append(f"🏦 {value}")
|
| 1468 |
+
else:
|
| 1469 |
+
text_parts.append(value)
|
| 1470 |
+
|
| 1471 |
+
if text_parts:
|
| 1472 |
+
extracted_text = "\n".join(text_parts)
|
| 1473 |
+
logger.info(f"📝 Sending {len(extracted_items)} extracted items as text")
|
| 1474 |
+
await send_telegram_message(
|
| 1475 |
+
bot_token=tenant.telegram_bot_token,
|
| 1476 |
+
chat_id=chat_id,
|
| 1477 |
+
text=extracted_text
|
| 1478 |
+
)
|
| 1479 |
else:
|
| 1480 |
# Fallback to text if voice fails
|
| 1481 |
logger.warning("⚠️ Voice send failed, falling back to text")
|
backend/app/services/llm_client.py
CHANGED
|
@@ -278,7 +278,8 @@ class GeminiLLMClient:
|
|
| 278 |
|
| 279 |
async def generate_speech(self, text: str, voice: str = "onyx") -> bytes:
|
| 280 |
"""Generate audio from text using configured VoiceService."""
|
| 281 |
-
|
|
|
|
| 282 |
|
| 283 |
async def analyze_image(self, image_bytes: bytes, mime_type: str = "image/jpeg") -> str:
|
| 284 |
"""
|
|
|
|
| 278 |
|
| 279 |
async def generate_speech(self, text: str, voice: str = "onyx") -> bytes:
|
| 280 |
"""Generate audio from text using configured VoiceService."""
|
| 281 |
+
audio, _ = await voice_service.generate_audio(text, voice)
|
| 282 |
+
return audio
|
| 283 |
|
| 284 |
async def analyze_image(self, image_bytes: bytes, mime_type: str = "image/jpeg") -> str:
|
| 285 |
"""
|
backend/app/services/voice_service.py
CHANGED
|
@@ -15,27 +15,100 @@ from app.core.config import settings
|
|
| 15 |
logger = logging.getLogger(__name__)
|
| 16 |
|
| 17 |
|
| 18 |
-
def clean_for_voice(text: str) -> str:
|
| 19 |
"""
|
| 20 |
-
Clean text for TTS synthesis
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
| 24 |
"""
|
| 25 |
import re
|
| 26 |
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
text = re.sub(r'\(Система:[^)]*\)', '', text)
|
| 29 |
text = re.sub(r'\[Система:[^\]]*\]', '', text)
|
| 30 |
-
|
| 31 |
-
# Remove common system markers
|
| 32 |
text = re.sub(r'✅\s*\(Система:[^)]*\)', '', text)
|
| 33 |
text = re.sub(r'❌\s*\(Система:[^)]*\)', '', text)
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
# Format phone numbers for speech
|
| 36 |
def format_phone(match):
|
| 37 |
phone = match.group(0)
|
| 38 |
-
# Map digits to words
|
| 39 |
digit_words = {
|
| 40 |
'0': 'ноль', '1': 'один', '2': 'два', '3': 'три', '4': 'четыре',
|
| 41 |
'5': 'пять', '6': 'шесть', '7': 'семь', '8': 'восемь', '9': 'девять'
|
|
@@ -46,28 +119,30 @@ def clean_for_voice(text: str) -> str:
|
|
| 46 |
result.append('плюс')
|
| 47 |
elif char.isdigit():
|
| 48 |
result.append(digit_words[char])
|
| 49 |
-
# Skip other characters like spaces, dashes
|
| 50 |
return ' '.join(result)
|
| 51 |
|
| 52 |
-
# Match phone patterns
|
| 53 |
text = re.sub(r'\+?\d[\d\s\-]{8,15}', format_phone, text)
|
| 54 |
|
| 55 |
-
# Remove
|
| 56 |
emoji_pattern = re.compile(
|
| 57 |
"["
|
| 58 |
"\U0001F600-\U0001F64F" # emoticons
|
| 59 |
"\U0001F300-\U0001F5FF" # symbols & pictographs
|
| 60 |
"\U0001F680-\U0001F6FF" # transport & map symbols
|
| 61 |
"\U0001F1E0-\U0001F1FF" # flags
|
|
|
|
|
|
|
| 62 |
"]+", flags=re.UNICODE
|
| 63 |
)
|
| 64 |
-
# Just remove all emojis for cleaner speech
|
| 65 |
text = emoji_pattern.sub('', text)
|
| 66 |
|
| 67 |
-
# Clean up
|
| 68 |
-
text = re.sub(r'\
|
|
|
|
|
|
|
| 69 |
|
| 70 |
-
return text
|
| 71 |
|
| 72 |
|
| 73 |
|
|
@@ -148,7 +223,7 @@ class VoiceService:
|
|
| 148 |
custom_voice_url: str = None, # Kept for compatibility, not used with ElevenLabs
|
| 149 |
exaggeration: float = 0.5, # Kept for compatibility
|
| 150 |
use_cache: bool = True # Enable/disable caching
|
| 151 |
-
) -> bytes:
|
| 152 |
"""
|
| 153 |
Generate speech from text.
|
| 154 |
|
|
@@ -160,22 +235,27 @@ class VoiceService:
|
|
| 160 |
use_cache: Whether to use cached audio if available
|
| 161 |
|
| 162 |
Returns:
|
| 163 |
-
|
|
|
|
|
|
|
| 164 |
"""
|
| 165 |
if not text or not text.strip():
|
| 166 |
raise ValueError("Text cannot be empty")
|
| 167 |
|
| 168 |
-
# Clean text for voice synthesis
|
| 169 |
-
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
selected_voice = voice or self.default_voice
|
| 172 |
|
| 173 |
-
# Check cache first
|
| 174 |
if use_cache:
|
| 175 |
-
cache_key = self._get_cache_key(
|
| 176 |
cached_audio = self._get_from_cache(cache_key)
|
| 177 |
if cached_audio:
|
| 178 |
-
return cached_audio
|
| 179 |
|
| 180 |
# Generate new audio
|
| 181 |
audio = None
|
|
@@ -183,19 +263,19 @@ class VoiceService:
|
|
| 183 |
# Try ElevenLabs first
|
| 184 |
if self.elevenlabs_api_key:
|
| 185 |
try:
|
| 186 |
-
audio = await self._elevenlabs_generate(
|
| 187 |
except Exception as e:
|
| 188 |
logger.warning(f"⚠️ ElevenLabs failed: {e}, falling back to Edge TTS")
|
| 189 |
|
| 190 |
# Fallback to Edge TTS
|
| 191 |
if not audio:
|
| 192 |
-
audio = await self._edge_tts_generate(
|
| 193 |
|
| 194 |
# Store in cache
|
| 195 |
if use_cache and audio:
|
| 196 |
self._add_to_cache(cache_key, audio)
|
| 197 |
|
| 198 |
-
return audio
|
| 199 |
|
| 200 |
async def _elevenlabs_generate(self, text: str, voice: str) -> bytes:
|
| 201 |
"""Generate audio using ElevenLabs API."""
|
|
|
|
| 15 |
logger = logging.getLogger(__name__)
|
| 16 |
|
| 17 |
|
| 18 |
+
def clean_for_voice(text: str) -> tuple[str, list[dict]]:
|
| 19 |
"""
|
| 20 |
+
Clean text for TTS synthesis and extract sensitive data for separate text messages.
|
| 21 |
+
|
| 22 |
+
Returns:
|
| 23 |
+
tuple: (cleaned_text, extracted_items)
|
| 24 |
+
- cleaned_text: Text safe for TTS
|
| 25 |
+
- extracted_items: List of dicts with {type, value, placeholder} for sending as text
|
| 26 |
"""
|
| 27 |
import re
|
| 28 |
|
| 29 |
+
extracted_items = []
|
| 30 |
+
|
| 31 |
+
# =============================================
|
| 32 |
+
# 1. EXTRACT SENSITIVE DATA (before cleaning)
|
| 33 |
+
# =============================================
|
| 34 |
+
|
| 35 |
+
# 1.1 URLs/Links
|
| 36 |
+
url_pattern = r'https?://[^\s<>"{}|\\^`\[\]]+'
|
| 37 |
+
urls = re.findall(url_pattern, text)
|
| 38 |
+
for url in urls:
|
| 39 |
+
extracted_items.append({
|
| 40 |
+
"type": "link",
|
| 41 |
+
"value": url,
|
| 42 |
+
"placeholder": "ссылка в чате"
|
| 43 |
+
})
|
| 44 |
+
text = re.sub(url_pattern, 'ссылка в чате', text)
|
| 45 |
+
|
| 46 |
+
# 1.2 Card Numbers (16 digits, various formats)
|
| 47 |
+
card_pattern = r'\b\d{4}[\s\-]?\d{4}[\s\-]?\d{4}[\s\-]?\d{4}\b'
|
| 48 |
+
cards = re.findall(card_pattern, text)
|
| 49 |
+
for card in cards:
|
| 50 |
+
extracted_items.append({
|
| 51 |
+
"type": "card",
|
| 52 |
+
"value": card,
|
| 53 |
+
"placeholder": "реквизиты в чате"
|
| 54 |
+
})
|
| 55 |
+
text = re.sub(card_pattern, 'реквизиты в чате', text)
|
| 56 |
+
|
| 57 |
+
# 1.3 Email addresses
|
| 58 |
+
email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
|
| 59 |
+
emails = re.findall(email_pattern, text)
|
| 60 |
+
for email in emails:
|
| 61 |
+
extracted_items.append({
|
| 62 |
+
"type": "email",
|
| 63 |
+
"value": email,
|
| 64 |
+
"placeholder": "адрес почты в чате"
|
| 65 |
+
})
|
| 66 |
+
text = re.sub(email_pattern, 'адрес почты в чате', text)
|
| 67 |
+
|
| 68 |
+
# 1.4 IBAN / Long account numbers
|
| 69 |
+
iban_pattern = r'\b[A-Z]{2}\d{2}[\s]?[\dA-Z]{4}[\s]?[\dA-Z]{4}[\s]?[\dA-Z]{4}[\s]?[\dA-Z]{4}[\s]?[\dA-Z]{0,4}\b'
|
| 70 |
+
ibans = re.findall(iban_pattern, text)
|
| 71 |
+
for iban in ibans:
|
| 72 |
+
extracted_items.append({
|
| 73 |
+
"type": "iban",
|
| 74 |
+
"value": iban,
|
| 75 |
+
"placeholder": "реквизиты в чате"
|
| 76 |
+
})
|
| 77 |
+
text = re.sub(iban_pattern, 'реквизиты в чате', text)
|
| 78 |
+
|
| 79 |
+
# =============================================
|
| 80 |
+
# 2. CLEAN FOR SPEECH (keep in text)
|
| 81 |
+
# =============================================
|
| 82 |
+
|
| 83 |
+
# Remove (Система: ...) and [Система: ...] tags
|
| 84 |
text = re.sub(r'\(Система:[^)]*\)', '', text)
|
| 85 |
text = re.sub(r'\[Система:[^\]]*\]', '', text)
|
|
|
|
|
|
|
| 86 |
text = re.sub(r'✅\s*\(Система:[^)]*\)', '', text)
|
| 87 |
text = re.sub(r'❌\s*\(Система:[^)]*\)', '', text)
|
| 88 |
|
| 89 |
+
# Remove markdown formatting
|
| 90 |
+
text = re.sub(r'\*\*([^*]+)\*\*', r'\1', text) # **bold** -> bold
|
| 91 |
+
text = re.sub(r'\*([^*]+)\*', r'\1', text) # *italic* -> italic
|
| 92 |
+
text = re.sub(r'__([^_]+)__', r'\1', text) # __underline__
|
| 93 |
+
text = re.sub(r'_([^_]+)_', r'\1', text) # _italic_
|
| 94 |
+
text = re.sub(r'~~([^~]+)~~', r'\1', text) # ~~strike~~
|
| 95 |
+
text = re.sub(r'`([^`]+)`', r'\1', text) # `code`
|
| 96 |
+
|
| 97 |
+
# Remove all remaining markdown chars
|
| 98 |
+
text = text.replace('#', '')
|
| 99 |
+
|
| 100 |
+
# Convert currency symbols to words
|
| 101 |
+
text = text.replace('₽', ' рублей')
|
| 102 |
+
text = text.replace('$', ' долларов ')
|
| 103 |
+
text = text.replace('€', ' евро ')
|
| 104 |
+
text = text.replace('%', ' процентов')
|
| 105 |
+
|
| 106 |
+
# Remove common special characters that don't read well
|
| 107 |
+
text = re.sub(r'[<>{}|\[\]\\^~`]', '', text)
|
| 108 |
+
|
| 109 |
# Format phone numbers for speech
|
| 110 |
def format_phone(match):
|
| 111 |
phone = match.group(0)
|
|
|
|
| 112 |
digit_words = {
|
| 113 |
'0': 'ноль', '1': 'один', '2': 'два', '3': 'три', '4': 'четыре',
|
| 114 |
'5': 'пять', '6': 'шесть', '7': 'семь', '8': 'восемь', '9': 'девять'
|
|
|
|
| 119 |
result.append('плюс')
|
| 120 |
elif char.isdigit():
|
| 121 |
result.append(digit_words[char])
|
|
|
|
| 122 |
return ' '.join(result)
|
| 123 |
|
| 124 |
+
# Match phone patterns (+7 999 384 666 or +79993846666)
|
| 125 |
text = re.sub(r'\+?\d[\d\s\-]{8,15}', format_phone, text)
|
| 126 |
|
| 127 |
+
# Remove emojis
|
| 128 |
emoji_pattern = re.compile(
|
| 129 |
"["
|
| 130 |
"\U0001F600-\U0001F64F" # emoticons
|
| 131 |
"\U0001F300-\U0001F5FF" # symbols & pictographs
|
| 132 |
"\U0001F680-\U0001F6FF" # transport & map symbols
|
| 133 |
"\U0001F1E0-\U0001F1FF" # flags
|
| 134 |
+
"\U00002702-\U000027B0" # dingbats
|
| 135 |
+
"\U0001F900-\U0001F9FF" # supplemental symbols
|
| 136 |
"]+", flags=re.UNICODE
|
| 137 |
)
|
|
|
|
| 138 |
text = emoji_pattern.sub('', text)
|
| 139 |
|
| 140 |
+
# Clean up excessive punctuation
|
| 141 |
+
text = re.sub(r'\.{3,}', '.', text) # ... -> .
|
| 142 |
+
text = re.sub(r'-{2,}', '-', text) # -- -> -
|
| 143 |
+
text = re.sub(r'\s+', ' ', text) # Multiple spaces -> single
|
| 144 |
|
| 145 |
+
return text.strip(), extracted_items
|
| 146 |
|
| 147 |
|
| 148 |
|
|
|
|
| 223 |
custom_voice_url: str = None, # Kept for compatibility, not used with ElevenLabs
|
| 224 |
exaggeration: float = 0.5, # Kept for compatibility
|
| 225 |
use_cache: bool = True # Enable/disable caching
|
| 226 |
+
) -> tuple[bytes, list[dict]]:
|
| 227 |
"""
|
| 228 |
Generate speech from text.
|
| 229 |
|
|
|
|
| 235 |
use_cache: Whether to use cached audio if available
|
| 236 |
|
| 237 |
Returns:
|
| 238 |
+
tuple: (audio_bytes, extracted_items)
|
| 239 |
+
- audio_bytes: MP3 audio data
|
| 240 |
+
- extracted_items: List of sensitive data extracted (links, cards, etc)
|
| 241 |
"""
|
| 242 |
if not text or not text.strip():
|
| 243 |
raise ValueError("Text cannot be empty")
|
| 244 |
|
| 245 |
+
# Clean text for voice synthesis and extract sensitive data
|
| 246 |
+
clean_text, extracted_items = clean_for_voice(text)
|
| 247 |
+
|
| 248 |
+
if not clean_text or not clean_text.strip():
|
| 249 |
+
raise ValueError("No speakable text after cleaning")
|
| 250 |
|
| 251 |
selected_voice = voice or self.default_voice
|
| 252 |
|
| 253 |
+
# Check cache first (use clean text for cache key)
|
| 254 |
if use_cache:
|
| 255 |
+
cache_key = self._get_cache_key(clean_text, selected_voice)
|
| 256 |
cached_audio = self._get_from_cache(cache_key)
|
| 257 |
if cached_audio:
|
| 258 |
+
return cached_audio, extracted_items
|
| 259 |
|
| 260 |
# Generate new audio
|
| 261 |
audio = None
|
|
|
|
| 263 |
# Try ElevenLabs first
|
| 264 |
if self.elevenlabs_api_key:
|
| 265 |
try:
|
| 266 |
+
audio = await self._elevenlabs_generate(clean_text, selected_voice)
|
| 267 |
except Exception as e:
|
| 268 |
logger.warning(f"⚠️ ElevenLabs failed: {e}, falling back to Edge TTS")
|
| 269 |
|
| 270 |
# Fallback to Edge TTS
|
| 271 |
if not audio:
|
| 272 |
+
audio = await self._edge_tts_generate(clean_text, selected_voice)
|
| 273 |
|
| 274 |
# Store in cache
|
| 275 |
if use_cache and audio:
|
| 276 |
self._add_to_cache(cache_key, audio)
|
| 277 |
|
| 278 |
+
return audio, extracted_items
|
| 279 |
|
| 280 |
async def _elevenlabs_generate(self, text: str, voice: str) -> bytes:
|
| 281 |
"""Generate audio using ElevenLabs API."""
|