
    yj/                        d Z ddlZddlZddlZddlZddlmZmZ ddlm	Z	 ddl
mZmZmZ ddlmZ ddlmZ  ej        ed	                                                                          d
k    Z	  G d de          Z G d de          ZdS )z
caching tools
    N)movermtree)Dict)	FILE_HASH'AISTUDIO_ENABLE_DEFAULT_HASH_VALIDATION	CACHE_KEY   )compute_hash)logFalsetruec                   f    e Zd ZdZdZdZdZdZ	 defdZ	d Z
d	 Zd
 Zd Zd Zd Zd Zd Zd ZdS )FileSystemCacheinfoz.mscz.mdlidz.mvcache_root_locationc                 h    t          j        |d           || _        |                                  dS )zBase file system cache interface.

        Args:
            cache_root_location (str): The root location to store files.
            kwargs(dict): The keyword arguments.
        Texist_okN)osmakedirsr   
load_cache)selfr   s     j/lsinfo/ai/hellotax_ai/data_center/backend/venv/lib/python3.11/site-packages/aistudio_sdk/utils/caching.py__init__zFileSystemCache.__init__   s8     	'$7777#6     c                     | j         S )location)r   r   s    r   get_root_locationz!FileSystemCache.get_root_location-   s    ''r   c                 8   g | _         t          j                            | j        t
          j                  }t          j                            |          rDt          |d          5 }t          j
        |          | _         ddd           dS # 1 swxY w Y   dS dS )loadrbN)cached_filesr   pathjoinr   r   KEY_FILE_NAMEexistsopenpickler"   )r   cache_keys_file_pathfs      r   r   zFileSystemCache.load_cache1   s    !w||D,D,;,I K  K7>>.// 	3*D11 3Q$*KNN!3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3	3 	3s   &BBBc                 4   t           j                            | j        t          j                  }t          j                    \  }}t          |d          5 }t          j
        | j        |           ddd           n# 1 swxY w Y   t          ||           dS )zSave cache metadata.wbN)r   r%   r&   r   r   r'   tempfilemkstempr)   r*   dumpr$   r   )r   r+   fdfnr,   s        r   save_cached_filesz!FileSystemCache.save_cached_files:   s      "w||D,D,;,I K  K!##B"d^^ 	.qK)1---	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	.R%&&&&&s   A==BBc                     dS )zCheck the key is in the cache, if exists, return the file, otherwise return None.

        Args:
            key(str): The cache key.

        Raises:
            None
        N r   keys     r   get_filezFileSystemCache.get_fileD   s	     	r   c                     dS )zPut file to the cache.

        Args:
            key (str): The cache key
            location (str): Location of the file, we will move the file to cache.

        Raises:
            None
        Nr6   )r   r8   r   s      r   put_filezFileSystemCache.put_fileO   s	     	r   c                 x    || j         v r0| j                             |           |                                  dS dS )zvRemove cache key in index, The file is removed manually

        Args:
            key (dict): The cache key.
        N)r$   remover4   r7   s     r   
remove_keyzFileSystemCache.remove_key[   sI     $###$$S)))""$$$$$ $#r   c                 ,    | j         D ]}||k    r dS dS )checkTF)r$   )r   r8   
cache_files      r   r(   zFileSystemCache.existse   s2    + 	 	JS  tt ! ur   c                 V    t          | j                   |                                  dS )zRemove all files and metadata from the cache
        In the case of multiple cache locations, this clears only the last one,
        which is assumed to be the read/write one.
        N)r   r   r   r   s    r   clear_cachezFileSystemCache.clear_cachem   s+    
 	t'(((r   c                 r    t          j        |                                                                          S )name)hashlibsha256encode	hexdigestr7   s     r   	hash_namezFileSystemCache.hash_nameu   s&    ~cjjll++55777r   N)__name__
__module____qualname____doc__r'   MODEL_META_FILE_NAMEMODEL_META_MODEL_IDMODEL_VERSION_FILE_NAMEstrr   r    r   r4   r9   r;   r>   r(   rC   rJ   r6   r   r   r   r      s        JM!#    ( ( (3 3 3' ' '	 	 	
 
 
% % %    8 8 8 8 8r   r   c                   r     e Zd ZdZd fd	Zd Zd ZdefdZd Z	d	 Z
d
 Zd Zd Zd Zd Zd Zd Z xZS )ModelFileSystemCachezLocal cache file layout
       cache_root/owner/model_name/individual cached files and cache index file '.mcs'
       Save only one version for each file.
    Nc                    ||St                                          t          j                            |                     |                                  nlt                                          t          j                            |||                     t          j        |d|i| _        | 	                                 | 
                                | _        dS )aU  Put file to the cache
        Args:
            cache_root(`str`): The aistudio local cache root(default: ~/.cache/aistudio/)
            owner(`str`): The model owner.
            name('str'): The name of the model
        Returns:
        Raises:
            None
        <Tip>
            model_id = {owner}/{name}
        </Tip>
        N/)superr   r   r%   r&   load_model_metar   rP   
model_metasave_model_metaload_model_versioncached_model_revision)r   
cache_rootownerrE   	__class__s       r   r   zModelFileSystemCache.__init__   s     =DLGGRW\\*55666  """"GGRW\\*eTBBCCC3tt5LDO   """%)%<%<%>%>"""r   c                 P   t           j                            | j        t          j                  }t           j                            |          rDt          |d          5 }t          j	        |          | _
        ddd           dS # 1 swxY w Y   dS t          j        di| _
        dS )zget metar#   Nunknown)r   r%   r&   r   r   rO   r(   r)   r*   r"   rY   rP   r   meta_file_pathr,   s      r   rX   z$ModelFileSystemCache.load_model_meta   s    d&>&5&JL L7>>.)) 	Ond++ 1q"(+a..1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1  /BINDOOOs   BB
B
c                 B   t           j                            | j        t          j                  }t           j                            |          rPt          |d          5 }|                                	                                cddd           S # 1 swxY w Y   dS dS )zuse version inforN)
r   r%   r&   r   r   rQ   r(   r)   readstrip)r   model_version_file_pathr,   s      r   r[   z'ModelFileSystemCache.load_model_version   s    "$',,$o&M#O #O7>>122 	-s33 (qvvxx~~''( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( 4s   &BBBrevision_infoc                 |   t           j                            | j        t          j                  }t          |d          5 }t          |t                    r9d|d         d|	                    d          pd}|
                    |           n|
                    |           ddd           dS # 1 swxY w Y   dS )zsave file infowz	Revision:Revisionz,CreatedAt:	CreatedAtra   N)r   r%   r&   r   r   rQ   r)   
isinstancedictgetwrite)r   ri   rh   r,   version_info_strs        r   save_model_versionz'ModelFileSystemCache.save_model_version   s   "$',,$o&M#O #O)3// 	'1-.. ' '!*---}/@/@/M/M/ZQZ/Z$\ ())))&&&	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	's    A$B11B58B5c                 0    | j         t          j                 S )rp   )rY   r   rP   r   s    r   get_model_idz!ModelFileSystemCache.get_model_id   s    BCCr   c                     t           j                            | j        t          j                  }t          |d          5 }t          j        | j	        |           ddd           dS # 1 swxY w Y   dS )saver.   N)
r   r%   r&   r   r   rO   r)   r*   r1   rY   rb   s      r   rZ   z$ModelFileSystemCache.save_model_meta   s    d&>&5&JL L.$'' 	,1K+++	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	,s    A((A,/A,c                     | j         D ]q}||d         k    rct          j                            | j        |d                   }t          j                            |          r|c S |                     |           rdS )zRetrieve the cache if there is file match the path.

        Args:
            file_path (str): The file path in the model.

        Returns:
            path: the full path of the file.
        PathN)r$   r   r%   r&   r   r(   r>   )r   	file_pathcached_filecached_file_paths       r   get_file_by_pathz%ModelFileSystemCache.get_file_by_path   s      , 	1 	1KK///#%7<<0H0;F0C$E $E 7>>"233 1++++OOK000tr   c                 d   | j         D ]}||d         k    r|d                             |          s|                    |d                   rct          j                            | j        |d                   }t          j                            |          r|c S |                     |           dS )zRetrieve the cache if there is file match the path.

        Args:
            file_path (str): The file path in the model.
            commit_id (str): The commit id of the file

        Returns:
            path: the full path of the file.
        ry   rl   N)r$   
startswithr   r%   r&   r   r(   r>   )r   rz   	commit_idr{   r|   s        r   get_file_by_path_and_commit_idz3ModelFileSystemCache.get_file_by_path_and_commit_id   s      , 	1 	1KK///J'229== 0AJAUAUVablVmAnAn 0#%7<<0H0;F0C$E $E 7>>"233 1++++OOK000tr   c                    |                      |          }| j        D ]m}||k    ret          j                            | j        |d                   }t          j                            |          r|c S |                     |            nndS )zCheck if exist cache file.

        Args:
            model_file_info (ModelFileInfo): The file information of the file.

        Returns:
            str: The file path.
        ry   N)$_ModelFileSystemCache__get_cache_keyr$   r   r%   r&   r   r(   r>   )r   model_file_info	cache_keyr{   	orig_paths        r   get_file_by_infoz%ModelFileSystemCache.get_file_by_info   s     ((99	, 	 	Ki''GLL)A)4V)<> >	7>>),, $$$$OOK000E ( tr   c                 (    |d         |d         d}|S )Nr%   sha)ry   rl   r6   )r   r   r   s      r   __get_cache_keyz$ModelFileSystemCache.__get_cache_key  s&    #F+'.
 
	 r   c                    |                      |          }d}|d         }t          j                            | j        |d                   }| j        D ]}|d         |k    r|d                             |d                   s!|d                             |d                   ri|t                   }|Zt          j                            |          r;t          rt          |          }n|}||k    rd} nt          j        d| d           |r6t          j                            |          rdS |                     |           dS )	a  Check the file is cached or not. Note existence check will also cover digest check

        Args:
            model_file_info (CachedFileInfo): The cached file info

        Returns:
            bool: If exists and has the same hash, return True otherwise False
        Fry   r%   rl   NTzFile [z?] exists in cache but with a mismatched hash, will re-download.)r   r   r%   r&   r   r$   r   r   r(   enable_default_hash_validationr
   r   r   r>   )	r   r   r8   	is_existsrz   cache_file_path
cached_keyexpected_hashcache_file_sha256s	            r   r(   zModelFileSystemCache.exists  sp    ""?33	K	',,t'?'6v'>@ @+ 	 	J&!Y..z*55c*oFF /:11*Z2HII / !0	 : ,'2) 2), 6 :,8,I,I)),9)$(999$(	oYooo    	%w~~o.. %t#% % %ur   c                 *   | j         D ]}|d         |d         k    rv|                     |           t          j                            | j        |d                   }t          j                            |          rt          j        |            dS dS )zWe in cache, remove it.

        Args:
            model_file_info (ModelFileInfo): The model file information from server.
        ry   r%   N)r$   r>   r   r%   r&   r   r(   r=   )r   r   r{   rz   s       r   remove_if_existsz%ModelFileSystemCache.remove_if_exists4  s      , 	 	K6"of&===,,,GLL)A)4V)<> >	7>>),, )Ii((( >	 	r   c                    |                      |           |                     |          }t          j                            | j        |d                   }t          j                            |          }t          j                            |          st          j        |d           t          ||           | j
                            |           |                                  |S )a[  Put model on model_file_location to cache, the model first download to /tmp, and move to cache.

        Args:
            model_file_info (str): The file description returned by get_model_files.
            model_file_location (str): The location of the temporary file.

        Returns:
            str: The location of the cached file.
        ry   Tr   )r   r   r   r%   r&   r   dirnamer(   r   r   r$   appendr4   )r   r   model_file_locationr   cache_full_pathcache_file_dirs         r   r;   zModelFileSystemCache.put_fileC  s     	o...((99	',,$f  99w~~n-- 	7K6666 /222  +++   r   )NN)rK   rL   rM   rN   r   rX   r[   r   rs   ru   rZ   r}   r   r   r   r(   r   r;   __classcell__)r_   s   @r   rT   rT   z   s        
? ? ? ? ? ?2O O O  
' 
' 
' 
' 
'D D D, , ,  (  ,  ,  ' ' 'R        r   rT   )rN   rF   r   r*   r/   shutilr   r   typingr   aistudio_sdk.configr   r   r   utilr
   aistudio_sdkr   getenvrg   lowerr   objectr   rT   r6   r   r   <module>r      sl     				                C C C C C C C C C C             BI5w??EEGGMMOOSYY a8 a8 a8 a8 a8f a8 a8 a8H_ _ _ _ _? _ _ _ _ _r   