File size: 5,448 Bytes
1e9a96d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from smolagents import Tool
from typing import Dict, Optional, Any
import logging

logger = logging.getLogger(__name__)


class TextCleanerTool(Tool):
    name = "clean_text"
    description = (
        "Cleans and normalizes text by removing or replacing unwanted elements"
    )
    inputs = {
        "text": {"type": "string", "description": "The input text to clean"},
        "fix_unicode": {
            "type": "boolean",
            "description": "Fix broken unicode characters and mojibake",
            "default": True,
        },
        "to_ascii": {
            "type": "boolean",
            "description": "Convert non-ASCII characters to their closest ASCII equivalents",
            "default": True,
        },
        "lower": {
            "type": "boolean",
            "description": "Convert text to lowercase",
            "default": True,
        },
        "no_line_breaks": {
            "type": "boolean",
            "description": "Replace line breaks with spaces",
            "default": False,
        },
        "no_urls": {
            "type": "boolean",
            "description": "Replace URLs with a token",
            "default": False,
        },
        "no_emails": {
            "type": "boolean",
            "description": "Replace email addresses with a token",
            "default": False,
        },
        "no_phone_numbers": {
            "type": "boolean",
            "description": "Replace phone numbers with a token",
            "default": False,
        },
        "no_numbers": {
            "type": "boolean",
            "description": "Replace all numbers with a token",
            "default": False,
        },
        "no_digits": {
            "type": "boolean",
            "description": "Replace all digits with 0",
            "default": False,
        },
        "no_currency_symbols": {
            "type": "boolean",
            "description": "Replace currency symbols with a token",
            "default": False,
        },
        "no_punct": {
            "type": "boolean",
            "description": "Remove all punctuation",
            "default": False,
        },
        "no_emoji": {
            "type": "boolean",
            "description": "Remove all emoji characters",
            "default": False,
        },
        "lang": {
            "type": "string",
            "description": "Language code for special handling ('en' or 'de' supported)",
            "default": "en",
        },
        "custom_replacements": {
            "type": "object",
            "description": "Dictionary of custom string replacements to apply",
            "optional": True,
        },
    }
    output_type = "string"

    def forward(
        self,
        text: str,
        fix_unicode: bool = True,
        to_ascii: bool = True,
        lower: bool = True,
        no_line_breaks: bool = False,
        no_urls: bool = False,
        no_emails: bool = False,
        no_phone_numbers: bool = False,
        no_numbers: bool = False,
        no_digits: bool = False,
        no_currency_symbols: bool = False,
        no_punct: bool = False,
        no_emoji: bool = False,
        lang: str = "en",
        custom_replacements: Optional[Dict[str, str]] = None,
    ) -> str:
        """Clean and normalize text by removing or replacing unwanted elements."""
        # Input validation
        if not text:
            return ""

        if not isinstance(text, str):
            try:
                text = str(text)
            except Exception as e:
                logger.error(f"Failed to convert input to string: {e}")
                return f"Error: Could not process input of type {type(text)}"

        # Import cleantext safely
        try:
            from cleantext import clean
        except ImportError:
            logger.error(
                "cleantext package not installed. Install with: pip install clean-text"
            )
            return "Error: Required dependency 'clean-text' is not installed."

        # Special parameter handling
        replace_params = {
            "replace_with_url": "<URL>",
            "replace_with_email": "<EMAIL>",
            "replace_with_phone_number": "<PHONE>",
            "replace_with_number": "<NUMBER>",
            "replace_with_digit": "0",
            "replace_with_currency_symbol": "<CUR>",
            "replace_with_punct": "",
        }

        try:
            # Apply cleantext with parameters
            cleaned_text = clean(
                text,
                fix_unicode=fix_unicode,
                to_ascii=to_ascii,
                lower=lower,
                no_line_breaks=no_line_breaks,
                no_urls=no_urls,
                no_emails=no_emails,
                no_phone_numbers=no_phone_numbers,
                no_numbers=no_numbers,
                no_digits=no_digits,
                no_currency_symbols=no_currency_symbols,
                no_punct=no_punct,
                no_emoji=no_emoji,
                lang=lang,
                **replace_params,
            )

            # Apply any custom replacements
            if custom_replacements:
                for old, new in custom_replacements.items():
                    cleaned_text = cleaned_text.replace(old, new)

            return cleaned_text

        except Exception as e:
            logger.error(f"Error cleaning text: {e}")
            return f"Error during text cleaning: {str(e)}"