File size: 12,000 Bytes
9deebf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
"""
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