o
    Gid                     @   s  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	 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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)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0 ddl1m2Z2 e2e3Z4ee5j6d Z7e	 j8Z9dCde:e;B dB de;fddZ<												dDde;de;dB de=de=de;dB de;de;dB de;dB de>e: dB de=dB de=d e=defd!d"Z?dCd#ed$e;e>e; B dB defd%d&Z@dCd'e;dB d(e;dB fd)d*ZAdCd+e;d,e;dB de;fd-d.ZBeddddddddddd/
d0e;eB d+e;d1e;dB d2e;dB d3e=d4e:dB d5e=de;dB de:e;B dB d6e;dB d(e;dB d7e:e;ef dB fd8d9ZC							:	dEd7e:e;ef dB fd;d<ZDdFd=e;d>e>e; d,e;fd?d@ZEG dAdB dBZFdS )G    N)Path)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HfHubHTTPErrorRepositoryNotFoundErrorRevisionNotFoundErroris_jinja_availablevalidate_hf_hub_args)version   )__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                 C   s   dt  dtj d  dt }tstr|d S t r"|dt 7 }t	 r3|dt
 7 }|dt 7 }t r=|d	t 7 }tjd
d tv rL|d7 }t| trc|dddd |  D  7 }|S t| trn|d|  7 }|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                 s   s"    | ]\}}| d | V  qdS )/N ).0kvr+   r+   M/home/ubuntu/.local/lib/python3.10/site-packages/diffusers/utils/hub_utils.py	<genexpr>\   s     z"http_user_agent.<locals>.<genexpr>)r   sysr   split
SESSION_IDr   r   r$   r!   r"   r   r   r#   r    osenvirongetupperr   
isinstancedictjoinitemsstr)r&   uar+   r+   r/   http_user_agentJ   s$    
 
r>   Frepo_id_or_pathtokenis_pipelinefrom_trainingmodel_description
base_modelpromptlicensewidget	inference
is_modularupdate_model_cardc                 C   s   t  std|r|
stdz%tj| |d}|r,|
r/|dur2|j}t|}||_W |S W |S W |S W |S  ttfy   |rRtjt|d|	|||dt	|d}Y |S t }|
re|duret|}||_Y |S |ridnd	}|du rud
| d}tj||d}Y |S w )a  
    Loads or creates a model card.

    Args:
        repo_id_or_path (`str`):
            The repo id (e.g., "stable-diffusion-v1-5/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.
        is_modular: (`bool`, optional): Boolean flag to denote if the model card is for a modular pipeline.
            When True, uses model_description as-is without additional template formatting.
        update_model_card: (`bool`, optional): When True, regenerates the model card content even if one
            already exists on the remote repo. Existing card metadata (tags, license, etc.) is preserved. Only
            supported for modular pipelines (i.e., `is_modular=True`).
    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`.zU`update_model_card=True` is only supported for modular pipelines (`is_modular=True`).r@   N	diffusers)rF   library_namerH   rD   instance_promptrG   )	card_datatemplate_pathrC   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.)rC   )
r   
ValueErrorr   loaddatar   r   from_templater   MODEL_CARD_TEMPLATE_PATH)r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   
model_cardexisting_datarO   	componentr+   r+   r/   load_or_create_model_cardb   sZ   +r[   rX   tagsc                 C   s\   | j jdu r
d| j _|dur,t|tr|g}| j jdu r g | j _|D ]	}| j j| q"| S )z?Populates the `model_card` with library name and optional tags.NrL   )rU   rM   r8   r<   r\   append)rX   r\   tagr+   r+   r/   populate_model_card   s   
r_   resolved_filecommit_hashc                 C   sZ   | du s|dur
|S t t|  } td| }|du rdS | d }t|r+|S dS )zP
    Extracts the commit hash from a resolved filename toward a cache file.
    Nzsnapshots/([^/]+)/r   )r<   r   as_posixresearchgroupsr   match)r`   ra   rd   r+   r+   r/   extract_commit_hash   s   rg   weights_namevariantc                 C   s>   |d ur|  d}|d d |g |dd   }d|} | S )N.)r2   r:   )rh   ri   splitsr+   r+   r/   _add_variant   s
   

rm   )
	subfolder	cache_dirforce_downloadproxieslocal_files_onlyr@   r&   revisionra   dduf_entriespretrained_model_name_or_pathrn   ro   rp   rq   rr   rs   rt   c                C   s  t | } |r.|d urtd| dkr|nd| |g}||v r!|S td| d|  dtj| r6| S tj| rutjtj| |rPtj| |}|S |d urjtjtj| ||rjtj| ||}|S td| d|  d|	t	v r|t
ks|tkrtttjtdkrz/t| t||	||||||||	p|
d	
}td
|	 d|  d|	 d|	 d|	 d|	 dt |W S    td|	 d|  d|	 d|	 d|  dt||	 d|  d|  dt||	 dt Y zt| |||||||||	p|
d	
}|W S  ty } zt|  d|d }~w ty* } zt|	 d|  d|d }~w tyA } zt|  d| d|d }~w tyX } ztd|  d| |d }~w tys } ztdt d |  d!| d"|d }~w ty } ztd#|  d$|  d%| |d }~ww )&NzDDUF file only allow for 1 level of directory (e.g transformer/model1/model.safetentors is not allowed). Please check the DDUF structurer)   r*   zError no file named z found in archive rj   z found in directory z0.22.0)	filenamero   rp   rq   rr   r@   r&   rn   rs   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 )r<   rS   r:   EnvironmentErrorkeysr4   pathisfileisdirr   r   r   r   parser   base_versionr   rm   warningswarnFutureWarningr   r   r   r   r   )ru   rh   rn   ro   rp   rq   rr   r@   r&   rs   ra   rt   
model_fileer+   r+   r/   _get_model_file   s   (Fr   r)   c
                    s|  |	r||	vrt d| d|  dntj|s#t d| d|  d|	r/t|	|  }
nt|d}t| }
W d   n1 sFw   Y  t	t
|
d  }|
d }t|
d  |d< |
d  |d< tj| tj| sz|	rfd	d
|D }|D ]#|	r|	vrt d dqtjst d dq||fS |}durfdd
|D }ddg}|st| ||d}|D ]tfdd|jD }|st d dqzt| ||||||||d	 durtj  W n ty } ztdt d|  d|d}~ww  fdd
|D }|D ]}tj|s8t  d| dq%||fS )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 rj   rN
weight_mapmetadataall_checkpoint_keysc                       g | ]	}t j |qS r+   r4   r{   r:   r,   f)shards_pathr+   r/   
<listcomp>      z/_get_checkpoint_shard_files.<locals>.<listcomp>rw   z5 which is required according to the checkpoint index.c                    r   r+   r   )r,   p)rn   r+   r/   r     r   z*.jsonz*.md)rs   r@   c                 3   s    | ]} |j v V  qd S N)	rfilename)r,   r-   )
shard_filer+   r/   r0     s    z._get_checkpoint_shard_files.<locals>.<genexpr>)ro   rq   rr   r@   rs   allow_patternsignore_patternsr&   rx   z
' to load z?. You should try again after checking your internet connection.c                    r   r+   r   r   )cached_folderr+   r/   r     r   z does not have a file named )rS   r4   r{   r|   jsonloads	read_textopenreadsortedsetvalueslistrz   copyr:   r}   FileNotFoundErrorexistsr	   anysiblingsry   r
   r   r   )ru   index_filenamero   rq   rr   r@   r&   rs   rn   rt   indexr   original_shard_filenamessharded_metadatashard_filenamesr   r   model_files_infoshard_file_presentr   cached_filenamescached_filer+   )r   r   r   rn   r/   _get_checkpoint_shard_filesg  s   r   folder	filenamesc                    s|   |r| rt d|s%g }t| D ]\}}}|D ]}|tj| qqd}td| d| d t fdd|D S )Nz1Both `filenames` and `folder` cannot be provided.z\d{5}-of-\d{5}z.*-z\.z	\.[a-z]+$c                 3   s    | ]
}  |d uV  qd S r   )rf   r   variant_file_rer+   r/   r0     s    z8_check_legacy_sharding_variant_format.<locals>.<genexpr>)	rS   r4   walkr]   r{   basenamerc   compiler   )r   r   ri   _filesfiletransformers_index_formatr+   r   r/   %_check_legacy_sharding_variant_format  s   r   c                   @   s   e Zd ZdZ				ddeejB dededB dedB ded	edB fd
dZ							ddededB dedB dedB dedededB d	edB defddZ	dS )PushToHubMixinzR
    A Mixin to push a model, scheduler, or pipeline to the Hugging Face Hub.
    NFworking_dirrepo_idr@   commit_message	create_prrn   c                 C   sf   |du rd| j jv rd}nd| j jv rd}nd| j j }td| d| d	 t||||||d
S )zB
        Uploads all files in `working_dir` to `repo_id`.
        NModelzUpload model	SchedulerzUpload schedulerzUpload zUploading the files of z to rj   )r   folder_pathr@   r   r   path_in_repo)	__class____name__loggerinfor   )selfr   r   r@   r   r   rn   r+   r+   r/   _upload_folder  s   zPushToHubMixin._upload_folderTprivatesafe_serializationri   r'   c	              	   C   s   t |||ddj}|st||d}	t|	}	d|i}
d| jjvr&|
d|i t (}| j	|fi |
 |s@|	
tj|d | j||||||dW  d	   S 1 sUw   Y  d	S )
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   r@   exist_okrK   r   r   ri   z	README.md)r@   r   r   rn   N)r   r   r[   r_   r   r   updatetempfileTemporaryDirectorysave_pretrainedsaver4   r{   r:   r   )r   r   r   r   r@   r   r   ri   rn   rX   save_kwargstmpdirr+   r+   r/   push_to_hub  s(   0
$zPushToHubMixin.push_to_hub)NNFN)NNNFTNN)
r   
__module____qualname____doc__r<   r4   PathLikeboolr   r   r+   r+   r+   r/   r     sZ    
!	
r   r   )NNFFNNNNNNFF)NNFNNNr)   N)NNN)Gr   r4   rc   r1   r   r   pathlibr   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   r   	packagingr   r)   r   	constantsr   r   r   r   import_utilsr   r   r   r    r!   r"   r#   r$   loggingr%   r   r   __file__parentrW   hexr3   r9   r<   r>   r   r   r[   r_   rg   rm   r   r   r   r   r+   r+   r+   r/   <module>   s   (
 (

	

$Z		

 

o