Spaces:
Running

axeronis commited on
Commit
1f6afe7
·
1 Parent(s): 263213f

feat: add PaymentMethod/KnowledgeFile to AI context, TTS time pronunciation fix, mixed language support

Browse files
backend/app/services/ai_memory_manager.py CHANGED
@@ -262,6 +262,13 @@ class AIMemoryManager:
262
  context = f"""Тебя зовут {bot_name}. Ты {bot_role} в компании "{company}".
263
  {gender_instruction}
264
 
 
 
 
 
 
 
 
265
  🧠 КОГНИТИВНАЯ АРХИТЕКТУРА (Chain of Thought)
266
  Для каждого ответа ты проходишь 3 этапа мышления (показываешь только финальное сообщение):
267
 
@@ -456,6 +463,88 @@ class AIMemoryManager:
456
  if p.description:
457
  context += f" └ {p.description}\n"
458
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
459
  # F. TRAINING EXAMPLES
460
  stmt_train = select(AITrainingExample).where(
461
  AITrainingExample.tenant_id == tenant.id,
 
262
  context = f"""Тебя зовут {bot_name}. Ты {bot_role} в компании "{company}".
263
  {gender_instruction}
264
 
265
+ 🌐 МУЛЬТИЯЗЫЧНОСТЬ:
266
+ - Клиенты могут писать на смешанном языке (русский + кыргызский + казахский + узбекский)
267
+ - ВСЕГДА понимай и отвечай на том языке, на котором пишет клиент
268
+ - Если пишут на кыргызском — отвечай на кыргызском
269
+ - Если смешивают языки — отвечай на преобладающем языке
270
+ - Не переспрашивай "на каком языке вам ответить?"
271
+
272
  🧠 КОГНИТИВНАЯ АРХИТЕКТУРА (Chain of Thought)
273
  Для каждого ответа ты проходишь 3 этапа мышления (показываешь только финальное сообщение):
274
 
 
463
  if p.description:
464
  context += f" └ {p.description}\n"
465
 
466
+ # E2. PAYMENT METHODS
467
+ from app.models.knowledge import PaymentMethod, KnowledgeFile
468
+ stmt_payments = select(PaymentMethod).where(
469
+ PaymentMethod.tenant_id == tenant.id,
470
+ PaymentMethod.is_active == True
471
+ ).order_by(PaymentMethod.sort_order)
472
+ payments_result = await session.execute(stmt_payments)
473
+ payment_methods = payments_result.scalars().all()
474
+
475
+ if payment_methods:
476
+ context += "\n═══════════════════════════════════════════════════════════════\n"
477
+ context += "[💳 СПОСОБЫ ОПЛАТЫ]\n"
478
+ context += "═══════════════════════════════════════════════════════════════\n"
479
+ context += """ПРАВИЛА ОТПРАВКИ РЕКВИЗИТОВ:
480
+ - "По запросу" → отправляй когда клиент спрашивает "как оплатить?"
481
+ - "После согласия" → отправляй когда клиент говорит "да, хочу купить" или "оформляю"
482
+ - "Всегда" → упоминай в конце любого предложения о товаре/услуге
483
+
484
+ """
485
+ for pm in payment_methods:
486
+ condition_text = {
487
+ "on_request": "По запросу клиента",
488
+ "after_agreement": "После согласия на покупку",
489
+ "always": "Всегда показывать"
490
+ }.get(pm.send_condition, pm.send_condition)
491
+
492
+ context += f"• {pm.name} [{condition_text}]\n"
493
+ if pm.payment_type == "requisites" and pm.requisites_text:
494
+ context += f" Реквизиты: {pm.requisites_text}\n"
495
+ elif pm.payment_type == "link" and pm.payment_link:
496
+ context += f" Ссылка: {pm.payment_link}\n"
497
+ elif pm.image_url:
498
+ context += f" (QR-код/изображение доступно)\n"
499
+ if pm.ai_instruction:
500
+ context += f" ⚠️ Инструкция: {pm.ai_instruction}\n"
501
+ context += "\n"
502
+
503
+ # E3. KNOWLEDGE FILES (Informational materials)
504
+ stmt_files = select(KnowledgeFile).where(
505
+ KnowledgeFile.tenant_id == tenant.id,
506
+ KnowledgeFile.is_active == True
507
+ ).order_by(KnowledgeFile.sort_order)
508
+ files_result = await session.execute(stmt_files)
509
+ knowledge_files = files_result.scalars().all()
510
+
511
+ if knowledge_files:
512
+ context += "\n═══════════════════════════════════════════════════════════════\n"
513
+ context += "[📁 ИНФОРМАЦИОННЫЕ МАТЕРИАЛЫ]\n"
514
+ context += "═══════════════════════════════════════════════════════════════\n"
515
+ context += """ПРАВИЛА ОТПРАВКИ ФАЙЛОВ:
516
+ - "По запросу" → отправляй когда клиент спрашивает об этом материале
517
+ - "После покупки" → отправляй после подтверждения оплаты
518
+ - "После записи" → отправляй после успешного бронирования
519
+ - "По ключевому слову" → отправляй когда клиент упоминает ключевые слова
520
+ - "На этапе" → отправляй когда диалог дойдёт до указанного этапа
521
+
522
+ Чтобы отправить файл клиенту, используй тег: [SEND_FILE: название_файла]
523
+
524
+ """
525
+ for kf in knowledge_files:
526
+ condition_text = {
527
+ "on_request": "По запросу",
528
+ "after_purchase": "После покупки",
529
+ "after_booking": "После записи",
530
+ "on_stage": f"На этапе: {kf.trigger_stage}",
531
+ "on_keyword": f"По словам: {kf.trigger_keywords}"
532
+ }.get(kf.send_condition, kf.send_condition)
533
+
534
+ file_type_text = {
535
+ "document": "📄 Документ",
536
+ "image": "🖼 Изображение",
537
+ "video": "🎬 Видео",
538
+ "link": "🔗 Ссылка"
539
+ }.get(kf.file_type, kf.file_type)
540
+
541
+ context += f"• {kf.name} [{file_type_text}] [{condition_text}]\n"
542
+ if kf.description:
543
+ context += f" Описание: {kf.description}\n"
544
+ if kf.ai_instruction:
545
+ context += f" ⚠️ Инструкция: {kf.ai_instruction}\n"
546
+ context += "\n"
547
+
548
  # F. TRAINING EXAMPLES
549
  stmt_train = select(AITrainingExample).where(
550
  AITrainingExample.tenant_id == tenant.id,
backend/app/services/voice_service.py CHANGED
@@ -103,6 +103,49 @@ def clean_for_voice(text: str) -> tuple[str, list[dict]]:
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
 
 
103
  text = text.replace('€', ' евро ')
104
  text = text.replace('%', ' процентов')
105
 
106
+ # =============================================
107
+ # FORMAT TIME FOR NATURAL SPEECH (12:00 → двенадцать ноль-ноль)
108
+ # =============================================
109
+ HOURS_WORDS = {
110
+ '0': 'ноль', '1': 'один', '2': 'два', '3': 'три', '4': 'четыре',
111
+ '5': 'пять', '6': 'шесть', '7': 'семь', '8': 'восемь', '9': 'девять',
112
+ '10': 'десять', '11': 'одиннадцать', '12': 'двенадцать',
113
+ '13': 'тринадцать', '14': 'четырнадцать', '15': 'пятнадцать',
114
+ '16': 'шестнадцать', '17': 'семнадцать', '18': 'восемнадцать',
115
+ '19': 'девятнадцать', '20': 'двадцать', '21': 'двадцать один',
116
+ '22': 'двадцать два', '23': 'двадцать три', '00': 'ноль'
117
+ }
118
+
119
+ MINUTES_WORDS = {
120
+ '00': 'ноль-ноль', '05': 'ноль пять', '10': 'десять',
121
+ '15': 'пятнадцать', '20': 'двадцать', '25': 'двадцать пять',
122
+ '30': 'тридцать', '35': 'тридцать пять', '40': 'сорок',
123
+ '45': 'сорок пять', '50': 'пятьдесят', '55': 'пятьдесят пять'
124
+ }
125
+
126
+ def time_to_words(match):
127
+ """Convert time format to words for natural TTS."""
128
+ hours = match.group(1).lstrip('0') or '0'
129
+ minutes = match.group(2)
130
+
131
+ hours_word = HOURS_WORDS.get(hours, hours)
132
+
133
+ # Special handling for minutes
134
+ if minutes == '00':
135
+ minutes_word = 'ноль-ноль'
136
+ elif minutes.startswith('0') and len(minutes) == 2:
137
+ # 01-09 → ноль одна, ноль две...
138
+ single = minutes[1]
139
+ single_word = HOURS_WORDS.get(single, single)
140
+ minutes_word = f'ноль {single_word}'
141
+ else:
142
+ minutes_word = MINUTES_WORDS.get(minutes, minutes)
143
+
144
+ return f'{hours_word} {minutes_word}'
145
+
146
+ # Match time patterns: 12:00, 09:30, 14:45
147
+ text = re.sub(r'\b(\d{1,2}):(\d{2})\b', time_to_words, text)
148
+
149
  # Remove common special characters that don't read well
150
  text = re.sub(r'[<>{}|\[\]\\^~`]', '', text)
151