
     hR                     ^   d Z g dZddlZddlZddlZddlZddlZddl	Zddl
ZddlmZ  G d dej                  j                        ZdZdZdZd	Zd
ZdZ G d d      Zddej.                  dddfdZddZddZddZddZddZddZddZddZ e!dk(  rddl"Z" e"jF                  e!       yy)a  encutils - encoding detection collection for Python

A collection of helper functions to detect encodings of text files
(like HTML, XHTML, XML, CSS, etc.) retrieved via HTTP, file or string.

:func:`getEncodingInfo` is probably the main function of interest which uses
other supplied functions itself and gathers all information together and
supplies an :class:`EncodingInfo` object.

example::

    >>> import encutils
    >>> info = encutils.getEncodingInfo(url='http://jaraco.com')

    >>> print(info)
    utf-8

    >>> info # doctest:+ELLIPSIS
    <encutils.EncodingInfo object encoding='utf-8' mismatch=False at...>

    >>> print(info.logtext)
    HTTP media_type: text/html
    HTTP encoding: utf-8
    Encoding (probably): utf-8 (Mismatch: False)
    <BLANKLINE>

references
    XML
        RFC 3023 (http://www.ietf.org/rfc/rfc3023.txt)

        easier explained in
            - http://feedparser.org/docs/advanced.html
            - http://www.xml.com/pub/a/2004/07/21/dive.html

    HTML
        http://www.w3.org/TR/REC-html40/charset.html#h-5.2.2

TODO
    - parse @charset of HTML elements?
    - check for more texttypes if only text given
)buildlogencodingByMediaTypegetHTTPInfogetMetaInfodetectXMLEncodinggetEncodingInfotryEncodingsEncodingInfo    N)Messagec                       e Zd ZdZdZd Zy)_MetaHTMLParserz6Parse given data for <meta http-equiv="content-type">.Nc                    |dk(  ry| j                   sl|D ci c]$  \  }}|j                         |j                         & }}}|j                  dd      j                         dk(  r|j                  d      | _         y y y y c c}}w )Nmetaz
http-equiv content-typecontent)content_typelowergetstrip)selftagattrsavattss         Q/var/www/api/v1/venv_getwork_v1/lib/python3.12/site-packages/encutils/__init__.pyhandle_starttagz_MetaHTMLParser.handle_starttagE   sw    &=!2!25:;UTQAGGIqwwy(UD;xxb)//1^C$(HHY$7! D "3=;s   )B )__name__
__module____qualname____doc__r   r        r   r   r   @   s    @L8r$   r                  c                   "    e Zd ZdZd Zd Zd Zy)r	   a  
    All encoding related information, returned by :func:`getEncodingInfo`.

    Attributes filled:
        - ``encoding``: The guessed encoding
            Encoding is the explicit or implicit encoding or None and
            always lowercase.

        - from HTTP response
            * ``http_encoding``
            * ``http_media_type``

        - from HTML <meta> element
            * ``meta_encoding``
            * ``meta_media_type``

        - from XML declaration
            * ``xml_encoding``

        - ``mismatch``: True if mismatch between XML declaration and HTTP
            header.
            Mismatch is True if any mismatches between HTTP header, XML
            declaration or textcontent (meta) are found. More detailed
            mismatch reports are written to the optional log or ``logtext``

            Mismatches are not necessarily errors as preferences are defined.
            For details see the specifications.

        - ``logtext``: if no log was given log reports are given here
    c                 t    dx| _         x| _        x| _        x| _        x| _        x| _        x| _        | _        y)zVInitialize all possible properties to ``None``, see class
        description
        N)encodingmismatchlogtexthttp_encodinghttp_media_typemeta_encodingmeta_media_typexml_encodingr   s    r   __init__zEncodingInfo.__init__   s[     MQ	Q 	Q 	Q 	Qt7I 	Q 	Q	Q!%!58Ir$   c                 4    | j                   r| j                   S y)z7Output the guessed encoding itself or the empty string.r   )r,   r4   s    r   __str__zEncodingInfo.__str__   s    ==== r$   c                     d| j                   j                   d| j                   j                   d| j                  d| j                   dt        |       ddS )N<.z object encoding=z
 mismatch=z at 0xx>)	__class__r    r   r,   r-   idr4   s    r   __repr__zEncodingInfo.__repr__   s    4>>,,-Qt~~/F/F.GGXY]YfYfXiistx  uB  uB  tC  CI  JL  MQ  JR  ST  IU  UV  W  	Wr$   N)r   r    r!   r"   r5   r7   r?   r#   r$   r   r	   r	   a   s    >QWr$   r	   encutilsINFOwz%(levelname)s	%(message)sc                 L   ddl }|j                  |       }|r|j                  ||      }n|j                  |      }|j	                  |      }	|j                  |	       |j                  |       |j                  |j                  j                  ||j                               |S )ae  Helper to build a basic log

    - if `filename` is given returns a log logging to `filename` with
      mode `filemode`
    - else uses a log streaming to `stream` which defaults to
      `sys.stderr`
    - `level` defines the level of the log
    - `format` defines the formatter format of the log

    :returns:
        a log with the name `logname`
    r
   N)logging	getLoggerFileHandlerStreamHandler	FormattersetFormatter
addHandlersetLevel__dict__r   rA   )
lognamelevelstreamfilenamefilemodeformatrD   loghdlr	formatters
             r   r   r      s    ( 


G
$C""8X6$$V,!!&)Ii NN4LL!!%%eW\\:;Jr$   c                    | st         S g d}g d}| j                         j                         } | |v sJt        j                  |d   | t        j
                  t        j                  z  t        j                  z        rt        S | |v sJt        j                  |d   | t        j
                  t        j                  z  t        j                  z        rt        S | dk(  rt        S | dk(  rt        S | j                  d      rt        S t         S )zF
    :returns:
        type as defined by constants in this class
    )zapplication/.*?\+xmlzapplication/xmlzapplication/xml-dtdz&application/xml-external-parsed-entity)ztext\/.*?\+xmlztext/xmlztext/xml-external-parsed-entityr
   z	text/htmlztext/cssztext/)_OTHER_TYPEr   r   rematchISX_XML_APPLICATION_TYPE_XML_TEXT_TYPE_HTML_TEXT_TYPE
_TEXT_UTF8
startswith
_TEXT_TYPE)
media_typerS   xml_application_typesxml_text_typess       r   _getTextTypeByMediaTyperf      s    
  XN!!#))+J**bhha *bddRTTkBDD.@/ %$	~	%q:rttbdd{RTT'9* 	{	"	z	!			w	'r$   c                 H    | dd j                  d      dk7  rt        S t        S )zSCheck if given text is XML (**naive test!**)
    used if no content-type given
    N   z<?xml version=)findr]   rW   )textrS   s     r   _getTextTyperl      s(     CRy~~&'2-$$r$   c                     t         dt        dt        dt        dt        dt
        di}t        |       }|j                  |d      }|r)|s|j                  d|        |S |j                  d| |       |S )aA  
    :param media_type:
        a media type like "text/html"
    :returns:
        a default encoding for given `media_type`. For example
        ``"utf-8"`` for ``media_type="application/xml"``.

        If no default encoding is available returns ``None``.

        Refers to RFC 3023 and HTTP MIME specification.
    utf-8ascii
iso-8859-1Nz'"%s" Media-Type has no default encodingz(Default encoding for Media Type "%s": %s)	r]   r^   r_   rb   r`   rW   rf   r   debug)rc   rS   defaultencodingstexttyper,   s        r   r   r      s|     	wLGT 'z2H##Hd3H
II?L O II@*hWOr$   c                     | j                         }|j                         |j                         }}|r|j                         }|r$|j                  d|       |j                  d|       ||fS )a  
    :param response:
        a HTTP response object
    :returns:
        ``(media_type, encoding)`` information from the `response`
        Content-Type HTTP header. (Case of headers is ignored.)
        May be ``(None, None)`` e.g. if no Content-Type header is
        available.
    zHTTP media_type: %szHTTP encoding: %s)infoget_content_typeget_content_charsetr   )responserS   ru   rc   r,   s        r   r   r     se     ==?D002D4L4L4NJ>>#
&
3$h/xr$   c                    t               }	 |j                  |        |j
                  rvt               }|j
                  |d<   |j                         }|j                  d      }|r|j                         }|r$|j                  d|       |j                  d|       ||fS dx}}||fS # t        j                  j                  $ r Y w xY w)a=  
    :param text:
        a byte string
    :returns:
        ``(media_type, encoding)`` information from (first)
        X/HTML Content-Type ``<meta>`` element if available in `text`.

        XHTML format::

            <meta http-equiv="Content-Type"
                  content="media_type;charset=encoding" />
    r   charsetzHTML META media_type: %szHTML META encoding: %sN)r   feedhtmlparserHTMLParseErrorr   r   rv   	get_paramr   ru   )rk   rS   pmrc   r,   s         r   r   r     s     	A	t 	~~INN.'')
;;y)~~'HHH/<HH-x8 x !%$
Xx# ;;%% s   B' 'CCc                 H   t        | t              rt        j                  |       } dddddd}| j	                         }| j                  d       t        t        t        | j                  d                  \  }}}}|j                  ||||f      }	|	s,|j                  |||d	f      }	|	s|j                  ||d	d	f      }	|	r)|r|j                  d
|	z         | j                  |       |	S | j                  d       | j                  d      }
d}t        j                  |t        j                        }|j                  |
      }| j                  |       |r7|j!                  d      j#                         }|r|j                  d|z         |S |r|r|j                  d       yy	)ap  Attempt to detect the character encoding of the xml file
    given by a file object `fp`. `fp` must not be a codec wrapped file
    object! `fp` may be a string or unicode string though.

    Based on a recipe by Lars Tiede:
    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/363841
    which itself is based on Paul Prescotts recipe:
    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52257

    :returns:
        - if detection of the BOM succeeds, the codec name of the
          corresponding unicode charset is returned

        - if BOM detection fails, the xml declaration is searched for
          the encoding attribute and its value returned. the "<"
          character has to be the very first in the file then (it's xml
          standard after all).

        - if BOM and xml declaration fail, utf-8 is returned according
          to XML 1.0.
    	utf_32_be	utf_32_le	utf_16_be	utf_16_lern   ))r
   r
         )r   r   r
   r
   )r   r   NN)r   r   NN)         Nr
   r)   NzXML BOM encoding: %si   a  
    ^<\?xml             # w/o BOM, xmldecl starts with <?xml at the first byte
    .+?                 # some chars (version info), matched minimal
    encoding=           # encoding attribute begins
    ["']                # attribute start delimiter
    (?P<encstr>         # what's matched in the brackets will be named encstr
     [^"']+              # every character not delimiter (not overly exact!)
    )                   # closes the brackets pair for the named group
    ["']                # attribute end delimiter
    .*?                 # some chars optionally (standalone decl or whitespace)
    \?>                 # xmldecl end
    encstrzXML encoding="%s"zXML encoding default utf-8)
isinstancestrioStringIOtellseektuplemapordreadr   ru   rX   compileVERBOSEsearchgroupr   )fprS   includeDefaultbomDictoldFPbyte1byte2byte3byte4bomDetectionbufferxmlDeclPattern	xmlDeclRErY   encs                  r   r   r   C  s   , "c[[_ #."-"-"-")G GGIEGGAJ#(S"''!*)=#> UE5% ;;ueU;<L{{E5%#>?";;udD'ABL HH+l:;
 GGAJWWT]FN 

>2::6I V$EGGENkk(#))+HH(3./
56r$   c                 T   	 ddl }|j                  |       d   }|S # t        $ r d}|r|j                  |       nt	        |       d}d}|D ]T  }	 | j                  |       d|k(  r'	 d| j                  d      v r Y yn# t        $ r Y nw xY w|c cY S # t        $ r Y Rw xY w Y |S w xY w)	a7  If installed uses chardet http://chardet.feedparser.org/ to detect
    encoding, else tries different encodings on `text` and returns the one
    that does not raise an exception which is not very advanced or may
    be totally wrong. The tried encoding are in order 'ascii', 'iso-8859-1',
    'windows-1252' (which probably will never happen as 'iso-8859-1' can decode
    these strings too) and lastly 'utf-8'.

    :param text:
        a byte string
    :returns:
        Working encoding or ``None`` if no encoding does work at all.

        The returned encoding might nevertheless be not the one intended by
        the author as it is only checked if the text might be encoded in
        that encoding. Some texts might be working in "iso-8859-1" *and*
        "windows-1252" *and* "ascii" *and* "utf-8" and ...
    r
   Nr,   zGUsing simplified encoding detection, you might want to install chardet.)ro   rp   rn   rp   u   €zwindows-1252)chardetdetectImportErrorwarnprintdecodeUnicodeDecodeError)rk   rS   r   r,   msg	encodingses          r   r   r     s    $ >>$'
3> O;  WHHSM#J
	 AA  1$ DKK$??#1 @-   &   O;s]    3B'B!B''A>:B'=B'>	B
B'	B

B'	BB'BB'&B'c                    |rt         j                  j                  |      } |	 | j                         }|d}t               }t        j                         }|st        |d      }| r0t        | |      \  |_
        |_        t        |j                  |      }nt        ||      }|t        k(  r	 t        ||      |_        |t&        k(  r	 t        ||d      |_        |t&        k(  s	|t(        k(  rt+        ||      \  |_        |_        |j                  |_        d|_        |t        k(  r|j0                  s|j                   |_        n|t&        k(  r`|j0                  s|j.                  |_        |j0                  st5        |j                        |_        |j0                  syt7        |      |_        nh|t8        k(  s	|t(        k(  r'|j0                  sJt5        |j                        |_        n/|t:        k(  r&|j0                  st5        |j                        |_        |j                  rX|j                   rL|j                  |j                   k7  r3d|_        |j=                  d|j                  d	|j                   d
       |j                  rX|j.                  rL|j                  |j.                  k7  r3d|_        |j=                  d|j                  d	|j.                  d       |j                   rX|j.                  rL|j                   |j.                  k7  r3d|_        |j=                  d|j                   d|j.                  d       |j?                  d|j0                  |j2                         |jA                         |_!        |S # t        $ r Y Xw xY w# t"        t$        f$ r d|_        Y w xY w# t"        t$        f$ r d|_        Y w xY w)a  Find all encoding related information in given `text`.

    Information in headers of supplied HTTPResponse, possible XML
    declaration and X/HTML ``<meta>`` elements are used.

    :param response:
        HTTP response object, e.g. via ``urllib.urlopen('url')``
    :param text:
        a byte string to guess encoding for. XML prolog with
        encoding pseudo attribute or HTML meta element will be used to detect
        the encoding
    :param url:
        When given fetches document at `url` and all needed information.
        No `reponse` or `text` parameters are needed in this case.
    :param log:
        an optional logging logger to which messages may go, if
        no log given all log messages are available from resulting
        ``EncodingInfo``

    :returns:
        instance of :class:`EncodingInfo`.

    How the resulting encoding is retrieved:

    XML
        RFC 3023 states if media type given in the Content-Type HTTP header is
        application/xml, application/xml-dtd,
        application/xml-external-parsed-entity, or any one of the subtypes of
        application/xml such as application/atom+xml or application/rss+xml
        etc then the character encoding is determined in this order:

        1. the encoding given in the charset parameter of the Content-Type HTTP
        header, or
        2. the encoding given in the encoding attribute of the XML declaration
        within the document, or
        3. utf-8.

        Mismatch possibilities:
            - HTTP + XMLdecla
            - HTTP + HTMLmeta

            application/xhtml+xml ?
                XMLdecla + HTMLmeta


        If the media type given in the Content-Type HTTP header is text/xml,
        text/xml-external-parsed-entity, or a subtype like text/Anything+xml,
        the encoding attribute of the XML declaration is ignored completely
        and the character encoding is determined in the order:
        1. the encoding given in the charset parameter of the Content-Type HTTP
        header, or
        2. ascii.

        No mismatch possible.


        If no media type is given the XML encoding pseuso attribute is used
        if present.

        No mismatch possible.

    HTML
        For HTML served as text/html:
            http://www.w3.org/TR/REC-html40/charset.html#h-5.2.2

        1. An HTTP "charset" parameter in a "Content-Type" field.
           (maybe defaults to ISO-8859-1, but should not assume this)
        2. A META declaration with "http-equiv" set to "Content-Type" and a
           value set for "charset".
        3. The charset attribute set on an element that designates an external
           resource. (NOT IMPLEMENTED HERE YET)

        Mismatch possibilities:
            - HTTP + HTMLmeta

    TEXT
        For most text/* types the encoding will be reported as iso-8859-1.
        Exceptions are XML formats send as text/* mime type (see above) and
        text/css which has a default encoding of UTF-8.
    Nr   z%(message)s)rO   rR   F)r   T"z" (HTTP) != "z" (XML) encoding mismatchz!" (HTML <meta>) encoding mismatchz" (XML) != "z&Encoding (probably): %s (Mismatch: %s))"urllibrequesturlopenr   OSErrorr	   r   r   r   r   r0   r/   rf   rl   r]   r   r3   AttributeError
ValueErrorr_   rb   r   r2   r1   r,   r-   r   r   r^   r`   warningru   getvaluer.   )rx   rk   rS   urlencinfo	logstreamrs   s          r   r   r     s\   b >>))#.|	==?D |nGIi> 9DXs9S6!6*7+B+BCH  c* ((	(#4T3#?G 
 ?"	(#4T3u#UG 
 ?"h*&<9DT39O6!6 ,,GG ((&33G 
_	$&44G273J3JKG+D1G 
^	#x:'=273J3JKG	Z	273J3JKG
 	  !!W%9%99$$g&:&:<	
 	!!!!W%:%::$$g&;&;=	
 	!!  G$9$99##W%:%:<	

 HH0'2B2BGDTDT  ((*GON[  		2 
+ 	(#'G 	( 
+ 	(#'G 	(s5   N .N 	N. 	NNN+*N+.OO__main__)N)NT)Nr   NN)$r"   __all__html.parserr|   r   rX   sysurllib.errorr   urllib.parseurllib.requestemail.messager   r}   
HTMLParserr   r]   r^   r_   rb   r`   rW   r	   stderrr   rf   rl   r   r   r   r   r   r   r   pydochelpr#   r$   r   <module>r      s   (T	  	 	 
    !	8dkk,, 	8     
 
 0W 0Wh 
::'#L F@ ." J^B4nFR zEJJx r$   