o
    pine                     @   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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 d dlmZ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/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7 ddl8m9Z9 e9e:Z;ee<j=d Z>e j?Z@dUdee
eAdf deAfddZB										dVdeAdeeA deCdeCdeeA deAdeeA deeA deeeD  d eeC defd!d"ZEdUd#ed$eeAeeA f defd%d&ZFdUd'eeA d(eeA fd)d*ZGejHIeJd+ejHKeJd,d-d.ZLejHKeLd/ZMdWd0eeA d1eeA ddfd2d3ZNejHKed4ZOejHPeOsId ZQn*eReOZSzeTeSU ZQW n eVyb   d ZQY nw W d   n	1 snw   Y  eQdk rejHWeMoeXeYeMd kZZeZre;[d5 zeN  W n- e\y Z] z d6Ke^e]j_Z`e;ad7e` d6e]jbj: d8e] d9 W Y dZ][]ndZ][]ww eQdk r z$ejced:d; eReOd<ZSeSdd= W d   n	1 sw   Y  W n e\y   e;[d>e d? Y nw dUd@eAdAeeA deAfdBdCZee#ddddddddddD	dEeeAef d@eAdFeeA dGeeA dHeCdIee
 dJeCdeeA deee
eAf  dKeeA d(eeA fdLdMZfdNdO Zg							PdXdQdRZhG dSdT dTZidS )Y    N)Path)DictListOptionalUnion)uuid4)	ModelCardModelCardDatacreate_repohf_hub_download
model_infosnapshot_downloadupload_folder)HF_HUB_CACHE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                 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/   W/home/ubuntu/SoloSpeech/.venv/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/   r3   http_user_agentK   s$    
 
rB   Frepo_id_or_pathtokenis_pipelinefrom_trainingmodel_description
base_modelpromptlicensewidget	inferencec
                 C   s   t  stdz
tj| |d}
W |
S  ttfyL   |r/tjt|d|	|||dt|d}
Y |
S t }|r6dnd}|du rBd	| 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., "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`.rD   	diffusers)rJ   library_namerL   rH   instance_promptrK   )	card_datatemplate_pathrG   pipelinemodelNu+   This is the model card of a 🧨 diffusers zS that has been pushed on the Hub. This model card has been automatically generated.)rG   )	r   
ValueErrorr   loadr   r   from_templater	   MODEL_CARD_TEMPLATE_PATH)rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   
model_cardrQ   	componentr/   r/   r3   load_or_create_model_cardc   s:   #r[   rY   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.NrN   )datarO   r<   r@   r\   append)rY   r\   tagr/   r/   r3   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)ra   rb   re   r/   r/   r3   extract_commit_hash   s   rh   HF_HOMEXDG_CACHE_HOMEz~/.cachehuggingfacerN   old_cache_dirnew_cache_dirc              	   C   s   |d u rt }| d u rt} t|  } t| }| dD ]6}| rS| sS|||  }|jj	ddd t
|| zt
|| W q tyR   td Y qw qd S )Nz
**/blobs/*T)parentsexist_okzCould not create symlink between old cache and new cache. If you use an older version of diffusers again, files will be re-downloaded.)r   old_diffusers_cacher   
expanduserglobis_file
is_symlinkrelative_toparentmkdirr8   replacesymlinkOSErrorloggerwarning)rl   rm   old_blob_pathnew_blob_pathr/   r/   r3   
move_cache   s(   r   zversion_diffusers_cache.txtzThe cache for model files in Diffusers v0.14.0 has moved to a new location. Moving your existing cached models. This is a one-time operation, you can interrupt it or run it later by calling `diffusers.utils.hub_utils.move_cache()`.
z5There was a problem when trying to move your cache:

z: z

Please file an issue at https://github.com/huggingface/diffusers/issues/new/choose, copy paste this whole message and we will do our best to help.T)ro   w1z?There was a problem when trying to write in your cache folder (z=). Please, ensure the directory exists and can be written to.weights_namevariantc                 C   sT   |d ur(|  d}| drdnd}|d |  |g || d   }d|} | S )N.z.index.json)r6   endswithr>   )r   r   splitssplit_indexr/   r/   r3   _add_variant  s   
"
r   )		subfolder	cache_dirforce_downloadproxieslocal_files_onlyrD   r*   revisionrb   pretrained_model_name_or_pathr   r   r   r   r   r   c       
         C   s  t | } tj| r| S tj| rKtjtj| |r&tj| |}|S |d ur@tjtj| ||r@tj| ||}|S td| d|  d|	tv r|tksW|t	krt
t
tjt
dkrz/t| t||	||||||||	pv|
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y } zt|  d| d|d }~w ty, } ztd|  d| |d }~w tyG } ztdt d|  d| d|d }~w tya } ztd|  d |  d!| |d }~ww )"NzError no file named z found in directory r   z0.22.0)	filenamer   r   r   r   rD   r*   r   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 `huggingface-cli 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@   r8   pathisfileisdirr>   EnvironmentErrorr   r    r   r   parser   base_versionr   r   warningswarnFutureWarningr   r   r   r   rU   r   )r   r   r   r   r   r   r   rD   r*   r   rb   
model_fileer/   r/   r3   _get_model_file  s   (Fr   c                    sN   t j| |  fdd|D }|D ]}t j|s$t  d| dqd S )Nc                       g | ]	}t j |qS r/   r8   r   r>   )r0   fshards_pathr/   r3   
<listcomp>      z2_check_if_shards_exist_locally.<locals>.<listcomp>r   5 which is required according to the checkpoint index.)r8   r   r>   existsrU   )	local_dirr   original_shard_filenamesshard_filenames
shard_filer/   r   r3   _check_if_shards_exist_locally  s   r   r-   c	                    s  t j|std| d|  dt|d}	t|	 }
W d   n1 s(w   Y  tt	|
d 
 }|
d }t|
d  |d< |
d  |d< t j| }t j| ret| |d	 ||fS |}durt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 ||fS W ||fS  ty } ztdt d|  d|d}~ww |rt||d durt j|}||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 r   rN
weight_mapmetadataall_checkpoint_keys)r   r   c                    r   r/   r   )r0   p)r   r/   r3   r     r   z/_get_checkpoint_shard_files.<locals>.<listcomp>z*.jsonz*.md)r   c                 3   s    | ]} |j v V  qd S N)	rfilename)r0   r1   )r   r/   r3   r4     s    z._get_checkpoint_shard_files.<locals>.<genexpr>r   r   )r   r   r   rD   r   allow_patternsignore_patternsr*   r   z
' to load z?. You should try again after checking your internet connection.)r   r   r   )r8   r   r   rU   openjsonloadsreadsortedsetvalueslistkeyscopyr>   r   r   r   anysiblingsr   r   r   r   )r   index_filenamer   r   r   rD   r*   r   r   r   indexr   sharded_metadatar   r   r   model_files_infoshard_file_presentcached_folderr   r/   )r   r   r3   _get_checkpoint_shard_files  sx   r   c                   @   s   e Zd ZdZ			ddeeejf dedee dee de	f
d	d
Z
						ddedee dee	 dee de	de	dee 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_idrD   commit_message	create_prc                 C   sd   |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 r   )r   folder_pathrD   r   r   )	__class____name__r{   infor   )selfr   r   rD   r   r   r/   r/   r3   _upload_folder  s   
zPushToHubMixin._upload_folderTprivatesafe_serializationr   r+   c                 C   s   t |||ddj}t||d}t|}d|i}	d| jjvr$|	d|i t %}
| j	|
fi |	 |
tj|
d | j|
||||dW  d	   S 1 sPw   Y  d	S )
u  
        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 or not the repository created should be private.
            token (`str`, *optional*):
                The token to use as HTTP bearer authorization for remote files. The token generated when running
                `huggingface-cli 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   rD   ro   rM   r   r   r   z	README.md)rD   r   r   N)r
   r   r[   r`   r   r   updatetempfileTemporaryDirectorysave_pretrainedsaver8   r   r>   r   )r   r   r   r   rD   r   r   r   rY   save_kwargstmpdirr/   r/   r3   push_to_hub  s"   .
$zPushToHubMixin.push_to_hub)NNF)NNNFTN)r   
__module____qualname____doc__r   r@   r8   PathLiker   boolr   r   r/   r/   r/   r3   r     sN    
	r   r   )
NNFFNNNNNN)NN)NNFNNNr-   )jr   r8   rd   r5   r   	tracebackr   pathlibr   typingr   r   r   r   uuidr   huggingface_hubr   r	   r
   r   r   r   r   huggingface_hub.constantsr   r   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__rv   rX   hexr7   r@   rB   r   r=   r[   r`   rh   r   rq   getenvr>   hf_cache_homerp   r   cache_version_filer   cache_versionr   r   intr   rU   r   lenlistdirold_cache_is_not_emptyr|   	Exceptionr   	format_tb__traceback__traceerrorr   makedirswriter   r   r   r   r   r/   r/   r/   r3   <module>   s$  $	(

	

$F 

 




	
x
\