Spaces:
Running
Running
axeronis commited on
Commit ·
b6f0e98
1
Parent(s): 254cb53
feat: smart reactivation - skip booked leads, AI decision, voice text cleanup
Browse files
backend/alembic/versions/2025_12_26_next_contact_at.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""add next_contact_at to leads
|
| 2 |
+
|
| 3 |
+
Revision ID: 2025_12_26_next_contact_at
|
| 4 |
+
Revises: 2025_12_24_fix_subscription_case
|
| 5 |
+
Create Date: 2025-12-26 05:00:00.000000
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
from typing import Sequence, Union
|
| 9 |
+
|
| 10 |
+
from alembic import op
|
| 11 |
+
import sqlalchemy as sa
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# revision identifiers, used by Alembic.
|
| 15 |
+
revision: str = '2025_12_26_next_contact_at'
|
| 16 |
+
down_revision: Union[str, None] = '2025_12_24_fix_subscription_case'
|
| 17 |
+
branch_labels: Union[str, Sequence[str], None] = None
|
| 18 |
+
depends_on: Union[str, Sequence[str], None] = None
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def upgrade() -> None:
|
| 22 |
+
"""Add next_contact_at field to leads for smart reactivation."""
|
| 23 |
+
# Add column (nullable, no default needed)
|
| 24 |
+
op.add_column('leads', sa.Column('next_contact_at', sa.DateTime(), nullable=True))
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def downgrade() -> None:
|
| 28 |
+
"""Remove next_contact_at from leads."""
|
| 29 |
+
op.drop_column('leads', 'next_contact_at')
|
backend/app/models/lead.py
CHANGED
|
@@ -101,6 +101,9 @@ class Lead(SQLModel, table=True):
|
|
| 101 |
|
| 102 |
# Blocking (spam, unsubscribed, etc.)
|
| 103 |
is_blocked: bool = Field(default=False)
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
|
| 106 |
# Timestamps
|
|
|
|
| 101 |
|
| 102 |
# Blocking (spam, unsubscribed, etc.)
|
| 103 |
is_blocked: bool = Field(default=False)
|
| 104 |
+
|
| 105 |
+
# Smart reactivation: when to contact next (extracted from "через неделю" etc.)
|
| 106 |
+
next_contact_at: Optional[datetime] = None
|
| 107 |
|
| 108 |
|
| 109 |
# Timestamps
|
backend/app/services/ai_core/lead_analyzer.py
CHANGED
|
@@ -363,10 +363,15 @@ async def evaluate_reactivation_impl(
|
|
| 363 |
conversation_history: List[Message]
|
| 364 |
) -> Dict[str, Any]:
|
| 365 |
"""
|
| 366 |
-
Evaluate if a stale lead should be reactivated
|
| 367 |
-
|
|
|
|
|
|
|
|
|
|
| 368 |
"""
|
| 369 |
from app.models.tenant import Tenant
|
|
|
|
|
|
|
| 370 |
|
| 371 |
# Load tenant settings
|
| 372 |
tenant = await session.get(Tenant, lead.tenant_id)
|
|
@@ -396,60 +401,88 @@ async def evaluate_reactivation_impl(
|
|
| 396 |
heat_score = getattr(lead, 'heat_score', 50) or 50
|
| 397 |
|
| 398 |
try:
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
📋 ИНФОРМАЦИЯ О КЛИЕНТЕ:
|
| 402 |
-
- Имя: {lead_name}
|
| 403 |
-
- Психотип (DISC): {psychotype}
|
| 404 |
-
- Теплота (heat): {heat_score}%
|
| 405 |
-
- Последнее общение: давно (холодный контакт)
|
| 406 |
-
|
| 407 |
-
🎤 ТВОЙ СТИЛЬ:
|
| 408 |
-
- Тон общения: {tone_of_voice}
|
| 409 |
-
- Обращение: {addressing_style}
|
| 410 |
-
- Используй местоимения: {you_pronoun}, {your_pronoun}
|
| 411 |
-
{f'- Дополнительные инструкции: {custom_instructions}' if custom_instructions else ''}
|
| 412 |
|
|
|
|
|
|
|
| 413 |
💬 ИСТОРИЯ ДИАЛОГА:
|
| 414 |
{conversation_text}
|
| 415 |
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
|
|
|
|
|
|
|
|
|
| 443 |
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 449 |
|
| 450 |
response = await ai_core.llm.generate_response(
|
| 451 |
prompt=reactivation_prompt,
|
| 452 |
-
system_instruction=
|
| 453 |
temperature=0.8
|
| 454 |
)
|
| 455 |
|
|
@@ -461,7 +494,7 @@ async def evaluate_reactivation_impl(
|
|
| 461 |
"should_reactivate": True,
|
| 462 |
"draft_message": message,
|
| 463 |
"message": message,
|
| 464 |
-
"reason":
|
| 465 |
}
|
| 466 |
|
| 467 |
except Exception as e:
|
|
|
|
| 363 |
conversation_history: List[Message]
|
| 364 |
) -> Dict[str, Any]:
|
| 365 |
"""
|
| 366 |
+
Evaluate if a stale lead should be reactivated with INTELLIGENT AI DECISION.
|
| 367 |
+
|
| 368 |
+
Two-step process:
|
| 369 |
+
1. AI DECIDES if we should message at all (checking context)
|
| 370 |
+
2. If yes, generates a human-like message
|
| 371 |
"""
|
| 372 |
from app.models.tenant import Tenant
|
| 373 |
+
import json
|
| 374 |
+
import re
|
| 375 |
|
| 376 |
# Load tenant settings
|
| 377 |
tenant = await session.get(Tenant, lead.tenant_id)
|
|
|
|
| 401 |
heat_score = getattr(lead, 'heat_score', 50) or 50
|
| 402 |
|
| 403 |
try:
|
| 404 |
+
# ============ STEP 1: AI DECISION ============
|
| 405 |
+
decision_prompt = f"""Проанализируй историю диалога и реши: СТОИТ ЛИ писать этому клиенту СЕЙЧАС?
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 406 |
|
| 407 |
+
📋 КЛИЕНТ: {lead_name}
|
| 408 |
+
📊 Теплота: {heat_score}%
|
| 409 |
💬 ИСТОРИЯ ДИАЛОГА:
|
| 410 |
{conversation_text}
|
| 411 |
|
| 412 |
+
❌ ОТВЕЧАЙ "NO" если:
|
| 413 |
+
- Клиент УЖЕ ЗАПИСАЛСЯ на встречу/звонок (видишь подтверждение записи)
|
| 414 |
+
- Клиент СКАЗАЛ "отвечу позже/через неделю/завтра" (и время еще не прошло)
|
| 415 |
+
- Клиент КУПИЛ продукт (видишь подтверждение покупки)
|
| 416 |
+
- Последнее сообщение от НАС (AI) - мы ждём ответа клиента
|
| 417 |
+
- Клиент просил НЕ БЕСПОКОИТЬ или отписался
|
| 418 |
+
- Клиент показал негатив и не хочет продолжать
|
| 419 |
+
- Мы УЖЕ писали несколько раз без ответа (спам)
|
| 420 |
+
|
| 421 |
+
✅ ОТВЕЧАЙ "YES" только если:
|
| 422 |
+
- Клиент показал интерес но замолчал
|
| 423 |
+
- Прошло достаточно времени с последнего контакта
|
| 424 |
+
- У нас есть реальная ценность для клиента
|
| 425 |
+
- Есть повод для естественного касания
|
| 426 |
+
|
| 427 |
+
ВАЖНО: Если видишь "(Система: Запись создана)" или подобное - значит клиент УЖЕ записан, писать НЕ НУЖНО!
|
| 428 |
+
|
| 429 |
+
Ответь в JSON формате (только JSON, без пояснений):
|
| 430 |
+
{{"decision": true/false, "reason": "краткая причина"}}"""
|
| 431 |
+
|
| 432 |
+
decision_response = await ai_core.llm.generate_response(
|
| 433 |
+
prompt=decision_prompt,
|
| 434 |
+
system_instruction="Ты строгий аналитик. Отвечай ТОЛЬКО валидным JSON.",
|
| 435 |
+
temperature=0.1
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
# Parse decision
|
| 439 |
+
decision_text = decision_response["text"].strip()
|
| 440 |
+
# Extract JSON from response
|
| 441 |
+
json_match = re.search(r'\{[^}]+\}', decision_text)
|
| 442 |
|
| 443 |
+
if json_match:
|
| 444 |
+
decision_data = json.loads(json_match.group())
|
| 445 |
+
should_contact = decision_data.get("decision", False)
|
| 446 |
+
reason = decision_data.get("reason", "No reason provided")
|
| 447 |
+
else:
|
| 448 |
+
# If can't parse, default to NO (safer)
|
| 449 |
+
logger.warning(f"Could not parse AI decision: {decision_text}")
|
| 450 |
+
should_contact = False
|
| 451 |
+
reason = "Could not parse AI decision"
|
| 452 |
+
|
| 453 |
+
if not should_contact:
|
| 454 |
+
logger.info(f"🛑 AI decided NOT to reactivate {lead_name}: {reason}")
|
| 455 |
+
return {
|
| 456 |
+
"decision": False,
|
| 457 |
+
"should_reactivate": False,
|
| 458 |
+
"draft_message": None,
|
| 459 |
+
"message": None,
|
| 460 |
+
"reason": reason
|
| 461 |
+
}
|
| 462 |
+
|
| 463 |
+
# ============ STEP 2: GENERATE MESSAGE ============
|
| 464 |
+
logger.info(f"✅ AI approved reactivation for {lead_name}: {reason}")
|
| 465 |
+
|
| 466 |
+
reactivation_prompt = f"""Ты — {bot_name}, опытный менеджер. Напиши ОДНО сообщение клиенту для возврата в диалог.
|
| 467 |
+
|
| 468 |
+
📋 КЛИЕНТ: {lead_name} (теплота: {heat_score}%)
|
| 469 |
+
🎤 Стиль: {tone_of_voice}, обращение {addressing_style}
|
| 470 |
+
|
| 471 |
+
💬 ИСТОРИЯ:
|
| 472 |
+
{conversation_text}
|
| 473 |
+
|
| 474 |
+
📝 ПРАВИЛА:
|
| 475 |
+
- Используй имя клиента
|
| 476 |
+
- Максимум 2-3 предложения
|
| 477 |
+
- Пиши как живой человек
|
| 478 |
+
- Обращайся {addressing_style}
|
| 479 |
+
{f'- {custom_instructions}' if custom_instructions else ''}
|
| 480 |
+
|
| 481 |
+
Напиши ТОЛЬКО само сообщение:"""
|
| 482 |
|
| 483 |
response = await ai_core.llm.generate_response(
|
| 484 |
prompt=reactivation_prompt,
|
| 485 |
+
system_instruction=f"Ты {bot_name} с тоном \"{tone_of_voice}\". Пиши естественно и коротко.",
|
| 486 |
temperature=0.8
|
| 487 |
)
|
| 488 |
|
|
|
|
| 494 |
"should_reactivate": True,
|
| 495 |
"draft_message": message,
|
| 496 |
"message": message,
|
| 497 |
+
"reason": reason
|
| 498 |
}
|
| 499 |
|
| 500 |
except Exception as e:
|
backend/app/services/reactivation_service.py
CHANGED
|
@@ -86,8 +86,16 @@ class ReactivationService:
|
|
| 86 |
"""
|
| 87 |
Find HOT leads who haven't responded within X hours.
|
| 88 |
Hot leads need faster follow-up (1 hour default).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
"""
|
|
|
|
|
|
|
| 90 |
cutoff = datetime.utcnow() - timedelta(hours=hours_threshold)
|
|
|
|
| 91 |
|
| 92 |
# Only HOT leads
|
| 93 |
hot_heat_levels = [LeadHeat.HOT, LeadHeat.WARM]
|
|
@@ -99,18 +107,59 @@ class ReactivationService:
|
|
| 99 |
LeadStatus.CLOSED_WON
|
| 100 |
]
|
| 101 |
|
|
|
|
| 102 |
stmt = select(Lead).where(
|
| 103 |
and_(
|
| 104 |
Lead.last_message_at < cutoff,
|
| 105 |
Lead.last_message_at > datetime.utcnow() - timedelta(days=7), # Not too old
|
| 106 |
col(Lead.heat_level).in_(hot_heat_levels),
|
| 107 |
col(Lead.status).notin_(excluded_statuses),
|
| 108 |
-
Lead.is_blocked == False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
)
|
| 110 |
-
).limit(
|
| 111 |
|
| 112 |
result = await session.execute(stmt)
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
async def run_hot_leads_batch(self, session: AsyncSession):
|
| 116 |
"""
|
|
|
|
| 86 |
"""
|
| 87 |
Find HOT leads who haven't responded within X hours.
|
| 88 |
Hot leads need faster follow-up (1 hour default).
|
| 89 |
+
|
| 90 |
+
SMART FILTERS:
|
| 91 |
+
- Skip leads with scheduled appointments (already booked)
|
| 92 |
+
- Skip leads with next_contact_at in the future (they said "call me later")
|
| 93 |
+
- Skip leads where last message was from AI (waiting for client reply)
|
| 94 |
"""
|
| 95 |
+
from app.models.booking import Appointment, AppointmentStatus
|
| 96 |
+
|
| 97 |
cutoff = datetime.utcnow() - timedelta(hours=hours_threshold)
|
| 98 |
+
now = datetime.utcnow()
|
| 99 |
|
| 100 |
# Only HOT leads
|
| 101 |
hot_heat_levels = [LeadHeat.HOT, LeadHeat.WARM]
|
|
|
|
| 107 |
LeadStatus.CLOSED_WON
|
| 108 |
]
|
| 109 |
|
| 110 |
+
# Step 1: Get candidate leads
|
| 111 |
stmt = select(Lead).where(
|
| 112 |
and_(
|
| 113 |
Lead.last_message_at < cutoff,
|
| 114 |
Lead.last_message_at > datetime.utcnow() - timedelta(days=7), # Not too old
|
| 115 |
col(Lead.heat_level).in_(hot_heat_levels),
|
| 116 |
col(Lead.status).notin_(excluded_statuses),
|
| 117 |
+
Lead.is_blocked == False,
|
| 118 |
+
# Smart filter: Don't contact before next_contact_at
|
| 119 |
+
or_(
|
| 120 |
+
Lead.next_contact_at == None,
|
| 121 |
+
Lead.next_contact_at <= now
|
| 122 |
+
)
|
| 123 |
)
|
| 124 |
+
).limit(50) # Get more, we'll filter below
|
| 125 |
|
| 126 |
result = await session.execute(stmt)
|
| 127 |
+
candidates = result.scalars().all()
|
| 128 |
+
|
| 129 |
+
# Step 2: Filter out leads with scheduled appointments
|
| 130 |
+
filtered_leads = []
|
| 131 |
+
for lead in candidates:
|
| 132 |
+
# Check for existing scheduled appointment
|
| 133 |
+
appt_stmt = select(Appointment).where(
|
| 134 |
+
and_(
|
| 135 |
+
Appointment.lead_id == lead.id,
|
| 136 |
+
Appointment.status == AppointmentStatus.SCHEDULED,
|
| 137 |
+
Appointment.start_time >= now
|
| 138 |
+
)
|
| 139 |
+
).limit(1)
|
| 140 |
+
|
| 141 |
+
appt_result = await session.execute(appt_stmt)
|
| 142 |
+
has_appointment = appt_result.scalar_one_or_none()
|
| 143 |
+
|
| 144 |
+
if has_appointment:
|
| 145 |
+
logger.info(f"⏭️ Skipping {lead.name} - has scheduled appointment")
|
| 146 |
+
continue
|
| 147 |
+
|
| 148 |
+
# Check if last message was from AI (we're waiting for reply)
|
| 149 |
+
history = await self._get_lead_history(session, lead)
|
| 150 |
+
if history:
|
| 151 |
+
last_msg = history[-1]
|
| 152 |
+
if last_msg.sender_type == "ai":
|
| 153 |
+
# Don't spam - we already sent a message
|
| 154 |
+
logger.info(f"⏭️ Skipping {lead.name} - last message was from AI (waiting for reply)")
|
| 155 |
+
continue
|
| 156 |
+
|
| 157 |
+
filtered_leads.append(lead)
|
| 158 |
+
|
| 159 |
+
if len(filtered_leads) >= 20: # Limit batch
|
| 160 |
+
break
|
| 161 |
+
|
| 162 |
+
return filtered_leads
|
| 163 |
|
| 164 |
async def run_hot_leads_batch(self, session: AsyncSession):
|
| 165 |
"""
|
backend/app/services/voice_service.py
CHANGED
|
@@ -15,6 +15,62 @@ from app.core.config import settings
|
|
| 15 |
logger = logging.getLogger(__name__)
|
| 16 |
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
# ElevenLabs Voice IDs (cloned from actors)
|
| 19 |
ELEVENLABS_VOICES = {
|
| 20 |
"professional_male": {
|
|
@@ -109,6 +165,9 @@ class VoiceService:
|
|
| 109 |
if not text or not text.strip():
|
| 110 |
raise ValueError("Text cannot be empty")
|
| 111 |
|
|
|
|
|
|
|
|
|
|
| 112 |
selected_voice = voice or self.default_voice
|
| 113 |
|
| 114 |
# Check cache first
|
|
|
|
| 15 |
logger = logging.getLogger(__name__)
|
| 16 |
|
| 17 |
|
| 18 |
+
def clean_for_voice(text: str) -> str:
|
| 19 |
+
"""
|
| 20 |
+
Clean text for TTS synthesis:
|
| 21 |
+
- Remove (Система: ...) annotations
|
| 22 |
+
- Format phone numbers for speech (+7 999 384 666 → плюс семь, девять девять девять...)
|
| 23 |
+
- Remove emojis that don't speak well
|
| 24 |
+
"""
|
| 25 |
+
import re
|
| 26 |
+
|
| 27 |
+
# Remove (Система: ...) tags
|
| 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': 'девять'
|
| 42 |
+
}
|
| 43 |
+
result = []
|
| 44 |
+
for char in phone:
|
| 45 |
+
if char == '+':
|
| 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 like +7 999 384 666 or +79993846666
|
| 53 |
+
text = re.sub(r'\+?\d[\d\s\-]{8,15}', format_phone, text)
|
| 54 |
+
|
| 55 |
+
# Remove excessive emojis (keep max 1 emoji per sentence)
|
| 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 extra whitespace
|
| 68 |
+
text = re.sub(r'\s+', ' ', text).strip()
|
| 69 |
+
|
| 70 |
+
return text
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
|
| 74 |
# ElevenLabs Voice IDs (cloned from actors)
|
| 75 |
ELEVENLABS_VOICES = {
|
| 76 |
"professional_male": {
|
|
|
|
| 165 |
if not text or not text.strip():
|
| 166 |
raise ValueError("Text cannot be empty")
|
| 167 |
|
| 168 |
+
# Clean text for voice synthesis (remove system tags, format phones, etc.)
|
| 169 |
+
text = clean_for_voice(text)
|
| 170 |
+
|
| 171 |
selected_voice = voice or self.default_voice
|
| 172 |
|
| 173 |
# Check cache first
|