Ë
    ^ãjÙ9  ã                   óH  — d Z ddlZddlZddlZddlZddlmZ dZdZdZ	dZ
dZ ej                  d«      j                  Z ej                  d	«      j                  Z	 d d
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d
ededee   deeef   dz  fd„Zd
ededee   deeef   dz  fd„Zdededefd„Zdedefd„Zdedeeeeeef   ef   f   fd„Zdeeeeeef   ef   f   defd„Zdeeeeeef   ef   f   dedeeef   fd„Zdee   dedefd„Z y)!a  Owner of the model-artifacts file format, write side and read side.

The model artifacts are the digest-locked file set the trainer produces as
one unit: ``models.bin`` (``CMD2``: per-model names and L2 norms, then
zlib-compressed dense bigram tables), ``rowmax.bin`` (``CRM1``: per-model
row maxima for upper-bound prescreening, digest-locked to the
``models.bin`` they were computed from), ``idf.bin`` (a 65536-byte
quantized IDF table), and ``langnorm.bin`` (``CLN1``: per-model norms
under the IDF-weighted metric the language tiers score in, digest-locked
like ``rowmax.bin``).  Keeping both directions in one module means a
format change cannot land on one side only: ``scripts/train.py`` calls
:func:`write_model_artifacts` and :func:`read_models`, while
:mod:`chardet.models` calls :func:`parse_models_bin` and
:func:`parse_rowmax_bin` behind its cached accessors.

Note: ``from __future__ import annotations`` is intentionally omitted
because this module is compiled with mypyc, which does not support PEP 563
string annotations.
é    N)ÚPaths   CMD2s   CRM1é$   s   CLN1z>Iz>dÚ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ó    é   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                     úX/var/www/html/metafoliadorv2/venv/lib/python3.12/site-packages/chardet/models/_format.pyÚ_decompress_tablesr(   ,   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˜%ÒØô5 ˆf‹+˜
Ó
"ô6 ˆ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 limité   zcorrupt models.bin: name_len=z exceeds 256úutf-8é   zcorrupt models.bin: )ÚMODELS_MAGICr   Ú_unpack_uint32ÚrangeÚdecodeÚ_unpack_float64Úappendr(   r   ÚerrorÚstructÚUnicodeDecodeError)r   r&   r   r   r   ÚnormsÚ_Úname_lenÚnameÚnormr   Úes               r'   Úparse_models_binr=   y   s{  € ð#%Ø��ˆ8”|Ò#Ø:ˆ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/Úmodels_digestÚ
model_keysc           
      óô   — | dd t         k(  rf| dt         |k(  rZt        | «      t        t        |«      dz  z   k(  r9t        |«      D ��ci c]"  \  }}|| t        |dz  z   t        |dz   dz  z    “Œ$ c}}S yc c}}w )u  Parse rowmax.bin into per-model row-maxima tables.

    :param data: Raw bytes of rowmax.bin.
    :param models_digest: SHA-256 digest of the current models.bin bytes.
    :param model_keys: Model keys in models.bin header order.
    :returns: Mapping of model key to its 256-byte row-maxima table, or
        ``None`` when the magic, digest, or size does not match â€” a stale
        or mismatched file would silently under-estimate row maxima and
        break the upper bound that prescreening depends on.
    Nr*   r+   r   )ÚROWMAX_MAGICÚROWMAX_HEADER_SIZEr   Ú	enumerate©r   r>   r?   ÚiÚkeys        r'   Úparse_rowmax_binrG   ª   s’   € ð 	ˆRˆaˆ”LÒ Ø�Ô%Ð&¨-Ò7Ü�‹IÔ+¬c°*«oÀÑ.CÑCÒCô $ JÓ/÷
á��3ð �Ô(¨1¨s©7Ñ2Ô5GÈ1ÈqÉ5ÐTWÉ-Ñ5WÐXÑXó
ð 	
ð ùó	
s   Á'A4c                 óî   — | dd t         k(  rc| dt         |k(  rWt        | «      t        t        |«      dz  z   k(  r6t        |«      D ��ci c]  \  }}|t	        | t        |dz  z   «      d   “Œ! c}}S yc c}}w )a  Parse langnorm.bin into per-model language-scoring norms.

    :param data: Raw bytes of langnorm.bin.
    :param models_digest: SHA-256 digest of the current models.bin bytes.
    :param model_keys: Model keys in models.bin header order.
    :returns: Mapping of model key to its IDF-weighted norm, or ``None``
        when the magic, digest, or size does not match -- a stale file
        would normalize every language score against the wrong length and
        silently tilt the comparison between languages.
    Nr*   r-   r   )ÚLANGNORM_MAGICÚLANGNORM_HEADER_SIZEr   rC   r2   rD   s        r'   Úparse_langnorm_binrK   Ã   sˆ   € ð 	ˆRˆaˆ”NÒ"Ø�Ô'Ð(¨MÒ9Ü�‹IÔ-´°J³À!Ñ0CÑCÒCô $ JÓ/÷
á��3ð ” Ô';¸aÀ!¹eÑ'CÓDÀQÑGÑGó
ð 	
ð ùó	
s   Á$A1r   Úidfc                 ó|   — d}t        d«      D ]  }| |   }|sŒ|||z  ||   z  z  }Œ t        j                  |«      S )a›  Derive one model's norm under the language-scoring metric.

    The language tiers compare an input profile weighted by IDF against
    models weighted by the square root of IDF, so a model's length in that
    space is the root of the sum of ``weight**2 * idf`` over its bigrams.
    Scoring folds the model-side factor into the profile and divides by
    this norm, so the table itself is never rescaled.
    r   r   )r0   ÚmathÚsqrt)r   rL   ÚtotalrE   Úvs        r'   Úlangnorm_from_tablerR   Ü   sO   € ð €EÜ�5‹\ò $ˆØ�!‰HˆÚØ�Q˜‘U˜S ™V‘^Ñ#‰Eð$ô �9‰9�UÓÐr   c                 óB   ‡ — t        ˆ fd„t        ddd«      D «       «      S )z»Derive the 256-byte row-maxima table of one dense model table.

    Entry ``b1`` holds the maximum weight in the model's row for lead byte
    ``b1``; a row with no bigrams yields 0.
    c              3   ó@   •K  — | ]  }t        ‰||d z    «      –— Œ y­w)r+   N)Úmax)Ú.0Ústartr   s     €r'   ú	<genexpr>z$rowmax_from_table.<locals>.<genexpr>ó   s!   øè ø€ ÒS°U”�U˜5 5¨3¡;Ð/×0ÑSùs   ƒr   r   r+   )r   r0   )r   s   `r'   Úrowmax_from_tablerY   í   s   ø€ ô ÓS¼eÀAÀuÈcÓ>RÔSÓSÐSr   Úmodels_pathc                 ó   — | j                  «       si S | j                  «       }|si S t        |«      \  }}i }|j                  «       D ]4  \  }}i }t	        d«      D ]  }||   }	|	dkD  sŒ|	||dz	  |dz  f<   Œ |||<   Œ6 |S )a¼  Read models.bin into the sparse per-model bigram dicts training uses.

    The inverse of :func:`write_model_artifacts`'s models.bin output: only
    non-zero weights appear in the dicts.  A missing or empty file reads as
    no models, so a first-ever training run and a full retrain look the
    same to the caller.

    :returns: Mapping of model key to ``{(b1, b2): weight}``.
    :raises ValueError: If the file exists but is corrupt.
    r   r   r-   éÿ   )Úis_fileÚ
read_bytesr=   Úitemsr0   )
rZ   r   ÚtablesÚ_normsr   r:   r   ÚbigramsÚidxÚweights
             r'   Úread_modelsre   ö   s¨   € ð ×ÑÔ Øˆ	Ø×!Ñ!Ó#€DÙØˆ	Ü% dÓ+�N€FˆFØ46€FØ—|‘|“~ò ‰ˆˆeØ.0ˆÜ˜“<ò 	9ˆCØ˜3‘ZˆFØ˜‹zØ28�˜ ™ 3¨¡:Ð.Ò/ð	9ð ˆˆtŠðð €Mr   r   c                 ó°  — t        | «      }dgdz  }| j                  «       D ]  }|D ]  \  }}||dz  |z  xx   dz  cc<   Œ Œ! |dkD  rt        j                  |«      nd}|dkD  rd|z  nd}t	        d«      }t        d«      D ]H  }	||	   }
|
dkD  r7t        j                  ||
z  «      }t        dt        ||z  «      dz   «      ||	<   ŒDd||	<   ŒJ t        |«      S )aA  Compute the 65536-byte quantized IDF table over all models.

    For each bigram index the byte holds a scaled inverse document
    frequency: bigrams present in every model score 1 (minimal signal),
    bigrams in exactly one model score 255 (maximum signal), and bigrams
    in no model score 1 (unknown, neutral).
    r   r   r-   r   g      ð?g     Ào@g        )	r   ÚvaluesrN   Úlogr   r0   rU   Úroundr   )r   r   Údoc_freqrb   Úb1Úb2Úmax_idfÚscaleÚ	idf_tablerc   ÚdfÚidf_vals               r'   Ú
_idf_tablerr     sô   € ô �V“€JØˆs�U‰{€HØ—=‘=“?ò *ˆØò 	*‰FˆB�Ø�b˜A‘g ‘^Ó$¨Ñ)Ô$ñ	*ð*ð '1°1¢nŒd�h‰h�zÔ"¸#€GØ&¨š{ˆE�GŠO°€EÜ˜%Ó €IÜ�U‹|ò ˆØ�c‰]ˆØ�Š6Ü—h‘h˜z¨B™Ó/ˆGÜ  ¤E¨'°E©/Ó$:¸QÑ$>Ó?ˆI�cŠNàˆI�cŠNðô �ÓÐr   c                 óê  — |j                   j                  dd¬«       t        | «      }t        | «      }t	        t
        «      }|t        j                  dt        |«      «      z  }t	        «       }g }g }|D ]ç  }t	        d«      }	d}
| |   j                  «       D ]  \  \  }}}||	|dz  |z  <   |
||z  z  }
Œ |j                  d«      }|t        j                  dt        |«      «      |z   z  }|t        j                  dt        j                  |
«      «      z  }t        |	«      }||z  }|j                  t        |«      «       |j                  t!        ||«      «       Œé t        |«      t#        j$                  t        |«      d	«      z   }|j'                  |«       t)        j*                  |«      j-                  «       }|j/                  d
«      j'                  |«       t	        t0        «      }||z  }|D ]  }||z  }Œ	 |j/                  d«      j'                  |«       t3        ||«      }|j/                  d«      j'                  |«       t        |«      t        |«      t        |«      t        |«      dœS )aE  Write the model artifacts as one digest-locked set.

    ``models.bin`` is written at *models_path* (whatever its basename);
    ``rowmax.bin`` and ``idf.bin`` are written beside it under their fixed
    names.  ``rowmax.bin`` embeds the SHA-256 of the exact ``models.bin``
    bytes written here and is deliberately written **last**: it is the
    commit marker for the whole set, so an interrupted run leaves a digest
    mismatch that :func:`parse_rowmax_bin` rejects at load time instead of
    a silently stale sibling (``idf.bin`` is validated by size only).

    :param models: Mapping of model key to sparse ``{(b1, b2): weight}``.
    :param models_path: Destination path for models.bin.
    :returns: Sizes in bytes, keyed by canonical artifact name
        (``models.bin``, ``rowmax.bin``, ``idf.bin``, ``langnorm.bin``).
    T)ÚparentsÚexist_okz!Ir   r   r-   r,   ú!dé	   úidf.binú
rowmax.binúlangnorm.bin)z
models.binry   rx   rz   )ÚparentÚmkdirÚsortedrr   r   r.   r5   Úpackr   r_   ÚencoderN   rO   r   r3   rY   rR   r   ÚcompressÚwrite_bytesÚhashlibÚsha256ÚdigestÚ	with_namerA   Úlangnorm_blob_for)r   rZ   Úsorted_namesro   Úheaderr`   Úrowmax_rowsÚ	langnormsr:   r   Úsq_sumrk   rl   rd   Ú
name_bytesÚfrozenÚmodels_blobr>   Úrowmax_blobÚrowÚlangnorm_blobs                        r'   Úwrite_model_artifactsr’   ,  sH  € ð& ×Ñ×Ñ T°DÐÔ9Ü˜&“>€LÜ˜6Ó"€Iä”|Ó$€FØ
Œf�k‰k˜$¤ LÓ 1Ó2Ñ2€FÜ‹[€FØ!€KØ€IØò Aˆä˜%Ó ˆØˆØ & t¡× 2Ñ 2Ó 4ò 	&Ñ‰HˆR��fØ$*ˆE�2˜‘7˜b‘.Ñ!Ø�f˜v‘oÑ%‰Fð	&ð —[‘[ Ó)ˆ
Ø”&—+‘+˜d¤C¨
£OÓ4°zÑAÑAˆØ”&—+‘+˜d¤D§I¡I¨fÓ$5Ó6Ñ6ˆô �u“ˆØ�&ÑˆØ×ÑÔ,¨VÓ4Ô5Ø×ÑÔ,¨V°YÓ?Õ@ðAô" ˜“-¤$§-¡-´°f³¸qÓ"AÑA€KØ×Ñ˜KÔ(Ü—N‘N ;Ó/×6Ñ6Ó8€Mà×Ñ˜)Ó$×0Ñ0°Ô;äœLÓ)€KØ�=Ñ €KØò ˆØ�sÑ‰ðà×Ñ˜,Ó'×3Ñ3°KÔ@ä% i°Ó?€MØ×Ñ˜.Ó)×5Ñ5°mÔDô ˜+Ó&Ü˜+Ó&Ü�y“>Ü˜MÓ*ñ	ð r   rŠ   c                 ó€   — t        t        «      }||z  }| D ]  }|t        j                  d|«      z  }Œ t	        |«      S )z<Serialize langnorm.bin for norms in models.bin header order.rv   )r   rI   r5   r~   r   )rŠ   r>   Úblobr;   s       r'   r†   r†   p  sD   € ä”^Ó$€DØˆMÑ€DØò (ˆØ”—‘˜D $Ó'Ñ'‰ð(ä�‹;Ðr   )i   )!Ú__doc__r‚   rN   r5   r   Úpathlibr   r.   rA   rB   rI   rJ   ÚStructÚunpack_fromr/   r2   r   ÚintÚlistÚstrÚdictr(   ÚtupleÚfloatr=   rG   rK   rR   rY   re   rr   r’   r†   © r   r'   ú<module>r       sD  ðñó( Û Û Û Ý ð €ð €ØÐ ð
 €ØÐ à�—‘˜tÓ$×0Ñ0€Ø�&—-‘- Ó%×1Ñ1€ð CIñJØ
ðJØðJØ%)¨#¡YðJØ<?ðJà	ˆ#ˆuˆ*ÑóJðZ.Ø
ð.à
ˆ4��U�
Ñ˜T # u *Ñ-Ð-Ñ.ó.ðbØ
ðØ %ðØ37¸±9ðà	ˆ#ˆuˆ*Ñ˜Ñóð2Ø
ðØ %ðØ37¸±9ðà	ˆ#ˆuˆ*Ñ˜Ñóð2˜uð ¨5ð °Uó ð"T˜Uð T uó Tð˜Tð  d¨3°°U¸3À¸8±_ÀcÐ5IÑ0JÐ+JÑ&Kó ð8�t˜C  e¨C°¨H¡o°sÐ&:Ñ!;Ð;Ñ<ð Àó ð4AØ��d˜5  c ™?¨CÐ/Ñ0Ð0Ñ1ðAàðAð 
ˆ#ˆsˆ(�^óAðH  e¡ð ¸Uð Àuô r   