
    6pj7                        S SK r S SKrS SKrS SKrS SKrS SKJrJr  S SKJ	r	  S SK
JrJr  S SKJr  S SKJr  \" 5       r\R$                  " \S5      R'                  5       R)                  5       S:H  r  " S	 S
\5      r " S S\5      rg)    N)movermtree)Dict)	FILE_HASH)MODELSCOPE_ENABLE_DEFAULT_HASH_VALIDATION)compute_hash)
get_loggerFalsetruec                   p    \ rS rSrSrSrSrSr S\4S jr	S r
S	 rS
 rS rS rS rS rS rS rS rSrg)FileSystemCache   z.mscz.mdlidz.mvcache_root_locationc                     [         R                  " 5       U l        [        R                  " USS9  Xl        U R                  5         g)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      X/var/www/html/pdf-tiff/venv/lib/python3.13/site-packages/modelscope/hub/utils/caching.py__init__FileSystemCache.__init__    s2     %??,
'$7#6     c                     U R                   $ N)r   r   s    r   get_root_location!FileSystemCache.get_root_location1   s    '''r   c                    / U l         [        R                  R                  U R                  [
        R                  5      n[        R                  R                  U5      (       as   [        US5       n[        R                  " U5      nS S S 5        [        W[        5      (       a  X0l         g [        R                  SU[        U5      R                   5        g g ! , (       d  f       NV= f! ["         aO  n[        R                  SX5         [        R$                  " UUS-   5         S nAg ! [&         a      S nAg f = fS nAff = f)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   FileSystemCache.load_cache4   s    !ww||D,D,D,;,I,I K77>>.//.5!;;q>D 6dD))(,%NNK,T
++- 055  	_(-JJ33lBD D 	sT   %C) 1C#C) ,*C) 
C&"C) )
E3D=
D))
D:3D=9D::D==Ec                    [         R                  R                  U R                  [        R
                  5      n[        R                  " SU R                  S9u  p# [         R                  " US5       n[        R                  " [        U R                  5      U5        UR                  5         [         R                  " UR                  5       5        SSS5        [         R                   " X15        g! , (       d  f       N%= f! ["         ad     [         R$                  " U5        O! [&         a     Of = f[         R                  R)                  U5      (       a  [         R*                  " U5        e f = f)z8Write .msc atomically. Caller must hold ``_cache_lock``.z.tmp)suffixdirwbN)r   r)   r*   r   r   r+   tempfilemkstempfdopenr.   dumpr1   r(   flushfsyncfilenor7   r6   closer8   r,   unlink)r   r9   fdtemp_filenamer:   s        r   _save_cached_files_unlocked+FileSystemCache._save_cached_files_unlockedN   s    !ww||D,D,D,;,I,I K$,,t779	2t$D!2!23Q7	$ % JJ};	 %$
  	 ww~~m,,		-(	sI   D 2AC0D 0
C>:D 
E/D#"E/#
D0-E//D00?E/c                 p    U R                      U R                  5         SSS5        g! , (       d  f       g= f)z
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   rM   r"   s    r   save_cached_files!FileSystemCache.save_cached_filesc   s%     ,,. s   '
5c                     g)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_fileFileSystemCache.get_filem   s     	r   c                     g)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
NrS   )r   rU   locations      r   put_fileFileSystemCache.put_filex   s     	r   c                 z    XR                   ;   a,  U R                   R                  U5        U R                  5         gg)z^Remove cache key in index, The file is removed manually

Args:
    key (dict): The cache key.
N)r(   removerP   rT   s     r   
remove_keyFileSystemCache.remove_key   s5     ###$$S)""$ $r   c                 8    U R                    H
  nX!:X  d  M
    g   g)NTF)r(   )r   rU   
cache_files      r   r,   FileSystemCache.exists   s     ++J  , r   c                 N    [        U R                  5        U R                  5         g)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_cacheFileSystemCache.clear_cache   s    
 	t''(r   c                 f    [         R                  " UR                  5       5      R                  5       $ r!   )hashlibsha256encode	hexdigestrT   s     r   	hash_nameFileSystemCache.hash_name   s     ~~cjjl+5577r   )r   r   r(   N)r5   
__module____qualname____firstlineno__r+   MODEL_META_FILE_NAMEMODEL_META_MODEL_IDMODEL_VERSION_FILE_NAMEstrr   r#   r   rM   rP   rV   rZ   r^   r,   rd   rk   __static_attributes__rS   r   r   r   r      s]    M!# "(4*/	
%8r   r   c                      ^  \ rS rSrSrSU 4S jjrS rS rS\4S jr	S r
S	 rS
 rS rS rS rS rS rS rSrU =r$ )ModelFileSystemCache   zLocal cache file layout
cache_root/owner/model_name/individual cached files and cache index file '.mcs'
Save only one version for each file.
c                 l  > Ub  Uc=  [         TU ]  [        R                  R	                  U5      5        U R                  5         O[[         TU ]  [        R                  R	                  XU5      5        [        R                  U< SU< 30U l        U R                  5         U R                  5       U l        g)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   rq   
model_metasave_model_metaload_model_versioncached_model_revision)r   
cache_rootownername	__class__s       r   r   ModelFileSystemCache.__init__   s     =DLGRWW\\*56  "GRWW\\*TBC33t5LDO   "%)%<%<%>"r   c                 ~   [         R                  R                  U R                  [        R
                  5      n[         R                  R                  U5      (       a^   [        US5       n[        R                  " U5      nS S S 5        [        W[        5      (       a  X0l        g [        R                  SU5        [        R$                  S0U l        g ! , (       d  f       NX= f! [         aN  n[        R                  SX5         [         R                   " XS-   5         S nANh! ["         a      S nANxf = fS nAff = f)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   rp   r,   r-   r.   r/   r0   dictr|   r2   r3   r6   r7   r8   rq   )r   meta_file_pathr:   r;   r<   s        r   r{   $ModelFileSystemCache.load_model_meta   s    d&>&>&5&J&JL77>>.)).$/1!;;q>D 0dD))&*ON-/ +>>	J 0/  M-2JJ~/LMM sT   C$ *C#C$ %C$ 
C!C$ $
D<.D7D##
D4-D73D44D77D<c                 F   [         R                  R                  U R                  [        R
                  5      n[         R                  R                  U5      (       a4  [        US5       nUR                  5       R                  5       sS S S 5        $ g ! , (       d  f       g = f)Nr)
r   r)   r*   r   r   rr   r,   r-   readstrip)r   model_version_file_pathr:   s      r   r~   'ModelFileSystemCache.load_model_version   sn    "$'',,$$o&M&M#O77>>122-s3qvvx~~' 43  43s   )B
B revision_infoc                 P   [         R                  R                  U R                  [        R
                  5      n[        US5       n[        U[        5      (       a"  SUS   < SUS   < 3nUR                  U5        OUR                  U5        S S S 5        g ! , (       d  f       g = f)Nwz	Revision:Revisionz,CreatedAt:	CreatedAt)
r   r)   r*   r   r   rr   r-   r0   r   write)r   r   r   r:   version_info_strs        r   save_model_version'ModelFileSystemCache.save_model_version   s~    "$'',,$$o&M&M#O)3/1-..!*-}[/I$K ()& 0//s   A	B
B%c                 <    U R                   [        R                     $ r!   )r|   r   rq   r"   s    r   get_model_id!ModelFileSystemCache.get_model_id   s    BBCCr   c                    [         R                  R                  U R                  [        R
                  5      n[        US5       n[        R                  " U R                  U5        S S S 5        g ! , (       d  f       g = f)NrA   )
r   r)   r*   r   r   rp   r-   r.   rE   r|   )r   r   r:   s      r   r}   $ModelFileSystemCache.save_model_meta   sP    d&>&>&5&J&JL.$'1KK+ (''s   "A00
A>c                 
   U R                    Hs  nXS   :X  d  M  [        R                  R                  U R                  US   5      n[        R                  R                  U5      (       a  Us  $ U R                  U5        Mu     g)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_path%ModelFileSystemCache.get_file_by_path   sn      ,,K//#%77<<0H0H0;F0C$E 77>>"233++OOK0 - r   c                 r   U R                    H  nXS   :X  d  M  US   R                  U5      (       d  UR                  US   5      (       d  MA  [        R                  R	                  U R
                  US   5      n[        R                  R                  U5      (       a  Us  $ U R                  U5        M     g)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,   r^   )r   r   	commit_idr   r   s        r   get_file_by_path_and_commit_id3ModelFileSystemCache.get_file_by_path_and_commit_id  s      ,,K//J'229==AUAUVablVmAnAn#%77<<0H0H0;F0C$E 77>>"233++OOK0 - r   c                 &   U R                  U5      nU R                   Hp  nX2:X  d  M
  [        R                  R	                  U R
                  US   5      n[        R                  R                  U5      (       a  Us  $ U R                  U5          g   g)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,   r^   )r   model_file_info	cache_keyr   	orig_paths        r   get_file_by_info%ModelFileSystemCache.get_file_by_info  s|     ((9	,,K'GGLL)A)A)4V)<>	77>>),,$$OOK0 - r   c                     US   US   S.nU$ )Nr   r   )r   r   rS   )r   r   r   s      r   __get_cache_key$ModelFileSystemCache.__get_cache_key2  s!    #F+'
3
	 r   c                    U R                  U5      nSnUS   n[        R                  R                  U R                  US   5      nU R
                   H  nUS   U:X  d  M  US   R                  US   5      (       d  US   R                  US   5      (       d  MH  U[           nUc  MV  [        R                  R                  U5      (       d  M|  [        (       a  [        U5      nOUnXx:X  a  Sn  O[        R                  SU S35        M     U(       a6  [        R                  R                  U5      (       a  gU R                  U5        g)zCheck 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   Tz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   r2   infor^   )	r   r   rU   	is_existsr   cache_file_path
cached_keyexpected_hashcache_file_sha256s	            r   r,   ModelFileSystemCache.exists9  s*    ""?3	K	'',,t'?'?'6v'>@++J&!Y.z*55c*oFF:11*Z2HII /	 : ,'2) 2) 65,8,I),9)$9$(	$YK/no! ,& ww~~o..#%r   c                 6   U R                    H  nUS   US   :X  d  M  U R                  U5        [        R                  R	                  U R
                  US   5      n[        R                  R                  U5      (       a  [        R                  " U5          g   g)zlWe in cache, remove it.

Args:
    model_file_info (ModelFileInfo): The model file information from server.
r   N)r(   r^   r   r)   r*   r   r,   r]   )r   r   r   r   s       r   remove_if_exists%ModelFileSystemCache.remove_if_existsb  sv      ,,K6"of&==,GGLL)A)A)4V)<>	77>>),,IIi( -r   c                    U R                  U5        U R                  U5      n[        R                  R	                  U R
                  US   5      n[        R                  R                  U5      n[        R                  R                  U5      (       d  [        R                  " USS9  [        X$5        U R                     U R                  R                  U5        U R                  5         SSS5        U$ ! , (       d  f       U$ = f)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(   appendrM   )r   r   model_file_locationr   cache_full_pathcache_file_dirs         r   rZ   ModelFileSystemCache.put_fileq  s     	o.((9	'',,t'?'?'0'8:9ww~~n--KK6 2$$Y/,,.    s   ?,C55
D)r   r|   )NN)r5   rm   rn   ro   __doc__r   r{   r~   r   r   r   r}   r   r   r   r   r,   r   rZ   rt   __classcell__)r   s   @r   rv   rv      sX    
?2K*	' 	'D,(,,'R r   rv   )rg   r   r.   rB   r   shutilr   r   typingr   modelscope.hub.constantsr   r   modelscope.hub.utils.utilsr   modelscope.utils.loggerr	   r2   getenvr   lowerr   objectr   rv   rS   r   r   <module>r      s~     	     : 3 .	 II7AGGIOOQU[[ F8f F8Re? er   