""" Encoding detection and normalization for text files. Handles the messy reality of 20 years of web-generated data with mixed encodings, mojibake, and partial writes containing null bytes. """ from pathlib import Path from typing import Optional, Tuple, List import chardet import ftfy from ..core.base_classes import BaseCleaner from ..core.config import Config from ..core.errata_logger import ErrataLogger from ..core.exceptions import EncodingError class EncodingCleaner(BaseCleaner): """ Detects and normalizes file encodings. Handles: - Automatic encoding detection using chardet - Fallback to candidate encodings - Mojibake correction using ftfy - Null byte removal from partial writes - Normalization to UTF-8 """ def __init__(self, config: Config, errata_logger: Optional[ErrataLogger] = None): """ Initialize encoding cleaner. Args: config: Configuration object errata_logger: Optional errata logger for error tracking """ super().__init__(config, errata_logger) # Get configuration self.candidate_encodings: List[str] = config.get( 'encoding.candidate_encodings', ['utf-8', 'latin-1', 'windows-1252', 'iso-8859-1'] ) self.confidence_threshold: float = config.get( 'encoding.confidence_threshold', 0.7 ) self.fix_mojibake: bool = config.get('encoding.fix_mojibake', True) def detect_encoding( self, file_path: str | Path, sample_size: int = 100000 ) -> Tuple[str, float]: """ Detect file encoding using chardet. Args: file_path: Path to file sample_size: Number of bytes to sample for detection Returns: Tuple of (encoding, confidence) Raises: EncodingError: If encoding cannot be detected """ file_path = Path(file_path) try: with open(file_path, 'rb') as f: raw_data = f.read(sample_size) # Remove null bytes before detection raw_data = raw_data.replace(b'\x00', b'') if not raw_data: raise EncodingError(f"File is empty or contains only null bytes: {file_path}") result = chardet.detect(raw_data) encoding = result['encoding'] confidence = result['confidence'] if encoding is None: raise EncodingError(f"Could not detect encoding for {file_path}") return encoding, confidence except IOError as e: raise EncodingError(f"Failed to read file {file_path}: {e}") def read_with_encoding( self, file_path: str | Path, encoding: str, remove_null_bytes: bool = True ) -> str: """ Read file with specified encoding. Args: file_path: Path to file encoding: Encoding to use remove_null_bytes: Whether to remove null bytes Returns: Decoded text content Raises: EncodingError: If reading with encoding fails """ file_path = Path(file_path) try: with open(file_path, 'rb') as f: raw_data = f.read() # Remove null bytes from partial writes if remove_null_bytes: raw_data = raw_data.replace(b'\x00', b'') # Decode with specified encoding text = raw_data.decode(encoding, errors='strict') return text except UnicodeDecodeError as e: raise EncodingError( f"Failed to decode {file_path} with {encoding}: {e}" ) except IOError as e: raise EncodingError(f"Failed to read file {file_path}: {e}") def clean( self, data: str | Path, file_path: Optional[str] = None, **kwargs ) -> str: """ Clean encoding of text data or file. Args: data: Either file path or text string to clean file_path: Optional file path for error logging **kwargs: Additional parameters Returns: Cleaned UTF-8 text Raises: EncodingError: If encoding cannot be resolved """ # If data is a path, read the file if isinstance(data, (str, Path)) and Path(data).is_file(): file_path = str(data) data, was_utf8 = self._read_file_smart_tagged(Path(data)) elif not isinstance(data, str): raise EncodingError(f"Invalid data type: {type(data)}") else: was_utf8 = False # Fast path: if file decoded as UTF-8, skip ftfy and round-trip # Normalize all line endings: CRLF -> LF, then bare CR -> LF # (some files have mixed line endings, e.g. card190309.dat, loc020520.dat) if was_utf8: return data.replace('\r\n', '\n').replace('\r', '\n') # Slow path: fix mojibake and normalize if self.fix_mojibake: try: data = ftfy.fix_text(data) except Exception as e: self.log_error( 'mojibake_fix_failed', f"Failed to fix mojibake: {e}", file_path=file_path ) # Normalize to UTF-8, logging any characters that get replaced encoded = data.encode('utf-8', errors='replace') replacement_count = encoded.count(b'\xef\xbf\xbd') # UTF-8 bytes of U+FFFD if replacement_count > 0: self.log_error( 'utf8_replacement_chars', f"{replacement_count} character(s) replaced with U+FFFD during UTF-8 normalization", file_path=file_path ) data = encoded.decode('utf-8') # Normalize line endings (same as fast path) data = data.replace('\r\n', '\n').replace('\r', '\n') return data def _read_file_smart_tagged(self, file_path: Path) -> Tuple[str, bool]: """ Read file and return (text, was_utf8). When was_utf8=True, the file decoded cleanly as UTF-8 and the caller can skip expensive ftfy/mojibake processing (just strip CR). """ try: with open(file_path, 'rb') as f: raw_data = f.read() raw_data = raw_data.replace(b'\x00', b'') if not raw_data: raise EncodingError(f"File is empty or contains only null bytes: {file_path}") try: return raw_data.decode('utf-8'), True except UnicodeDecodeError: pass # Fall through — need slow path for non-UTF-8 except IOError: pass # Non-UTF-8 or IO error: use full smart reader return self._read_file_smart(file_path), False def _read_file_smart(self, file_path: Path) -> str: """ Read file with intelligent encoding detection and fallback. Tries: 1. Fast path: UTF-8 decode (covers ~99% of files) 2. Fast fallback: latin-1 decode (covers remaining) 3. Slow path: chardet detection (only if fast paths produce issues) Args: file_path: Path to file Returns: Decoded text Raises: EncodingError: If all attempts fail """ last_error = None # Fast path: try UTF-8 directly, fallback to latin-1 # Profiling shows ~99% of files are ASCII/UTF-8 compatible. # This avoids expensive chardet detection for the common case. try: with open(file_path, 'rb') as f: raw_data = f.read() raw_data = raw_data.replace(b'\x00', b'') if not raw_data: raise EncodingError(f"File is empty or contains only null bytes: {file_path}") try: return raw_data.decode('utf-8') except UnicodeDecodeError: return raw_data.decode('latin-1') except (IOError, EncodingError): pass # Fall through to slow path # Slow path: Try automatic detection with chardet try: encoding, confidence = self.detect_encoding(file_path) # Skip ASCII if detected - it's too restrictive, try UTF-8 or latin-1 instead if encoding and encoding.lower() != 'ascii': if confidence >= self.confidence_threshold: text = self.read_with_encoding(file_path, encoding) return text else: self.log_error( 'low_confidence_encoding', f"Low confidence ({confidence:.2f}) for detected encoding {encoding}", file_path=str(file_path) ) except EncodingError as e: last_error = str(e) self.log_error( 'encoding_detection_failed', str(e), file_path=str(file_path) ) # Try candidate encodings in order # Prioritize more permissive encodings for problematic files for encoding in self.candidate_encodings: try: text = self.read_with_encoding(file_path, encoding) # Log which fallback encoding worked if last_error: self.log_error( 'encoding_fallback_success', f"Successfully read with {encoding} after detection failed", file_path=str(file_path) ) return text except EncodingError as e: last_error = str(e) continue # Last resort: latin-1 (never fails, so validate the result) self.log_error( 'encoding_fallback', f"All encodings failed, falling back to latin-1", file_path=str(file_path) ) try: text = self.read_with_encoding(file_path, 'latin-1') except EncodingError as e: raise EncodingError( f"Fatal: Could not read {file_path} even with latin-1: {e}" ) # Sanity check: latin-1 accepts any byte sequence, so a binary/corrupt # file will decode without error into garbage. Reject if the result # has a high ratio of control characters (excluding \t, \n, \r). if text: control_chars = sum( 1 for ch in text if ch < ' ' and ch not in ('\t', '\n', '\r') ) ratio = control_chars / len(text) if ratio > 0.05: self.log_error( 'encoding_garbage_detected', f"latin-1 fallback produced {ratio:.1%} control characters — file appears corrupt", file_path=str(file_path) ) raise EncodingError( f"File appears corrupt (latin-1 decoded to {ratio:.1%} control chars): {file_path}" ) return text def clean_batch( self, file_paths: List[str | Path] ) -> List[Tuple[str, str]]: """ Clean encoding for a batch of files. Args: file_paths: List of file paths to process Returns: List of tuples (file_path, cleaned_text) """ results = [] for file_path in file_paths: try: cleaned = self.clean(file_path) results.append((str(file_path), cleaned)) except EncodingError as e: self.log_error( 'batch_encoding_failed', str(e), file_path=str(file_path) ) # Continue processing other files return results