| """ |
| 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) |
|
|
| |
| 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) |
|
|
| |
| 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() |
|
|
| |
| if remove_null_bytes: |
| raw_data = raw_data.replace(b'\x00', b'') |
|
|
| |
| 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 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 |
|
|
| |
| |
| |
| if was_utf8: |
| return data.replace('\r\n', '\n').replace('\r', '\n') |
|
|
| |
| 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 |
| ) |
|
|
| |
| encoded = data.encode('utf-8', errors='replace') |
| replacement_count = encoded.count(b'\xef\xbf\xbd') |
| 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') |
|
|
| |
| 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 |
| except IOError: |
| pass |
|
|
| |
| 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 |
|
|
| |
| |
| |
| 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 |
|
|
| |
| try: |
| encoding, confidence = self.detect_encoding(file_path) |
|
|
| |
| 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) |
| ) |
|
|
| |
| |
| for encoding in self.candidate_encodings: |
| try: |
| text = self.read_with_encoding(file_path, encoding) |
| |
| 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 |
|
|
| |
| 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}" |
| ) |
|
|
| |
| |
| |
| 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) |
| ) |
| |
|
|
| return results |