
    {-jA              
      D   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 dnd3Zcdod6Zddd7lemfZf d8d9dpd=Zgdqd>Zhdrd@ZidsdBZj ed8          dtdD            Zkd8d8dEdudJZl edK          dvdM            ZmdwdNZndxdPZodydTZpdzdUZqd{dYZrd|d\Zsd}d`Ztd~deZud8d8d8d8dd8dfd8d8dg	ddmZvd8S )    )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                n    	 t          |           S # t          $ r}t          d| d          |d }~ww xY wNz(No engine bindings registered for model .)r   r   
ValueError)r>   es     a/var/www/html/banglarbhumi/venv/lib/python3.11/site-packages/paddlex/inference/models/__init__.py_get_supported_enginesrH   E   sW    $Z000   FzFFF
 
	s    
4/4enginer   c                    	 t          | |          S # t          $ r}t          d| d          |d }~wt          $ r"}t          t	          |                    |d }~ww xY wrC   )r   r   rE   r   r?   )r>   rI   rF   s      rG   _get_predictor_bindingrK   N   s    (:v...   FzFFF
 
	 " ( ( (Q  a'(s    
A0AAA)resolve_model_nameNmodel_formats	model_dirOptional[str]r   c                   |#t          t          j        | |                    S t          |          }|                                st	          | d          |S )NrM   z does not exist!)r   r   get_model_pathexistsFileNotFoundError)r>   rO   rN   resolveds       rG   _resolve_model_dirrV   \   ss     *+  
 
 	
 IH?? @9 > > >???O    c                    t          |           }dD ]
}||v r|c S t          d| dt          |          d          )N)paddle_staticpaddle_dynamiczModel z6 does not support engine 'paddle'. Supported engines: rD   )rH   rE   list)r>   	supportedrI   s      rG   _resolve_default_paddle_enginer]   o   sr    &z22I5  YMMM 
	3 	3 	3"9oo	3 	3 	3  rW   tuple[str, Optional[Path]]c                    |dk    r|d fS |t          |           d fS t          | |          }t          |          }|t          d|d          ||fS )Npaddlez$No Paddle model files were found in rD   )r]   rV   r;   rE   )r>   rI   rO   model_dir_resolvedresolved_engines        rG   _resolve_requested_enginerc   z   s|    
 t|-j994??+J	BB<=OPPON	NNNOOO...rW   boolc                L    	 t          |           dk    S # t          $ r Y dS w xY w)N)flexibleF)rH   rE   )r>   s    rG   _is_flexible_only_modelrg      s<    %j11]BB   uus    
##r   c                    	  t          j        |                       S # t          j        $ r}t	          d| d          |d }~ww xY w)NzUnsupported engine: rD   )r   getr   ClassNotFoundExceptionrE   )rI   rF   s     rG   _get_inference_enginerk      sc    D*"6**,,,( D D D;;;;<<!CDs    AAAr>   devicecfgAOptional[Union[Dict[str, Any], PaddlePredictorOption, BaseModel]]rm   Dict[str, Any]c               L    t          |                               |||          S )zIParse, validate and normalize engine-specific config to a canonical dict.rl   )rk   normalize_config)rI   rn   r>   rm   s       rG   normalize_engine_configrs      s2     !((99 :   rW   )maxsize	frozensetc                 f    t          t          j                                                              S )z.Registered inference engine ids (bucket keys).)ru   r   allkeys rW   rG   #_engine_config_bucket_key_allowlistrz      s'     _(**//11222rW   c           	     R  	 t                      	t          |                                          }	fd|D             }||z
  }|r2|r0t          dt	          |          dt	          |          d          |s|S |                                D ]B\  }}t          |t                    s(t          d|dt          |          j	        d          C|
                    |           }t          |t                    rt          |          ni }| |vrt          j        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                    h | ]}|v |	S ry   ry   ).0k	allowlists     rG   	<setcomp>z2_flatten_bucketed_engine_config.<locals>.<setcomp>   s    555a9nn1nnnrW   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: rD   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.)rz   setrx   rE   sorteditems
isinstancer   type__name__ri   dictr   warning)
rI   rn   rx   allowlistedotherr~   vbucketflat_for_enginer   s
            @rG   _flatten_bucketed_engine_configr      s    455Isxxzz??D5555d555K;E 
u 
]  &e}}] ] EK;DWDW] ] ]
 
 	
  
		  1!W%% 	<< <&*1gg&6< < <  	 WWV__F&0&A&AId6lllrOS,	
 	
 	
 rW   NOptional[Union[Dict[str, Any], PaddlePredictorOption, HPIConfig, GenAIConfig]]c                T    |t          |t                    s|S t          | |          S )N)r   r   r   )rI   rn   s     rG   %_maybe_flatten_bucketed_engine_configr      s,     {*S$//{
*63777rW   use_hpipgenai_config,Optional[Union[Dict[str, Any], GenAIConfig]]c                Z    ||S t          |          rdS |rdS t          |           rdS dS )Ngenai_clienthpirf   r`   )r   rg   )r>   rI   r   r   s       rG   _resolve_effective_enginer      sK     <(( ~ uz** z8rW   c                >    ||S | dk    r|S | dk    r|S | dk    r|S d S )NrY   r   r   ry   rI   engine_config	pp_option
hpi_configr   s        rG   _select_engine_config_sourcer      sF        4rW   inference_enginera   Optional[Path]c                `    || j         s|S t          |||                                           S )NrM   )needs_local_modelrV   get_supported_model_formatsr   r>   rO   ra   s       rG   _resolve_local_model_dirr     sE     %-=-O%!!&BBDD   rW   r   Optional[Dict[str, Any]]c                x    | sd S t          j        |          }||d         d         k    rt          d          |S )NGlobalr>   u9   Model name mismatch，please input the correct model dir.)r,   load_configrE   )r   r>   rO   configs       rG   _load_local_model_configr     sJ      t&y11FVH%l333UVVVMrW   bindingmodel_configr   c                    t          | t                    sd S ddlm} t	          ||          s%t          dt          |          j        d          |                    |||||          S )Nr   )RunnerEnginezInferenceEngine z& does not support runner construction.)r>   rO   r   r   r   )	
issubclassr.   enginesr   r   RuntimeErrorr   r   build_runner)predictor_clsr   r   r>   rO   r   r   r   s           rG   _build_predictor_runnerr   &  s     m_55 t%%%%%%&55 
ht$455>hhh
 
 	
 ((!# )   rW   
batch_sizeintnormalized_engine_configpredictor_engine_configc           	         | j         }||d}	|r||	d<   t          ||| ||||          }
|
|
|	d<   t          |t                    r
||	d<   ||	d<   |	S )N)r>   r   r   )r   r   r   r>   rO   r   r   runnerrO   r   )	predictorr   r   r-   )r   r   r>   r   r   r   rO   r   r   create_kwargsr   s              rG   _build_predictor_kwargsr   A  s     %M   M  A)@o&$#)!.  F "(h-!455 5%.k"(4n%rW   F)	rO   rm   rI   r   r   r   r   r   r   r   Optional[PaddlePredictorOption]r   *Optional[Union[Dict[str, Any], HPIConfig]]r,   c       	   
        |r|t          j        d|           t          | |          \  } }}t          | |||	          }t	          | ||          \  }}t          |          }t          | |          }|j        }t          || ||          }t          |||||	          }t          ||          }t          ||| |          }|r|                    |           |                                 |r|r|}nt          || |          }|                    |          }t!          || ||||||          } |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>   rO   r   r   rl   )r   r>   rO   )r   r>   r   r   r   rO   r   r   ry   )r   r   rL   r   rc   rk   rK   r   r   r   r   rs   ensure_model_filesensure_environmentr   to_predictor_configr   r   )r>   rO   rm   rI   r   r   r   r   r   r   kwargsra   resolved_configrequested_enginepredictor_binding
need_localconfig_to_validater   r   r   r   s                        rG   create_predictorr   d  s   j  
F&$ 		
 	
 	
 7I7 7 73J"O
 'z68\RRF!:FI" "F -V44.z6BB!3J1)-	   6#!   ?"   7	       @++,>???''))) 
: 
 )(!(
 
 
 /BB   ,!!9 7$)	 	 	M '&AAA&AAArW   )r>   r?   r@   rA   )r>   r?   rI   r?   r@   r   )r>   r?   rO   rP   r@   r   )r>   r?   r@   r?   )r>   r?   rI   r?   rO   rP   r@   r^   )r>   r?   r@   rd   )rI   r?   r@   r   )
rI   r?   rn   ro   r>   rP   rm   rP   r@   rp   )r@   ru   )rI   r?   rn   rp   r@   rp   )rI   r?   rn   r   r@   r   )
r>   r?   rI   rP   r   rd   r   r   r@   r?   )rI   r?   r@   r   )
r   r   r>   r?   rO   rP   ra   r   r@   r   )r   rd   r>   r?   rO   r   r@   r   )r   r   r   r   r>   r?   rO   r   r   r   r   rp   )r   r   r   r   r>   r?   r   r   r   rp   r   rp   rO   r   r   r   r@   rp   )r>   r?   rO   rP   rm   rP   rI   rP   r   r   r   r   r   r   r   rd   r   r   r   r   r@   r,   )w
__future__r   collections.abcr   	functoolsr   pathlibr   typingr   r   r	   r
   r   pydanticr   utilsr   r   utils.official_modelsr   anomaly_detectionr   bindingsr   r   r   r   r   common.genair   r   r   doc_vlmr   r   r   face_featurer   formula_recognitionr   image_classificationr    image_featurer!   image_multilabel_classificationr"   image_unwarpingr#   instance_segmentationr$   keypoint_detectionr%   layout_analysisr&   m_3d_bev_detectionr'   multilingual_speech_recognitionr(   object_detectionr)   open_vocabulary_detectionr*   open_vocabulary_segmentationr+   
predictorsr,   r-   r.   runners.hpir/   runners.paddle_static.configr0   semantic_segmentationr1   table_structure_recognitionr2   text_detectionr3   text_recognitionr4   text_to_pinyinr5   text_to_speech_acousticr6   text_to_speech_vocoderr7   ts_anomaly_detectionr8   ts_classificationr9   ts_forecastingr:   utils.model_pathsr;   video_classificationr<   video_detectionr=   rH   rK   utils.model_resolverrL   rV   r]   rc   rg   rk   rs   rz   r   r   r   r   r   r   r   r   r   ry   rW   rG   <module>r      s   # " " " " " # # # # # #             4 4 4 4 4 4 4 4 4 4 4 4 4 4       $ $ $ $ $ $ $ $ 3 3 3 3 3 3 + + + + + +              M L L L L L L L L L $ $ $ $ $ $ $ $ $ $ $ $ . . . . . . 4 4 4 4 4 4 / / / / / / 0 0 0 0 0 0 < < < < < < * * * * * * 7 7 7 7 7 7 , , , , , , 4 4 4 4 4 4 1 1 1 1 1 1 = = = = = = * * * * * * 5 5 5 5 5 5 8 8 8 8 8 8 K K K K K K K K K K " " " " " " ? ? ? ? ? ? / / / / / / 7 7 7 7 7 7 , , , , , , . . . . . . 1 1 1 1 1 1 9 9 9 9 9 9 2 2 2 2 2 2 / / / / / / - - - - - - ) ) ) ) ) ) E E E E E E 4 4 4 4 4 4 . . . . . .   ( ( ( ( 5 4 4 4 4 4 	     &   / / / /$    4D D D D !%       13 3 3 3
( ( ( (V8 8 8 8   "   &          6       L  $  .215=AAE}B }B }B }B }B }B }B }BrW   