Spaces:
Running on Zero

File size: 2,211 Bytes
77da222
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Data preprocessing module for Customer Complaint Sentiment Detection.

Responsible for cleaning text:
- Lowercasing
- URL, HTML tag, and special punctuation removal
- Whitespace normalization
- Edge case handling (None, empty, non-string, very long strings)
"""

from __future__ import annotations

import re
import string
import sys
from pathlib import Path
from typing import Any

# Ensure project root is in sys.path
PROJECT_ROOT = Path(__file__).resolve().parent.parent
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

# Pre-compiled regular expressions for fast performance
URL_PATTERN = re.compile(r"https?://\S+|www\.\S+", re.IGNORECASE)
HTML_PATTERN = re.compile(r"<[^>]+>", re.IGNORECASE)
EMAIL_PATTERN = re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b")
MULTISPACE_PATTERN = re.compile(r"\s+")
MAX_TEXT_LENGTH = 10000


def clean_text(text: Any, max_len: int = MAX_TEXT_LENGTH) -> str:
    """Clean and normalize raw customer complaint text.

    Args:
        text: Raw input string or arbitrary type.
        max_len: Maximum length threshold to avoid memory/DOS issues.

    Returns:
        Cleaned, lowercased, and normalized string. Returns empty string for invalid inputs.
    """
    if text is None:
        return ""

    if not isinstance(text, str):
        text = str(text)

    # Strip initial whitespace
    text = text.strip()
    if not text:
        return ""

    # Truncate defensively if text exceeds max length
    if len(text) > max_len:
        text = text[:max_len]

    # Convert to lowercase
    text = text.lower()

    # Remove URLs
    text = URL_PATTERN.sub(" ", text)

    # Remove HTML tags
    text = HTML_PATTERN.sub(" ", text)

    # Remove email addresses
    text = EMAIL_PATTERN.sub(" ", text)

    # Remove standard punctuation while keeping words and spaces
    # Replacing punctuation with spaces prevents tokens from merging together
    punctuation_translator = str.maketrans(string.punctuation, " " * len(string.punctuation))
    text = text.translate(punctuation_translator)

    # Normalize multiple whitespace characters and strip
    text = MULTISPACE_PATTERN.sub(" ", text).strip()

    return text