ó
    �®žj7%  ã                   ó¨  • % S r SSKrSSKrSSKJr  SSKJrJrJ	r	J
r
JrJr  SSKrSSKJr  SSKJr  SSKJr  SSKJr  SS	KJr  \R2                  " \5      r\R8                  S
\R:                  S\R<                  S0r\	\\ 4   \!S'   S\S\\    4S jr"S\S\\    SS4S jr#S\S\\    S\$4S jr%S\\R$                  \RL                  4   S\R$                  4S jr'S\
\\R$                  \RL                  4      S\
\R$                     4S jr(S\	\ \4   S\
\   4S jr)S\ S\ S\\\\ 4      S\\ \ /\4   S\4
S jr* S#S\ S \S!\S\\    S\\    4
S" jjr+g)$z¸Internal utilities for VLM runtimes.

This module contains shared utility functions used across different VLM runtime
implementations to avoid code duplication and ensure consistency.
é    N)ÚPath)ÚAnyÚCallableÚDictÚListÚOptionalÚUnion)Úversion)ÚImage)ÚTransformersPromptStyle)ÚVlmEngineType)ÚGenerationStopperzmlx-vlmÚtransformersÚvllmÚ_ENGINE_PACKAGESÚengine_typeÚreturnc                 ó¼   • [         R                  U 5      nUc  g [        R                  R	                  U5      $ ! [        R                  R
                   a     gf = f)zÉInstalled version of an engine's backing library.

Returns None when the engine has no known backing package or the package is
not installed, in which case the version requirement cannot be evaluated.
N)r   ÚgetÚ	importlibÚmetadatar
   ÚPackageNotFoundError)r   Úpackages     Úh/home/mande/repo/quber/.venv/lib/python3.13/site-packages/docling/models/inference_engines/vlm/_utils.pyÚ_installed_engine_versionr   "   sV   € ô ×"Ñ" ;Ó/€GØ�ØðÜ×!Ñ!×)Ñ)¨'Ó2Ð2øÜ×Ñ×2Ñ2ó Ùðús   ›: ºAÁAÚmin_versionc                 óÈ   • Uc  g[        U 5      nUc  g[        R                  " U5      [        R                  " U5      :  a!  [        U    n[	        SU SU SU SU S3	5      eg)a  Raise when the engine's backing library is older than the model requires.

Why: an outdated backing library typically fails deep inside the vendor code
(e.g. a TypeError in mlx-vlm's Qwen3-VL vision tower) rather than at load
time, which is hard to act on.
NzThis model requires z>=z, but z is installed. Upgrade z, or select a different engine.)r   r
   Úparser   ÚRuntimeError©r   r   Ú	installedr   s       r   Úcheck_min_engine_versionr"   1   s   € ð ÑØä)¨+Ó6€IØÑð 	ä‡}‚}�YÓ¤'§-¢-°Ó"<Ó<Ü" ;Ñ/ˆÜØ" 7 )¨2¨k¨]¸&ÀÀð L"Ø") Ð*IðKó
ð 	
ð =ó    c           	      óä   • Uc  g[        U 5      nUc  g[        R                  " U5      [        R                  " U5      :¼  a  g[        U    n[        R                  SU R                  UUUUU5        g)z‹Non-raising variant of :func:`check_min_engine_version` for auto-selection.

Logs why an engine was skipped so the fallback is not silent.
Tzb%s engine not selected: %s %s is installed but this model requires >=%s. Install %s>=%s to use it.F)r   r
   r   r   Ú_logÚwarningÚvaluer    s       r   Úengine_version_satisfiedr(   K   su   € ð ÑØä)¨+Ó6€IØÑØä‡}‚}�YÓ¤7§=¢=°Ó#=Ó=Øä˜{Ñ+€GÜ‡L�Lð	*à×ÑØØØØØô	ð r#   Úimagec                 óê  • [        U [        R                  5      (       a²  U R                  S:X  aG  U R                  S   S;   a4  [
        R                  " U R                  [        R                  5      5      n O[U R                  S:X  a3  [
        R                  " U R                  [        R                  5      SS9n O[        SU R                   35      eU R                  S:w  a  U R                  S5      n U $ )z¿Convert any image format to RGB PIL Image.

Args:
    image: Input image as PIL Image or numpy array

Returns:
    RGB PIL Image

Raises:
    ValueError: If numpy array has unsupported shape
é   é   )r+   é   ÚL)ÚmodezUnsupported numpy array shape: ÚRGB)Ú
isinstanceÚnpÚndarrayÚndimÚshaper   Ú	fromarrayÚastypeÚuint8Ú
ValueErrorr/   Úconvert)r)   s    r   Únormalize_image_to_pilr;   j   sª   € ô �%œŸ™×$Ñ$Ø�:‰:˜‹?˜uŸ{™{¨1™~°Ó7ä—O’O E§L¡L´·±Ó$:Ó;‰EØ�Z‰Z˜1‹_ä—O’O E§L¡L´·±Ó$:ÀÑE‰EäÐ>¸u¿{¹{¸mÐLÓMÐMð ‡z�z�UÓØ—‘˜eÓ$ˆà€Lr#   Úimagesc                 óD   • U  Vs/ s H  n[        U5      PM     sn$ s  snf )z•Preprocess a batch of images to RGB PIL Images.

Args:
    images: List of images as PIL Images or numpy arrays

Returns:
    List of RGB PIL Images
)r;   )r<   Úimgs     r   Úpreprocess_image_batchr?   ˆ   s"   € ñ 4:Ó:²6¨CÔ" 3Ö'±6Ñ:Ð:ùÒ:s   …Úextra_configc                 ó  • / nU R                  S/ 5      nU Ho  n[        U[        5      (       a  UR                  U5        M+  [        U[        5      (       d  MB  [        U[        5      (       d  MY  UR                  U" 5       5        Mq     U$ )a  Extract and instantiate GenerationStopper instances from config.

This handles both GenerationStopper instances and classes, instantiating
classes as needed.

Args:
    extra_config: Extra generation configuration dictionary

Returns:
    List of GenerationStopper instances
Úcustom_stopping_criteria)r   r1   r   ÚappendÚtypeÚ
issubclass)r@   ÚstoppersÚcustom_criteriaÚcriterias       r   Úextract_generation_stoppersrI   –   so   € ð )+€HØ"×&Ñ&Ð'AÀ2ÓF€Oã#ˆÜ�hÔ 1×2Ñ2à�O‰O˜HÖ%Ü˜¤$×'Ó'¬J°xÔAR×,SÓ,Sà�O‰O™H›JÖ'ñ $ð €Or#   Úrepo_idÚrevisionÚartifacts_pathÚdownload_fnc                 ó´  • U R                  SS5      nUc  UO
[        U5      nUc  U" X5      $ X$-  R                  5       (       a  X$-  $ / nUR                  5       (       a@  UR                  5        Vs/ s H%  ofR	                  5       (       d  M  UR
                  PM'     nn[        SU  SX$-   SU SU(       a  SR                  U5      OS S	U  S
35      es  snf )aD  Resolve the path to model artifacts, downloading if needed.

This standardizes the logic for finding or downloading model artifacts
across different runtimes.

Args:
    repo_id: HuggingFace repository ID (e.g., "microsoft/Phi-3.5-vision-instruct")
    revision: Model revision (e.g., "main")
    artifacts_path: Optional path to cached artifacts directory
    download_fn: Function to download models, takes (repo_id, revision) and returns Path

Returns:
    Path to the model artifacts directory

Raises:
    FileNotFoundError: If artifacts_path is provided but model not found
Ú/z--zModel 'z2' not found in artifacts_path.
Expected location: z
Available models in ú: ú, ÚnonezT

To fix this issue:
  1. Download the model: docling-tools models download-hf-repo zy
  2. Or remove --artifacts-path to enable auto-download
  3. Or use a different model that exists in your artifacts_path)Úreplacer   ÚexistsÚiterdirÚis_dirÚnameÚFileNotFoundErrorÚjoin)rJ   rK   rL   rM   Úrepo_cache_folderÚavailable_modelsÚps          r   Úresolve_model_artifacts_pathr]   ³   sø   € ð.  Ÿ™¨¨TÓ2Ðà'5Ñ'=‘^Ä4ÈÓCW€NàÑá˜7Ó-Ð-Ø
Ñ
,×	4Ñ	4×	6Ñ	6àÑ1Ð1ð ÐØ× Ñ ×"Ñ"Ø0>×0FÑ0FÔ0HÓWÒ0H¨1ÏHÉHÏJ£ §¤Ñ0HÐÐWäØ�g�Yð "Ø"0Ñ"DÐ!Eð F#Ø#1Ð"2°"Þ.>ˆt�y‰yÐ)Ô*ÀFÐKð LNàNUÈYð WOðPó	
ð 		
ùò  Xs   Á2CÂCÚpromptÚ	processorÚprompt_stylec           	      ó¢  • U[         R                  :X  a  U $ U[         R                  :X  a  gUS:X  aC  [        R	                  S5        SnSnSnU SU  U U 3n[        R	                  SU S	U 35        U$ U[         R
                  :X  a  S
SS0SU S./S./nUR                  USS9$ [        SU SSR                  S [          5       5       35      e)aÉ  Format a prompt according to the specified style.

This centralizes prompt formatting logic that was previously duplicated
across different model implementations.

Args:
    prompt: User prompt text
    processor: Model processor with apply_chat_template method
    prompt_style: Style of prompt formatting to use
    repo_id: Optional model repository ID for model-specific formatting

Returns:
    Formatted prompt string, or None if prompt_style is NONE
Nz#microsoft/Phi-4-multimodal-instructz"Using specialized prompt for Phi-4z<|user|>z<|assistant|>z<|end|>z<|image_1|>zFormatted prompt for rP   ÚuserrD   r)   Útext)rD   rc   )ÚroleÚcontentT)Úadd_generation_promptzUnknown prompt style: z. Valid values are rQ   c              3   ó8   #   • U  H  oR                   v •  M     g 7f©N)r'   )Ú.0Úss     r   Ú	<genexpr>Ú(format_prompt_for_vlm.<locals>.<genexpr>  s   é € Ð)SÒ;R°a¯'®'Ò;Rùs   ‚)	r   ÚRAWÚNONEr%   ÚdebugÚCHATÚapply_chat_templater9   rY   )	r^   r_   r`   rJ   Úuser_prompt_prefixÚassistant_promptÚprompt_suffixÚ	formattedÚmessagess	            r   Úformat_prompt_for_vlmrw   æ   s  € ð( Ô.×2Ñ2Ó2ØˆØ	Ô0×5Ñ5Ó	5ØØ	Ð9Ó	9ä�
‰
Ð7Ô8Ø'ÐØ*ÐØ!ˆà!Ð" +¨f¨X°m°_ÐEUÐDVÐWð 	ô 	�
‰
Ð*¨7¨)°2°i°[ÐAÔBØÐØ	Ô0×5Ñ5Ó	5ð à˜WÐ%Ø#¨VÑ4ðñð
ˆð ×,Ñ,¨XÈTÐ,ÐRÐRäØ$ \ Nð 3 Ø $§	¡	Ñ)SÕ;RÓ)SÓ SÐTðVó
ð 	
r#   rh   ),Ú__doc__Úimportlib.metadatar   ÚloggingÚpathlibr   Útypingr   r   r   r   r   r	   Únumpyr2   Ú	packagingr
   ÚPILr   Ú,docling.datamodel.pipeline_options_vlm_modelr   Ú)docling.models.inference_engines.vlm.baser   Ú%docling.models.utils.generation_utilsr   Ú	getLoggerÚ__name__r%   ÚMLXÚTRANSFORMERSÚVLLMr   ÚstrÚ__annotations__r   r"   Úboolr(   r3   r;   r?   rI   r]   rw   © r#   r   Ú<module>rŒ      sã  ðòó Û Ý ß =× =ã Ý Ý å PÝ CÝ Cà×Ò˜Ó"€ð
 ×Ñ�yØ×Ñ Ø×Ñ˜ð.Ð �$�} cÐ)Ñ*ó ð¨=ð ¸XÀc¹]ô ð
Øð
Ø-5°c©]ð
à	ô
ð4ØðØ-5°c©]ðà	ôð> %¨¯©°R·Z±ZÐ(?Ñ"@ð ÀUÇ[Á[ô ð<;Ø��u—{‘{ B§J¡JÐ.Ñ/Ñ0ð;à	ˆ%�+‰+Ñô;ðØ�s˜C�x‘.ðà	Ð
Ñôð:0
Øð0
àð0
ð ˜U 4¨ 9Ñ-Ñ.ð0
ð ˜3 ˜* dÐ*Ñ+ð	0
ð
 
ô0
ðn "ñ	3
Øð3
àð3
ð *ð3
ð �c‰]ð	3
ð
 ˆc�]ö3
r#   