File size: 3,576 Bytes
92d2175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Text Tool - Xử lý câu hỏi viết ngược
"""

from typing import Dict, Any

def reverse_text(text: str) -> str:
    """
    Đảo ngược text
    """
    return text[::-1]

def is_likely_reversed(text: str) -> bool:
    """
    Kiểm tra xem text có khả năng bị viết ngược không
    Dựa trên các dấu hiệu:
    - Câu kết thúc bằng dấu phẩy thay vì dấu chấm hỏi
    - Có từ "rewsna" (answer ngược)
    - Có từ kết thúc bằng các ký tự đặc biệt
    """
    # Dấu hiệu câu hỏi viết ngược
    reverse_indicators = [
        "rewsna",  # "answer" ngược
        "noitseuq",  # "question" ngược  
        "ecnetnes",  # "sentence" ngược
        "dnatsrednu",  # "understand" ngược
        "etirw",  # "write" ngược
        text.strip().endswith(","),  # Kết thúc bằng dấu phẩy
        text.strip().startswith("?"),  # Bắt đầu bằng dấu hỏi
    ]
    
    # Đếm số dấu hiệu
    indicators_found = sum([
        1 for indicator in reverse_indicators 
        if (isinstance(indicator, str) and indicator.lower() in text.lower()) or 
           (isinstance(indicator, bool) and indicator)
    ])
    
    # Nếu có >= 2 dấu hiệu thì có thể là text ngược
    return indicators_found >= 2

def reverse_text_if_needed(question: str, ai_brain=None) -> Dict[str, Any]:
    """
    Main function: Kiểm tra và cung cấp thông tin về câu hỏi có thể bị viết ngược
    
    Args:
        question: Câu hỏi gốc
        ai_brain: AI brain instance để hỏi lại (optional)
        
    Returns:
        Dict chứa thông tin phân tích text
    """
    analysis = {
        "original_text": question,
        "reversed_text": reverse_text(question),
        "likely_reversed": is_likely_reversed(question),
        "should_reverse": False,
        "processed_text": question
    }
    
    # Nếu có dấu hiệu bị viết ngược
    if analysis["likely_reversed"]:
        print(f"🔄 Detected likely reversed text: {question[:50]}...")
        
        # Nếu có AI brain, hỏi AI quyết định
        if ai_brain:
            check_prompt = f"""
            Original: {question}
            Reversed: {analysis["reversed_text"]}
            
            Which version makes more sense as a question? Answer "original" or "reversed" only.
            """
            try:
                ai_response = ai_brain.think(check_prompt).strip().lower()
                analysis["should_reverse"] = "reversed" in ai_response
                analysis["ai_decision"] = ai_response
            except:
                # Fallback nếu AI không hoạt động
                analysis["should_reverse"] = True
                analysis["ai_decision"] = "fallback_reverse"
        else:
            # Không có AI, AI sẽ quyết định sau
            analysis["should_reverse"] = None  # Để AI quyết định
        
        if analysis["should_reverse"]:
            analysis["processed_text"] = analysis["reversed_text"]
            print(f"🔄 Reversed to: {analysis['reversed_text'][:50]}...")
    
    return analysis

# Test function
if __name__ == "__main__":
    # Test case từ đề bài
    test_question = ".rewsna eht sa \"tfel\" drow eht fo etisoppo eht etirw ,ecnetnes siht dnatsrednu uoy fI"
    
    print("Original:", test_question)
    print("Is likely reversed:", is_likely_reversed(test_question))
    
    analysis = reverse_text_if_needed(test_question)
    print("Analysis:", analysis)