Ë
    Dü´j,i  ã                   ó¸  — U 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	Z	ddl
mZ ddlmZmZ ddlmZmZ  ej                  d«       ej                  d«      fZej&                  j)                  d«      Z ej,                  d«      j.                  Z ej,                  d	«      j.                  Z ed
„  ed«      D «       «      ZdZdZi Ze e!e!f   e"d<    ejF                  «       D ]4  Z$ e%e$jL                  «      dk(  sŒe$jL                  d   ee$jN                  <   Œ6 	 d2dede(de)e!   de(de e!ef   f
d„Z*dede+e e!ef   e e!e,f   f   fd„Z-ej\                  de+e e!ef   e e!e,f   f   fd„«       Z/de e!ef   fd„Z0de e!ef   de e!e)e+e!dz  ee!f      f   fd„Z1ej\                  de e!e)e+e!dz  ee!f      f   fd„«       Z2de!de!dz  fd„Z3de!de4fd„Z5de e!e,f   fd„Z6ej\                  de e!ef   fd „«       Z7ej\                  defd!„«       Z8 G d"„ d#«      Z9	 d3d$e9d%d&d'e!de,fd(„Z: e;h d)£«      Z<e;e!   e"d*<   d+Z=d,Z>d-Z?	 d4d.d/œdede!d$e9dz  d0e4de+e,e!dz  f   f
d1„Z@y)5zÒModel loading and bigram scoring utilities.

Note: ``from __future__ import annotations`` is intentionally omitted because
this module is compiled with mypyc, which does not support PEP 563 string
annotations.
é    N)Ú_kernel)Ú
dot_packedÚpack_profile)ÚREGISTRYÚlookup_encodingÚi)z.soz.pydz>Iz>dc              #   ó,   K  — | ]  }|d v rdnd–— Œ y­w))é    é	   é
   é   é   é   é    é   r   N© )Ú.0Úbs     úU/root/workspace/ytshorts/venv/lib/python3.12/site-packages/chardet/models/__init__.pyú	<genexpr>r   9   s"   è ø€ ò  ØDEˆÐ8Ñ	8�A¸aÓ?ñ ùs   ‚é   s   CMD2s   CRM1Ú_SINGLE_LANG_MAPr   ÚdataÚoffsetÚnamesÚ
chunk_sizeÚreturnc                 ó(  — t        |«      }|dz  }t        j                  «       }i }t        «       }d}	|}
t        | «      }d}t        |«      |k  rçdt        |«      z
  }|j                  r|j                  |j                  |«      }nF|
|k  r)| |
|
|z    }|
t        |«      z  }
|j                  ||«      }n|sd}|j                  «       }|snknj|	t        |«      z  }	||z  }t        |«      dk(  r+t        |«      ||t        |«         <   |j                  «        nt        |«      dkD  rnt        |«      |k  rŒçt        |«      |k(  r§d}|j                  r|j                  |j                  d«      }|sM|j                  sA|
|k  r<| |
|
|z    }|
t        |«      z  }
|j                  |d«      }|s|j                  s|
|k  rŒ<|s|j                  s|s|j                  «       }|	t        |«      z  }	|	|k7  st        |«      |k7  rd|	› d|› �}t        |«      ‚|S )	uû  Decompress the model tables from ``data[offset:]``, one per name.

    Each model is stored as its own bytes object rather than a memoryview
    slice of one big blob: mypyc compiles bytes indexing in the scoring hot
    loop to a native C array access, while memoryview indexing goes through
    a boxed generic call.  Decompression is incremental, one 64 KB table at
    a time â€” materializing the whole multi-megabyte blob and slicing it
    would transiently double the allocation and strand the freed pages in
    process RSS.  Trailing compressed bytes are ignored, as with whole-blob
    ``zlib.decompress``; the decompressed size is validated instead.

    :raises ValueError: If the decompressed size is not exactly
        ``len(names) * 65536``.
    é   r   FTó    r   z&corrupt models.bin: decompressed size z != expected )ÚlenÚzlibÚdecompressobjÚ	bytearrayÚunconsumed_tailÚ
decompressÚflushÚbytesÚclearÚeofÚ
ValueError)r   r   r   r   Ú
num_modelsÚexpected_sizeÚdecompÚmodelsÚtableÚproducedÚposÚendÚflushedÚneedÚpieceÚchunkÚextraÚmsgs                     r   Ú_decompress_tablesr:   I   s$  € ô" �U“€JØ Ñ&€MÜ×ÑÓ!€FØ!€FÜ‹K€EØ€HØ
€CÜ
ˆd‹)€CØ€GÜ
ˆf‹+˜
Ò
"Ø”s˜5“zÑ!ˆØ×!Ò!Ø×%Ñ% f×&<Ñ&<¸dÓC‰EØ�3ŠYØ˜˜s ZÑ/Ð0ˆEØ”3�u“:ÑˆCØ×%Ñ% e¨TÓ2‰EÙØˆGØ—L‘L“NˆEÙØàØ”C˜“JÑˆØ�‰ˆÜˆu‹:˜ÒÜ).¨u«ˆF�5œ˜V›Ñ%Ñ&Ø�K‰K�MÜ�‹Z˜%ÒØô+ ˆf‹+˜
Ó
"ô, ˆ6ƒ{�jÒ ð
 ˆØ×!Ò!Ø×%Ñ% f×&<Ñ&<¸aÓ@ˆEÙ §
¢
¨s°SªyØ˜˜s ZÑ/Ð0ˆEØ”3�u“:ÑˆCØ×%Ñ% e¨QÓ/ˆEñ  §
¢
¨s°S«yñ ˜VŸZšZ±Ø—L‘L“NˆEØ”C˜“JÑˆØ�=Ò ¤C¨£K°:Ò$=à4°X°Jð ?Ø(˜/ð+ð 	ô ˜‹oÐØ€Mr    c                 ód  — 	 | dd t         k7  rd}t        |«      ‚d}t        | |«      \  }|dz  }|dkD  rd|› d�}t        |«      ‚g }i }t        |«      D ]p  }t        | |«      \  }|dz  }|dkD  rd|› d	�}t        |«      ‚| |||z    j	                  d
«      }||z  }t        | |«      \  }	|dz  }|j                  |«       |	||<   Œr t        | ||«      }
|
|fS # t        j                  $ r}d|› �}t        |«      |‚d}~wt        j                  t        f$ r}d|› �}t        |«      |‚d}~ww xY w)záParse the v2 dense zlib-compressed models.bin format.

    :param data: Raw bytes of models.bin (must be non-empty).
    :returns: A ``(models, norms)`` tuple.
    :raises ValueError: If the data is corrupt or truncated.
    Né   z&corrupt models.bin: missing CMD2 magici'  zcorrupt models.bin: num_models=z exceeds limitr   zcorrupt models.bin: name_len=z exceeds 256zutf-8é   zcorrupt models.bin: )Ú	_V2_MAGICr+   Ú_unpack_uint32ÚrangeÚdecodeÚ_unpack_float64Úappendr:   r"   ÚerrorÚstructÚUnicodeDecodeError)r   r9   r   r,   r   ÚnormsÚ_Úname_lenÚnameÚnormr/   Úes               r   Ú_parse_models_binrM   ‘   s{  € ð#%Ø��ˆ8”yÒ Ø:ˆCÜ˜S“/Ð!àˆÜ& t¨VÓ4‰ˆØ�!‰ˆà˜ÒØ3°J°<¸~ÐNˆCÜ˜S“/Ð!àˆØ"$ˆÜ�zÓ"ò 	ˆAÜ(¨¨vÓ6‰KˆXØ�a‰KˆFØ˜#Š~Ø5°h°Z¸|ÐL�Ü  “oÐ%Ø˜ ¨(Ñ!2Ð3×:Ñ:¸7ÓCˆDØ�hÑˆFÜ% d¨FÓ3‰GˆTØ�a‰KˆFØ�L‰L˜ÔØˆE�$ŠKð	ô $ D¨&°%Ó8ˆð �5ˆ=Ðøô �:‰:ò %Ø$ Q CÐ(ˆÜ˜‹o 1Ð$ûÜ�L‰LÔ,Ð-ò %Ø$ Q CÐ(ˆÜ˜‹o 1Ð$ûð%ús$   ‚CC ÃD/Ã,C=Ã=D/ÄD*Ä*D/c                  óØ   — t         j                  j                  d«      j                  d«      } | j	                  «       }|s t        j                  dt        d¬«       i i fS t        |«      S )zkLoad and parse models.bin, returning (models, norms).

    Cached: only reads from disk on first call.
    úchardet.modelsú
models.binuX   chardet models.bin is empty â€” statistical detection disabled; reinstall chardet to fixé   ©Ú
stacklevel)	Ú	importlibÚ	resourcesÚfilesÚjoinpathÚ
read_bytesÚwarningsÚwarnÚRuntimeWarningrM   ©Úrefr   s     r   Ú_load_models_datar^   Â   sb   € ô ×
Ñ
×
#Ñ
#Ð$4Ó
5×
>Ñ
>¸|Ó
L€CØ�>‰>Ó€DáÜ�‰ð'äØõ		
ð �2ˆvˆä˜TÓ"Ð"r    c                  ó   — t        «       d   S )zôLoad all bigram models from the bundled models.bin file.

    Each model is a bytes object of length 65536 (256*256).
    Index: (b1 << 8) | b2 -> weight (0-255).

    :returns: A dict mapping model key strings to 65536-byte lookup tables.
    r   ©r^   r   r    r   Úload_modelsra   ×   s   € ô Ó˜qÑ!Ð!r    r/   c                 ó  — i }| j                  «       D ]>  \  }}|j                  dd«      \  }}|j                  |g «      j                  |||f«       Œ@ t	        |«      D ]  }t        |«      }|€Œ||vsŒ||   ||<   Œ |S )zËBuild a grouped index from a models dict.

    :param models: Mapping of ``"lang/encoding"`` keys to 65536-byte tables.
    :returns: Mapping of encoding name to ``[(lang, model, model_key), ...]``.
    ú/r   )ÚitemsÚsplitÚ
setdefaultrC   Úlistr   )r/   ÚindexÚkeyÚmodelÚlangÚencÚenc_nameÚ	canonicals           r   Ú_build_enc_indexro   â   s™   € ð =?€EØ—l‘l“nò =‰
ˆˆUØ—I‘I˜c 1Ó%‰	ˆˆcØ×Ñ˜˜bÓ!×(Ñ(¨$°°sÐ);Õ<ð=ô ˜“Kò /ˆÜ# HÓ-ˆ	ØÑ  Y°eÒ%;Ø$ X™ˆE�)Òð/ð
 €Lr    c                  ó(   — t        t        «       «      S )zTReturn a pre-grouped index mapping encoding name -> [(lang, model, model_key), ...].)ro   ra   r   r    r   Úget_enc_indexrq   ù   s   € ô œK›MÓ*Ð*r    Úencodingc                 ó,   — t         j                  | «      S )zÕReturn the language for a single-language encoding, or None.

    :param encoding: The canonical encoding name.
    :returns: An ISO 639-1 language code, or ``None`` if the encoding is
        multi-language.
    )r   Úget©rr   s    r   Úinfer_languagerv   ÿ   s   € ô ×Ñ Ó)Ð)r    c                 ó   — | t        «       v S )z¾Return True if the encoding has language variants in the model index.

    :param encoding: The canonical encoding name.
    :returns: ``True`` if bigram models exist for this encoding.
    )rq   ru   s    r   Úhas_model_variantsrx   	  s   € ð ”}“Ð&Ð&r    c                  ó   — t        «       d   S )zAReturn cached L2 norms for all models, keyed by model key string.r   r`   r   r    r   Ú_get_model_normsrz     s   € äÓ˜qÑ!Ð!r    c                  óè  ‡— t        «       } t        j                  j                  d«      }	 |j	                  d«      j                  «       }t        j                  |j	                  d«      j                  «       «      j                  «       }d}|dd t        k(  rV|d| |k(  rNt        |«      |t        | «      dz  z   k(  r1t        | «      D ��ci c]  \  }}||||dz  z   ||d	z   dz  z    “Œ c}}S | rt        j                  d
t         d¬«       | j#                  «       D ��‡ci c]%  \  }Š|t%        ˆfd„t'        ddd«      D «       «      “Œ' c}}S # t        t        f$ r d}d}Y ŒÙw xY wc c}}w c c}}w )uï  Return per-model row-maximum tables for upper-bound prescreening.

    For each model, entry ``b1`` of its 256-byte table holds the maximum
    weight in the model's row for lead byte ``b1``.  Because every bigram
    weight is bounded by its row maximum, a dot product against the row
    maxima (256 terms) upper-bounds the dot product against the full table
    (65536 terms) â€” statistical scoring uses this to rule out candidate
    models without scoring them fully.

    Loads the precomputed ``rowmax.bin`` (written by ``scripts/train.py`` in
    the same model order as ``models.bin``).  The file starts with a ``CRM1``
    magic and the SHA-256 of the ``models.bin`` it was derived from: a stale
    or mismatched file would silently under-estimate row maxima and break
    the upper bound that pruning depends on, so anything that does not match
    the *current* ``models.bin`` byte-for-byte is rejected and the tables
    are derived from the models directly (slower, but always correct).
    rO   z
rowmax.binrP   r    é$   Nr<   r   r   zpchardet rowmax.bin is missing or does not match models.bin; deriving row maxima from the models (slower startup)rQ   rR   c              3   ó@   •K  — | ]  }t        ‰||d z    «      –— Œ y­w)r   N)Úmax)r   Ústartr0   s     €r   r   zget_rowmax.<locals>.<genexpr>G  s!   øè ø€ ÒU°u”3�u˜U U¨S¡[Ð1×2ÑUùs   ƒr   r   )ra   rT   rU   rV   rW   rX   ÚhashlibÚsha256ÚdigestÚFileNotFoundErrorÚOSErrorÚ_ROWMAX_MAGICr!   Ú	enumeraterY   rZ   r[   rd   r(   r@   )r/   rV   r   Úmodels_digestÚheader_sizer   ri   r0   s          `r   Ú
get_rowmaxr‰     s~  ø€ ô& ‹]€FÜ×Ñ×%Ñ%Ð&6Ó7€EðØ�~‰~˜lÓ+×6Ñ6Ó8ˆÜŸ™Ø�N‰N˜<Ó(×3Ñ3Ó5ó
ç
‰&‹(ð 	ð €KàˆRˆaˆ”MÒ!Ø��;Ð =Ò0Ü�‹I˜¤s¨6£{°SÑ'8Ñ8Ò8ô
 $ FÓ+÷
á��3ð ��k A¨¡GÑ+¨k¸QÀ¹UÀc¹MÑ.IÐJÑJó
ð 	
ñ Ü�‰ðCäØõ		
ð !Ÿ,™,›.÷ð áˆC�ð 	ŒUÓUÄÀaÈÐPSÓ@TÔUÓUÑUóð øô+ œwÐ'ò ØˆØŠðüó
ùós   ¬AE ÃE(Ä!*E.ÅE%Å$E%c                  óú   — t         j                  j                  d«      j                  d«      } | j	                  «       }t        |«      dk7  r.t        j                  dt        |«      › d�t        d¬«       ddz  S |S )	uÎ  Return a 65536-byte IDF weight table for bigram profile construction.

    Loads a precomputed table from ``idf.bin`` (generated at training time).
    For each bigram index, the weight reflects how discriminative that bigram
    is across all models:

    - Bigrams in every model (common ASCII) â†’ weight 1 (minimal signal)
    - Bigrams in one model â†’ weight 255 (maximum signal)
    - Bigrams not in any model â†’ weight 1 (unknown, treat as neutral)
    rO   zidf.binr   z chardet idf.bin has wrong size (z"), falling back to uniform weightsrQ   rR   ó   )	rT   rU   rV   rW   rX   r!   rY   rZ   r[   r\   s     r   Úget_idf_weightsrŒ   L  sv   € ô ×
Ñ
×
#Ñ
#Ð$4Ó
5×
>Ñ
>¸yÓ
I€CØ�>‰>Ó€DÜ
ˆ4ƒy�EÒÜ�‰Ø.¬s°4«y¨kð :.ð .äØõ		
ð ˜‰ÐØ€Kr    c            
       óv   — e Zd ZdZdZdeddfd„Zdee   dee   d	ee   d
eddf
d„Z	e
deeef   dd fd„«       Zy)ÚBigramProfileu  Pre-computed bigram frequency distribution for a data sample.

    Computing this once and reusing it across all models reduces per-model
    scoring from O(n) to O(distinct_bigrams).

    Each bigram is weighted by its IDF (inverse document frequency) across all
    models â€” bigrams unique to few models get high weight, bigrams common to
    all models get weight 1.  ``nonzero`` lists the indices carrying weight,
    in first-encounter order.

    The weights are reachable two ways, and which one a profile fills
    depends on how it was built:

    * ``idx_arr``/``val_arr`` â€” parallel ``array('i')`` buffers, what
      :func:`score_with_profile` reads for a streaming profile.  Filled by
      the streaming constructor only.
    * ``values`` â€” a plain list parallel to ``nonzero``, filled by
      :meth:`from_weighted_freq` for the small focused profiles confusion
      resolution builds, which are scored inline instead.
    ``row_freq`` aggregates the weights by lead byte (256 entries) and
    ``nonzero_rows`` lists the lead bytes with non-zero total; together with
    per-model row maxima (:func:`get_rowmax`) they let statistical scoring
    compute a cheap upper bound on a model's score.

    **Input limit.** Weights are packed as int32, which holds any value an
    input of at most 16 MB can produce (``255`` per occurrence against a
    2.1-billion ceiling).  Detection truncates to ``max_bytes`` long before
    that; construct a profile directly from a larger buffer and packing
    raises :exc:`OverflowError`.
    )	ÚfreqÚidx_arrÚ
input_normÚnonzeroÚnonzero_rowsÚrow_freqÚval_arrÚvaluesÚ
weight_sumr   r   Nc                 óÌ  — t        |«      dz
  }|dk  rEg | _        g | _        g | _        t        \  | _        | _        g | _        g | _        d| _	        d| _
        yt        «       }dgdz  }g }d}t        |«      D ]V  }||   }||dz      }	||	k(  r
t        |   rŒ|dz  |	z  }
||
   }||
   dk(  r|j                  |
«       ||
xx   |z  cc<   ||z  }ŒX | j                  ||g |«       y)a?  Compute the bigram frequency distribution for *data*.

        Each bigram is weighted by its IDF (inverse document frequency) across
        all loaded models.  Bigrams unique to few models get high weight;
        bigrams common to all models get weight 1.

        :param data: The raw byte data to profile.
        r   r   ç        Nr   r=   )r!   r�   r’   r–   Ú_EMPTY_PACKEDr�   r•   r”   r“   r—   r‘   rŒ   r@   Ú_ASCII_WHITESPACE_TABLErC   Ú_finish)Úselfr   Útotal_bigramsÚidfr�   r’   Úw_sumr   Úb1Úb2ÚidxÚws               r   Ú__init__zBigramProfile.__init__‘  s  € ô ˜D›	 A™ˆØ˜AÒà#%ˆDŒIØ&(ˆDŒLØ%'ˆDŒKÜ)6Ñ&ˆDŒL˜$œ,Ø')ˆDŒMØ+-ˆDÔØ#$ˆDŒOØ%(ˆDŒOØäÓˆØ˜# ™+ˆØˆØˆÜ�}Ó%ò 	ˆAØ�a‘ˆBØ�a˜!‘e‘ˆBð
 �RŠxÔ3°BÒ7ØØ˜‘7˜b‘.ˆCØ�C‘ˆAØ�C‰y˜AŠ~Ø—‘˜sÔ#Ø�‹I˜‰N‹IØ�Q‰J‰Eð	ð$ 	�‰�T˜7 B¨Õ.r    r�   r’   r–   r—   c                 ó*  — || _         || _        || _        d}dgdz  }|r:t        t	        |«      «      D ]"  }||   }|||z  z  }|||   dz	  xx   |z  cc<   Œ$ n$|D ]  }	||	   }|||z  z  }||	dz	  xx   |z  cc<   Œ! t        j                  |«      | _        || _        t        d«      D �
cg c]
  }
||
   sŒ	|
‘Œ c}
| _	        |st        st        \  | _        | _        nt        ||«      \  | _        | _        |st        rg | _        y|| _        yc c}
w )aQ  Store the frequency data and derive the norm and row aggregates.

        Single finalization path shared by both constructors so pruning
        fields cannot silently diverge between them.

        Exactly one of *freq* and *values* carries the weights, never both.
        The streaming constructor passes the dense *freq* table it had to
        build and leaves *values* empty; the sparse constructor fills
        *values* parallel to *nonzero* and passes no table, which is what
        lets it skip a 65536-entry allocation per call.

        Neither is retained.  *freq* is read here to derive the norm, the row
        aggregates and the packed buffers, and is then dropped -- scoring
        reads ``idx_arr``/``val_arr`` or ``values``, never the dense table,
        so keeping it alive would pin 512 KB per profile for nothing.
        r   r   r=   N)r’   r–   r—   r@   r!   ÚmathÚsqrtr‘   r”   r“   Ú_KERNEL_COMPILEDrš   r�   r•   r   r�   )r�   r�   r’   r–   r—   Únorm_sqr”   r   Úvr£   r¡   s              r   rœ   zBigramProfile._finish¿  s(  € ð. ˆŒØˆŒØ$ˆŒØˆØ ˜c C™iˆÙÜœ3˜w›<Ó(ò /�Ø˜1‘I�Ø˜1˜q™5Ñ �Ø˜ ™ q™Ó)¨QÑ.Ô)ñ/ð
 ò (�Ø˜‘I�Ø˜1˜q™5Ñ �Ø˜ ™Ó" aÑ'Ô"ð(ô Ÿ)™) GÓ,ˆŒØ ˆŒÜ*/°«*ÖE B¸À»šRÒEˆÔñ Õ)Ü)6Ñ&ˆDŒL˜$�,ä)5°g¸tÓ)DÑ&ˆDŒL˜$œ,á!Õ%5�Bˆ�	¸Dˆ�	ùò Fs   Â,
DÂ7DÚweighted_freqc                 óÎ   —  | d«      }g }g }d}|j                  «       D ]/  \  }}|sŒ	|j                  |«       |j                  |«       ||z  }Œ1 |j                  g |||«       |S )u  Create a BigramProfile from pre-computed weighted frequencies.

        Computes ``weight_sum`` and ``input_norm`` from *weighted_freq* to
        ensure consistency between the stored fields.

        Deliberately does not build the dense 65536-entry ``freq`` table
        the streaming constructor uses.  Callers here pass a handful of
        bigrams â€” confusion resolution's focused profiles hold a median of
        eight â€” and allocating a 65536-element list per call cost about
        24us, which measured as roughly 40% of the whole bigram-rescore
        stage.  Scoring reads ``nonzero``/``values``, so the table is
        never needed.

        :param weighted_freq: Mapping of bigram index to weighted count.
        :returns: A new :class:`BigramProfile` instance.
        r    r   )rd   rC   rœ   )Úclsr¬   Úprofiler’   r–   r    r£   Úcounts           r   Úfrom_weighted_freqz BigramProfile.from_weighted_freqò  su   € ñ$ �c“(ˆØˆØˆØˆØ'×-Ñ-Ó/ò 	‰JˆC�ÚØ—‘˜sÔ#Ø—‘˜eÔ$Ø˜‘‘ð		ð
 	�‰˜˜G V¨UÔ3Øˆr    )Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú	__slots__r(   r¥   rg   Úintrœ   ÚclassmethodÚdictr±   r   r    r   rŽ   rŽ   e  s”   „ ñð>
€Ið,/˜Uð ,/ tó ,/ð\1Aà�3‰ið1Að �c‘ð1Að �S‘	ð	1Að
 ð1Að 
ó1Aðf ð¨t°C¸°H©~ð À/ò ó ñr    rŽ   r¯   rj   zbytes | bytearray | memoryviewÚ	model_keyc                 ó\  — t        |t        «      st        |«      }| j                  dk(  ryt        «       }|r|j	                  |«      nd}|€7d}t        d«      D ]  }||   }|sŒ|||z  z  }Œ t        j                  |«      }|dk(  ry| j                  }| j                  }	|	r-d}
t        t        |«      «      D ]  }|
|||      |	|   z  z  }
Œ nKt        r"t        | j                  | j                  |«      }
n#d}
| j                  }|D ]  }|
||   ||   z  z  }
Œ |
|| j                  z  z  S )an  Score a pre-computed bigram profile against a single model using cosine similarity.

    ``bytearray``/``memoryview`` tables are accepted for compatibility but
    copied to ``bytes`` first: the narrow type lets mypyc compile the
    dot-product loop with native byte indexing (and keeps compiled and
    pure-Python installs accepting the same argument types).
    r™   Nr   r   )Ú
isinstancer(   r‘   rz   rt   r@   r§   r¨   r’   r–   r!   r©   r   r�   r•   r�   )r¯   rj   rº   rG   Ú
model_normÚsq_sumr   r«   r’   r–   Údotr�   r£   s                r   Úscore_with_profilerÀ     sI  € ô �eœUÔ#Ü�e“ˆØ×Ñ˜SÒ ØÜÓ€EÙ)2�—‘˜9Ô%¸€JØÐØˆÜ�u“ò 	 ˆAØ�a‘ˆAÚØ˜!˜a™%‘‘ð	 ô —Y‘Y˜vÓ&ˆ
Ø�SÒØØ�o‰o€GØ�^‰^€FÙð ˆÜ”s˜7“|Ó$ò 	1ˆAØ�5˜ ™Ñ$ v¨a¡yÑ0Ñ0‰Cñ	1å	Ü˜Ÿ™¨'¯/©/¸5ÓA‰ð ˆØ�|‰|ˆØò 	*ˆCØ�5˜‘:  S¡	Ñ)Ñ)‰Cð	*à�*˜w×1Ñ1Ñ1Ñ2Ð2r    >   ÚbrÚcyÚgaÚgdÚRARE_LANGUAGESÚzxxé€   g¸…ëQ¸ž?F)Údemote_thin_rarerÈ   c                ó4  — | s|€yt        «       }|j                  |«      }|€y|€t        | «      }d}d}d}d}	|D ]<  \  }
}}t        |||«      }||kD  r|}|
}|sŒ |
t        vsŒ)|
t
        k7  sŒ3||kD  sŒ9|}|
}	Œ> |r|�|t        v r|	�||z
  t        k  r|	}||fS )a  Score data against all language variants of an encoding.

    Returns (best_score, best_language). Uses a pre-grouped index for O(L)
    lookup where L is the number of language variants for the encoding.

    If *profile* is provided, it is reused instead of recomputing the bigram
    frequency distribution from *data*.

    :param data: The raw byte data to score.
    :param encoding: The canonical encoding name to match against.
    :param profile: Optional pre-computed :class:`BigramProfile` to reuse.
    :param demote_thin_rare: Pass true only when the caller has judged the
        *original* input thin (under :data:`_THIN_RARE_MAX_BYTES` before
        any transcoding).  A :data:`RARE_LANGUAGES` winner that leads the
        best prevalent-language variant by less than the measured noise
        band is then reported under the prevalent language instead.  The
        length judgment deliberately lives with the caller: this function
        may receive transcoded bytes or a profile without its source data,
        so ``len(data)`` here is not a reliable proxy for input size.
        Language-fill callers pass this; encoding-ranking callers must not,
        so that candidate ordering stays byte-identical.
    :returns: A ``(score, language)`` tuple.  The score is always the best
        cosine similarity across variants; the language matches it except
        when ``demote_thin_rare`` fires, in which case the label is the
        best prevalent-language variant's while the score remains the
        rare winner's.
    N)r™   Nr™   )rq   rt   rŽ   rÀ   rÅ   ÚART_LANGUAGEÚ_THIN_RARE_MARGIN)r   rr   r¯   rÈ   rh   ÚvariantsÚ
best_scoreÚ	best_langÚbest_prevalentÚbest_prevalent_langrk   rj   rº   Úss                 r   Úscore_best_languagerÒ   ]  sã   € ñD �G�OØä‹O€EØ�y‰y˜Ó"€HØÐØà€Ü Ó%ˆà€JØ €IØ€NØ&*ÐØ"*ò 'Ñˆˆe�YÜ˜w¨¨yÓ9ˆØˆzŠ>ØˆJØˆIâØœNÒ*ØœÓ$Ø�NÓ"àˆNØ"&Ñð'ñ 	ØÐ!ØœÑ'ØÐ+Ø˜Ñ'Ô*;Ò;à'ˆ	à�yÐ Ð r    )i   )Ú )N)Arµ   ÚarrayÚ	functoolsr€   Úimportlib.resourcesrT   r§   rE   rY   r"   Úchardetr   Úchardet._kernelr   r   Úchardet.registryr   r   rš   Ú__file__Úendswithr©   ÚStructÚunpack_fromr?   rB   r(   r@   r›   r>   r…   r   r¹   ÚstrÚ__annotations__r–   Ú_encr!   Ú	languagesrJ   r·   rg   r:   ÚtupleÚfloatrM   Úcacher^   ra   ro   rq   rv   Úboolrx   rz   r‰   rŒ   rŽ   rÀ   Ú	frozensetrÅ   rÊ   Ú_THIN_RARE_MAX_BYTESrË   rÒ   r   r    r   ú<module>rè      s§  ðòó Û Û Û Û Û Û Û å ß 4ß 6ð �—‘˜SÓ! ; 5§;¡;¨sÓ#3Ð4€ð  ×#Ñ#×,Ñ,¨_Ó=Ð à�—‘˜tÓ$×0Ñ0€Ø�&—-‘- Ó%×1Ñ1€ñ  ñ  ÙINÈsËô ó Ð ð €	ð €ð $&Ð �$�s˜C�x‘.Ó %ØˆH�O‰OÓò 8€DÙ
ˆ4�>‰>Ó˜aÓØ&*§n¡n°QÑ&7Ð˜Ÿ™Ò#ð8ð CIñEØ
ðEØðEØ%)¨#¡YðEØ<?ðEà	ˆ#ˆuˆ*ÑóEðP.Ø
ð.à
ˆ4��U�
Ñ˜T # u *Ñ-Ð-Ñ.ó.ðb ‡�ð#˜5  c¨5 jÑ!1°4¸¸U¸
Ñ3CÐ!CÑDò #ó ð#ð("�T˜#˜u˜*Ñ%ó "ðØ��e�Ñðà	ˆ#ˆt�E˜# ™* e¨SÐ0Ñ1Ñ2Ð
2Ñ3óð. ‡�ð+�t˜C  e¨C°$©J¸¸sÐ,BÑ&CÑ!DÐDÑEò +ó ð+ð
*˜Sð * S¨4¡Zó *ð' ð '¨ó 'ð"˜$˜s E˜zÑ*ó "ð
 ‡�ð1�D˜˜e˜Ñ$ò 1ó ð1ðh ‡�ð˜ò ó ð÷0iñ ið^ ñ-3Øð-3à+ð-3ð ð-3ð ó	-3ñh "+Ò+CÓ!D€�	˜#‘Ó Dð
 €ð Ð ð Ð ð %)ðH!ð
 #òH!Ø
ðH!àðH!ð ˜TÑ!ðH!ð
 ðH!ð ˆ5�#˜‘*ÐÑôH!r    