a
    Šxdº(  ã                   @   s   d Z ddlZddlZddlZddlmZmZmZmZm	Z	m
Z
 ddlmZmZ ddlZe dej¡Zee ee dœdd„Zd	Zd
Zed Zed Zed Zed Zdeeeeef Ze eejejB ¡Ze e d¡ejejB ¡Zeee dœdd„Z ddddddddddddddddddddœZ!eedœdd „Z"eee d!œd"d#„Z#ej$d$fej%d%fej&d&fej'd'fej(d(fgZ)d)d*„ e)D ƒZ*e+e	ed+ eee+f f d,œd-d.„Z,e -d/d0d1„ ¡ e+eed2œd3d4„Z.d9ee e+eeee+gee f  eeef d6œd7d8„Z/dS ):z.
Functions for handling encoding of web pages
é    N)ÚCallableÚMatchÚOptionalÚTupleÚUnionÚcast)ÚAnyUnicodeErrorÚ
StrOrByteszcharset=([\w-]+))Úcontent_typeÚreturnc                 C   s$   | r t  | ¡}|r t| d¡ƒS dS )zÅExtract 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)r
   Úmatch© r   úF/var/www/html/Ranjet/env/lib/python3.9/site-packages/w3lib/encoding.pyÚhttp_content_type_encoding   s
    	
r   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*(?:meta%s(?:(?:\s+%s|\s+%s){2}|\s+%s)|\?xml\s[^>]+%s|body)Úascii)Úhtml_body_strr   c                 C   sf   | dd… }t |tƒr"t |¡}n
t |¡}|rb| d¡pL| d¡pL| d¡}|rbttj 	|¡ƒ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   Zcharset2Z
xmlcharset)
Ú
isinstanceÚbytesÚ_BODY_ENCODING_BYTES_REr   Ú_BODY_ENCODING_STR_REr   r   Úw3libÚutilÚ
to_unicode)r   Úchunkr   r   r   r   r   Úhtml_body_declared_encoding>   s    


ÿýr"   Úcp1252Ú	big5hkscsÚcp949Úgb18030Úcp874Úcp1254Ú	mac_romanÚcp932Úcp1251)r   Úbig5Úeuc_krÚgb2312Z
gb_2312_80ÚgbkÚ
iso8859_11Ú	iso8859_9Úlatin_1Ú	macintoshÚ	shift_jisÚtis_620Zwin_1251Zwindows_31jZwin_31jZwindows_874Zwin_874Zx_sjisÚzh_cn)r   r   c                 C   s$   t  | ¡ ¡ }ttt jj ||¡ƒS )z~Canonicalize an encoding name

    This performs normalization and translates aliases using python's
    encoding aliases
    )Ú	encodingsÚnormalize_encodingÚlowerr   ÚstrÚaliasesÚget)r   Únormedr   r   r   Ú_c18n_encoding„   s    r>   )Úencoding_aliasr   c                 C   s<   t | ƒ}t ||¡}zt |¡jW S  ty6   Y dS 0 dS )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)r?   Zc18n_encodingZ
translatedr   r   r   r   Ž   s    r   z	utf-32-bez	utf-32-lez	utf-16-bez	utf-16-lezutf-8c                 C   s   h | ]\}}|d  ’qS )r   r   )Ú.0ÚcÚ_r   r   r   Ú	<setcomp>©   ó    rH   ©NN)Údatar   c                 C   s8   | r4| d t v r4tD ]\}}|  |¡r||f  S q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   rJ   )Ú_FIRST_CHARSÚ
_BOM_TABLEÚ
startswith)rK   Úbomr   r   r   r   Úread_bom¬   s
    
rP   Zw3lib_replacec                 C   s   dt t| ƒjfS )Nu   ï¿½)r   r   Úend)Úexcr   r   r   Ú<lambda>Ì   rI   rS   )Údata_strr   r   c                 C   s   |   |d¡S )z¯Convert a str object to unicode using the encoding given

    Characters that cannot be converted will be converted to ``\ufffd`` (the
    unicode replacement character).
    Úreplace)Údecode)rT   r   r   r   r   r    Ð   s    r    Úutf8)Úcontent_type_headerr   Údefault_encodingÚauto_detect_funr   c                 C   s¨   t |ƒ\}}|dur8tt|ƒ}|t|t|ƒd… |ƒfS t| ƒ}|durn|dksX|dkr`|d7 }|t||ƒfS t|ƒ}|du rŽ|durŽ||ƒ}|du rš|}|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:

    * BOM (byte-order mark)
    * http content type header
    * 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', '<!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)rP   r   r   r    Úlenr   r"   )rX   r   rY   rZ   Zbom_encrO   Úencr   r   r   Úhtml_to_unicodeÙ   s    C
r]   )rW   N)0Ú__doc__ÚrerA   r7   Útypingr   r   r   r   r   r   Zw3lib._typesr   r	   Z
w3lib.utilr   ÚcompileÚIr   r:   r   Z	_TEMPLATEZ_SKIP_ATTRSZ_HTTPEQUIV_REZ_CONTENT_REZ_CONTENT2_REZ_XML_ENCODING_REZ_BODY_ENCODING_PATTERNÚVERBOSEr   Úencoder   r"   r@   r>   r   ÚBOM_UTF32_BEÚBOM_UTF32_LEÚBOM_UTF16_BEÚBOM_UTF16_LEÚBOM_UTF8rM   rL   r   rP   Úregister_errorr    r]   r   r   r   r   Ú<module>   s„    ÿÿÿ0í
û$ÿ  ü
û