
    6pjV                        S SK r 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  S SKJr  S SK	J
r
JrJrJr  S SKJrJrJrJr  S SKJrJrJrJrJrJrJr  S SKJr  \" 5       rS rS	 rS]S
 jr S\\!\\!   4   4S jr"  S^S\\\!      S\\\!      S\\!   4S jjr#S r$S\%S\!4S jr&S\!S\%4S jr'S\!S\!4S jr(S_S\\!   4S jjr)S\4S jr*  S`S\!S\!S\\\!\4      S\\!   4S jjr+S\S\,4S jr-S  r.S]S! jr/  SaS"\\!   S#\,S\!4S$ jjr0S% r1S\,4S& jr2  SbS'\!S(\\!   S)\\!   SS4S* jjr3S+r4S,\5S\!4S- jr6S.\\\\!\%4         S/\\!   S\!4S0 jr7S1 r8\ Rr                  SS2.S3\\!\4   S4\\5   S\
\SS4   4S5 jj5       r: ScS6\\%\!\4   S7\!S\\   4S8 jjr;0 S9S:_S;S<_S=S>_S?S@_SASB_SCSB_SDSE_SFSG_SHSI_SJSK_SLSM_SNSM_SOSP_SQSR_SSST_SUSV_SWSX_SYSZ0Er<S[\!S\!4S\ jr=g)d    N)datetime)Path)	GeneratorListOptionalUnion)BaseFileLockFileLockSoftFileLockTimeout)DEFAULT_MODELSCOPE_DOMAINDEFAULT_MODELSCOPE_GROUPDEFAULT_MODELSCOPE_INTL_DOMAINMODEL_ID_SEPARATORMODELSCOPE_DOMAINMODELSCOPE_SDK_DEBUGMODELSCOPE_URL_SCHEME)
get_loggerc                     [         U ;   a3  U R                  [         5      S   nU R                  [         5      S   nX4$ [        nU nX4$ )Nr      )r   splitr   )model_idgroup_or_ownernames      V/var/www/html/pdf-tiff/venv/lib/python3.13/site-packages/modelscope/hub/utils/utils.pymodel_id_to_group_owner_namer      sR    X%!(:;A>~~01!4  2    c                     [         R                  R                  U S5      R                  5       R	                  5       nUS:H  $ )N true)osenvirongetstriplower)var_namevalues     r   is_env_truer(   $   s2    JJNN8R(..0668EF?r   c                     [         [        R                  ;   a9  [        R                  " [         5      (       a  [        R                  " [         5      $ U (       a  [        $ [
        $ N)r   r!   r"   getenvr   r   cn_sites    r   
get_domainr.   )   s<    BJJ&2995F+G+Gyy*++((--r   	raw_inputc                 T   S n[        U [        5      (       ab  [        5       nSU ;   a0  U R                  S5       Vs/ s H  o"R	                  5       PM     nnU$ UR                  U R	                  5       5         U$ [        U [        5      (       a  [        5       nU  H  n[        U[        5      (       d  M  SU;   a@  UR                  UR                  S5       Vs/ s H  o3R	                  5       PM     sn5        M`  UR                  UR	                  5       5        M     U$ s  snf s  snf )N,)
isinstancestrlistr   r$   appendextend)r/   outputssss       r   convert_patternsr:   2   s    F)S!!))2)=>)=Aggi)=F> M MM)//+, M 
It	$	$A!S!!!8MM"E"88:"EFMM!''),  M ? #Fs   D D%
allow_file_patternallow_patternsreturnc                   ^ / nU (       a  UR                  U 5        U(       a  UR                  U5        U(       d  g/ nU H  n[        U5      nS H'  nUR                  U5      nUS:w  d  M  [        XW5      nM)     USU nUR	                  S5      n	U	S:  d  MY  USU	 m[        U4S jS 5       5      (       a  Mz  UR                  T5        M     U(       d  g[        U5      S:X  a  US   $ U V
s/ s H  oR                  S5      PM     nn
/ n[        U6  H1  n[        [        U5      5      S:X  a  UR                  US   5        M1    O   U(       d  gSR                  U5      $ s  sn
f )a  Extract common directory prefix from include patterns for server-side filtering.

Only processes allow/include patterns (ignore/exclude is irrelevant for prefix).
Returns None if no meaningful prefix can be extracted.

Algorithm:
1. Merge allow_file_pattern and allow_patterns into one list
2. For each pattern, find position of first wildcard char (* ? [)
3. Extract text before that position, then take directory part (up to last '/')
4. Find longest common directory prefix (path-segment-aware)
5. Return None if no valid common prefix

Examples:
    ['TacExo/*'] -> 'TacExo'
    ['data/train/*.parquet'] -> 'data/train'
    ['data/train/*', 'data/valid/*'] -> 'data'
    ['*.safetensors'] -> None
    ['TacExo/*', 'OtherDir/*'] -> None (no common prefix)
    ['data/*/train.csv'] -> 'data'
N)*?[/r   c              3   ,   >#    U  H	  oT;   v   M     g 7fr*    ).0cdir_parts     r   	<genexpr>-extract_root_from_patterns.<locals>.<genexpr>x   s     >oH}os   r   )r6   lenfindminrfindanyr5   r   zipsetjoin)r;   r<   patternsextracted_dirspatternfirst_wildcardwcposprefixlast_sepdsplit_pathscommon_segmentssegmentsrH   s                 @r   extract_root_from_patternsr_   E   sT   2 H*+'NW!B,,r"Cby!$^!9 " .) <<$a<ix(H>o>>>%%h/# (  >aa   *88A773<K8O%s8}"""8A;/	 & 88O$$ 9s   /E#c                     [         R                  R                  S5      (       a  U R                  SS5      nOU R                  SS5      n[        R
                  R                  US   UR                  SS5      5      nU$ )Nwin\   rC   r   .___)sysplatform
startswithrsplitr!   pathrR   replace)	directoryr   partsmasked_directorys       r   get_model_masked_directoryro      sg    
||u%%  q)  a(ww||E!Hh.>.>sE.JKr   
size_bytesc                     SS K nU S:X  a  gSn[        UR                  UR                  U S5      5      5      nUR	                  SU5      n[        X-  S5      nU SX#    3$ )Nr   0B)	BKBMBGBTBPBEBZBYBi   rc    )mathintfloorlogpowround)rp   r}   	size_nameipr8   s         r   convert_readable_sizer      sc    QEIDJJtxx
D123AqAjna AS),  r   folder_pathc                     Sn[        U 5      R                  S5       H6  nUR                  5       (       d  M  XR                  5       R                  -  nM8     U$ )Nr   r?   )r   rglobis_filestatst_size)r   
total_sizerj   s      r   get_folder_sizer      sH    J[!'',<<>>))+---J - r   c                 &    [        [        U S95      $ )Nr   )r   r   r   s    r   get_readable_folder_sizer      s     [!IJJr   r   c                    [         R                  " 5       R                  SS5      n[        R                  " S[        R
                  R                  US5      5      nU c  U$ [        R
                  R                  X S-   5      $ )zcache dir precedence:
    function parameter > environment > ~/.cache/modelscope/hub
Args:
    model_id (str, optional): The model id.
Returns:
    str: the model_id dir if model_id not None, otherwise cache root dir.
.cache
modelscopeMODELSCOPE_CACHEhubrC   )r   homejoinpathr!   r+   rj   rR   )r   default_cache_dir	base_paths      r   get_cache_dirr      sj     		,,X|D		,'',,'8%@BI (9 #bggllc>/# #r   c                      [         R                  R                  S5      n U (       a  [        U 5      R	                  5       $ [        R
                  " 5       S-  S-  $ )zFCache root used by ``modelscope_hub`` downloads (not SDK ``.../hub``).r   r   r   )r!   r"   r#   r   
expanduserr   )envs    r   _modelscope_hub_cache_rootr      sA    
**..+
,C
Cy##%%99;!L00r   repo_id	repo_type	cache_dirc                 >   U (       a  SU ;  a  gUb  [        U5      R                  5       O	[        5       nUR                  S5      (       d  U S3OUnU R	                  SS5      u  pVUR                  SS5      nU R                  SS5      nX4-  U-  X4-  U-  U-  /n	U	 H  n
[        U
5      (       d  M    g   X5-  U-  X5-  U-  US-  U-  U-  US-  U-  U-  X4-  U-  U-  /nU H7  n
[        U
5      (       d  M  [        R                  S	U
U 5        [        U
5      s  $    g)
a  Find old on-disk cache layouts that ``modelscope_hub`` download misses.

``modelscope_hub`` reuses ``{cache}/{type}s/{owner}/{safe_name}/`` (dots in
``name`` replaced by ``___``) and writes to
``{cache}/{type}s/{owner}--{name}/snapshots/{rev}/``. Older SDKs also
stored repos at:

- ``{cache}/{owner}/{name}/`` (flat, when ``MODELSCOPE_CACHE`` was set)
- ``{cache}/hub/{owner}/{name}/`` (pre-``models/`` restructuring)
- ``{cache}/{type}s/{owner}/{name}/`` (unsafed name; hub only checks
  ``safe_name``)

Returns a non-empty legacy path only when the layouts hub already handles
are absent, so callers can pass it as ``local_dir`` and avoid re-download.
rC   Nr8   r   rd   re   z--r   z)Found legacy cache at %s for %s, reusing.)
r   r   r   endswithr   rk   _non_empty_dirloggerinfor3   )r   r   r   basesegmentownerr   	safe_namesafe_id	hub_knownrj   legacy_candidatess               r   find_reusable_legacy_repo_dirr      sE   ( c(+4+@4	?%%'"$ 	%.%7%7%<%<1o)G--Q'KES%(Iooc4(G 	 *I $  	ty uut#uuy(% "$KKCT!t9	 "
 r   rj   c                     U R                  5       (       d  g [        U R                  5       5      $ ! [         a     gf = fNF)is_dirrO   iterdirOSError)rj   s    r   r   r     s8    ;;==4<<>"" s   1 
>>c                  2   [         [        R                  ;   a7  [        [	        [
        R                  " 5       R                  5       5      5      n U $ SSKJ	n  [        [	        [
        R                  " UR                  S5      R                  5       5      5      n U $ )Nr   )version%Y-%m-%d %H:%M:%S)r   r!   r"   r~   r   r   now	timestampr   r   strptime__release_datetime__)rtr   s     r   get_release_datetimer     ss    rzz)x||~//123 I 	'!!'">">"577@y{DE Ir   c                 &    [         [        U 5      -   $ r*   )r   r.   r,   s    r   get_endpointr     s     :g#666r   cli_endpointr-   c                     U c	  [        US9$ U R                  5       R                  S5      nU(       d	  [        US9$ UR                  S5      (       d  UR                  S5      (       d	  [        U-   nU$ )a^  Resolve the ModelScope API endpoint with automatic scheme completion.

Priority (highest to lowest):
    1. ``cli_endpoint`` (explicit CLI --endpoint argument)
    2. Environment variable ``MODELSCOPE_DOMAIN``
    3. Built-in default (https://www.modelscope.cn)

Scheme auto-completion:
    If the resolved value does not start with ``http://`` or ``https://``,
    ``https://`` is prepended automatically so that callers may pass bare
    domain names such as ``modelscope.ai``.

Args:
    cli_endpoint: Value from the CLI ``--endpoint`` flag.  When *None*,
        the function falls back to :func:`get_endpoint`.
    cn_site: Forwarded to :func:`get_endpoint` when *cli_endpoint* is
        *None*.  ``True`` selects the Chinese site, ``False`` the
        international site.

Returns:
    A fully-qualified endpoint URL, e.g. ``https://www.modelscope.cn``.
r,   rC   zhttp://zhttps://)r   r$   rstriprh   r   )r   r-   endpoints      r   resolve_endpointr     sq    0 G,,!!#**3/HG,,y))(2E2E3 3(83Or   c                    Sn[         R                  " 5       n[        U S5       n UR                  U5      nU(       d  OUR	                  U5        M,  S S S 5        UR                  5       $ ! , (       d  f       UR                  5       $ = f)Ni   rb)hashlibsha256openreadupdate	hexdigest)	file_pathBUFFER_SIZEsha256_hashfdatas        r   compute_hashr   @  sy    "K.."K	i	!66+&Dt$	  
   "" 
	   ""s   .A**
Bc                     [        U 5      nX!:X  d;  [        R                  " U 5        SU < SU< SU< S3n[        R	                  U5        gg)zValidate the file hash is expected, if not, delete the file

Args:
    file_path (str): The file to validate
    expected_sha256 (str): The expected sha256 hash

Returns:
    bool: True if the file is valid, False otherwise
zFile z6 integrity check failed, expected sha256 signature is z, actual is z3, the download may be incomplete, please try again.FT)r   r!   remover   error)r   expected_sha256file_sha256msgs       r   file_integrity_validationr   M  s@     y)K)
		)5Sr   	file_namerS   commit_messagec                    [        U[        5      (       a  U/nUc  SUS    SU 3nU R                  n[        R                  R                  XQ5      n[        R                  R                  U5      (       a%  [        USSS9 nUR                  5       nS S S 5        OSnWn	U H;  n
X;  d  M
  [        U	5      S:  a  U	R                  S5      (       d  U	S-  n	X S3-  n	M=     X:w  a@  [        US	SS9 n[        R                  S
U SU	 35        UR                  U	5        S S S 5         U R                  U5        g ! , (       d  f       N= f! , (       d  f       N2= f! [         a  nU(       a   S nAg UeS nAff = f)NzAdd `r   z` patterns to rutf-8)encodingr   
wzWriting z file. Content: )r2   r3   	model_dirr!   rj   rR   existsr   r   rK   r   r   debugwritepush	Exception)repor   rS   r   ignore_push_errorrepo_dirr   r   current_contentcontentrU   es               r   add_content_to_filer   b  sT   
 (C  : !^I;G ~~HX1I	ww~~i  )S73qffhO 43 G!7|a(8(8(>(>4"~%G	  !)S73qLL8I;.>wiHIGGG 4		.!% 43 43
  G	s6   D80-E	&E 8
E	
E
E7$E20E22E7))secondr   <   )minuter   r   )houri     )dayiQ    )weeki:	 r   )monthi '    )yeari3Ntsc                     [         R                   " 5       U -
  nUS:  a  g[         H  u  p#n[        X-  5      nUc  M  XT::  d  M    O   W SW US:  a  S S3$ S S3$ )zOFormat timestamp in seconds into a human-readable string, relative to now.
       za few seconds agor|   r   r8   r   z ago)time_TIMESINCE_CHUNKSr   )r   deltalabeldivider	max_valuer'   s         r   format_timesincer    st     IIK"Erz"%6!	eo& U%7 &7 WAeWEAIS6d;;26d;;r   rowsheadersc           	         [        / U QUP76  Vs/ s H  n[        S U 5       5      PM     nnS[        U5      -  R                  " U6 n/ nUR	                  UR                  " U6 5        UR	                  UR                  " U Vs/ s H  nSU-  PM
     sn6 5        U  H!  nUR	                  UR                  " U6 5        M#     SR                  U5      $ s  snf s  snf )zy
Inspired by:

- stackoverflow.com/a/8356620/593036
- stackoverflow.com/questions/9535954/printing-lists-as-tabular-data
c              3   J   #    U  H  n[        [        U5      5      v   M     g 7fr*   )rK   r3   )rF   xs     r   rI   tabulate.<locals>.<genexpr>  s     /3ac#a&kk3s   !#z{{:{}}} -r   )rP   maxrK   formatr5   rR   )r  r  col
col_widths
row_formatlinesr   rows           r   tabulater    s     <?;N;Ng;NO;NC#/3//;NJOs7|+33Z@JE	LL""G,-	LL""j$AjS1Wj$ABCZ&&,- 99U P %Bs   CCc                 \    U R                  5       n U S;   a  gU S;   a  g[        SU < 35      e)N>   1tyonyesr    r   >   0r   nnoofffalser   zinvalid truth value )r%   
ValueError)vals    r   	strtoboolr     s8    
))+C
22
33
+C73
44r   timeout	lock_filer"  c             #   N  #    Sn[        XS9n[        R                  " 5       n [        R                  " 5       U-
  nUb  XQ:  a  [        [        U 5      5      e UR	                  U(       a  [        X!U-
  5      OUS9    Uv    UR!                  5         g ! [         a6    [        R                  SU  S[        R                  " 5       U-
  S S35         O[         a:  nS[        U5      ;   a%  [        R                  SU 5        [        XS9n S nAM  e S nAf[         at  nUR                  [        R                  [        R                  [        R                  4;   a1  [        R                  S	UR                  U 5        [        XS9n S nAGMj  e S nAff = fGMu  ! [         a.     [#        U 5      R%                  5          g ! [         a      g f = ff = f!  UR!                  5         f ! [         a.     [#        U 5      R%                  5          f ! [         a      f f = ff = f= f7f)
Nr   r!  z!Still waiting to acquire lock on z (elapsed: z.1fz	 seconds)zuse SoftFileLock insteadzPFileSystem does not appear to support flock. Falling back to SoftFileLock for %szCEncountered OSError (errno=%d) on %s, Falling back to SoftFileLock.)r
   r   r   r3   acquirerM   r   r   NotImplementedErrorwarningr   r   errnoESTALEENOENT	EREMOTEIOreleaser   unlink)r#  r"  default_intervallock
start_timeelapsed_timer   s          r   weak_file_lockr2    s    
 I8DJ
yy{Z/<#:#i.))	LL ,.DE 0  22 	
	LLN9  	KK3I;k$))+XbJbcfIggpq # 	)SV3f $IH 	ww5<<uGGYGGY( $IH	+ L  	Y&&( 		LLN 	Y&&( 	s   AH%$B =H%?G F H%=FH%	F.DH%DFA'FH%FFH%
G$F?=H%?
G	G
H%GGH%H"G'&H"'
H2HH"
H	HH"H	HH""H%
time_stamp	time_zonec                    SSK nU (       d  g[        U [        5      (       a  U $ [        U [        5      (       Ga   U R	                  S5      (       a  SU ;  a	  U SS S-   n O3U SS R                  S5      u  p4USS R                  SS5      nU SU S3n [        R                  " U S	5      R                  UR                  S
5      S9nUS
:w  a   UR                  UR                  U5      5      nU$ / SQnU H7  n [        R                  " U U5      R                  UR                  U5      S9s  $    [        SU  S35      e[        U [        5      (       aB   [        R                  " XR                  S
5      S9R                  UR                  U5      5      $ [        S[!        U 5       S35      e! [         a     M  f = f! [         a  n[        SU  S35      UeSnAff = f! [        [        4 a  n[        SU  S35      UeSnAff = f)a&  Convert a UNIX/string timestamp to a timezone-aware datetime object.
Args:
    time_stamp: UNIX timestamp (int), ISO string, or datetime object
    time_zone: Target timezone for non-UTC timestamps (default: 'Asia/Shanghai')
Returns:
    Timezone-aware datetime object or None if input is None
r   NZrd   rB   z.000000Zr   r  z%Y-%m-%dT%H:%M:%S.%fZUTC)tzinfo)z%Y-%m-%dT%H:%M:%S.%fz%Y-%m-%dT%H:%M:%Sz%Y-%m-%d %H:%M:%S.%fr   zUnsupported timestamp format: ''zCannot parse 'zr' as a datetime. Expected formats: 'YYYY-MM-DDTHH:MM:SS[.ffffff]Z' (UTC) or 'YYYY-MM-DDTHH:MM:SS[.ffffff]' (local))tzzCannot convert 'z2' to datetime. Ensure it's a valid UNIX timestamp.zUnsupported type 'z"'. Expected int, str, or datetime.)zoneinfor2   r   r3   r   r   ljustr   rk   ZoneInfo
astimezoner  r~   fromtimestampr   	TypeErrortype)	r3  r4  r;  r   fractiondtformatsfmtr   s	            r   convert_timestamprF    sU     *h''*c""*	""3''j(!+CR:!=J &0_%:%:3%?ND'|11!S9H$(68*A!6J&&z'>@@G2:2C2CE2J AH AL  %x'8'8'CDB	 #C!'00& !!(0A0A)0L!MN # !5j\CE E 
J	$	$	))00799C%%i0:22  j!1 22TU
 	
1 & ! !  	  -b c 	 G$ 	":,.`a	sa   B2F> .	F> 82F-*F> -F> A G  -
F;7F> :F;;F> >
GGG H0H  Hz.webpz
image/webpz.avifz
image/avifz.heicz
image/heicz.heifz
image/heifz.jpgz
image/jpegz.jpegz.pngz	image/pngz.gifz	image/gifz.bmpz	image/bmpz.svgzimage/svg+xmlz.tiffz
image/tiffz.tifz.icozimage/x-iconz.mp4z	video/mp4z.webmz
video/webmz.avizvideo/x-msvideoz.movzvideo/quicktimez.mkvzvideo/x-matroskamedia_file_pathc                    SSK nSSKn[        R                  R	                  U 5      n [        R                  R                  U 5      (       d  [        SU  35      e[        R                  R                  U 5      (       d  [        SU  35      eUR                  U 5      u  p4U(       dC  [        R                  [        R                  R                  U 5      S   R                  5       5      nU(       d  [        SU  35      e[        U S5       nUR                  5       nUR!                  U5      R#                  S5      nSSS5        S	U S
W 3$ ! , (       d  f       N= f)a  
Encode image or video file to base64 string.

Args:
    media_file_path (str): Path to the image or video file

Returns:
    str: Base64 encoded string with data URL prefix

Raises:
    FileNotFoundError: If image/video file doesn't exist
    ValueError: If file is not a valid format
r   NzImage file not found: zPath is not a file: r   zFile is not a valid format: r   r   zdata:z;base64,)base64	mimetypesr!   rj   r   r   FileNotFoundErrorisfiler  
guess_type_FALLBACK_MIME_TYPESr#   splitextr%   r   r   	b64encodedecode)rG  rI  rJ  	mime_type_
media_file
image_database64_datas           r   encode_media_to_base64rW  [  s$     gg((9O77>>/**"88I JKK77>>/**//@ABB
 ''8LI(,,GG_-a0668:	77HIJJ 
ot	$
__&
&&z299'B 
%
 9+Xk]33 
%	$s   
1E
E)T)NNr*   )modelN)NTr   )zAsia/Shanghai)>
contextlibr(  r   r!   rf   r   r   pathlibr   typingr   r   r   r   filelockr	   r
   r   r   modelscope.hub.constantsr   r   r   r   r   r   r   modelscope.utils.loggerr   r   r   r(   r.   r3   r:   r_   ro   r~   r   r   r   r   r   r   boolr   r   r   r   r   r   r   r   floatr  r  r   contextmanagerr2  rF  rN  rW  rE   r   r   <module>rb     s      	 
    3 3 B B= = = /	 
.c49n 5 ( /3*.J% c+J%T#Y'J% c]J%^!c !c !  K# K# K#HSM #1D 1 ,0444 c4i()4 c]	4n $ 	7 48%) 8C=  " .1 F
#T 0 9=*/	%#&%"&s)% )1% 59	%P	 
< 
<3 
<4U38_-. c s $5  /32eCI. 2$UO2 ",d":;2 2l (7L
%S((:"; L
!$L
;CH;ML
b\\ \ \	
 L \ K K K O \ L N K \  !" #$ % ,*4C *4C *4r   