Spaces:
Running

File size: 3,189 Bytes
8edb0d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9aa757
 
8edb0d5
e9aa757
8edb0d5
 
 
 
e9aa757
8edb0d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
AI Summary Validator - prevents saving broken/invalid summaries
"""
from typing import Dict, Any, List, Tuple
from app.core.logging import get_logger

logger = get_logger(__name__)

# Error indicators that suggest invalid data
ERROR_PATTERNS = [
    'error', 'failed', 'undefined', 'null', 'none',  
    'n/a', 'unknown error', 'exception', 'invalid',
    'generation error', 'summary generation error'
]

REQUIRED_FIELDS = ['intent', 'budget', 'timeline', 'authority', 'psychotype', 'heat_score']


def validate_summary(summary: Dict[str, Any]) -> Tuple[bool, List[str]]:
    """
    Validate AI summary for quality and correctness.
    
    Returns:
        (is_valid, list_of_errors)
    """
    errors = []
    
    # Check all required fields exist
    for field in REQUIRED_FIELDS:
        if field not in summary:
            errors.append(f"Missing required field: {field}")
    
    if errors:
        return False, errors
    
    # Check text fields don't contain error indicators
    text_fields = ['intent', 'budget', 'timeline', 'authority',  
                   'hidden_signals', 'recommendation', 'draft_reply']
    
    for field in text_fields:
        value = str(summary.get(field, '')).lower()
        
        # Skip if field is intentionally empty or unavailable
        if not value or value in ['не указано', 'неизвестно', 'требуется', 'будет уточнено']:
            continue
            
        # Check for error patterns
        for pattern in ERROR_PATTERNS:
            if pattern in value:
                errors.append(f"Field '{field}' contains error indicator: '{pattern}'")
                break
    
    # Validate heat_score range
    heat_score = summary.get('heat_score')
    if not isinstance(heat_score, (int, float)) or not (0 <= heat_score <= 100):
        errors.append(f"Invalid heat_score: {heat_score} (must be 0-100)")
    
    # Psychotype validation removed - Gemini returns Russian values as instructed
    # Accept both English and Russian psychotypes
    
    # Don't fail on empty pain_points - "Будет уточнено" is valid placeholder
    
    is_valid = len(errors) == 0
    
    if not is_valid:
        logger.warning(f"⚠️ Summary validation failed: {errors}")
    
    return is_valid, errors


def should_update_summary(old_summary: Dict[str, Any], new_summary: Dict[str, Any]) -> bool:
    """
    Determine if new summary is better than old one.
    Don't replace good data with bad data.
    """
    # If old summary doesn't exist, always update
    if not old_summary:
        return True
    
    # Validate both summaries
    new_valid, new_errors = validate_summary(new_summary)
    old_valid, old_errors = validate_summary(old_summary)
    
    # Keep old if new is invalid and old is valid
    if old_valid and not new_valid:
        logger.info(f"⚠️ Keeping old summary (new one is invalid)")
        return False
    
    # Replace old invalid with new valid
    if not old_valid and new_valid:
        logger.info(f"✅ Replacing invalid old summary with new valid one")
        return True
    
    # Both valid or both invalid - update
    return True