Spaces:
Running on Zero

MyNewWebSite / data /preprocess.py
SHADOWMONARCK097's picture
Deploy Customer Complaint Sentiment FastAPI Docker backend
77da222 verified
Raw History Blame Contribute Delete
2.21 kB
"""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