
    a0(                        d Z ddlZddlZddlZddlmZ  ej        dej                  Zd Z	dZ
dZe
dz  Ze
d	z  Ze
d
z  Ze
dz  ZdedededededZ ej        eej        ej        z            Z ej        e                    d          ej        ej        z            Zd Zi dddddddddddddddd d!dd"d#d$d%d&dd'd(d)d%d*d%d+dd,dd%dd-Zd. Zd/ Zej        d0fej        d1fej        d2fej        d3fej        d4fgZ ed5 eD                       Z d6 Z! ej"        d7d8            d9 Z#	 d<d;Z$dS )=z.
Functions for handling encoding of web pages
    N)version_infozcharset=([\w-]+)c                     | r>t                               |           }|r$t          |                    d                    S dS dS )zExtract the encoding in the content-type header

    >>> import w3lib.encoding
    >>> w3lib.encoding.http_content_type_encoding("Content-Type: text/html; charset=ISO-8859-4")
    'iso8859-4'

       N)_HEADER_ENCODING_REsearchresolve_encodinggroup)content_typematchs     .lib/python3.11/site-packages/w3lib/encoding.pyhttp_content_type_encodingr   
   sS      4#**<88 	4#EKKNN3334 4	4 	4    z%s\s*=\s*["']?\s*%s\s*["']?a  (?:\s+
    [^=<>/\s"' -]+  # Attribute name
    (?:\s*=\s*
    (?:  # ' and " are entity encoded (&apos;, &quot;), so no need for ', "
        '[^']*'   # attr in '
        |
        "[^"]*"   # attr in "
        |
        [^'"\s]+  # attr having no ' nor "
    ))?
)*?)z
http-equivzContent-Type)contentz.(?P<mime>[^;]+);\s*charset=(?P<charset>[\w-]+))charsetz(?P<charset2>[\w-]+))encodingz(?P<xmlcharset>[\w-]+)z<\s*(?:metaz	(?:(?:\s+z|\s+z){2}|\s+z)|\?xml\s[^>]+z|body)asciic                 V   | dd         }t          |t                    rt                              |          }nt                              |          }|rP|                    d          p)|                    d          p|                    d          }|rt          |          S dS dS )a  Return the encoding specified in meta tags in the html body,
    or ``None`` if no suitable encoding was found

    >>> import w3lib.encoding
    >>> w3lib.encoding.html_body_declared_encoding(
    ... """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    ...      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    ... <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    ... <head>
    ...     <title>Some title</title>
    ...     <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    ... </head>
    ... <body>
    ... ...
    ... </body>
    ... </html>""")
    'utf-8'
    >>>

    Ni   r   charset2
xmlcharset)
isinstancebytes_BODY_ENCODING_BYTES_REr   _BODY_ENCODING_STR_REr	   r   )html_body_strchunkr   r   s       r   html_body_declared_encodingr   1   s    . %4% E% 4'..u55%,,U33 .;;y)) -U[[-D-D -;;|,, 	 	.#H---	. .	. 	.r   cp1252big5	big5hkscseuc_krcp949gb2312gb18030
gb_2312_80gbk
iso8859_11cp874	iso8859_9cp1254latin_1	macintosh	mac_roman	shift_jiscp932tis_620win_1251cp1251windows_31jwin_31jwindows_874win_874)x_sjiszh_cnc                     t          j        |                                           }t           j        j                            ||          S )zCannonicalize an encoding name

    This performs normalization and translates aliases using python's
    encoding aliases
    )	encodingsnormalize_encodingloweraliasesget)r   normeds     r   _c18n_encodingr?   o   s<     )(3399;;F$((888r   c                     t          |           }t                              ||          }	 t          j        |          j        S # t          $ r Y dS w xY w)a  Return the encoding that `encoding_alias` maps to, or ``None``
    if the encoding cannot be interpreted

    >>> import w3lib.encoding
    >>> w3lib.encoding.resolve_encoding('latin1')
    'cp1252'
    >>> w3lib.encoding.resolve_encoding('gb_2312-80')
    'gb18030'
    >>>

    N)r?   DEFAULT_ENCODING_TRANSLATIONr=   codecslookupnameLookupError)encoding_aliasc18n_encoding
translateds      r   r   r   x   s`     #>22M-11-OOJ}Z((--   tts   A 
AAz	utf-32-bez	utf-32-lez	utf-16-bez	utf-16-lezutf-8c              #   ,   K   | ]\  }}|d          V  dS )r   N ).0c_s      r   	<genexpr>rN      s*      11FQ1Q4111111r   c                 x    | r7| d         t           v r(t          D ] \  }}|                     |          r||fc S !dS )a  Read the byte order mark in the text, if present, and
    return the encoding represented by the BOM and the BOM.

    If no BOM can be detected, ``(None, None)`` is returned.

    >>> import w3lib.encoding
    >>> w3lib.encoding.read_bom(b'\xfe\xff\x6c\x34')
    ('utf-16-be', '\xfe\xff')
    >>> w3lib.encoding.read_bom(b'\xff\xfe\x34\x6c')
    ('utf-16-le', '\xff\xfe')
    >>> w3lib.encoding.read_bom(b'\x00\x00\xfe\xff\x00\x00\x6c\x34')
    ('utf-32-be', '\x00\x00\xfe\xff')
    >>> w3lib.encoding.read_bom(b'\xff\xfe\x00\x00\x34\x6c\x00\x00')
    ('utf-32-le', '\xff\xfe\x00\x00')
    >>> w3lib.encoding.read_bom(b'\x01\x02\x03\x04')
    (None, None)
    >>>

    r   )NN)_FIRST_CHARS
_BOM_TABLE
startswith)databomr   s      r   read_bomrU      s[    ,  %Q<''' 	% 	%MCs## %}$$$%:r   w3lib_replacec                     d| j         fS )Nu   �)end)excs    r   <lambda>rZ      s    Isw3G r   c                 X    |                      |t          dd         dk    rdnd          S )zConvert a str object to unicode using the encoding given

    Characters that cannot be converted will be converted to ``\ufffd`` (the
    unicode replacement character).
    r      )   r]   replacerV   )decoder   )data_strr   s     r   
to_unicodera      s0     ??8,qs2Cv2M2MYYSbcccr   utf8c                    t          |           }t          |          \  }}|r||k    r|t          |          d         }nB|dk    s|dk    r6|/|                    |          r|}|t          |          d         }n|dz  }|t	          ||          fS |'|t	          |t          |          d         |          fS t          |          }|| ||          }||}|t	          ||          fS )a	  Convert raw html bytes to unicode

    This attempts to make a reasonable guess at the content encoding of the
    html body, following a similar process to a web browser.

    It will try in order:

    * http content type header
    * BOM (byte-order mark)
    * meta or xml tag declarations
    * auto-detection, if the `auto_detect_fun` keyword argument is not ``None``
    * default encoding in keyword arg (which defaults to utf8)

    If an encoding other than the auto-detected or default encoding is used,
    overrides will be applied, converting some character encodings to more
    suitable alternatives.

    If a BOM is found matching the encoding, it will be stripped.

    The `auto_detect_fun` argument can be used to pass a function that will
    sniff the encoding of the text. This function must take the raw text as an
    argument and return the name of an encoding that python can process, or
    None.  To use chardet, for example, you can define the function as::

        auto_detect_fun=lambda x: chardet.detect(x).get('encoding')

    or to use UnicodeDammit (shipped with the BeautifulSoup library)::

        auto_detect_fun=lambda x: UnicodeDammit(x).originalEncoding

    If the locale of the website or user language preference is known, then a
    better default encoding can be supplied.

    If `content_type_header` is not present, ``None`` can be passed signifying
    that the header was not present.

    This method will not fail, if characters cannot be converted to unicode,
    ``\\ufffd`` (the unicode replacement character) will be inserted instead.

    Returns a tuple of ``(<encoding used>, <unicode_string>)``

    Examples:

    >>> import w3lib.encoding
    >>> w3lib.encoding.html_to_unicode(None,
    ... b"""<!DOCTYPE html>
    ... <head>
    ... <meta charset="UTF-8" />
    ... <meta name="viewport" content="width=device-width" />
    ... <title>Creative Commons France</title>
    ... <link rel='canonical' href='http://creativecommons.fr/' />
    ... <body>
    ... <p>Creative Commons est une organisation \xc3\xa0 but non lucratif
    ... qui a pour dessein de faciliter la diffusion et le partage des oeuvres
    ... tout en accompagnant les nouvelles pratiques de cr\xc3\xa9ation \xc3\xa0 l\xe2\x80\x99\xc3\xa8re numerique.</p>
    ... </body>
    ... </html>""")
    ('utf-8', u'<!DOCTYPE html>\n<head>\n<meta charset="UTF-8" />\n<meta name="viewport" content="width=device-width" />\n<title>Creative Commons France</title>\n<link rel=\'canonical\' href=\'http://creativecommons.fr/\' />\n<body>\n<p>Creative Commons est une organisation \xe0 but non lucratif\nqui a pour dessein de faciliter la diffusion et le partage des oeuvres\ntout en accompagnant les nouvelles pratiques de cr\xe9ation \xe0 l\u2019\xe8re numerique.</p>\n</body>\n</html>')
    >>>

    Nzutf-16zutf-32z-be)r   rU   lenrR   ra   r   )content_type_headerr   default_encodingauto_detect_funencbom_encrT   s          r   html_to_unicoderj      s   @ %%8
9
9CM**LGS
'>>)#c(())4MMH__x "w'9'9#'>'>" -c#hhii 8uJ}c2222
=S#;WEEEE
%m
4
4C
{3om,,
{
=#....r   )rb   N)%__doc__rerB   r9   sysr   compileIr   r   	_TEMPLATE_SKIP_ATTRS_HTTPEQUIV_RE_CONTENT_RE_CONTENT2_RE_XML_ENCODING_RE_BODY_ENCODING_PATTERNVERBOSEr   encoder   r   rA   r?   r   BOM_UTF32_BEBOM_UTF32_LEBOM_UTF16_BEBOM_UTF16_LEBOM_UTF8rQ   setrP   rU   register_errorra   rj   rJ   r   r   <module>r      s                      bj!4bd;; 4 4 4 /	
 ::XX??FF   KK\\\;K;K;KM "
#924"*;LMM $"*%;%B%B7%K%K%'TBJ%68 8 !. !. !.P X 
K  g  i	 
 )  
9  '    x      w    7  w   7! " w# $ '      ,9 9 9  ( +&+&+&+&_g
 s11j11111  <  o'G'G H H Hd d d 26V/ V/ V/ V/ V/ V/r   