
    bi_                        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m	Z	m
Z
mZmZ d dlmZ d dlmZmZmZmZmZmZmZmZ d dlmZmZ d dlmZ d dlmZmZm Z m!Z!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.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6 ddl7m8Z8  e8e9      Z: ee;      jx                  dz  Z= e       j|                  Z?d:dee	e@df   de@fdZA	 	 	 	 	 	 	 	 	 	 d;de@dee@   deBdeBdee@   de@dee@   dee@   dee
eC      deeB   defd ZDd:d!ed"ee@e
e@   f   defd#ZEd:d$ee@   d%ee@   fd&ZFd:d'e@d(ee@   de@fd)ZGe"ddddddddddd*
d+ee@ef   d'e@d,ee@   d-ee@   d.eBd/ee	   d0eBdee@   deee	e@f      d1ee@   d%ee@   d2ee	e@ef      fd3       ZH	 	 	 	 	 	 	 	 d<d2ee	e@ef      fd4ZId=d5e@d6e
e@   d(e@fd7ZJ G d8 d9      ZKy)>    N)Path)DictListOptionalUnion)uuid4)	DDUFEntry	ModelCardModelCardDatacreate_repohf_hub_download
model_infosnapshot_downloadupload_folder)HF_HUB_DISABLE_TELEMETRYHF_HUB_OFFLINE)REGEX_COMMIT_HASH)EntryNotFoundErrorRepositoryNotFoundErrorRevisionNotFoundErroris_jinja_availablevalidate_hf_hub_args)version)	HTTPError   )__version__   )DEPRECATED_REVISION_ARGSHUGGINGFACE_CO_RESOLVE_ENDPOINTSAFETENSORS_WEIGHTS_NAMEWEIGHTS_NAME)ENV_VARS_TRUE_VALUES_flax_version_jax_version_onnxruntime_version_torch_versionis_flax_availableis_onnx_availableis_torch_available)
get_loggerzmodel_card_template.md
user_agentreturnc                 F   dt          dt        j                  j                         d    dt         }t
        st        r|dz   S t               r|dt         z  }t               r|dt         z  }|dt         z  }t               r|d	t         z  }t        j                  j!                  d
d      j#                         t$        v r|dz  }t'        | t(              r.|ddj+                  d | j-                         D              z   z  }|S t'        | t.              r|d| z   z  }|S )zF
    Formats a user-agent string with basic info about a request.
    z
diffusers/z	; python/r   z; session_id/z; telemetry/offz; torch/z; jax/z; flax/z; onnxruntime/DIFFUSERS_IS_CI z; is_ci/truez; c              3   0   K   | ]  \  }}| d |   yw)/N ).0kvs      T/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/utils/hub_utils.py	<genexpr>z"http_user_agent.<locals>.<genexpr>]   s     Ida!AaSzIs   )r   sysr   split
SESSION_IDr   r   r)   r&   r'   r$   r#   r(   r%   osenvirongetupperr"   
isinstancedictjoinitemsstr)r+   uas     r6   http_user_agentrE   K   s    k])CKK,=,=,?,B+C=Q[P\	]B>%%%
())
|n%%
''
3455	zz~~',2248LL
n*d#
dTYYIj6F6F6HIIII I 
J	$
dZI    Frepo_id_or_pathtokenis_pipelinefrom_trainingmodel_description
base_modelpromptlicensewidget	inferencec
                 J   t               st        d      	 t        j                  | |      }
|
S # t        t
        f$ rc |r.t        j                  t        |d|	|||      t        |      }
Y |
S t               }|rdnd}|d| d	}t        j                  ||
      }
Y |
S w xY w)a  
    Loads or creates a model card.

    Args:
        repo_id_or_path (`str`):
            The repo id (e.g., "runwayml/stable-diffusion-v1-5") or local path where to look for the model card.
        token (`str`, *optional*):
            Authentication token. Will default to the stored token. See https://huggingface.co/settings/token for more
            details.
        is_pipeline (`bool`):
            Boolean to indicate if we're adding tag to a [`DiffusionPipeline`].
        from_training: (`bool`): Boolean flag to denote if the model card is being created from a training script.
        model_description (`str`, *optional*): Model description to add to the model card. Helpful when using
            `load_or_create_model_card` from a training script.
        base_model (`str`): Base model identifier (e.g., "stabilityai/stable-diffusion-xl-base-1.0"). Useful
            for DreamBooth-like training.
        prompt (`str`, *optional*): Prompt used for training. Useful for DreamBooth-like training.
        license: (`str`, *optional*): License of the output artifact. Helpful when using
            `load_or_create_model_card` from a training script.
        widget (`List[dict]`, *optional*): Widget to accompany a gallery template.
        inference: (`bool`, optional): Whether to turn on inference widget. Helpful when using
            `load_or_create_model_card` from a training script.
    zModelcard rendering is based on Jinja templates. Please make sure to have `jinja` installed before using `load_or_create_model_card`. To install it, please run `pip install Jinja2`.rH   	diffusers)rN   library_namerP   rL   instance_promptrO   )	card_datatemplate_pathrK   pipelinemodelu+   This is the model card of a 🧨 diffusers zS that has been pushed on the Hub. This model card has been automatically generated.)rK   )	r   
ValueErrorr
   loadr   r   from_templater   MODEL_CARD_TEMPLATE_PATH)rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   
model_cardrV   	components                r6   load_or_create_model_cardr`   c   s    F ?
 	
a^^O5A
. -  78 a"00'#!,')$*! 7"3J&  &I&1
wI (&QR[Q\  ]p  %q!"00N_`J-as   0 <B"//B"!B"r^   tagsc                 $   | j                   j                  d| j                   _        |ft        |t              r|g}| j                   j                  g | j                   _        |D ]'  }| j                   j                  j                  |       ) | S )z?Populates the `model_card` with library name and optional tags.rS   )datarT   r?   rC   ra   append)r^   ra   tags      r6   populate_model_cardrf      s    ##+'2
$dC 6D??'#%JOO  	-COO  '',	- rF   resolved_filecommit_hashc                     | ||S t        t        |       j                               } t        j                  d|       }|y|j                         d   }t        j                  |      r|S dS )zP
    Extracts the commit hash from a resolved filename toward a cache file.
    Nzsnapshots/([^/]+)/r   )rC   r   as_posixresearchgroupsr   match)rg   rh   rl   s      r6   extract_commit_hashro      sn      7]+4467MYY,m<F~--/!$K+11+>;HDHrF   weights_namevariantc                 l    |1| j                  d      }|d d |gz   |dd  z   }dj                  |      } | S )N.)r9   rA   )rp   rq   splitss      r6   _add_variantrv      sI    ##C(y(6"#;6xx'rF   )
	subfolder	cache_dirforce_downloadproxieslocal_files_onlyrH   r+   revisionrh   dduf_entriespretrained_model_name_or_pathrw   rx   ry   rz   r{   r|   r}   c                   t        |       } |rM|t        d      | dk(  r|ndj                  | |g      }||v r|S t        d| d|j	                          d      t
        j                  j                  |       r| S t
        j                  j                  |       rt
        j                  j                  t
        j                  j                  | |            r"t
        j                  j                  | |      }|S |at
        j                  j                  t
        j                  j                  | ||            r#t
        j                  j                  | ||      }|S t        d| d|  d      |	t        v r|t        k(  s	|t        k(  rt        j                  t        j                  t              j                        t        j                  d      k\  rS	 t!        | t#        ||	      ||||||||	xs |
	
      }t%        j&                  d
|	 d|  d|	 d|	 d|	 d|	 dt(               |S 	 t!        | |||||||||	xs |
	
      }|S #  t%        j&                  d|	 d|  d|	 d|	 d|  dt#        ||	       d|  d|  dt#        ||	       dt(               Y jxY w# t*        $ r}t        |  d      |d }~wt,        $ r}t        |	 d|  d      |d }~wt.        $ r}t        |  d| d      |d }~wt0        $ r}t        d|  d|       |d }~wt        $ r}t        dt2         d |  d!| d"      |d }~wt        $ r}t        d#|  d$|  d%|       |d }~ww xY w)&NzDDUF file only allow for 1 level of directory (e.g transformer/model1/model.safetentors is not allowed). Please check the DDUF structurer/   r1   zError no file named z found in archive rs   z found in directory z0.22.0)	filenamerx   ry   rz   r{   rH   r+   rw   r|   zLoading the variant z from z via `revision='zG'` is deprecated. Loading instead from `revision='main'` with `variant=z)`. Loading model variants via `revision='z9'` will be removed in diffusers v1. Please use `variant='z'` instead.zYou are loading the variant z^'`. This behavior is deprecated and will be removed in diffusers v1. One should use `variant='z%'` instead. However, it appears that z currently does not have a z file in the 'main' branch of z. 
 The Diffusers team and community would be very grateful if you could open an issue: https://github.com/huggingface/diffusers/issues/new with the title 'z is missing z0' so that the correct variant file can be added.z is not a local folder and is not a valid model identifier listed on 'https://huggingface.co/models'
If this is a private repository, make sure to pass a token having permission to this repo with `token` or log in with `hf auth login`.z is not a valid git identifier (branch name, tag name or commit id) that exists for this model name. Check the model page at 'https://huggingface.co/z' for available revisions.& does not appear to have a file named z:There was a specific connection error when trying to load z:
We couldn't connect to 'zM' to load this model, couldn't find it in the cached files and it looks like z8 is not the path to a directory containing a file named z or 
Checkout your internet connection or see how to run the library in offline mode at 'https://huggingface.co/docs/diffusers/installation#offline-mode'.zCan't load the model for 'z'. If you were trying to load it from 'https://huggingface.co/models', make sure you don't have a local directory with the same name. Otherwise, make sure 'z=' is the correct path to a directory containing a file named )rC   rZ   rA   EnvironmentErrorkeysr;   pathisfileisdirr   r!   r    r   parser   base_versionr   rv   warningswarnFutureWarningr   r   r   r   r   )r~   rp   rw   rx   ry   rz   r{   rH   r+   r|   rh   r}   
model_filees                 r6   _get_model_filer      s     %((E$F! 2  -2 8,GH 	
 %"%9,GYZfZkZkZmYnno#pqq	5	6,,	4	577>>"'',,'DlST&C\RJ"rww~~GGLL6	<P(
 &CYP\]J"&|n4HIfHgghi  00-AY1YgmmK8EEF'--X`Jaa,1),A'#1#%5)'%4
 *8*F;X:YYijris  t{  |D  {E  En  ow  nx  xq  rz  q{  {F  G! "!2	(-%#-!1%#!0[J '28*FC`Baaqrzq{  |Z  [c  Zd  dI  Jg  Ih  hC  DP  Q]  _g  Dh  Ci  iG  He  Gf  fC	  D	a	  C	b	  b	n	  o	{	  |	H
  J
R
  o	S
  n	T
  T
D  E!( ' 	"01 2d d 	
 % 	"* ++H*IIce 	
 " 	"011WXdWeefg  	"LMjLkknopnqr  	"*+J*K L::W9X Y66B^ Dff    	",-J,K L))F(G H++7.:
 	sb   AI )J AJ	MJ--M9KMK))M5LML--M9MMc
                 X   |	r||	vrCt        d| d|  d      t        j                  j                  |      st        d| d|  d      |	r't	        j
                  |	|   j                               }
n8t        |d      5 }t	        j
                  |j                               }
ddd       t        t        
d   j                                     }|
d   }t        |
d   j                               |d<   |
d   j                         |d<   t        j                  j                  | |      }t        j                  j!                  |       s|	r|D cg c]"  }t        j                  j                  ||      $ }}|D ]J  |	r|	vs
t#        | d	 d
      t        j                  j%                        r;t#        | d	 d
       ||fS |}|-|D cg c]"  }t        j                  j                  ||      $ }}ddg}|sFt'        | ||      }|D ]3  t)        fd|j*                  D              }|r$t-        | d	 d
       	 t/        | ||||||||	      }| t        j                  j                  ||      }|D cg c]"  }t        j                  j                  ||      $ }}|D ]2  }t        j                  j                  |      r#t-        | d| d
       ||fS # 1 sw Y   FxY wc c}w c c}w # t0        $ r}t-        dt2         d|  d      |d}~ww xY wc c}w )a  
    For a given model:

    - download and cache all the shards of a sharded checkpoint if `pretrained_model_name_or_path` is a model ID on the
      Hub
    - returns the list of paths to all the shards, as well as some metadata.

    For the description of each arg, see [`PreTrainedModel.from_pretrained`]. `index_filename` is the full path to the
    index (downloaded and cached if `pretrained_model_name_or_path` is a model ID on the Hub).
    zCan't find a checkpoint index (z) in rs   rN
weight_mapmetadataall_checkpoint_keysr   z5 which is required according to the checkpoint index.z*.jsonz*.md)r|   rH   c              3   :   K   | ]  }|j                   v   y wN)	rfilename)r3   r4   
shard_files     r6   r7   z._get_checkpoint_shard_files.<locals>.<genexpr>  s     $b1Z1;;%>$bs   )rx   rz   r{   rH   r|   allow_patternsignore_patternsr+   r   z
' to load z?. You should try again after checking your internet connection.z does not have a file named )rZ   r;   r   r   jsonloads	read_textopenreadsortedsetvalueslistr   copyrA   r   FileNotFoundErrorexistsr   anysiblingsr   r   r   r   )r~   index_filenamerx   rz   r{   rH   r+   r|   rw   r}   indexforiginal_shard_filenamessharded_metadatashards_pathshard_filenamesr   pr   model_files_infoshard_file_presentcached_folderr   cached_filenamescached_filer   s                            @r6   _get_checkpoint_shard_filesr   T  s   , ->~>NeTqSrrstuuww~~n->~>NeTqSrrstuu

<7AACD.#& 	)!JJqvvx(E	)  &c%*=*D*D*F&GHZ(.253F3K3K3M.N*+%*<%8%=%=%?\"'',,<iHK 
ww}}23|AYZA277<<Q7ZZ) 	J\1+&-'Mj\ ZF F 
 ww~~j1+&-'Mj\ ZF F 	  000 .N>LM"'',,y!4MM(O %&Ch^cd2 	J!$$bHXHaHa$b!b%&"m#I* VB B 	))-)+!

  GGLL	BM AYY1]A6YY' ww~~k*" /!=k]J  A  ---Y	) 	) [& NB  &'F&GzRoQp q> >
 	 Zs6    $K('K5'K:
6K? 'L'(K2?	L$LL$folder	filenamesc                 4   |r| rt        d      |sUg }t        j                  |       D ];  \  }}}|D ]0  }|j                  t        j                  j                  |             2 = d}t        j                  d| d| d      t        fd|D              S )Nz1Both `filenames` and `folder` cannot be provided.z\d{5}-of-\d{5}z.*-z\.z	\.[a-z]+$c              3   D   K   | ]  }j                  |      d u  y wr   )rn   )r3   r   variant_file_res     r6   r7   z8_check_legacy_sharding_variant_format.<locals>.<genexpr>  s!     G$$Q't3Gs    )	rZ   r;   walkrd   r   basenamerk   compiler   )r   r   rq   _filesfiletransformers_index_formatr   s          @r6   %_check_legacy_sharding_variant_formatr     s    VLMM	776? 	9KAq% 9  !1!1$!789	9 !2jjC(A'B"WIY!WXOGYGGGrF   c                       e Zd ZdZ	 	 	 	 ddeeej                  f   dedee   dee   de	dee   fd	Z
	 	 	 	 	 	 	 ddedee   d
ee	   dee   de	de	dee   dee   defdZy)PushToHubMixinzR
    A Mixin to push a model, scheduler, or pipeline to the Hugging Face Hub.
    Nworking_dirrepo_idrH   commit_message	create_prrw   c                     |Od| j                   j                  v rd}n4d| j                   j                  v rd}nd| j                   j                   }t        j                  d| d| d       t	        ||||||	      S )
zB
        Uploads all files in `working_dir` to `repo_id`.
        ModelzUpload model	SchedulerzUpload schedulerzUpload zUploading the files of z to rs   )r   folder_pathrH   r   r   path_in_repo)	__class____name__loggerinfor   )selfr   r   rH   r   r   rw   s          r6   _upload_folderzPushToHubMixin._upload_folder  s     !$..111!/ 7 77!3#*4>>+B+B*C!D-k]$wiqIJ#)"
 	
rF   privatesafe_serializationrq   r,   c	           	         t        |||d      j                  }|st        ||      }	t        |	      }	d|i}
d| j                  j
                  vr|
j                  d|i       t        j                         5 } | j                  |fi |
 |s/	j                  t        j                  j                  |d             | j                  ||||||      cd	d	d	       S # 1 sw Y   y	xY w)
uy  
        Upload model, scheduler, or pipeline files to the 🤗 Hugging Face Hub.

        Parameters:
            repo_id (`str`):
                The name of the repository you want to push your model, scheduler, or pipeline files to. It should
                contain your organization name when pushing to an organization. `repo_id` can also be a path to a local
                directory.
            commit_message (`str`, *optional*):
                Message to commit while pushing. Default to `"Upload {object}"`.
            private (`bool`, *optional*):
                Whether to make the repo private. If `None` (default), the repo will be public unless the
                organization's default is private. This value is ignored if the repo already exists.
            token (`str`, *optional*):
                The token to use as HTTP bearer authorization for remote files. The token generated when running `hf
                auth login` (stored in `~/.huggingface`).
            create_pr (`bool`, *optional*, defaults to `False`):
                Whether or not to create a PR with the uploaded files or directly commit.
            safe_serialization (`bool`, *optional*, defaults to `True`):
                Whether or not to convert the model weights to the `safetensors` format.
            variant (`str`, *optional*):
                If specified, weights are saved in the format `pytorch_model.<variant>.bin`.

        Examples:

        ```python
        from diffusers import UNet2DConditionModel

        unet = UNet2DConditionModel.from_pretrained("stabilityai/stable-diffusion-2", subfolder="unet")

        # Push the `unet` to your namespace with the name "my-finetuned-unet".
        unet.push_to_hub("my-finetuned-unet")

        # Push the `unet` to an organization with the name "my-finetuned-unet".
        unet.push_to_hub("your-org/my-finetuned-unet")
        ```
        T)r   rH   exist_okrR   r   r   rq   z	README.md)rH   r   r   rw   N)r   r   r`   rf   r   r   updatetempfileTemporaryDirectorysave_pretrainedsaver;   r   rA   r   )r   r   r   r   rH   r   r   rq   rw   r^   save_kwargstmpdirs               r6   push_to_hubzPushToHubMixin.push_to_hub  s    ` gwedS[[ 27%HJ,Z8J ,-?@dnn555	734((* 	f D  7;7 V[ AB&&-## ' 	 	 	s   7ACC%)NNFN)NNNFTNN)r   
__module____qualname____doc__r   rC   r;   PathLiker   boolr   r   r2   rF   r6   r   r     s     $(,#'
3+,
 
 }	

 !
 
 C=
B )-"&##'!%#'JJ !J $	J
 }J J !J #J C=J 
JrF   r   r   )
NNFFNNNNNN)NNFNNNr/   N)NNN)Lr   r;   rk   r8   r   r   pathlibr   typingr   r   r   r   uuidr   huggingface_hubr	   r
   r   r   r   r   r   r   huggingface_hub.constantsr   r   huggingface_hub.file_downloadr   huggingface_hub.utilsr   r   r   r   r   	packagingr   requestsr   r/   r   	constantsr   r   r    r!   import_utilsr"   r#   r$   r%   r&   r'   r(   r)   loggingr*   r   r   __file__parentr]   hexr:   rC   rE   r   r@   r`   rf   ro   rv   r   r   r   r   r2   rF   r6   <module>r      s7  "  	 	 
    . . 	 	 	 O ;     	 	 	   
H	>003KK W[[
dCo 6 # 2  '+ !#' $CCC=C C 	C
  }C C SMC c]C T$Z C ~C CLI U3S	>5J V_  Ix} I8C= Is Xc] c  
  $# ""-1"!%37@#(d#3@ @ }	@
 }@ @ d^@ @ C=@ tSy)*@ sm@ #@ 4Y/0@ @L 
37l. 4Y/0l.^
H# 
Hc 
Hdg 
Hm mrF   