o
    *jlG                     @   st  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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mZ d d
lmZmZmZmZ d dlT d dl m!Z! ej"dk rzd dl#Z#nd dlm$Z# e!ej%dZ&de'fddZ(dd Z)de*de'de+fddZ,dddZ-dd Z.h dZ/e/0dhZ1ej23d d4 Z5ej23d!d4 Z6d"Z7e6e1v re5e/vrej89d#duZ:e:rze#;d#Z7e&<d$e7 d% W n e#j=y   dZ:Y n	w ne&<d& dZ:ej89d'duZ>ze#;d'Z?e&@d(e?  W n e#j=y   dZ>Y nw d"ZAe5e1v rve6e/vrvej89d)duZBeBrWd*ZCdZAeCD ]ZDze#;eDZAW  n e#j=yR   Y q<w eAduZBeBrud d+lEm;Z; e;FeAe;Fd,k rlne&<d-eA d% ne&<d. dZBd/d0 ZGd1d2 ZHd3d4 ZId5d6 ZJd7d8 ZKd9d: ZLd;d< ZMd=d> ZNd?d@ ZOdAdB ZPdCdD ZQdEdF ZRdGdH ZSdIdJ ZTdKdL ZUdMdN ZVdOdP ZWdQdR ZXdSdT ZYdUdV ZZedWe'fdXdYZ[edWe'fdZd[Z\ed\eJe]ffd]eIe^ffd^eHe_ffd_eQe`ffd)eQe`ffd'eLeaffd`eKebffd#eMecffdaeOededbe7ffdceGefffddeRegffdeeSehffdfeUdgeiffdheVejedidjffdjeVejedidjffdkeUdkekffdleUdlekffdmeUdmelffdneUdnemffdoeUdoenffdpeUdpeoffdqeUdqepffdreUdreqffdseUdserffdteUdtesffdueUduetffdveUdveuffdweUdwevffgZwexg dxZydydz Zzd{d| Z{d}d~ Z|G dd deZ}de+fddZ~dS )    N)OrderedDict)	lru_cache)import_module)chain)Path)
ModuleType)Any)Requirement)	INDEX_KEY
MODULE_KEYREQUIREMENT_KEY
load_index)*)
get_logger)      )Z	log_levelpy_filec                 C   s`   t j| \}}|dkrt }t|d }tjd| t	|  t
|}tjd ||fS )zw Import module from a certrain file

    Args:
        py_file: path to a python file to be imported

    Return:

     r   )ospathsplitr   cwdospsplitextsysinsertvalidate_py_syntaxr   pop)r   dirnameZbasefilemodule_namemod r!   ^/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/modelscope/utils/import_utils.pyimport_modules_from_file$   s   	r#   c                 C   s>   t |ts	J dt |ts|j}t|| }t|| }||kS )a  Check if a method of base class is overridden in derived class.

    Args:
        method (str): the method name to check.
        base_class (type): the class of the base class.
        derived_class (type | Any): the class or instance of the derived class.
    z>base_class doesn't accept instance, Please pass class instead.)
isinstancetype	__class__getattr)methodZ
base_classZderived_classZbase_methodZderived_methodr!   r!   r"   is_method_overridden8   s   


r)   objr(   returnc                 C   s   t | |ott| |S )zCheck whether the object has a method.

    Args:
        method (str): The method name to check.
        obj (object): The object to check.

    Returns:
        bool: True if the object has the method else False.
    )hasattrcallabler'   )r*   r(   r!   r!   r"   
has_methodK   s   
r.   Fc              	   C   s   | sdS d}t | trd}| g} t | tstdt|  g }| D ]7}t |ts5t| dt| dzt|}W n tyS   |rOt| d d}ntY nw |	| q"|r`|d }|S )	aA  Import modules from the given list of strings.

    Args:
        imports (list | str | None): The given module names to be imported.
        allow_failed_imports (bool): If True, the failed imports will return
            None. Otherwise, an ImportError is raise. Default: False.

    Returns:
        list[module] | module | None: The imported modules.

    Examples:
        >>> osp, sys = import_modules(
        ...     ['os.path', 'sys'])
        >>> import os.path as osp_
        >>> import sys as sys_
        >>> assert osp == osp_
        >>> assert sys == sys_
    NFTz+custom_imports must be a list but got type z is of type z and cannot be imported.z! failed to import and is ignored.r   )
r$   strlist	TypeErrorr%   r   ImportErrorloggerwarningappend)ZimportsZallow_failed_importsZsingle_importZimportedimpZimported_tmpr!   r!   r"   import_modulesX   s:   


r7   c              
   C   st   t | ddd}| }W d    n1 sw   Y  zt| W d S  ty9 } z
td|  d| d }~ww )Nrzutf-8)encodingz'There are syntax errors in config file z: )openreadastparseSyntaxError)filenamefcontenter!   r!   r"   r      s   
r   >   1ZYESTRUEONZAUTOUSE_TF	USE_TORCHzN/AtorchzPyTorch version z Found.z'Disabling PyTorch because USE_TF is setZtimmz#Successfully imported timm version 
tensorflow)
rI   ztensorflow-cpuztensorflow-gpuz
tf-nightlyztf-nightly-cpuztf-nightly-gpuzintel-tensorflowzintel-tensorflow-avx512ztensorflow-rocmztensorflow-macos)version2zTensorFlow version z-Disabling Tensorflow because USE_TORCH is setc                   C      t jdd uS )Nscipy	importlibutil	find_specr!   r!   r!   r"   is_scipy_available      rR   c                   C   s&   t jdd u r
dS t ot jdS )NsklearnFzsklearn.metrics)rO   rP   rQ   rR   r!   r!   r!   r"   is_sklearn_available   s   rU   c                   C   rL   )NsentencepiecerN   r!   r!   r!   r"   is_sentencepiece_available   rS   rW   c                   C   s$   t jdd u r
dS t jdd uS )NZgoogleFzgoogle.protobufrN   r!   r!   r!   r"   is_protobuf_available   s   rX   c                   C   rL   )N
tokenizersrN   r!   r!   r!   r"   is_tokenizers_available   rS   rZ   c                   C      t S N)_timm_availabler!   r!   r!   r"   is_timm_available      r^   c                   C   r[   r\   )_torch_availabler!   r!   r!   r"   is_torch_available   r_   ra   c                  C   s   t  rdd l} | j S dS )Nr   F)ra   rH   cudaZis_available)rH   r!   r!   r"   is_torch_cuda_available   s   
rc   c                   C   rL   )NwenetruntimerN   r!   r!   r!   r"   is_wenetruntime_available   rS   re   c                   C   rL   )NswiftrN   r!   r!   r!   r"   is_swift_available   rS   rg   c                   C   r[   r\   )_tf_availabler!   r!   r!   r"   is_tf_available  r_   ri   c                   C   rL   )Ncv2rN   r!   r!   r!   r"   is_opencv_available  rS   rk   c                   C   rL   )Nz	PIL.ImagerN   r!   r!   r!   r"   is_pillow_available	  rS   rl   c                 C   s   t j| d uS r\   rN   pkg_namer!   r!   r"   _is_package_available_fn  rS   ro   c                 C   s   t t| S r\   )	functoolspartialro   rm   r!   r!   r"   is_package_available  s   rr   c                 C   s   t jdd uot jdS )Nespnet2espnetrN   rm   r!   r!   r"   is_espnet_available  s   
ru   c                   C   rL   )NZvllmrN   r!   r!   r!   r"   is_vllm_available  rS   rv   c                   C   rL   )NZtransformersrN   r!   r!   r!   r"   is_transformers_available  rS   rw   c                   C   rL   )NZ	diffusersrN   r!   r!   r!   r"   is_diffusers_available"  rS   rx   c                   C   rL   )NZtensorrt_llmrN   r!   r!   r!   r"   is_tensorrt_llm_available&  rS   ry   packagec                 C   sx   t | }|j}z#tj|}|jr%|j|s(td| d| d|j W d S W d S  tjjy;   td| dw )Nz	Package 'z
' version z does not satisfy zRequired package 'z' is not installed)	r	   namerO   metadatarJ   	specifiercontainsr2   PackageNotFoundError)rz   reqrn   installed_versionr!   r!   r"   	_requires*  s    r   c                 C   s$   zt |  W dS  ty   Y dS w )NTF)r   r2   )rz   r!   r!   r"   exists9  s   r   protobufrV   rT   tfrY   rd   Z	TORCH_VERrM   rj   ZPILzpai-easynlpZeasynlprs   REQrt   ZfunasrZkwsbpZdecordZ	deepspeedZfairseqZfasttextZmegatron_utilZtext2sql_lgesqlZmpi4pyZ	open_clipZtamingZxformersrf   )r   r   typingc                    s   t |ttfs
|g}t | tr|  nt| dr| jn| jj g }|D ]'}|dks,|tv r-q"|tv r6t| }nt	|}t
d|}||f}|| q" fdd|D }|r\td|d S )N__name__r   r   c                    s    g | ]\}}| s|  qS r!   )format).0	availablemsgr{   r!   r"   
<listcomp>  s     zrequires.<locals>.<listcomp>)r$   r0   tupler/   r,   r   r&   SYSTEM_PACKAGEREQUIREMENTS_MAAPINGrr   GENERAL_IMPORT_ERRORreplacer5   r2   join)r*   requirementsZchecksr   checkZcheck_fnerr_msgfailedr!   r   r"   requiresk  s.   


r   c                       t   fdd}|S )Nc                     &   t  r
 | i |S td j d)NMethod `z` requires PyTorch.)ra   r2   r   argskwargsfuncr!   r"   wrapper     ztorch_required.<locals>.wrapperrp   wrapsr   r   r!   r   r"   torch_required     r   c                    r   )Nc                     r   )Nr   z` requires TF.)ri   r2   r   r   r   r!   r"   r     r   ztf_required.<locals>.wrapperr   r   r!   r   r"   tf_required  r   r   c                       s~   e Zd ZdZ				d fdd	Zdd Z fddZd	ed
efddZ	defddZ
dd Zedd Zedd Z  ZS )LazyImportModuleNFc                    s   t  | t| | _i | _| D ]\}}	|	D ]}
|| j|
< qqt| tt|	   | _
|| _|| _tj|g| _|d u rFi n|| _|| _|| _|| _|rZ|   d S d S r\   )super__init__setkeys_modules_class_to_moduleitemsr0   r   values__all____file____spec__r   r   r   __path___objects_name_import_structure_extra_import_func_try_to_import)selfr{   Zmodule_fileZimport_structureZmodule_specZextra_objectsZtry_to_pre_importZextra_import_funckeyr   valuer&   r!   r"   r     s(   
zLazyImportModule.__init__c                 C   s\   | j  D ]&}zt| | W q ty+ } ztd| d|  W Y d }~qd }~ww d S )Nzpre load module z error, please check )r   r   r'   	Exceptionr3   r4   )r   Z
sub_modulerB   r!   r!   r"   r     s   zLazyImportModule._try_to_importc                    s,   t   }| jD ]}||vr|| q|S r\   )r   __dir__r   r5   )r   resultattrr   r!   r"   r     s   


zLazyImportModule.__dir__r{   r+   c                 C   s   || j v r
| j | S || jv r| |}n:|| j v r*| | j| }t||}n%| jd urD| |}|d u rCtd| j d| ntd| j d| t	| || |S )Nzmodule z has no attribute )
r   r   _get_moduler   r   r'   r   AttributeErrorr   setattr)r   r{   r   moduler!   r!   r"   __getattr__  s&   




zLazyImportModule.__getattr__r   c              
      s   z1| j d |  t fdddD s(|  } |t v r(|t   }t | td| | j W S  tyL } ztd| j  d| d| |d }~ww )N.c                 3   s     | ]}  d | V  qdS )zmodelscope.N)
startswith)r   prefixZmodule_name_fullr!   r"   	<genexpr>  s
    
z/LazyImportModule._get_module.<locals>.<genexpr>)ZhubutilsrJ   ZfileiozFailed to import z@ because of the following error (look up to see its traceback):
)	r   anyget_ast_indexr   r   rO   r   r   RuntimeError)r   r   	ast_indexr   rB   r!   r   r"   r     s(   
zLazyImportModule._get_modulec                 C   s   | j | j| j| jffS r\   )r&   r   r   r   )r   r!   r!   r"   
__reduce__  s   zLazyImportModule.__reduce__c                   C   s   t jd u r	t t _t jS r\   )r   
_AST_INDEXr   r!   r!   r!   r"   r     s   
zLazyImportModule.get_ast_indexc                 C   sl   t  }| |t v r,|t |  }|t }||t v r%|t | }t|| t| dS t	|  d dS )z import a lazy import module using signature

        Args:
            signature (tuple): a tuple of str, (registry_name, registry_group_name, module_name)
        z not found in ast index fileN)
r   r   r
   r   r   r   rO   r   r3   r4   )	signaturer   Z	mod_indexr   r   r!   r!   r"   r     s   
zLazyImportModule.import_module)NNFN)r   
__module____qualname__r   r   r   r   r/   r   r   r   r   staticmethodr   r   __classcell__r!   r!   r   r"   r     s     		
r   c                 C   s*   | j }t|}|j}t| }||v S )z
    Determine if attribute in specific class.

    Args:
        cls: target class.
        attribute_name: the attribute name.

    Returns:
        The attribute in the class or not.
    )r   inspectr   
parametersr0   r   )clsZattribute_nameZinit_methodr   r   Zparam_namesr!   r!   r"   has_attr_in_class  s
   
r   )F)r<   rp   rO   importlib.metadataimportlib.utilr   loggingr   Zos.pathr   r   r   collectionsr   r   r   	itertoolsr   pathlibr   typesr   r   r   Zpackaging.requirementsr	   Zmodelscope.utils.ast_utilsr
   r   r   r   Zmodelscope.utils.errorZmodelscope.utils.loggerr   version_infoZimportlib_metadatar|   WARNINGr3   r/   r#   r)   objectboolr.   r7   r   ZENV_VARS_TRUE_VALUESunionZENV_VARS_TRUE_AND_AUTO_VALUESenvirongetupperrF   rG   Z_torch_versionrP   rQ   r`   rJ   infor   r]   Z_timm_versiondebugZ_tf_versionrh   
candidatespkg	packagingr=   rR   rU   rW   rX   rZ   r^   ra   rc   re   rg   ri   rk   rl   ro   rr   ru   rv   rw   rx   ry   r   r   ZPROTOBUF_IMPORT_ERRORZSENTENCEPIECE_IMPORT_ERRORZSKLEARN_IMPORT_ERRORZTENSORFLOW_IMPORT_ERRORZTIMM_IMPORT_ERRORZTOKENIZERS_IMPORT_ERRORZPYTORCH_IMPORT_ERRORZWENETRUNTIME_IMPORT_ERRORr   ZSCIPY_IMPORT_ERRORZOPENCV_IMPORT_ERRORZPILLOW_IMPORT_ERRORZEASYNLP_IMPORT_ERRORr   ZAUDIO_IMPORT_ERRORZDECORD_IMPORT_ERRORZDEEPSPEED_IMPORT_ERRORZFAIRSEQ_IMPORT_ERRORZFASTTEXT_IMPORT_ERRORZMEGATRON_UTIL_IMPORT_ERRORZTEXT2SQL_LGESQL_IMPORT_ERRORZMPI4PY_IMPORT_ERRORZOPENCLIP_IMPORT_ERRORZTAMING_IMPORT_ERRORZXFORMERS_IMPORT_ERRORZSWIFT_IMPORT_ERRORr   r   r   r   r   r   r   r   r!   r!   r!   r"   <module>   s,  


/




	












&r