o
    0jA                  
   @  s2  d dl m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mZ d dlmZ ddlmZmZ d	d
lmZ ddlmZ ddlmZmZmZmZmZ ddlmZmZm Z  ddl!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z, ddl-m.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z: ddl;m<Z< ddl=m>Z> ddl?m@Z@ ddlAmBZBmCZCmDZD dd lEmFZF dd!lGmHZH dd"lImJZJ dd#lKmLZL dd$lMmNZN dd%lOmPZP dd&lQmRZR dd'lSmTZT dd(lUmVZV dd)lWmXZX dd*lYmZZZ dd+l[m\Z\ dd,l]m^Z^ dd-l_m`Z` dd.lambZb dd3d4Zcdd7d8Zddd9lemfZf d:d;dd?d@ZgddAdBZhddDdEZiddGdHZjed:ddJdKZkd:d:dLddQdRZleddSddUdVZmddWdXZnddZd[Zodd_d`ZpddadbZqddfdgZrddjdkZsddodpZtddudvZud:d:d:d:dd:dwd:d:dx	dd~dZvd:S )    )annotations)Mapping)	lru_cache)Path)AnyDictOptionalTupleUnion)	BaseModel   )errorslogging   )official_models   )UadPredictor)BindingUnknownModelErrorUnsupportedEngineErrorget_bindingget_supported_engines)GenAIConfigneed_local_modeluses_server_backend)DocVLMPredictor)InferenceEngine)FaceFeaturePredictor)FormulaRecPredictor)ClasPredictor)ImageFeaturePredictor)MLClasPredictor)WarpPredictor)InstanceSegPredictor)KptPredictor)LayoutAnalysisPredictor)BEVDet3DPredictor)WhisperPredictor)DetPredictor)OVDetPredictor)OVSegPredictor)BasePredictorLocalModelPredictorRunnerPredictor)	HPIConfig)PaddlePredictorOption)SegPredictor)TablePredictor)TextDetPredictor)TextRecPredictor)TextToPinyinPredictor)Fastspeech2Predictor)PwganPredictor)TSAdPredictor)TSClsPredictor)TSFcPredictor)&resolve_paddle_engine_from_model_files)VideoClasPredictor)VideoDetPredictor
model_namestrreturnTuple[str, ...]c              
   C  s6   zt | W S  ty } z	td| d|d }~ww Nz(No engine bindings registered for model .)r   r   
ValueError)r=   e rE   b/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/paddlex/inference/models/__init__.py_get_supported_enginesE   s   

rG   enginer   c              
   C  s\   zt | |W S  ty } z	td| d|d }~w ty- } ztt||d }~ww rA   )r   r   rC   r   r>   )r=   rH   rD   rE   rE   rF   _get_predictor_bindingN   s   
rI   )resolve_model_nameNmodel_formats	model_dirOptional[str]r   c                C  s<   |d u rt tj| |dS t |}| st| d|S )NrK   z does not exist!)r   r   Zget_model_pathexistsFileNotFoundError)r=   rM   rL   resolvedrE   rE   rF   _resolve_model_dir\   s   rR   c                 C  s<   t | }dD ]
}||v r|  S qtd| dt|d)N)paddle_staticZpaddle_dynamiczModel z6 does not support engine 'paddle'. Supported engines: rB   )rG   rC   list)r=   	supportedrH   rE   rE   rF   _resolve_default_paddle_engineo   s   rV   tuple[str, Optional[Path]]c                 C  sV   |dkr|d fS |d u rt | d fS t| |}t|}|d u r'td|d||fS )Npaddlez$No Paddle model files were found in rB   )rV   rR   r:   rC   )r=   rH   rM   model_dir_resolvedZresolved_enginerE   rE   rF   _resolve_requested_enginez   s   
rZ   boolc                 C  s$   zt | dkW S  ty   Y dS w )N)flexibleF)rG   rC   )r=   rE   rE   rF   _is_flexible_only_model   s
   r]   r   c              
   C  s<   zt |  W S  tjy } z	td| d|d }~ww )NzUnsupported engine: rB   )r   getr   ZClassNotFoundExceptionrC   )rH   rD   rE   rE   rF   _get_inference_engine   s   r_   r=   devicecfgAOptional[Union[Dict[str, Any], PaddlePredictorOption, BaseModel]]ra   Dict[str, Any]c                C  s   t | j|||dS )zIParse, validate and normalize engine-specific config to a canonical dict.r`   )r_   Znormalize_config)rH   rb   r=   ra   rE   rE   rF   normalize_engine_config   s
   re   )maxsize	frozensetc                   C  s   t t  S )z.Registered inference engine ids (bucket keys).)rg   r   allkeysrE   rE   rE   rF   #_engine_config_bucket_key_allowlist   s   rj   c           	        s   t   t| } fdd|D }|| }|r)|r)tdt|dt|d|s-|S | D ]\}}t|tsHtd|dt|j	dq1|
| }t|trWt|ni }| |vrctd|  |S )	a
  Resolve bucketed engine_config to a single dict for the resolved engine.

    Bucketed form: every top-level key must be a registered engine name, and every
    value must be a mapping. Mixing those keys with any other top-level key is not
    allowed (strict).
    c                   s   h | ]}| v r|qS rE   rE   ).0kZ	allowlistrE   rF   	<setcomp>   s    z2_flatten_bucketed_engine_config.<locals>.<setcomp>zengine_config cannot mix per-engine bucket keys with flat config keys. Use either a flat dict for the resolved engine only, or a dict whose top-level keys are exclusively inference engine names. Flat-like keys: z; bucket-like keys: rB   zJBucketed engine_config requires each top-level value to be a mapping; key z
 has type zbBucketed engine_config has no entry for resolved engine %r; using an empty config for that engine.)rj   setri   rC   sorteditems
isinstancer   type__name__r^   dictr   warning)	rH   rb   ri   Zallowlistedotherrl   vZbucketZflat_for_enginerE   rm   rF   _flatten_bucketed_engine_config   s@   

ry   NOptional[Union[Dict[str, Any], PaddlePredictorOption, HPIConfig, GenAIConfig]]c                 C  s    |d u s	t |ts|S t| |S )N)rr   ru   ry   )rH   rb   rE   rE   rF   %_maybe_flatten_bucketed_engine_config   s   
r{   use_hpipgenai_config,Optional[Union[Dict[str, Any], GenAIConfig]]c                 C  s0   |d ur|S t |rdS |rdS t| rdS dS )Ngenai_clienthpir\   rX   )r   r]   )r=   rH   r|   r}   rE   rE   rF   _resolve_effective_engine   s   r   c                 C  s4   |d ur|S | dkr|S | dkr|S | dkr|S d S )NrS   r   r   rE   rH   engine_config	pp_option
hpi_configr}   rE   rE   rF   _select_engine_config_source   s   r   inference_enginerY   Optional[Path]c                 C  s$   |d us| j s	|S t|||  dS )NrK   )needs_local_modelrR   Zget_supported_model_formatsr   r=   rM   rY   rE   rE   rF   _resolve_local_model_dir  s   r   r   Optional[Dict[str, Any]]c                 C  s.   | sd S t |}||d d krtd|S )NGlobalr=   u9   Model name mismatch，please input the correct model dir.)r+   Zload_configrC   )r   r=   rM   configrE   rE   rF   _load_local_model_config  s   
r   bindingmodel_configr   c                 C  sN   t | tsd S ddlm} t||stdt|jd|j|||||dS )Nr   )RunnerEnginezInferenceEngine z& does not support runner construction.)r=   rM   r   r   r   )	
issubclassr-   enginesr   rr   RuntimeErrorrs   rt   Zbuild_runner)predictor_clsr   r   r=   rM   r   r   r   rE   rE   rF   _build_predictor_runner&  s   


r   
batch_sizeintnormalized_engine_configpredictor_engine_configc              	   C  s`   | j }||d}	|r||	d< t||| ||||d}
|
d ur!|
|	d< t|tr.||	d< ||	d< |	S )N)r=   r   r   )r   r   r   r=   rM   r   r   runnerrM   r   )	predictorr   r   r,   )r   r   r=   r   r   r   rM   r   r   create_kwargsr   rE   rE   rF   _build_predictor_kwargsA  s*   	
r   F)	rM   ra   rH   r   r   r   r|   r   r}   r   Optional[PaddlePredictorOption]r   *Optional[Union[Dict[str, Any], HPIConfig]]r+   c       	      
   K  s  |r|durt d| t| |d\} }}t| |||	}t| ||\}}t|}t| |}|j}t|| ||d}t	|||||	d}t
||}t||| |d}|rU|| |  |r`|r`|}nt|| |d}||}t|| ||||||d}|jd	i ||
S )
aX	  Create a predictor for the given model and engine.

    Args:
        model_name: Model name.
        model_dir (Optional[str]): Path to model directory. Required for local engines
            when the model is not official. Ignored when a local model is not needed.
        device (Optional[str]): Device to run on (e.g. `'gpu'`, `'cpu'`). Used by local
            engines.
        engine (Optional[str]): Inference engine. One of `'paddle'` (resolved to
            `paddle_static` or `paddle_dynamic` from local model files when
            `model_dir` is provided; otherwise resolved from predictor support,
            preferring `paddle_static`), `'paddle_static'`,
            `'paddle_dynamic'`, `'hpi'`, `'flexible'`, `'transformers'`,
            `'onnxruntime'`, `'genai_client'`, or `None`.
            When `None`: if `genai_config.backend` is a server backend, engine
            becomes `'genai_client'`; else if `use_hpip=True` and model supports
            hpi, engine becomes `'hpi'`; else if model is flexible-only, engine
            becomes `'flexible'`; otherwise defaults to `'paddle'`.
        engine_config (Optional[Dict[str, Any]]): Engine-specific config for the
            resolved engine (flat dict), **or** a bucketed dict whose top-level keys
            are only registered engine names (e.g. ``hpi``, ``paddle_static``), each
            mapping to a nested dict. Bucketed and flat keys must not be mixed at the
            same level; use either form exclusively.
        batch_size (int): Batch size for inference. Defaults to 1.
        pp_option (Optional[PaddlePredictorOption]): Paddle predictor options. Used when
            `engine='paddle_static'` and `engine_config` is not specified. Prefer
            `engine_config` for new code.
        use_hpip: When `engine` is `None`, if `True`, resolves to `engine='hpi'`.
            Ignored when `engine` is set.
        hpi_config (Optional[Union[Dict[str, Any], HPIConfig]]): HPI configuration.
            Used when `engine='hpi'` and `engine_config` is not specified. Prefer
            `engine_config` for new code.
        genai_config (Optional[Union[Dict[str, Any], GenAIConfig]]): GenAI configuration.
            Mainly used when `engine='genai_client'` and `engine_config` is not specified.
            Prefer `engine_config` for new code.

    Returns:
        A predictor instance.
    Nz`use_hpip` only takes effect when `engine` is None. Since engine=%r is explicitly set, use_hpip will be ignored. To use HPI, pass engine='hpi' instead.)r=   rM   r   r   r`   )r   r=   rM   )r   r=   r   r   r   rM   r   r   rE   )r   rv   rJ   r   rZ   r_   rI   r   r   r   r{   re   Zensure_model_filesZensure_environmentr   Zto_predictor_configr   r   )r=   rM   ra   rH   r   r   r   r|   r   r}   kwargsrY   Zresolved_configZrequested_engineZpredictor_bindingZ
need_localZconfig_to_validater   r   r   r   rE   rE   rF   create_predictord  s|   5

r   )r=   r>   r?   r@   )r=   r>   rH   r>   r?   r   )r=   r>   rM   rN   r?   r   )r=   r>   r?   r>   )r=   r>   rH   r>   rM   rN   r?   rW   )r=   r>   r?   r[   )rH   r>   r?   r   )
rH   r>   rb   rc   r=   rN   ra   rN   r?   rd   )r?   rg   )rH   r>   rb   rd   r?   rd   )rH   r>   rb   rz   r?   rz   )
r=   r>   rH   rN   r|   r[   r}   r~   r?   r>   )rH   r>   r?   rz   )
r   r   r=   r>   rM   rN   rY   r   r?   r   )r   r[   r=   r>   rM   r   r?   r   )r   r   r   r   r=   r>   rM   r   r   r   r   rd   )r   r   r   r   r=   r>   r   r   r   rd   r   rd   rM   r   r   r   r?   rd   )r=   r>   rM   rN   ra   rN   rH   rN   r   r   r   r   r   r   r|   r[   r   r   r}   r~   r?   r+   )w
__future__r   collections.abcr   	functoolsr   pathlibr   typingr   r   r   r	   r
   Zpydanticr   utilsr   r   Zutils.official_modelsr   Zanomaly_detectionr   Zbindingsr   r   r   r   r   Zcommon.genair   r   r   Zdoc_vlmr   r   r   Zface_featurer   Zformula_recognitionr   Zimage_classificationr   Zimage_featurer    Zimage_multilabel_classificationr!   Zimage_unwarpingr"   Zinstance_segmentationr#   Zkeypoint_detectionr$   Zlayout_analysisr%   Zm_3d_bev_detectionr&   Zmultilingual_speech_recognitionr'   Zobject_detectionr(   Zopen_vocabulary_detectionr)   Zopen_vocabulary_segmentationr*   Z
predictorsr+   r,   r-   Zrunners.hpir.   Zrunners.paddle_static.configr/   Zsemantic_segmentationr0   Ztable_structure_recognitionr1   Ztext_detectionr2   Ztext_recognitionr3   Ztext_to_pinyinr4   Ztext_to_speech_acousticr5   Ztext_to_speech_vocoderr6   Zts_anomaly_detectionr7   Zts_classificationr8   Zts_forecastingr9   Zutils.model_pathsr:   Zvideo_classificationr;   Zvideo_detectionr<   rG   rI   Zutils.model_resolverrJ   rR   rV   rZ   r]   r_   re   rj   ry   r{   r   r   r   r   r   r   r   rE   rE   rE   rF   <module>   s   

	




+
	




&