U
    j                     @  sx  U d dl mZ d dlZd dlmZ d dlmZ d dlmZ ddl	m
Z
mZmZmZ ddlmZmZmZmZmZ dd	lmZ dd
lmZmZ ddlmZmZmZmZmZmZ e dZ!e" Z#e#$e%d e&edd dZ'de(d< d.ddddddddddddd d!Z)d/d"ddddddddddd#d$d%Z*d0d&ddddddddddd'd(d)Z+d1d*ddddddddddd+d,d-Z,dS )2    )annotationsN)	lru_cache)PathLike)BinaryIO   )coherence_ratioencoding_languagesmb_encoding_languagesmerge_coherence_ratios)IANA_SUPPORTEDIANA_SUPPORTED_SIMILARTOO_BIG_SEQUENCETOO_SMALL_SEQUENCETRACE)
mess_ratio)CharsetMatchCharsetMatches)any_specified_encodingcut_sequence_chunks	iana_nameidentify_sig_or_bomis_multi_byte_encodingshould_strip_sig_or_bomZcharset_normalizerz)%(asctime)s | %(levelname)s | %(message)sc                 C  s
   t |  S N)r   encoding r   :/tmp/pip-unpacked-wheel-bwd693va/charset_normalizer/api.py<lambda>.       r   )keyz	list[str]IANA_SUPPORTED_MB_FIRST      皙?TF皙?zbytes | bytearrayintfloatzlist[str] | Noneboolr   )	sequencessteps
chunk_size	thresholdcp_isolationcp_exclusionpreemptive_behaviourexplainlanguage_thresholdenable_fallbackreturnc
           <      C  s  t | ttfs tdt| |r>tj}
tt	 t
t t| }|dkrtd |rptt	 t
|
 tt| dddg dgS |dk	rttd	d
| dd |D }ng }|dk	rttdd
| dd |D }ng }||| krttd||| d}|}|dkr4|| |k r4t|| }t| tk }t| tk}|rbttd| n|rvttd| g }|rt| nd}|dk	r|| ttd| t }g }g }t }tddt}tddt}d}t }d}d}d}d}d}d}t }t }t| \} }!| dk	rB|d|  ttdt|!|  |d d|kr`|d |t D 	]v}"|r|"|krqh|r|"|krqh|"|krqh||" d}#| |"k}$|$ot |"}%|"dkr|$sttd|" qh|"dkr|$sttd|" qh|"|kr(ttd|" qhzt!|"}&W n. t"t#fk
rb   ttd|" Y qhY nX |r|&s~tt$|"}'ntt%|"}'|'&|sttd|"|'| qh|r|&s||krttd|"|| qh|r|&sttd |" qh|& o| }(z|rF|&sFt'|%s*| dtd! n| t|!td! |"d" nf|(s|"d#kr|$rt'| |"d"}#|#r|#d d$kr|#dd }#n"t'|%s| n| t|!d |"d"}#W n\ t(t)fk
r
 }) z8t |)t)sttd%|"t'|) ||" W Y qhW 5 d})~)X Y nX t*|$sdnt|!|t|| }*|&oH|#dk	oHt|#|k }+|+r^ttd&|" tt|*d' },t+|,d(},d}-d}.g }/g }0zt,| |"|*||$|%|!|&|#|(
D ]t}1|/|1 |0||1||odt|  kod(kn   |0d) |kr|-d7 }-|-|,ks|$r|%s qqW nr t(t)fk
r }) zN|(rbttd%|"t'|) ||" W Y $qhttd*|"t'|) |,}-d+}.W 5 d})~)X Y nX |0rt-|0t|0 nd}2|.s<|r<|&s<|2|k r<|-|,k r<z| td,d j.|"d-d. W nL t(k
r: }) z,ttd/|"t'|) ||" W Y qhW 5 d})~)X Y nX |2|ksP|-|,krX||" |"t/krr|0t/|"  ttd0|"|-t1|2d1 d2d3 |	rh|"dd|d4d5fkrh|.sh|#dkrz&t'|%s| n| t|!d |"d"}#W n. t(t)fk
r   ttd6|" Y qhY nX |rd}#t| |"||$g |#|d7}3|"|kr@|3}n|"dkrP|3}n|3}qh|(rz&t'|%sl| n| t|!d |"d"}#W nP t(t)fk
r }) z,ttd%|"t'|) ||" W Y qhW 5 d})~)X Y nX ttd8|"t1|2d1 d2d3 |&	st$|"}4nt%|"}4|4	r ttd9|"|4 g }5|"dk	rd|4	r>d:|4nd}6|/D ]}1||1||6}7|5|7 	qFt2|5}8|8	rttd;|8|" t| |"|2|$|8|	r|"|ddfk	r|#nd|d7}9||9 |	r|&	s|2d<k 	r|d7 }|"|ddfk
r>|2d=k 
r>|2dk
r4td>|9j3 |
r&tt	 t
|
 t|9g  S ||9 t|
r|dk
s\||k
rd|k
rd|k
r|4 }:|:dk	
st5td>|:j3 |
rtt	 t
|
 t|:g  S |s&|&s&|8
rt+d?d@ |8D ddAnd};|;dBkr&d|kr&d|kr&d+}|0|4 ttdC|"|2|; |s|&r|+r|#dk	rt|#|dD k r|"dEkrd|krd|krd+}ttdF|"|2t|#|t|#| d1  |"| krhtdG|" |rtt	 t
|
 t||" g  S qht|dkr|s|s|rttdH |r.tdI|j3 || nd|r>|dksb|rX|rX|j6|j6ksb|dk	rxtdJ || n|rtdK || |rtdL|4 j3t|d  n
tdM |rtt	 t
|
 |S )Naf  
    Given a raw bytes sequence, return the best possibles charset usable to render str objects.
    If there is no results, it is a strong indicator that the source is binary/not text.
    By default, the process will extract 5 blocks of 512o each to assess the mess and coherence of a given sequence.
    And will give up a particular code page after 20% of measured mess. Those criteria are customizable at will.

    The preemptive behavior DOES NOT replace the traditional detection workflow, it prioritize a particular code page
    but never take it for granted. Can improve the performance.

    You may want to focus your attention to some code page or/and not others, use cp_isolation and cp_exclusion for that
    purpose.

    This function will strip the SIG in the payload/sequence every time except on UTF-16, UTF-32.
    By default the library does not setup any handler other than the NullHandler, if you choose to set the 'explain'
    toggle to True it will alter the logger configuration to add a StreamHandler that is suitable for debugging.
    Custom logging format and handler can be set manually.
    z3Expected object of type bytes or bytearray, got: {}r   z<Encoding detection on empty bytes, assuming utf_8 intention.utf_8g        F Nz`cp_isolation is set. use this flag for debugging purpose. limited list of encoding allowed : %s.z, c                 S  s   g | ]}t |d qS Fr   .0cpr   r   r   
<listcomp>l   s     zfrom_bytes.<locals>.<listcomp>zacp_exclusion is set. use this flag for debugging purpose. limited list of encoding excluded : %s.c                 S  s   g | ]}t |d qS r6   r7   r8   r   r   r   r;   w   s     z^override steps (%i) and chunk_size (%i) as content does not fit (%i byte(s) given) parameters.r   z>Trying to detect encoding from a tiny portion of (%i) byte(s).zIUsing lazy str decoding because the payload is quite large, (%i) byte(s).z@Detected declarative mark in sequence. Priority +1 given for %s.)maxsize   zIDetected a SIG or BOM mark on first %i byte(s). Priority +1 given for %s.ascii>   utf_16utf_32z\Encoding %s won't be tested as-is because it require a BOM. Will try some sub-encoder LE/BE.>   utf_7zREncoding %s won't be tested as-is because detection is unreliable without BOM/SIG.zY%s is deemed too similar to a code page that was already considered unsuited. Continuing!z2Encoding %s does not provide an IncrementalDecoderzbSkipping %s: definitive match already found, this encoding targets different languages (%s vs %s).zXSkipping %s: already accumulated %d same-family results after definitive match (cap=%d).zCSkipping single-byte %s: multi-byte definitive match already found.g    Ar   rA   u   ﻿z9Code page %s does not fit given bytes sequence at ALL. %szpCode page %s is a multi byte encoding table and it appear that at least one character was encoded using n-bytes.      zaLazyStr Loading: After MD chunk decode, code page %s does not fit given bytes sequence at ALL. %sTg     j@strict)errorsz^LazyStr Loading: After final lookup, code page %s does not fit given bytes sequence at ALL. %szc%s was excluded because of initial chaos probing. Gave up %i time(s). Computed mean chaos is %f %%.d      )ndigitsr?   r@   z>%s does not decode the whole payload: fallback entry withheld.)Zpreemptive_declarationz=%s passed initial chaos probing. Mean measured chaos is %f %%z&%s should target any language(s) of %s,z We detected language %s using %sg{Gz?r%   z.Encoding detection: %s is most likely the one.c                 s  s   | ]\}}|V  qd S r   r   )r9   _vr   r   r   	<genexpr>  s     zfrom_bytes.<locals>.<genexpr>)defaultg      ?zyDefinitive match found: %s (chaos=%.3f, coherence=%.2f). Encodings targeting different language families will be skipped.g\(\?>	   	utf_32_ler4   	utf_16_le	utf_32_be	utf_16_ber?   rA   	utf_8_sigr@   zjMulti-byte definitive match: %s (chaos=%.3f, decoded=%d/%d=%.1f%%). Single-byte encodings will be skipped.zoEncoding detection: %s is most likely the one as we detected a BOM or SIG within the beginning of the sequence.zONothing got out of the detection process. Using ASCII/UTF-8/Specified fallback.z7Encoding detection: %s will be used as a fallback matchz:Encoding detection: utf_8 will be used as a fallback matchz:Encoding detection: ascii will be used as a fallback matchz]Encoding detection: Found %s as plausible (best-candidate) for content. With %i alternatives.z=Encoding detection: Unable to determine any suitable charset.)7
isinstance	bytearraybytes	TypeErrorformattypeloggerlevel
addHandlerexplain_handlersetLevelr   lendebugremoveHandlerr   r   logjoinr&   r   r   r   appendsetr   r   r   r   insertr!   addr   r   ModuleNotFoundErrorImportErrorr   r	   intersectionstrUnicodeDecodeErrorLookupErrorrangemaxr   sumdecoder   updateroundr
   r   bestAssertionErrorfingerprint)<r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   Zprevious_logger_levellengthZis_too_small_sequenceZis_too_large_sequenceZprioritized_encodingsZspecified_encodingZtestedZtested_but_hard_failureZtested_but_soft_failureZsoft_failure_skipZcached_mess_ratioZcached_coherence_ratioZdefinitive_match_foundZdefinitive_target_languagesZ post_definitive_sb_success_countZPOST_DEFINITIVE_SB_CAPZmb_definitive_match_foundZfallback_asciiZfallback_u8Zfallback_specifiedresultsZearly_stop_resultsZsig_encodingZsig_payloadZencoding_ianaZdecoded_payloadZbom_or_sig_availableZstrip_sig_or_bomZis_multi_byte_decoderZenc_languagesZdeferred_decodingeZr_Zmulti_byte_bonusZmax_chunk_gave_upZearly_stop_countZlazy_str_hard_failureZ	md_chunksZ	md_ratioschunkZmean_mess_ratioZfallback_entryZtarget_languagesZ	cd_ratiosZlg_inclusionZchunk_languagesZcd_ratios_mergedZcurrent_matchZprobable_resultZbest_coherencer   r   r   
from_bytes2   sP   






	







	





"









	












	





	






r{   r   )fpr*   r+   r,   r-   r.   r/   r0   r1   r2   r3   c
           
      C  s   t |  |||||||||	
S )z
    Same thing than the function from_bytes but using a file pointer that is already ready.
    Will not close the file pointer.
    )r{   read)
r|   r*   r+   r,   r-   r.   r/   r0   r1   r2   r   r   r   from_fp*  s    r~   zstr | bytes | PathLike)pathr*   r+   r,   r-   r.   r/   r0   r1   r2   r3   c
                 C  s<   t | d(}
t|
|||||||||	
W  5 Q R  S Q R X dS )z
    Same thing than the function from_bytes but with one extra step. Opening and reading given file path in binary mode.
    Can raise IOError.
    rbN)openr~   )r   r*   r+   r,   r-   r.   r/   r0   r1   r2   r|   r   r   r   	from_pathH  s    r   z!PathLike | str | BinaryIO | bytes)fp_or_path_or_payloadr*   r+   r,   r-   r.   r/   r0   r1   r2   r3   c
                 C  sz   t | ttfr,t| |||||||||	d
}
nHt | ttfrXt| |||||||||	d
}
nt| |||||||||	d
}
|
 S )a)  
    Detect if the given input (file, bytes, or path) points to a binary file. aka. not a string.
    Based on the same main heuristic algorithms and default kwargs at the sole exception that fallbacks match
    are disabled to be stricter around ASCII-compatible but unlikely to be a string.
    )	r*   r+   r,   r-   r.   r/   r0   r1   r2   )rT   rk   r   r   rV   rU   r{   r~   )r   r*   r+   r,   r-   r.   r/   r0   r1   r2   Zguessesr   r   r   	is_binaryg  sX    r   )	r"   r#   r$   NNTFr%   T)	r"   r#   r$   NNTFr%   T)	r"   r#   r$   NNTFr%   T)	r"   r#   r$   NNTFr%   F)-
__future__r   logging	functoolsr   osr   typingr   Zcdr   r   r	   r
   Zconstantr   r   r   r   r   Zmdr   modelsr   r   utilsr   r   r   r   r   r   	getLoggerrZ   StreamHandlerr]   setFormatter	Formattersortedr!   __annotations__r{   r~   r   r   r   r   r   r   <module>   s     	
          $                $          $!         