Process a file in binary mode for cases where text encoding is problematic. Specifically handles UTF-16 encoded files.
(file_path, output_file)
| 155 | return result['encoding'] |
| 156 | |
| 157 | def process_binary_file(file_path, output_file): |
| 158 | """ |
| 159 | Process a file in binary mode for cases where text encoding is problematic. |
| 160 | Specifically handles UTF-16 encoded files. |
| 161 | """ |
| 162 | try: |
| 163 | with open(file_path, 'rb') as f: |
| 164 | content = f.read() |
| 165 | |
| 166 | # Check for UTF-16 LE BOM |
| 167 | if content.startswith(b'\xff\xfe'): |
| 168 | encoding = 'utf-16-le' |
| 169 | content = content[2:] # Skip BOM |
| 170 | # Check for UTF-16 BE BOM |
| 171 | elif content.startswith(b'\xfe\xff'): |
| 172 | encoding = 'utf-16-be' |
| 173 | content = content[2:] # Skip BOM |
| 174 | else: |
| 175 | # Default to UTF-16 LE if no BOM |
| 176 | encoding = 'utf-16-le' |
| 177 | |
| 178 | try: |
| 179 | text = content.decode(encoding) |
| 180 | |
| 181 | # Process lines |
| 182 | lines = text.split('\n') |
| 183 | with open(output_file, 'w', encoding='utf-8') as out: |
| 184 | for line in lines: |
| 185 | if not line.strip(): |
| 186 | continue |
| 187 | |
| 188 | parts = line.strip().split('\t') |
| 189 | if len(parts) != 2: |
| 190 | continue |
| 191 | |
| 192 | url, schema_json_str = parts |
| 193 | site = url.split("/")[2].replace("www.", "").replace(".com", "") |
| 194 | |
| 195 | # Clean up the JSON string - remove ^@ and similar artifacts |
| 196 | json_str = schema_json_str.replace("#N#", ' ').replace('^@', '') |
| 197 | |
| 198 | # Process as normal |
| 199 | try: |
| 200 | schema_json = json.loads(json_str) |
| 201 | # Continue with normal processing |
| 202 | if not isinstance(schema_json, list): |
| 203 | continue |
| 204 | |
| 205 | if isinstance(schema_json[0], list): |
| 206 | schema_json = schema_json[0] |
| 207 | |
| 208 | trimmed_json = [] |
| 209 | for item in schema_json: |
| 210 | try: |
| 211 | trimmed_item = trim_schema_json(item, site) |
| 212 | if trimmed_item is not None: |
| 213 | trimmed_json.append(trimmed_item) |
| 214 | except Exception as e: |
no test coverage detected