
    uj7                     2   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mZ d dlm	Z	 d dl
mZmZ d dlmZ d dlmZ  e            Z ej        ed                                                                          dk    Z	  G d	 d
e          Z G d de          ZdS )    N)movermtree)Dict)	FILE_HASH)MODELSCOPE_ENABLE_DEFAULT_HASH_VALIDATION)compute_hash)
get_loggerFalsetruec                   h    e 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 ZdS )FileSystemCachez.mscz.mdlidz.mvcache_root_locationc                     t          j                    | _        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)	threadingRLock_cache_lockosmakedirsr   
load_cache)selfr   kwargss      l/lsinfo/ai/hellotax_ai/data_center/backend/venv/lib/python3.11/site-packages/modelscope/hub/utils/caching.py__init__zFileSystemCache.__init__    sH     %?,,
'$7777#6     c                     | j         S N)r   r   s    r   get_root_locationz!FileSystemCache.get_root_location1   s    ''r   c                    g | _         t          j                            | j        t
          j                  }t          j                            |          r	 t          |d          5 }t          j
        |          }d d d            n# 1 swxY w Y   t          |t                    r	|| _         d S t                              d|t          |          j                   d S # t"          $ rW}t                              d||           	 t          j        ||dz              n# t&          $ r Y n
w xY wY d }~d S Y d }~d S d }~ww xY wd S )Nrbz1Cache index %s has unexpected type %s, resetting.uk   Failed to load cache index %s: %s. Resetting — already-downloaded files will be re-validated on next run.
.corrupted)cached_filesr   pathjoinr   r   KEY_FILE_NAMEexistsopenpickleload
isinstancelistloggerwarningtype__name__	ExceptionreplaceOSError)r   cache_keys_file_pathfdataes        r   r   zFileSystemCache.load_cache4   s   !w||D,D,;,I K  K7>>.// 	.55 *!;q>>D* * * * * * * * * * * * * * *dD)) -(,D%%%NNK,T

+- - - - -  	 	 	_(!- - -J33lBD D D D   DD D D D D D DDDDD		 	sf   C! 'B<C! BC! BC! 1.C! !
E+D=D! D=!
D.+D=-D..D==Ec                    t           j                            | j        t          j                  }t          j        d| j                  \  }}	 t          j        |d          5 }t          j
        t          | j                  |           |                                 t          j        |                                           ddd           n# 1 swxY w Y   t          j        ||           dS # t"          $ r[ 	 t          j        |           n# t&          $ r Y nw xY wt           j                            |          rt          j        |            w xY w)z8Write .msc atomically. Caller must hold ``_cache_lock``.z.tmp)suffixdirwbN)r   r&   r'   r   r   r(   tempfilemkstempfdopenr+   dumpr.   r%   flushfsyncfilenor4   r3   closer5   r)   unlink)r   r6   fdtemp_filenamer7   s        r   _save_cached_files_unlockedz+FileSystemCache._save_cached_files_unlockedN   s   !w||D,D,;,I K  K$,t79 9 9M	2t$$ %D!233Q777			$$$% % % % % % % % % % % % % % % J}&:;;;;; 	 	 	   w~~m,, )	-(((	sU   C4 $A"CC4 CC4 CC4 4
E?DE
D!E D!!8Ec                 n    | j         5  |                                  ddd           dS # 1 swxY w Y   dS )a  
        Save cache metadata in order to verify that the cached content is consistent with the remote content.

        Example of the cached content:
            [{'Path': 'configuration.json', 'Revision': 'f01dxxx'}, {'Path': 'model.bin', 'Revision': '1159xxx'}, ...]
        N)r   rI   r    s    r   save_cached_filesz!FileSystemCache.save_cached_filesc   s      	/ 	/,,...	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/s   *..c                     dS )zCheck the key is in the cache, if exist, return the file, otherwise return None.

        Args:
            key(str): The cache key.

        Raises:
            None
        N r   keys     r   get_filezFileSystemCache.get_filem   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
        NrM   )r   rO   locations      r   put_filezFileSystemCache.put_filex   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%   removerK   rN   s     r   
remove_keyzFileSystemCache.remove_key   sI     $###$$S)))""$$$$$ $#r   c                 ,    | j         D ]}||k    r dS dS )NTF)r%   )r   rO   
cache_files      r   r)   zFileSystemCache.exists   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_cache   s+    
 	t'(((r   c                 r    t          j        |                                                                          S r   )hashlibsha256encode	hexdigestrN   s     r   	hash_namezFileSystemCache.hash_name   s&    ~cjjll++55777r   N)r2   
__module____qualname__r(   MODEL_META_FILE_NAMEMODEL_META_MODEL_IDMODEL_VERSION_FILE_NAMEstrr   r!   r   rI   rK   rP   rS   rV   r)   rZ   r`   rM   r   r   r   r      s        M!#    "( ( (  4  */ / /	 	 	
 
 
% % %    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 )a\  Put file to the cache
        Args:
            cache_root(`str`): The modelscope local cache root(default: ~/.cache/modelscope/hub)
            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   rd   
model_metasave_model_metaload_model_versioncached_model_revision)r   
cache_rootownername	__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                            |          r	 t          |d          5 }t          j	        |          }d d d            n# 1 swxY w Y   t          |t                    r	|| _        d S t                              d|           n]# t          $ rP}t                              d||           	 t          j        ||dz              n# t"          $ r Y nw xY wY d }~nd }~ww xY wt          j        di| _        d S )Nr#   z-Model meta %s has unexpected type, resetting.z,Failed to load model meta %s: %s. Resetting.r$   unknown)r   r&   r'   r   r   rc   r)   r*   r+   r,   r-   dictrm   r/   r0   r3   r4   r5   rd   )r   meta_file_pathr7   r8   r9   s        r   rl   z$ModelFileSystemCache.load_model_meta   s   d&>&5&JL L7>>.)) 	.$// *1!;q>>D* * * * * * * * * * * * * * *dD)) &*DOFN-/ / / /   M-q2 2 2J~~/LMMMM   D +>	Jsf   C  B5C BC B	C *C 
D D-DD
DDDDD 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 )Nr)
r   r&   r'   r   r   re   r)   r*   readstrip)r   model_version_file_pathr7   s      r   ro   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                    r*d|d         d|d         }|	                    |           n|	                    |           d d d            d S # 1 swxY w Y   d S )Nwz	Revision:Revisionz,CreatedAt:	CreatedAt)
r   r&   r'   r   r   re   r*   r-   rw   write)r   r~   r}   r7   version_info_strs        r   save_model_versionz'ModelFileSystemCache.save_model_version   s    "$',,$o&M#O #O)3// 	'1-.. ' '!*---}[/I/I$K ())))&&&	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	's    AB""B&)B&c                 0    | j         t          j                 S r   )rm   r   rd   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 )Nr=   )
r   r&   r'   r   r   rc   r*   r+   rA   rm   )r   rx   r7   s      r   rn   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)   rV   )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.
        r   r   N)r%   
startswithr   r&   r'   r   r)   rV   )r   r   	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.
        r   N)$_ModelFileSystemCache__get_cache_keyr%   r   r&   r'   r   r)   rV   )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   r   )r   r   rM   )r   r   r   s      r   __get_cache_keyz$ModelFileSystemCache.__get_cache_key2  s&    #F+'
3
 
	 r   c                    |                      |          }d}|d         }t          j                            | j        |d                   }| j        D ]}|d         |k    r|d                             |d                   s!|d                             |d                   ro|t                   }|`t          j                            |          rAt          rt          |          }n|}||k    rd} nt                              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
        Fr   r   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/   inforV   )	r   r   rO   	is_existsr   cache_file_path
cached_keyexpected_hashcache_file_sha256s	            r   r)   zModelFileSystemCache.exists9  sr    ""?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.
        r   N)r%   rV   r   r&   r'   r   r)   rU   )r   r   r   r   s       r   remove_if_existsz%ModelFileSystemCache.remove_if_existsb  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
        5  | j                            |           |                                  ddd           n# 1 swxY w Y   |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.
        r   Tr   N)r   r   r   r&   r'   r   dirnamer)   r   r   r   r%   appendrI   )r   r   model_file_locationr   cache_full_pathcache_file_dirs         r   rS   zModelFileSystemCache.put_fileq  s+    	o...((99	',,t'?'0'8: :99w~~n-- 	7K6666 /222 	/ 	/$$Y///,,...	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ s   /C<<D D )NN)r2   ra   rb   __doc__r   rl   ro   r   r   r   rn   r   r   r   r   r)   r   rS   __classcell__)rt   s   @r   rh   rh      s        
? ? ? ? ? ?2K K K*  	' 	' 	' 	' 	'D D D, , ,  (  ,  ,  ' ' 'R        r   rh   )r\   r   r+   r>   r   shutilr   r   typingr   modelscope.hub.constantsr   r   modelscope.hub.utils.utilsr   modelscope.utils.loggerr	   r/   getenvr|   lowerr   objectr   rh   rM   r   r   <module>r      se    				                    : : : : : : : : 3 3 3 3 3 3 . . . . . .	 BI7AAGGIIOOQQU[[ F8 F8 F8 F8 F8f F8 F8 F8Re e e e e? e e e e er   