Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/charset_normalizer/utils.py: 43%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

230 statements  

1from __future__ import annotations 

2 

3import importlib 

4import logging 

5import unicodedata 

6from bisect import bisect_right 

7from codecs import IncrementalDecoder 

8from typing import Generator 

9 

10from .constant import ( 

11 ENCODING_MARKS, 

12 IANA_SUPPORTED_SIMILAR, 

13 RE_POSSIBLE_ENCODING_INDICATION, 

14 UNICODE_RANGES_COMBINED, 

15 _SECONDARY_RANGE_NAMES, 

16 COMMON_CJK_CHARACTERS, 

17 _LATIN, 

18 _CJK, 

19 _HANGUL, 

20 _KATAKANA, 

21 _HIRAGANA, 

22 _HALFWIDTH_KATAKANA, 

23 _THAI, 

24 _ARABIC, 

25 _ARABIC_ISOLATED_FORM, 

26 _LIGATURE, 

27 _SUPERSCRIPT, 

28 _SENTENCE_OPEN_PUNCTUATION, 

29 _ACCENT_KEYWORDS, 

30 _ACCENTUATED, 

31 _KNOWN_MB_DECODERS, 

32 _SINGLE_BYTE_DECODERS, 

33 _IANA_NAMES, 

34 _MULTIBYTE_SEARCH_RADIUS, 

35) 

36 

37 

38def _character_flags(character: str) -> int: 

39 """Compute all name-based classification flags with a single unicodedata.name() call.""" 

40 try: 

41 desc: str = unicodedata.name(character) 

42 except ValueError: 

43 return 0 

44 

45 if desc.startswith(("CJK UNIFIED IDEOGRAPH-", "CJK COMPATIBILITY IDEOGRAPH-")): 

46 return _CJK 

47 if desc.startswith("HANGUL SYLLABLE "): 

48 return _HANGUL 

49 

50 flags: int = 0 

51 

52 if "LATIN" in desc: 

53 flags |= _LATIN 

54 if "CJK" in desc: 

55 flags |= _CJK 

56 if "HANGUL" in desc: 

57 flags |= _HANGUL 

58 if "KATAKANA" in desc: 

59 flags |= _KATAKANA 

60 if "HALFWIDTH" in desc: 

61 flags |= _HALFWIDTH_KATAKANA 

62 if "HIRAGANA" in desc: 

63 flags |= _HIRAGANA 

64 if "THAI" in desc: 

65 flags |= _THAI 

66 if "ARABIC" in desc: 

67 flags |= _ARABIC 

68 if "ISOLATED FORM" in desc: 

69 flags |= _ARABIC_ISOLATED_FORM 

70 if "LIGATURE" in desc or desc.endswith("LETTER AE"): 

71 flags |= _LIGATURE 

72 if "SUPERSCRIPT" in desc: 

73 flags |= _SUPERSCRIPT 

74 if desc in {"INVERTED QUESTION MARK", "INVERTED EXCLAMATION MARK"}: 

75 flags |= _SENTENCE_OPEN_PUNCTUATION 

76 

77 for kw in _ACCENT_KEYWORDS: 

78 if kw in desc: 

79 flags |= _ACCENTUATED 

80 break 

81 

82 return flags 

83 

84 

85def is_accentuated(character: str) -> bool: 

86 return bool(_character_flags(character) & _ACCENTUATED) 

87 

88 

89def remove_accent(character: str) -> str: 

90 decomposed: str = unicodedata.decomposition(character) 

91 if not decomposed: 

92 return character 

93 

94 codes: list[str] = decomposed.split(" ") 

95 

96 return chr(int(codes[0], 16)) 

97 

98 

99# Pre-built sorted lookup table for O(log n) binary search in unicode_range(). 

100# Each entry is (range_start, range_end_exclusive, range_name). 

101_UNICODE_RANGES_SORTED: list[tuple[int, int, str]] = sorted( 

102 (ord_range.start, ord_range.stop, name) 

103 for name, ord_range in UNICODE_RANGES_COMBINED.items() 

104) 

105_UNICODE_RANGE_STARTS: list[int] = [e[0] for e in _UNICODE_RANGES_SORTED] 

106 

107 

108def unicode_range(character: str) -> str | None: 

109 """ 

110 Retrieve the Unicode range official name from a single character. 

111 """ 

112 character_ord: int = ord(character) 

113 

114 if character_ord < 32: 

115 return "Control character" 

116 if character_ord < 128: 

117 return "Basic Latin" 

118 

119 # Binary search: find the rightmost range whose start <= character_ord 

120 idx = bisect_right(_UNICODE_RANGE_STARTS, character_ord) - 1 

121 if idx >= 0: 

122 start, stop, name = _UNICODE_RANGES_SORTED[idx] 

123 if character_ord < stop: 

124 return name 

125 

126 return None 

127 

128 

129def is_latin(character: str) -> bool: 

130 return bool(_character_flags(character) & _LATIN) 

131 

132 

133def is_punctuation(character: str) -> bool: 

134 character_category: str = unicodedata.category(character) 

135 

136 if "P" in character_category: 

137 return True 

138 

139 character_range: str | None = unicode_range(character) 

140 

141 if character_range is None: 

142 return False 

143 

144 return "Punctuation" in character_range 

145 

146 

147def is_symbol(character: str) -> bool: 

148 character_category: str = unicodedata.category(character) 

149 

150 if "S" in character_category or "N" in character_category: 

151 return True 

152 

153 character_range: str | None = unicode_range(character) 

154 

155 if character_range is None: 

156 return False 

157 

158 return "Forms" in character_range and character_category != "Lo" 

159 

160 

161def is_emoticon(character: str) -> bool: 

162 character_range: str | None = unicode_range(character) 

163 

164 if character_range is None: 

165 return False 

166 

167 return "Emoticons" in character_range or "Pictographs" in character_range 

168 

169 

170def is_separator(character: str) -> bool: 

171 if character.isspace() or character in {"|", "+", "<", ">"}: 

172 return True 

173 

174 character_category: str = unicodedata.category(character) 

175 

176 return "Z" in character_category or character_category in {"Po", "Pd", "Pc"} 

177 

178 

179def is_case_variable(character: str) -> bool: 

180 return character.islower() != character.isupper() 

181 

182 

183def is_cjk(character: str) -> bool: 

184 return bool(_character_flags(character) & _CJK) 

185 

186 

187def is_hiragana(character: str) -> bool: 

188 return bool(_character_flags(character) & _HIRAGANA) 

189 

190 

191def is_katakana(character: str) -> bool: 

192 return bool(_character_flags(character) & _KATAKANA) 

193 

194 

195def is_hangul(character: str) -> bool: 

196 return bool(_character_flags(character) & _HANGUL) 

197 

198 

199def is_thai(character: str) -> bool: 

200 return bool(_character_flags(character) & _THAI) 

201 

202 

203def is_arabic(character: str) -> bool: 

204 return bool(_character_flags(character) & _ARABIC) 

205 

206 

207def is_arabic_isolated_form(character: str) -> bool: 

208 return bool(_character_flags(character) & _ARABIC_ISOLATED_FORM) 

209 

210 

211def is_cjk_uncommon(character: str) -> bool: 

212 return character not in COMMON_CJK_CHARACTERS 

213 

214 

215def is_unicode_range_secondary(range_name: str) -> bool: 

216 return range_name in _SECONDARY_RANGE_NAMES 

217 

218 

219def is_unprintable(character: str) -> bool: 

220 return ( 

221 not character.isspace() # includes \n \t \r \v 

222 and not character.isprintable() 

223 and character != "\x1a" # Why? Its the ASCII substitute character. 

224 and character != "\ufeff" # bug discovered in Python, 

225 # Zero Width No-Break Space located in Arabic Presentation Forms-B, Unicode 1.1 not acknowledged as space. 

226 ) 

227 

228 

229def any_specified_encoding( 

230 sequence: bytes | bytearray, search_zone: int = 8192 

231) -> str | None: 

232 """ 

233 Extract using ASCII-only decoder any specified encoding in the first n-bytes. 

234 """ 

235 if not isinstance(sequence, (bytes, bytearray)): 

236 raise TypeError 

237 

238 seq_len: int = len(sequence) 

239 

240 # Cheap literal pre-filter. 

241 search_bytes = sequence[: min(seq_len, search_zone)] 

242 lowered_bytes = search_bytes.lower() 

243 if b"coding" not in lowered_bytes and b"charset" not in lowered_bytes: 

244 return None 

245 

246 decoded_zone: str = search_bytes.decode("ascii", errors="ignore") 

247 

248 for match in RE_POSSIBLE_ENCODING_INDICATION.finditer(decoded_zone): 

249 specified_encoding = match.group(1).lower().replace("-", "_") 

250 encoding_iana = _IANA_NAMES.get(specified_encoding) 

251 if encoding_iana is not None: 

252 return encoding_iana 

253 

254 return None 

255 

256 

257def is_multi_byte_encoding(name: str) -> bool: 

258 """Return whether the codec may be multibyte, resolving known aliases.""" 

259 return iana_name(name, False) not in _SINGLE_BYTE_DECODERS 

260 

261 

262def identify_sig_or_bom(sequence: bytes | bytearray) -> tuple[str | None, bytes]: 

263 """ 

264 Identify and extract SIG/BOM in given sequence. 

265 """ 

266 

267 for iana_encoding in ENCODING_MARKS: 

268 marks: bytes | list[bytes] = ENCODING_MARKS[iana_encoding] 

269 

270 if isinstance(marks, bytes): 

271 marks = [marks] 

272 

273 for mark in marks: 

274 if sequence.startswith(mark): 

275 return iana_encoding, mark 

276 

277 return None, b"" 

278 

279 

280def should_strip_sig_or_bom(iana_encoding: str) -> bool: 

281 return iana_encoding not in {"utf_16", "utf_32"} 

282 

283 

284def iana_name(cp_name: str, strict: bool = True) -> str: 

285 """Returns the Python normalized encoding name (Not the IANA official name).""" 

286 cp_name = cp_name.lower().replace("-", "_") 

287 

288 encoding_iana = _IANA_NAMES.get(cp_name) 

289 if encoding_iana is not None: 

290 return encoding_iana 

291 

292 if strict: 

293 raise ValueError(f"Unable to retrieve IANA for '{cp_name}'") 

294 

295 return cp_name 

296 

297 

298def cp_similarity(iana_name_a: str, iana_name_b: str) -> float: 

299 if is_multi_byte_encoding(iana_name_a) or is_multi_byte_encoding(iana_name_b): 

300 return 0.0 

301 

302 decoder_a = importlib.import_module(f"encodings.{iana_name_a}").IncrementalDecoder 

303 decoder_b = importlib.import_module(f"encodings.{iana_name_b}").IncrementalDecoder 

304 

305 id_a: IncrementalDecoder = decoder_a(errors="ignore") 

306 id_b: IncrementalDecoder = decoder_b(errors="ignore") 

307 

308 character_match_count: int = 0 

309 

310 for i in range(256): 

311 to_be_decoded: bytes = bytes([i]) 

312 if id_a.decode(to_be_decoded) == id_b.decode(to_be_decoded): 

313 character_match_count += 1 

314 

315 return character_match_count / 256 

316 

317 

318def is_cp_similar(iana_name_a: str, iana_name_b: str) -> bool: 

319 """ 

320 Determine if two code page are at least 80% similar. IANA_SUPPORTED_SIMILAR dict was generated using 

321 the function cp_similarity. 

322 """ 

323 return ( 

324 iana_name_a in IANA_SUPPORTED_SIMILAR 

325 and iana_name_b in IANA_SUPPORTED_SIMILAR[iana_name_a] 

326 ) 

327 

328 

329def set_logging_handler( 

330 name: str = "charset_normalizer", 

331 level: int = logging.INFO, 

332 format_string: str = "%(asctime)s | %(levelname)s | %(message)s", 

333) -> None: 

334 logger = logging.getLogger(name) 

335 logger.setLevel(level) 

336 

337 handler = logging.StreamHandler() 

338 handler.setFormatter(logging.Formatter(format_string)) 

339 logger.addHandler(handler) 

340 

341 

342def cut_sequence_chunks( 

343 sequences: bytes | bytearray, 

344 encoding_iana: str, 

345 offsets: range, 

346 chunk_size: int, 

347 bom_or_sig_available: bool, 

348 strip_sig_or_bom: bool, 

349 sig_payload: bytes, 

350 is_multi_byte_decoder: bool, 

351 decoded_payload: str | None = None, 

352 deferred_decoding: bool = False, 

353) -> Generator[str, None, None]: 

354 # ISO-2022 needs decoder state, and custom codecs have no known boundaries. 

355 # Sample their strictly decoded text at proportional character offsets. 

356 if ( 

357 decoded_payload is not None 

358 and is_multi_byte_decoder 

359 and ( 

360 encoding_iana not in _KNOWN_MB_DECODERS 

361 or encoding_iana.startswith("iso2022_") 

362 or encoding_iana == "utf_7" 

363 ) 

364 ): 

365 decoded_length = len(decoded_payload) 

366 sequence_length = len(sequences) 

367 if not sequence_length: 

368 return 

369 for i in offsets: 

370 decoded_offset = i * decoded_length // sequence_length 

371 chunk = decoded_payload[decoded_offset : decoded_offset + chunk_size] 

372 if not chunk: 

373 break 

374 yield chunk 

375 elif decoded_payload and not is_multi_byte_decoder: 

376 for i in offsets: 

377 chunk = decoded_payload[i : i + chunk_size] 

378 if not chunk: 

379 break 

380 yield chunk 

381 elif deferred_decoding: 

382 # Deferred single-byte probing: the whole payload is not decoded 

383 # yet. Single-byte codecs are stateless (1 byte == 1 char), hence 

384 # decode(base)[i:j] == decode(base[i:j]): slicing the raw bytes 

385 # yields exactly the chunks the branch above would have produced, 

386 # short trailing chunks included, and raises UnicodeDecodeError on 

387 # invalid bytes just like the whole-payload decode would. 

388 base_bytes = ( 

389 sequences if not strip_sig_or_bom else sequences[len(sig_payload) :] 

390 ) 

391 for i in offsets: 

392 cut_sequence = base_bytes[i : i + chunk_size] 

393 if not cut_sequence: 

394 break 

395 yield str(cut_sequence, encoding_iana) 

396 else: 

397 # UTF-8 resynchronizes at the next complete character. Ignoring 

398 # partial edge characters leaves a substring of the validated text. 

399 check_alignment = is_multi_byte_decoder and ( 

400 encoding_iana not in {"utf_8", "utf_8_sig"} 

401 or (bom_or_sig_available and not strip_sig_or_bom) 

402 ) 

403 for i in offsets: 

404 chunk_end = i + chunk_size 

405 if chunk_end > len(sequences) + 8: 

406 continue 

407 

408 cut_sequence = sequences[i : i + chunk_size] 

409 

410 if bom_or_sig_available and not strip_sig_or_bom: 

411 cut_sequence = sig_payload + cut_sequence 

412 

413 chunk = cut_sequence.decode( 

414 encoding_iana, 

415 errors="ignore" if is_multi_byte_decoder else "strict", 

416 ) 

417 

418 # multi-byte bad cutting detector and adjustment 

419 # not the cleanest way to perform that fix but clever enough for now. 

420 if check_alignment and i > 0: 

421 chunk_partial_size_chk: int = min(chunk_size, 16) 

422 chunk_prefix = chunk[:chunk_partial_size_chk] 

423 found_nearby = False 

424 

425 if decoded_payload is not None: 

426 decoded_length = len(decoded_payload) 

427 # For short text the window covers the whole payload; 

428 # use the global membership check once below. 

429 if decoded_length > _MULTIBYTE_SEARCH_RADIUS: 

430 expected_offset = i * decoded_length // len(sequences) 

431 search_start = max( 

432 0, expected_offset - _MULTIBYTE_SEARCH_RADIUS 

433 ) 

434 search_end = min( 

435 decoded_length, expected_offset + _MULTIBYTE_SEARCH_RADIUS 

436 ) 

437 found_nearby = ( 

438 decoded_payload.find(chunk_prefix, search_start, search_end) 

439 >= 0 

440 ) 

441 

442 if ( 

443 decoded_payload 

444 and not found_nearby 

445 and chunk_prefix not in decoded_payload 

446 ): 

447 # The original offset was already decoded and checked above. 

448 for j in range(i - 1, i - 4, -1): 

449 cut_sequence = sequences[j:chunk_end] 

450 

451 if bom_or_sig_available and not strip_sig_or_bom: 

452 cut_sequence = sig_payload + cut_sequence 

453 

454 chunk = cut_sequence.decode(encoding_iana, errors="ignore") 

455 

456 if chunk[:chunk_partial_size_chk] in decoded_payload: 

457 break 

458 

459 yield chunk