|
| 1 | +# This Source Code Form is subject to the terms of the Mozilla Public |
| 2 | +# License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 | +# file, You can obtain one at https://mozilla.org/MPL/2.0/. |
| 4 | + |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | + |
| 8 | +class InstrumentFile: |
| 9 | + """ |
| 10 | + Generic file loader for laboratory text exports. |
| 11 | +
|
| 12 | + Responsibilities |
| 13 | + ---------------- |
| 14 | + - read raw bytes |
| 15 | + - decode using fallback encodings |
| 16 | + - repair known character issues |
| 17 | + - expose text and lines |
| 18 | + - provide small helpers for line-based inspection |
| 19 | + """ |
| 20 | + |
| 21 | + def __init__( |
| 22 | + self, |
| 23 | + file_path, |
| 24 | + encodings=None, |
| 25 | + replacements=None, |
| 26 | + strip_bom=True, |
| 27 | + ): |
| 28 | + # Store the file path as a Path object for reliable cross-platform handling. |
| 29 | + self.file_path = Path(file_path) |
| 30 | + |
| 31 | + # List of encodings to try in order. Many lab instruments export files |
| 32 | + # with Windows-specific encodings (cp1252, latin1) rather than UTF-8. |
| 33 | + # The first encoding that decodes the file without errors is used. |
| 34 | + self.encodings = encodings or [ |
| 35 | + "utf-8", |
| 36 | + "cp1252", |
| 37 | + "latin1", |
| 38 | + "utf-16", |
| 39 | + "utf-16-le", |
| 40 | + "utf-16-be", |
| 41 | + ] |
| 42 | + |
| 43 | + # Character repairs applied after decoding. Some instruments export |
| 44 | + # special characters (e.g. degree sign °) using byte sequences that |
| 45 | + # do not survive encoding conversion cleanly. These replacements fix |
| 46 | + # the most common cases. The order matters: more specific patterns |
| 47 | + # (e.g. "°C") must come before broader ones (e.g. "°") to avoid |
| 48 | + # partial replacements. |
| 49 | + self.replacements = replacements or { |
| 50 | + "": "°", |
| 51 | + "›C": "°C", # cp1252: byte decodes to › before C → °C |
| 52 | + "›": "°", # cp1252: byte decodes to › standalone → ° |
| 53 | + "�C": "°C", # UTF-8 mojibake for degree-Celsius |
| 54 | + "�": "°", # Unicode replacement character U+FFFD → degree sign |
| 55 | + } |
| 56 | + |
| 57 | + # If True, strip the Byte Order Mark (BOM) that some editors and |
| 58 | + # instruments prepend to UTF-8 or UTF-16 files. |
| 59 | + self.strip_bom = strip_bom |
| 60 | + |
| 61 | + # These attributes are populated by read(). |
| 62 | + self.raw_bytes = None # original file content as bytes |
| 63 | + self.text = None # decoded and repaired full text |
| 64 | + self.lines = None # text split into individual lines |
| 65 | + self.used_encoding = None # whichever encoding succeeded |
| 66 | + |
| 67 | + def read(self): |
| 68 | + # Read the entire file as raw bytes first, before any decoding. |
| 69 | + self.raw_bytes = self.file_path.read_bytes() |
| 70 | + |
| 71 | + # Try each encoding in order until one succeeds. |
| 72 | + self.text, self.used_encoding = self._decode_bytes(self.raw_bytes) |
| 73 | + |
| 74 | + # Fix known character encoding artefacts in the decoded text. |
| 75 | + self.text = self._repair_text(self.text) |
| 76 | + |
| 77 | + # Remove a leading BOM character if present (common in UTF-8/16 files). |
| 78 | + if self.strip_bom: |
| 79 | + self.text = self.text.lstrip("") |
| 80 | + |
| 81 | + # Split into lines for line-by-line processing by the parsers. |
| 82 | + self.lines = self.text.splitlines() |
| 83 | + return self |
| 84 | + |
| 85 | + def _decode_bytes(self, raw_bytes): |
| 86 | + last_error = None |
| 87 | + |
| 88 | + # Try each candidate encoding and return on the first success. |
| 89 | + for enc in self.encodings: |
| 90 | + try: |
| 91 | + return raw_bytes.decode(enc), enc |
| 92 | + except UnicodeDecodeError as exc: |
| 93 | + last_error = exc |
| 94 | + |
| 95 | + # None of the encodings worked — raise a descriptive error. |
| 96 | + raise ValueError( |
| 97 | + f"Could not decode file '{self.file_path}' with tried encodings: {self.encodings}" |
| 98 | + ) from last_error |
| 99 | + |
| 100 | + def _repair_text(self, text): |
| 101 | + # Apply each search-and-replace pair from the replacements dict. |
| 102 | + for old, new in self.replacements.items(): |
| 103 | + text = text.replace(old, new) |
| 104 | + return text |
| 105 | + |
| 106 | + def preview(self, start=0, stop=10): |
| 107 | + # Quick inspection helper: return a slice of lines without printing all. |
| 108 | + if self.lines is None: |
| 109 | + raise RuntimeError("Call read() first.") |
| 110 | + return self.lines[start:stop] |
| 111 | + |
| 112 | + def find_first_line(self, startswith=None, contains=None): |
| 113 | + # Search for the first line that matches a prefix or a substring. |
| 114 | + # Returns the line index, or None if no match is found. |
| 115 | + if self.lines is None: |
| 116 | + raise RuntimeError("Call read() first.") |
| 117 | + |
| 118 | + for idx, line in enumerate(self.lines): |
| 119 | + if startswith is not None and line.startswith(startswith): |
| 120 | + return idx |
| 121 | + if contains is not None and contains in line: |
| 122 | + return idx |
| 123 | + return None |
0 commit comments