Spaces:
Sleeping

File size: 12,245 Bytes
0bdce5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53ff096
0bdce5c
 
 
 
53ff096
 
0bdce5c
 
 
 
 
 
 
 
 
53ff096
0bdce5c
 
 
 
 
 
 
53ff096
 
0bdce5c
 
 
 
 
53ff096
 
 
 
 
 
0bdce5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ee10ee
 
 
 
 
 
 
 
0bdce5c
 
 
 
 
 
 
 
 
bc09d91
0bdce5c
 
 
 
 
 
 
 
267e544
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e07887
4d35386
bc09d91
0bdce5c
4e07887
 
 
0bdce5c
 
4e07887
bc09d91
 
 
 
 
 
 
 
 
 
 
0bdce5c
 
 
 
 
 
 
 
 
 
 
 
 
 
a65240a
 
 
0bdce5c
 
 
 
a65240a
 
 
0bdce5c
a65240a
0bdce5c
a65240a
 
 
0bdce5c
a65240a
 
 
 
 
 
 
 
8f0d24c
 
 
 
 
 
 
 
fec5732
8f0d24c
 
 
fec5732
 
 
 
 
 
 
 
 
 
 
 
 
 
8f0d24c
 
 
 
fec5732
 
 
 
 
 
 
 
 
 
 
 
 
 
8f0d24c
 
 
 
 
 
a65240a
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
"""
Name Extraction Utility

Extracts real names from user messages to avoid using nicknames from Telegram/WhatsApp.
Uses regex patterns first (fast), then LLM as fallback.
"""

import re
from typing import Optional
from app.core.logging import get_logger

logger = get_logger(__name__)


async def extract_name_from_message(
    user_text: str,
    llm_client = None,
    use_llm_first: bool = True
) -> Optional[str]:
    """
    Extract real name from user message if they introduce themselves.
    
    Now uses LLM FIRST for accuracy, regex as fast fallback.
    
    Examples:
    - "Привет, я Дмитрий" → "Дмитрий"
    - "My name is Sarah Johnson" → "Sarah Johnson"
    - "Меня зовут Алексей Иванов" → "Алексей Иванов"
    - "Hi, I'm John" → "John"
    
    Args:
        user_text: User's message text
        llm_client: Optional LLM client for AI-based extraction
        use_llm_first: Use LLM as primary method (more accurate)
        
    Returns:
        Extracted name or None if no name found
    """
    if not user_text or len(user_text) < 5:
        return None
    
    # 1. Try LLM first (most accurate)
    if use_llm_first and llm_client:
        name = await _extract_name_with_llm(user_text, llm_client)
        if name:
            logger.info(f"✅ Extracted name via LLM: {name}")
            return name
    
    # 2. Fallback to regex (fast but less accurate)
    name = _extract_name_with_regex(user_text)
    if name:
        logger.info(f"✅ Extracted name via regex: {name}")
        return name
    
    return None


def _extract_name_with_regex(text: str) -> Optional[str]:
    """
    Extract name using regex patterns.
    
    Supports:
    - Russian: "меня зовут X", "я X"
    - English: "my name is X", "I'm X", "I am X"
    - Common patterns: "это X", "this is X"
    """
    # Russian patterns
    russian_patterns = [
        r"меня зовут ([А-ЯЁA-Z][а-яёa-z]+(?:\s+[А-ЯЁA-Z][а-яёa-z]+)?)",
        r"зовут меня ([А-ЯЁA-Z][а-яёa-z]+(?:\s+[А-ЯЁA-Z][а-яёa-z]+)?)",
        r"я\s+([А-ЯЁA-Z][а-яёa-z]+(?:\s+[А-ЯЁA-Z][а-яёa-z]+)?)[,\.]",
        r"это\s+([А-ЯЁA-Z][а-яёa-z]+(?:\s+[А-ЯЁA-Z][а-яёa-z]+)?)",
        r"имя\s+([А-ЯЁA-Z][а-яёa-z]+(?:\s+[А-ЯЁA-Z][а-яёa-z]+)?)",
    ]
    
    # English patterns
    english_patterns = [
        r"my name is ([A-Z][a-z]+(?:\s+[A-Z][a-z]+)?)",
        r"i'm ([A-Z][a-z]+(?:\s+[A-Z][a-z]+)?)",
        r"i am ([A-Z][a-z]+(?:\s+[A-Z][a-z]+)?)",
        r"this is ([A-Z][a-z]+(?:\s+[A-Z][a-z]+)?)",
        r"call me ([A-Z][a-z]+(?:\s+[A-Z][a-z]+)?)",
    ]
    
    all_patterns = russian_patterns + english_patterns
    
    for pattern in all_patterns:
        match = re.search(pattern, text, re.IGNORECASE)
        if match:
            name = match.group(1).strip()
            # Validate name (not too long, not empty)
            if 2 <= len(name) <= 50 and not _is_invalid_name(name):
                return name
    
    return None


def _is_invalid_name(name: str) -> bool:
    """Check if extracted string is likely not a real name."""
    invalid_words = [
        # Common non-names
        "привет", "hello", "здравствуйте", "спасибо", "thanks",
        "пожалуйста", "please", "интересно", "хочу", "want",
        "нужно", "need", "можно", "можете", "can", "could",
        # Telegram artifacts
        "telegram", "username", "user", "client", "клиент",
        # Verbs and phrases that start with capital after "я"
        "демонстрирую", "показываю", "представляю", "описываю", 
        "рассказываю", "объясняю", "уточняю", "спрашиваю",
        "работаю", "живу", "учусь", "занимаюсь", "ищу",
        "хотел", "хотела", "думаю", "считаю", "понимаю",
        # Common words that look like names
        "экспертность", "качество", "сервис", "услуга", "товар",
        "продукт", "заказ", "доставка", "оплата", "цена",
    ]
    
    name_lower = name.lower()
    return any(word in name_lower for word in invalid_words)


async def _extract_name_with_llm(text: str, llm_client) -> Optional[str]:
    """
    Use LLM to extract name from text.
    Only used as fallback when regex fails or for higher accuracy.
    """
    try:
        # Import here to avoid circular dependency
        from app.services.llm_client import get_llm_client
        
        if not llm_client:
            llm_client = get_llm_client()
        
        prompt = f"""Ты - система извлечения имён. ОЧЕНЬ СТРОГО определи, представился ли человек.

ИЗВЛЕКАЙ ИМЯ ТОЛЬКО если человек ЯВНО представился одной из этих фраз:
- "Меня зовут [ИМЯ]"
- "Я [ИМЯ]" (в начале предложения как представление)
- "Мое имя [ИМЯ]"
- "Это [ИМЯ]" (как представление себя)
- "My name is [NAME]"
- "I'm [NAME]" / "I am [NAME]"

⚠️ НЕ ИЗВЛЕКАЙ ИМЯ в следующих случаях:
- Человек просто отвечает на вопрос: "Да", "Нет", "Хорошо", "Ладно"
- Человек пишет ЛЮБОЙ текст без явного представления
- Человек пишет что хочет: "Хочу заказать", "Интересует продукт"
- Названия городов, товаров, компаний
- Глаголы и действия: "Я думаю", "Я хочу", "Я работаю"
- Вопросы: "А вы?", "Какие цены?"
- Никнеймы и юзернеймы

ПРИМЕРЫ:
"Привет, меня зовут Анна" → Анна ✅
"Я Дмитрий, хочу узнать цены" → Дмитрий ✅
"Да, хочу заказать" → NONE ✅
"Интересно, расскажите" → NONE ✅
"Алматы" → NONE ✅ (это город, НЕ имя)
"Нравится" → NONE ✅
"Супер" → NONE ✅
"Я работаю в IT" → NONE ✅ (это не представление)
"Хорошо" → NONE ✅

Сообщение: "{text[:300]}"

Если человек НЕ представился ЯВНО — верни NONE.
Ответ (ТОЛЬКО имя или NONE):"""
        
        response = await llm_client.generate_text(prompt, max_output_tokens=20)
        extracted = response.strip().strip('"').strip("'").strip(".")
        
        # Clean up response
        if extracted.startswith("Ответ:"):
            extracted = extracted[6:].strip()
        
        # Validate LLM response
        if extracted and extracted.upper() != "NONE" and 2 <= len(extracted) <= 50:
            # Check if it's just a common word or verb
            if _is_invalid_name(extracted):
                logger.info(f"🚫 LLM extracted invalid name (discarded): {extracted}")
                return None
                
            if extracted.startswith("@") or any(c.isdigit() for c in extracted):
                logger.info(f"🚫 LLM extracted nickname/illegal chars (discarded): {extracted}")
                return None

            logger.info(f"🧠 LLM extracted name: {extracted}")
            return extracted
    
    except Exception as e:
        logger.error(f"LLM name extraction failed: {e}")
    
    return None


def should_update_lead_name(current_name: str, extracted_name: str) -> bool:
    """
    Determine if we should update the lead's name with extracted name.
    
    Only update if:
    - Current name is empty/None
    - Current name looks like a Telegram username (@xxx)
    - Current name is generic (User, Client, etc.)
    - Current name is ALL CAPS (likely Telegram display name)
    - Extracted name is a "better" real name
    """
    if not current_name:
        return True
    
    if not extracted_name or len(extracted_name) < 2:
        return False
    
    current_lower = current_name.lower().strip()
    current_stripped = current_name.strip()
    
    # Always update if current name starts with @
    if current_stripped.startswith("@"):
        return True
    
    # Update if current name is ALL CAPS (Telegram nickname like "AXERON")
    if current_stripped.isupper() and len(current_stripped) > 2:
        return True
    
    # Update if current name has numbers or special chars (nickname-like)
    if any(c.isdigit() for c in current_stripped) or any(c in "_-." for c in current_stripped):
        return True
    
    # NEW: Detect Telegram-style nicknames
    # Pattern 1: Single letter + word (e.g., "G Scream", "J Smith", "V Lord")
    words = current_stripped.split()
    if len(words) == 2 and len(words[0]) == 1 and words[0].isupper():
        return True
    
    # Pattern 2: CamelCase or single English words that look like nicknames
    english_nickname_patterns = [
        # Gaming/fantasy terms
        "scream", "lord", "king", "queen", "dark", "night", "wolf", "dragon",
        "fire", "ice", "shadow", "phantom", "ghost", "storm", "blade", "star",
        "moon", "sun", "sky", "master", "boss", "pro", "gamer", "hacker",
        "ninja", "samurai", "snake", "eagle", "lion", "tiger", "bear", "fox",
        # More common gaming terms
        "killer", "sniper", "hunter", "warrior", "knight", "devil", "demon",
        "angel", "death", "blood", "rage", "fury", "chaos", "doom", "dark",
        "black", "white", "red", "blue", "gold", "silver", "crystal", "diamond",
        "cyber", "neo", "max", "ultra", "mega", "super", "hyper", "alpha", "omega",
        # Tech/coding terms used as nicknames  
        "dev", "code", "byte", "pixel", "hack", "root", "sudo", "admin", "mod",
        # Common English nickname suffixes/prefixes
        "mr", "mrs", "miss", "the", "just", "only", "real", "official",
        # Abstract concepts
        "dream", "love", "soul", "spirit", "mind", "heart", "life", "hope",
        # Common random words used as nicknames
        "banana", "apple", "cat", "dog", "panda", "bunny", "kitty", "puppy",
    ]
    if any(pattern in current_lower for pattern in english_nickname_patterns):
        return True
    
    # Pattern 3: Name is entirely in English/Latin but too "nickname-like"
    # Single English word (no spaces) that doesn't look like a real name
    if len(words) == 1 and len(current_stripped) > 3:
        # Single word, all ASCII, check if it looks like a real name or nickname
        if all('a' <= c.lower() <= 'z' for c in current_stripped):
            # Real first names usually: start uppercase, rest lowercase, 3-10 chars
            # Nicknames often: all lowercase, weird capitalizations, or very long
            if current_stripped.islower() or current_stripped.isupper():
                return True  # All lower or all upper = nickname
            # Mixed case that's not proper title case (like "JohnDoe" or "xXnameXx")
            if not current_stripped.istitle() and len(current_stripped) > 6:
                return True
    
    # Pattern 4: Contains ASCII letters but not Cyrillic (likely English nickname for Russian context)
    has_ascii = any('a' <= c.lower() <= 'z' for c in current_stripped)
    has_cyrillic = any('\u0400' <= c <= '\u04FF' for c in current_stripped)
    # If name is only in English but we're in Russian context (extracted name is Cyrillic), update
    if has_ascii and not has_cyrillic and any('\u0400' <= c <= '\u04FF' for c in extracted_name):
        return True
    
    # Update if current is generic
    generic_names = ["user", "client", "lead", "пользователь", "клиент", "лид", "unknown", "неизвестно"]
    if any(generic in current_lower for generic in generic_names):
        return True
    
    # Update if current is single very short word (< 3 chars) like "Al" vs "Alex"
    if len(current_stripped) < 3 and len(extracted_name) >= 3:
        return True
    
    return False