dammit.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  1. # -*- coding: utf-8 -*-
  2. """Beautiful Soup bonus library: Unicode, Dammit
  3. This library converts a bytestream to Unicode through any means
  4. necessary. It is heavily based on code from Mark Pilgrim's Universal
  5. Feed Parser. It works best on XML and HTML, but it does not rewrite the
  6. XML or HTML to reflect a new encoding; that's the tree builder's job.
  7. """
  8. __license__ = "MIT"
  9. import codecs
  10. from html.entities import codepoint2name
  11. import re
  12. import logging
  13. # Import a library to autodetect character encodings.
  14. chardet_type = None
  15. try:
  16. # First try the fast C implementation.
  17. # PyPI package: cchardet
  18. import cchardet
  19. def chardet_dammit(s):
  20. return cchardet.detect(s)['encoding']
  21. except ImportError:
  22. try:
  23. # Fall back to the pure Python implementation
  24. # Debian package: python-chardet
  25. # PyPI package: chardet
  26. import chardet
  27. def chardet_dammit(s):
  28. return chardet.detect(s)['encoding']
  29. #import chardet.constants
  30. #chardet.constants._debug = 1
  31. except ImportError:
  32. # No chardet available.
  33. def chardet_dammit(s):
  34. return None
  35. xml_encoding_re = re.compile(
  36. r'^<\?.*encoding=[\'"](.*?)[\'"].*\?>'.encode(), re.I)
  37. html_meta_re = re.compile(
  38. r'<\s*meta[^>]+charset\s*=\s*["\']?([^>]*?)[ /;\'">]'.encode(), re.I)
  39. class EntitySubstitution(object):
  40. """Substitute XML or HTML entities for the corresponding characters."""
  41. def _populate_class_variables():
  42. lookup = {}
  43. reverse_lookup = {}
  44. characters_for_re = []
  45. for codepoint, name in list(codepoint2name.items()):
  46. character = chr(codepoint)
  47. if codepoint != 34:
  48. # There's no point in turning the quotation mark into
  49. # &quot;, unless it happens within an attribute value, which
  50. # is handled elsewhere.
  51. characters_for_re.append(character)
  52. lookup[character] = name
  53. # But we do want to turn &quot; into the quotation mark.
  54. reverse_lookup[name] = character
  55. re_definition = "[%s]" % "".join(characters_for_re)
  56. return lookup, reverse_lookup, re.compile(re_definition)
  57. (CHARACTER_TO_HTML_ENTITY, HTML_ENTITY_TO_CHARACTER,
  58. CHARACTER_TO_HTML_ENTITY_RE) = _populate_class_variables()
  59. CHARACTER_TO_XML_ENTITY = {
  60. "'": "apos",
  61. '"': "quot",
  62. "&": "amp",
  63. "<": "lt",
  64. ">": "gt",
  65. }
  66. BARE_AMPERSAND_OR_BRACKET = re.compile(r"([<>]|"
  67. r"&(?!#\d+;|#x[0-9a-fA-F]+;|\w+;)"
  68. r")")
  69. AMPERSAND_OR_BRACKET = re.compile(r"([<>&])")
  70. @classmethod
  71. def _substitute_html_entity(cls, matchobj):
  72. entity = cls.CHARACTER_TO_HTML_ENTITY.get(matchobj.group(0))
  73. return "&%s;" % entity
  74. @classmethod
  75. def _substitute_xml_entity(cls, matchobj):
  76. """Used with a regular expression to substitute the
  77. appropriate XML entity for an XML special character."""
  78. entity = cls.CHARACTER_TO_XML_ENTITY[matchobj.group(0)]
  79. return "&%s;" % entity
  80. @classmethod
  81. def quoted_attribute_value(self, value):
  82. """Make a value into a quoted XML attribute, possibly escaping it.
  83. Most strings will be quoted using double quotes.
  84. Bob's Bar -> "Bob's Bar"
  85. If a string contains double quotes, it will be quoted using
  86. single quotes.
  87. Welcome to "my bar" -> 'Welcome to "my bar"'
  88. If a string contains both single and double quotes, the
  89. double quotes will be escaped, and the string will be quoted
  90. using double quotes.
  91. Welcome to "Bob's Bar" -> "Welcome to &quot;Bob's bar&quot;
  92. """
  93. quote_with = '"'
  94. if '"' in value:
  95. if "'" in value:
  96. # The string contains both single and double
  97. # quotes. Turn the double quotes into
  98. # entities. We quote the double quotes rather than
  99. # the single quotes because the entity name is
  100. # "&quot;" whether this is HTML or XML. If we
  101. # quoted the single quotes, we'd have to decide
  102. # between &apos; and &squot;.
  103. replace_with = "&quot;"
  104. value = value.replace('"', replace_with)
  105. else:
  106. # There are double quotes but no single quotes.
  107. # We can use single quotes to quote the attribute.
  108. quote_with = "'"
  109. return quote_with + value + quote_with
  110. @classmethod
  111. def substitute_xml(cls, value, make_quoted_attribute=False):
  112. """Substitute XML entities for special XML characters.
  113. :param value: A string to be substituted. The less-than sign
  114. will become &lt;, the greater-than sign will become &gt;,
  115. and any ampersands will become &amp;. If you want ampersands
  116. that appear to be part of an entity definition to be left
  117. alone, use substitute_xml_containing_entities() instead.
  118. :param make_quoted_attribute: If True, then the string will be
  119. quoted, as befits an attribute value.
  120. """
  121. # Escape angle brackets and ampersands.
  122. value = cls.AMPERSAND_OR_BRACKET.sub(
  123. cls._substitute_xml_entity, value)
  124. if make_quoted_attribute:
  125. value = cls.quoted_attribute_value(value)
  126. return value
  127. @classmethod
  128. def substitute_xml_containing_entities(
  129. cls, value, make_quoted_attribute=False):
  130. """Substitute XML entities for special XML characters.
  131. :param value: A string to be substituted. The less-than sign will
  132. become &lt;, the greater-than sign will become &gt;, and any
  133. ampersands that are not part of an entity defition will
  134. become &amp;.
  135. :param make_quoted_attribute: If True, then the string will be
  136. quoted, as befits an attribute value.
  137. """
  138. # Escape angle brackets, and ampersands that aren't part of
  139. # entities.
  140. value = cls.BARE_AMPERSAND_OR_BRACKET.sub(
  141. cls._substitute_xml_entity, value)
  142. if make_quoted_attribute:
  143. value = cls.quoted_attribute_value(value)
  144. return value
  145. @classmethod
  146. def substitute_html(cls, s):
  147. """Replace certain Unicode characters with named HTML entities.
  148. This differs from data.encode(encoding, 'xmlcharrefreplace')
  149. in that the goal is to make the result more readable (to those
  150. with ASCII displays) rather than to recover from
  151. errors. There's absolutely nothing wrong with a UTF-8 string
  152. containg a LATIN SMALL LETTER E WITH ACUTE, but replacing that
  153. character with "&eacute;" will make it more readable to some
  154. people.
  155. """
  156. return cls.CHARACTER_TO_HTML_ENTITY_RE.sub(
  157. cls._substitute_html_entity, s)
  158. class EncodingDetector:
  159. """Suggests a number of possible encodings for a bytestring.
  160. Order of precedence:
  161. 1. Encodings you specifically tell EncodingDetector to try first
  162. (the override_encodings argument to the constructor).
  163. 2. An encoding declared within the bytestring itself, either in an
  164. XML declaration (if the bytestring is to be interpreted as an XML
  165. document), or in a <meta> tag (if the bytestring is to be
  166. interpreted as an HTML document.)
  167. 3. An encoding detected through textual analysis by chardet,
  168. cchardet, or a similar external library.
  169. 4. UTF-8.
  170. 5. Windows-1252.
  171. """
  172. def __init__(self, markup, override_encodings=None, is_html=False,
  173. exclude_encodings=None):
  174. self.override_encodings = override_encodings or []
  175. exclude_encodings = exclude_encodings or []
  176. self.exclude_encodings = set([x.lower() for x in exclude_encodings])
  177. self.chardet_encoding = None
  178. self.is_html = is_html
  179. self.declared_encoding = None
  180. # First order of business: strip a byte-order mark.
  181. self.markup, self.sniffed_encoding = self.strip_byte_order_mark(markup)
  182. def _usable(self, encoding, tried):
  183. if encoding is not None:
  184. encoding = encoding.lower()
  185. if encoding in self.exclude_encodings:
  186. return False
  187. if encoding not in tried:
  188. tried.add(encoding)
  189. return True
  190. return False
  191. @property
  192. def encodings(self):
  193. """Yield a number of encodings that might work for this markup."""
  194. tried = set()
  195. for e in self.override_encodings:
  196. if self._usable(e, tried):
  197. yield e
  198. # Did the document originally start with a byte-order mark
  199. # that indicated its encoding?
  200. if self._usable(self.sniffed_encoding, tried):
  201. yield self.sniffed_encoding
  202. # Look within the document for an XML or HTML encoding
  203. # declaration.
  204. if self.declared_encoding is None:
  205. self.declared_encoding = self.find_declared_encoding(
  206. self.markup, self.is_html)
  207. if self._usable(self.declared_encoding, tried):
  208. yield self.declared_encoding
  209. # Use third-party character set detection to guess at the
  210. # encoding.
  211. if self.chardet_encoding is None:
  212. self.chardet_encoding = chardet_dammit(self.markup)
  213. if self._usable(self.chardet_encoding, tried):
  214. yield self.chardet_encoding
  215. # As a last-ditch effort, try utf-8 and windows-1252.
  216. for e in ('utf-8', 'windows-1252'):
  217. if self._usable(e, tried):
  218. yield e
  219. @classmethod
  220. def strip_byte_order_mark(cls, data):
  221. """If a byte-order mark is present, strip it and return the encoding it implies."""
  222. encoding = None
  223. if isinstance(data, str):
  224. # Unicode data cannot have a byte-order mark.
  225. return data, encoding
  226. if (len(data) >= 4) and (data[:2] == b'\xfe\xff') \
  227. and (data[2:4] != '\x00\x00'):
  228. encoding = 'utf-16be'
  229. data = data[2:]
  230. elif (len(data) >= 4) and (data[:2] == b'\xff\xfe') \
  231. and (data[2:4] != '\x00\x00'):
  232. encoding = 'utf-16le'
  233. data = data[2:]
  234. elif data[:3] == b'\xef\xbb\xbf':
  235. encoding = 'utf-8'
  236. data = data[3:]
  237. elif data[:4] == b'\x00\x00\xfe\xff':
  238. encoding = 'utf-32be'
  239. data = data[4:]
  240. elif data[:4] == b'\xff\xfe\x00\x00':
  241. encoding = 'utf-32le'
  242. data = data[4:]
  243. return data, encoding
  244. @classmethod
  245. def find_declared_encoding(cls, markup, is_html=False, search_entire_document=False):
  246. """Given a document, tries to find its declared encoding.
  247. An XML encoding is declared at the beginning of the document.
  248. An HTML encoding is declared in a <meta> tag, hopefully near the
  249. beginning of the document.
  250. """
  251. if search_entire_document:
  252. xml_endpos = html_endpos = len(markup)
  253. else:
  254. xml_endpos = 1024
  255. html_endpos = max(2048, int(len(markup) * 0.05))
  256. declared_encoding = None
  257. declared_encoding_match = xml_encoding_re.search(markup, endpos=xml_endpos)
  258. if not declared_encoding_match and is_html:
  259. declared_encoding_match = html_meta_re.search(markup, endpos=html_endpos)
  260. if declared_encoding_match is not None:
  261. declared_encoding = declared_encoding_match.groups()[0].decode(
  262. 'ascii', 'replace')
  263. if declared_encoding:
  264. return declared_encoding.lower()
  265. return None
  266. class UnicodeDammit:
  267. """A class for detecting the encoding of a *ML document and
  268. converting it to a Unicode string. If the source encoding is
  269. windows-1252, can replace MS smart quotes with their HTML or XML
  270. equivalents."""
  271. # This dictionary maps commonly seen values for "charset" in HTML
  272. # meta tags to the corresponding Python codec names. It only covers
  273. # values that aren't in Python's aliases and can't be determined
  274. # by the heuristics in find_codec.
  275. CHARSET_ALIASES = {"macintosh": "mac-roman",
  276. "x-sjis": "shift-jis"}
  277. ENCODINGS_WITH_SMART_QUOTES = [
  278. "windows-1252",
  279. "iso-8859-1",
  280. "iso-8859-2",
  281. ]
  282. def __init__(self, markup, override_encodings=[],
  283. smart_quotes_to=None, is_html=False, exclude_encodings=[]):
  284. self.smart_quotes_to = smart_quotes_to
  285. self.tried_encodings = []
  286. self.contains_replacement_characters = False
  287. self.is_html = is_html
  288. self.detector = EncodingDetector(
  289. markup, override_encodings, is_html, exclude_encodings)
  290. # Short-circuit if the data is in Unicode to begin with.
  291. if isinstance(markup, str) or markup == '':
  292. self.markup = markup
  293. self.unicode_markup = str(markup)
  294. self.original_encoding = None
  295. return
  296. # The encoding detector may have stripped a byte-order mark.
  297. # Use the stripped markup from this point on.
  298. self.markup = self.detector.markup
  299. u = None
  300. for encoding in self.detector.encodings:
  301. markup = self.detector.markup
  302. u = self._convert_from(encoding)
  303. if u is not None:
  304. break
  305. if not u:
  306. # None of the encodings worked. As an absolute last resort,
  307. # try them again with character replacement.
  308. for encoding in self.detector.encodings:
  309. if encoding != "ascii":
  310. u = self._convert_from(encoding, "replace")
  311. if u is not None:
  312. logging.warning(
  313. "Some characters could not be decoded, and were "
  314. "replaced with REPLACEMENT CHARACTER.")
  315. self.contains_replacement_characters = True
  316. break
  317. # If none of that worked, we could at this point force it to
  318. # ASCII, but that would destroy so much data that I think
  319. # giving up is better.
  320. self.unicode_markup = u
  321. if not u:
  322. self.original_encoding = None
  323. def _sub_ms_char(self, match):
  324. """Changes a MS smart quote character to an XML or HTML
  325. entity, or an ASCII character."""
  326. orig = match.group(1)
  327. if self.smart_quotes_to == 'ascii':
  328. sub = self.MS_CHARS_TO_ASCII.get(orig).encode()
  329. else:
  330. sub = self.MS_CHARS.get(orig)
  331. if type(sub) == tuple:
  332. if self.smart_quotes_to == 'xml':
  333. sub = '&#x'.encode() + sub[1].encode() + ';'.encode()
  334. else:
  335. sub = '&'.encode() + sub[0].encode() + ';'.encode()
  336. else:
  337. sub = sub.encode()
  338. return sub
  339. def _convert_from(self, proposed, errors="strict"):
  340. proposed = self.find_codec(proposed)
  341. if not proposed or (proposed, errors) in self.tried_encodings:
  342. return None
  343. self.tried_encodings.append((proposed, errors))
  344. markup = self.markup
  345. # Convert smart quotes to HTML if coming from an encoding
  346. # that might have them.
  347. if (self.smart_quotes_to is not None
  348. and proposed in self.ENCODINGS_WITH_SMART_QUOTES):
  349. smart_quotes_re = b"([\x80-\x9f])"
  350. smart_quotes_compiled = re.compile(smart_quotes_re)
  351. markup = smart_quotes_compiled.sub(self._sub_ms_char, markup)
  352. try:
  353. #print "Trying to convert document to %s (errors=%s)" % (
  354. # proposed, errors)
  355. u = self._to_unicode(markup, proposed, errors)
  356. self.markup = u
  357. self.original_encoding = proposed
  358. except Exception as e:
  359. #print "That didn't work!"
  360. #print e
  361. return None
  362. #print "Correct encoding: %s" % proposed
  363. return self.markup
  364. def _to_unicode(self, data, encoding, errors="strict"):
  365. '''Given a string and its encoding, decodes the string into Unicode.
  366. %encoding is a string recognized by encodings.aliases'''
  367. return str(data, encoding, errors)
  368. @property
  369. def declared_html_encoding(self):
  370. if not self.is_html:
  371. return None
  372. return self.detector.declared_encoding
  373. def find_codec(self, charset):
  374. value = (self._codec(self.CHARSET_ALIASES.get(charset, charset))
  375. or (charset and self._codec(charset.replace("-", "")))
  376. or (charset and self._codec(charset.replace("-", "_")))
  377. or (charset and charset.lower())
  378. or charset
  379. )
  380. if value:
  381. return value.lower()
  382. return None
  383. def _codec(self, charset):
  384. if not charset:
  385. return charset
  386. codec = None
  387. try:
  388. codecs.lookup(charset)
  389. codec = charset
  390. except (LookupError, ValueError):
  391. pass
  392. return codec
  393. # A partial mapping of ISO-Latin-1 to HTML entities/XML numeric entities.
  394. MS_CHARS = {b'\x80': ('euro', '20AC'),
  395. b'\x81': ' ',
  396. b'\x82': ('sbquo', '201A'),
  397. b'\x83': ('fnof', '192'),
  398. b'\x84': ('bdquo', '201E'),
  399. b'\x85': ('hellip', '2026'),
  400. b'\x86': ('dagger', '2020'),
  401. b'\x87': ('Dagger', '2021'),
  402. b'\x88': ('circ', '2C6'),
  403. b'\x89': ('permil', '2030'),
  404. b'\x8A': ('Scaron', '160'),
  405. b'\x8B': ('lsaquo', '2039'),
  406. b'\x8C': ('OElig', '152'),
  407. b'\x8D': '?',
  408. b'\x8E': ('#x17D', '17D'),
  409. b'\x8F': '?',
  410. b'\x90': '?',
  411. b'\x91': ('lsquo', '2018'),
  412. b'\x92': ('rsquo', '2019'),
  413. b'\x93': ('ldquo', '201C'),
  414. b'\x94': ('rdquo', '201D'),
  415. b'\x95': ('bull', '2022'),
  416. b'\x96': ('ndash', '2013'),
  417. b'\x97': ('mdash', '2014'),
  418. b'\x98': ('tilde', '2DC'),
  419. b'\x99': ('trade', '2122'),
  420. b'\x9a': ('scaron', '161'),
  421. b'\x9b': ('rsaquo', '203A'),
  422. b'\x9c': ('oelig', '153'),
  423. b'\x9d': '?',
  424. b'\x9e': ('#x17E', '17E'),
  425. b'\x9f': ('Yuml', ''),}
  426. # A parochial partial mapping of ISO-Latin-1 to ASCII. Contains
  427. # horrors like stripping diacritical marks to turn á into a, but also
  428. # contains non-horrors like turning “ into ".
  429. MS_CHARS_TO_ASCII = {
  430. b'\x80' : 'EUR',
  431. b'\x81' : ' ',
  432. b'\x82' : ',',
  433. b'\x83' : 'f',
  434. b'\x84' : ',,',
  435. b'\x85' : '...',
  436. b'\x86' : '+',
  437. b'\x87' : '++',
  438. b'\x88' : '^',
  439. b'\x89' : '%',
  440. b'\x8a' : 'S',
  441. b'\x8b' : '<',
  442. b'\x8c' : 'OE',
  443. b'\x8d' : '?',
  444. b'\x8e' : 'Z',
  445. b'\x8f' : '?',
  446. b'\x90' : '?',
  447. b'\x91' : "'",
  448. b'\x92' : "'",
  449. b'\x93' : '"',
  450. b'\x94' : '"',
  451. b'\x95' : '*',
  452. b'\x96' : '-',
  453. b'\x97' : '--',
  454. b'\x98' : '~',
  455. b'\x99' : '(TM)',
  456. b'\x9a' : 's',
  457. b'\x9b' : '>',
  458. b'\x9c' : 'oe',
  459. b'\x9d' : '?',
  460. b'\x9e' : 'z',
  461. b'\x9f' : 'Y',
  462. b'\xa0' : ' ',
  463. b'\xa1' : '!',
  464. b'\xa2' : 'c',
  465. b'\xa3' : 'GBP',
  466. b'\xa4' : '$', #This approximation is especially parochial--this is the
  467. #generic currency symbol.
  468. b'\xa5' : 'YEN',
  469. b'\xa6' : '|',
  470. b'\xa7' : 'S',
  471. b'\xa8' : '..',
  472. b'\xa9' : '',
  473. b'\xaa' : '(th)',
  474. b'\xab' : '<<',
  475. b'\xac' : '!',
  476. b'\xad' : ' ',
  477. b'\xae' : '(R)',
  478. b'\xaf' : '-',
  479. b'\xb0' : 'o',
  480. b'\xb1' : '+-',
  481. b'\xb2' : '2',
  482. b'\xb3' : '3',
  483. b'\xb4' : ("'", 'acute'),
  484. b'\xb5' : 'u',
  485. b'\xb6' : 'P',
  486. b'\xb7' : '*',
  487. b'\xb8' : ',',
  488. b'\xb9' : '1',
  489. b'\xba' : '(th)',
  490. b'\xbb' : '>>',
  491. b'\xbc' : '1/4',
  492. b'\xbd' : '1/2',
  493. b'\xbe' : '3/4',
  494. b'\xbf' : '?',
  495. b'\xc0' : 'A',
  496. b'\xc1' : 'A',
  497. b'\xc2' : 'A',
  498. b'\xc3' : 'A',
  499. b'\xc4' : 'A',
  500. b'\xc5' : 'A',
  501. b'\xc6' : 'AE',
  502. b'\xc7' : 'C',
  503. b'\xc8' : 'E',
  504. b'\xc9' : 'E',
  505. b'\xca' : 'E',
  506. b'\xcb' : 'E',
  507. b'\xcc' : 'I',
  508. b'\xcd' : 'I',
  509. b'\xce' : 'I',
  510. b'\xcf' : 'I',
  511. b'\xd0' : 'D',
  512. b'\xd1' : 'N',
  513. b'\xd2' : 'O',
  514. b'\xd3' : 'O',
  515. b'\xd4' : 'O',
  516. b'\xd5' : 'O',
  517. b'\xd6' : 'O',
  518. b'\xd7' : '*',
  519. b'\xd8' : 'O',
  520. b'\xd9' : 'U',
  521. b'\xda' : 'U',
  522. b'\xdb' : 'U',
  523. b'\xdc' : 'U',
  524. b'\xdd' : 'Y',
  525. b'\xde' : 'b',
  526. b'\xdf' : 'B',
  527. b'\xe0' : 'a',
  528. b'\xe1' : 'a',
  529. b'\xe2' : 'a',
  530. b'\xe3' : 'a',
  531. b'\xe4' : 'a',
  532. b'\xe5' : 'a',
  533. b'\xe6' : 'ae',
  534. b'\xe7' : 'c',
  535. b'\xe8' : 'e',
  536. b'\xe9' : 'e',
  537. b'\xea' : 'e',
  538. b'\xeb' : 'e',
  539. b'\xec' : 'i',
  540. b'\xed' : 'i',
  541. b'\xee' : 'i',
  542. b'\xef' : 'i',
  543. b'\xf0' : 'o',
  544. b'\xf1' : 'n',
  545. b'\xf2' : 'o',
  546. b'\xf3' : 'o',
  547. b'\xf4' : 'o',
  548. b'\xf5' : 'o',
  549. b'\xf6' : 'o',
  550. b'\xf7' : '/',
  551. b'\xf8' : 'o',
  552. b'\xf9' : 'u',
  553. b'\xfa' : 'u',
  554. b'\xfb' : 'u',
  555. b'\xfc' : 'u',
  556. b'\xfd' : 'y',
  557. b'\xfe' : 'b',
  558. b'\xff' : 'y',
  559. }
  560. # A map used when removing rogue Windows-1252/ISO-8859-1
  561. # characters in otherwise UTF-8 documents.
  562. #
  563. # Note that \x81, \x8d, \x8f, \x90, and \x9d are undefined in
  564. # Windows-1252.
  565. WINDOWS_1252_TO_UTF8 = {
  566. 0x80 : b'\xe2\x82\xac', # €
  567. 0x82 : b'\xe2\x80\x9a', # ‚
  568. 0x83 : b'\xc6\x92', # ƒ
  569. 0x84 : b'\xe2\x80\x9e', # „
  570. 0x85 : b'\xe2\x80\xa6', # …
  571. 0x86 : b'\xe2\x80\xa0', # †
  572. 0x87 : b'\xe2\x80\xa1', # ‡
  573. 0x88 : b'\xcb\x86', # ˆ
  574. 0x89 : b'\xe2\x80\xb0', # ‰
  575. 0x8a : b'\xc5\xa0', # Š
  576. 0x8b : b'\xe2\x80\xb9', # ‹
  577. 0x8c : b'\xc5\x92', # Œ
  578. 0x8e : b'\xc5\xbd', # Ž
  579. 0x91 : b'\xe2\x80\x98', # ‘
  580. 0x92 : b'\xe2\x80\x99', # ’
  581. 0x93 : b'\xe2\x80\x9c', # “
  582. 0x94 : b'\xe2\x80\x9d', # ”
  583. 0x95 : b'\xe2\x80\xa2', # •
  584. 0x96 : b'\xe2\x80\x93', # –
  585. 0x97 : b'\xe2\x80\x94', # —
  586. 0x98 : b'\xcb\x9c', # ˜
  587. 0x99 : b'\xe2\x84\xa2', # ™
  588. 0x9a : b'\xc5\xa1', # š
  589. 0x9b : b'\xe2\x80\xba', # ›
  590. 0x9c : b'\xc5\x93', # œ
  591. 0x9e : b'\xc5\xbe', # ž
  592. 0x9f : b'\xc5\xb8', # Ÿ
  593. 0xa0 : b'\xc2\xa0', #  
  594. 0xa1 : b'\xc2\xa1', # ¡
  595. 0xa2 : b'\xc2\xa2', # ¢
  596. 0xa3 : b'\xc2\xa3', # £
  597. 0xa4 : b'\xc2\xa4', # ¤
  598. 0xa5 : b'\xc2\xa5', # ¥
  599. 0xa6 : b'\xc2\xa6', # ¦
  600. 0xa7 : b'\xc2\xa7', # §
  601. 0xa8 : b'\xc2\xa8', # ¨
  602. 0xa9 : b'\xc2\xa9', # ©
  603. 0xaa : b'\xc2\xaa', # ª
  604. 0xab : b'\xc2\xab', # «
  605. 0xac : b'\xc2\xac', # ¬
  606. 0xad : b'\xc2\xad', # ­
  607. 0xae : b'\xc2\xae', # ®
  608. 0xaf : b'\xc2\xaf', # ¯
  609. 0xb0 : b'\xc2\xb0', # °
  610. 0xb1 : b'\xc2\xb1', # ±
  611. 0xb2 : b'\xc2\xb2', # ²
  612. 0xb3 : b'\xc2\xb3', # ³
  613. 0xb4 : b'\xc2\xb4', # ´
  614. 0xb5 : b'\xc2\xb5', # µ
  615. 0xb6 : b'\xc2\xb6', # ¶
  616. 0xb7 : b'\xc2\xb7', # ·
  617. 0xb8 : b'\xc2\xb8', # ¸
  618. 0xb9 : b'\xc2\xb9', # ¹
  619. 0xba : b'\xc2\xba', # º
  620. 0xbb : b'\xc2\xbb', # »
  621. 0xbc : b'\xc2\xbc', # ¼
  622. 0xbd : b'\xc2\xbd', # ½
  623. 0xbe : b'\xc2\xbe', # ¾
  624. 0xbf : b'\xc2\xbf', # ¿
  625. 0xc0 : b'\xc3\x80', # À
  626. 0xc1 : b'\xc3\x81', # Á
  627. 0xc2 : b'\xc3\x82', # Â
  628. 0xc3 : b'\xc3\x83', # Ã
  629. 0xc4 : b'\xc3\x84', # Ä
  630. 0xc5 : b'\xc3\x85', # Å
  631. 0xc6 : b'\xc3\x86', # Æ
  632. 0xc7 : b'\xc3\x87', # Ç
  633. 0xc8 : b'\xc3\x88', # È
  634. 0xc9 : b'\xc3\x89', # É
  635. 0xca : b'\xc3\x8a', # Ê
  636. 0xcb : b'\xc3\x8b', # Ë
  637. 0xcc : b'\xc3\x8c', # Ì
  638. 0xcd : b'\xc3\x8d', # Í
  639. 0xce : b'\xc3\x8e', # Î
  640. 0xcf : b'\xc3\x8f', # Ï
  641. 0xd0 : b'\xc3\x90', # Ð
  642. 0xd1 : b'\xc3\x91', # Ñ
  643. 0xd2 : b'\xc3\x92', # Ò
  644. 0xd3 : b'\xc3\x93', # Ó
  645. 0xd4 : b'\xc3\x94', # Ô
  646. 0xd5 : b'\xc3\x95', # Õ
  647. 0xd6 : b'\xc3\x96', # Ö
  648. 0xd7 : b'\xc3\x97', # ×
  649. 0xd8 : b'\xc3\x98', # Ø
  650. 0xd9 : b'\xc3\x99', # Ù
  651. 0xda : b'\xc3\x9a', # Ú
  652. 0xdb : b'\xc3\x9b', # Û
  653. 0xdc : b'\xc3\x9c', # Ü
  654. 0xdd : b'\xc3\x9d', # Ý
  655. 0xde : b'\xc3\x9e', # Þ
  656. 0xdf : b'\xc3\x9f', # ß
  657. 0xe0 : b'\xc3\xa0', # à
  658. 0xe1 : b'\xa1', # á
  659. 0xe2 : b'\xc3\xa2', # â
  660. 0xe3 : b'\xc3\xa3', # ã
  661. 0xe4 : b'\xc3\xa4', # ä
  662. 0xe5 : b'\xc3\xa5', # å
  663. 0xe6 : b'\xc3\xa6', # æ
  664. 0xe7 : b'\xc3\xa7', # ç
  665. 0xe8 : b'\xc3\xa8', # è
  666. 0xe9 : b'\xc3\xa9', # é
  667. 0xea : b'\xc3\xaa', # ê
  668. 0xeb : b'\xc3\xab', # ë
  669. 0xec : b'\xc3\xac', # ì
  670. 0xed : b'\xc3\xad', # í
  671. 0xee : b'\xc3\xae', # î
  672. 0xef : b'\xc3\xaf', # ï
  673. 0xf0 : b'\xc3\xb0', # ð
  674. 0xf1 : b'\xc3\xb1', # ñ
  675. 0xf2 : b'\xc3\xb2', # ò
  676. 0xf3 : b'\xc3\xb3', # ó
  677. 0xf4 : b'\xc3\xb4', # ô
  678. 0xf5 : b'\xc3\xb5', # õ
  679. 0xf6 : b'\xc3\xb6', # ö
  680. 0xf7 : b'\xc3\xb7', # ÷
  681. 0xf8 : b'\xc3\xb8', # ø
  682. 0xf9 : b'\xc3\xb9', # ù
  683. 0xfa : b'\xc3\xba', # ú
  684. 0xfb : b'\xc3\xbb', # û
  685. 0xfc : b'\xc3\xbc', # ü
  686. 0xfd : b'\xc3\xbd', # ý
  687. 0xfe : b'\xc3\xbe', # þ
  688. }
  689. MULTIBYTE_MARKERS_AND_SIZES = [
  690. (0xc2, 0xdf, 2), # 2-byte characters start with a byte C2-DF
  691. (0xe0, 0xef, 3), # 3-byte characters start with E0-EF
  692. (0xf0, 0xf4, 4), # 4-byte characters start with F0-F4
  693. ]
  694. FIRST_MULTIBYTE_MARKER = MULTIBYTE_MARKERS_AND_SIZES[0][0]
  695. LAST_MULTIBYTE_MARKER = MULTIBYTE_MARKERS_AND_SIZES[-1][1]
  696. @classmethod
  697. def detwingle(cls, in_bytes, main_encoding="utf8",
  698. embedded_encoding="windows-1252"):
  699. """Fix characters from one encoding embedded in some other encoding.
  700. Currently the only situation supported is Windows-1252 (or its
  701. subset ISO-8859-1), embedded in UTF-8.
  702. The input must be a bytestring. If you've already converted
  703. the document to Unicode, you're too late.
  704. The output is a bytestring in which `embedded_encoding`
  705. characters have been converted to their `main_encoding`
  706. equivalents.
  707. """
  708. if embedded_encoding.replace('_', '-').lower() not in (
  709. 'windows-1252', 'windows_1252'):
  710. raise NotImplementedError(
  711. "Windows-1252 and ISO-8859-1 are the only currently supported "
  712. "embedded encodings.")
  713. if main_encoding.lower() not in ('utf8', 'utf-8'):
  714. raise NotImplementedError(
  715. "UTF-8 is the only currently supported main encoding.")
  716. byte_chunks = []
  717. chunk_start = 0
  718. pos = 0
  719. while pos < len(in_bytes):
  720. byte = in_bytes[pos]
  721. if not isinstance(byte, int):
  722. # Python 2.x
  723. byte = ord(byte)
  724. if (byte >= cls.FIRST_MULTIBYTE_MARKER
  725. and byte <= cls.LAST_MULTIBYTE_MARKER):
  726. # This is the start of a UTF-8 multibyte character. Skip
  727. # to the end.
  728. for start, end, size in cls.MULTIBYTE_MARKERS_AND_SIZES:
  729. if byte >= start and byte <= end:
  730. pos += size
  731. break
  732. elif byte >= 0x80 and byte in cls.WINDOWS_1252_TO_UTF8:
  733. # We found a Windows-1252 character!
  734. # Save the string up to this point as a chunk.
  735. byte_chunks.append(in_bytes[chunk_start:pos])
  736. # Now translate the Windows-1252 character into UTF-8
  737. # and add it as another, one-byte chunk.
  738. byte_chunks.append(cls.WINDOWS_1252_TO_UTF8[byte])
  739. pos += 1
  740. chunk_start = pos
  741. else:
  742. # Go on to the next character.
  743. pos += 1
  744. if chunk_start == 0:
  745. # The string is unchanged.
  746. return in_bytes
  747. else:
  748. # Store the final chunk.
  749. byte_chunks.append(in_bytes[chunk_start:])
  750. return b''.join(byte_chunks)