
    g              $          d 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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 ddlmZ ddlmZ ddlZddlZddlmZmZmZmZ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)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z:m;Z; ddl<m=Z= ddl>m?Z?m@Z@mAZAmBZBmCZCmDZD ddl;mEZE  e;jF        eG          ZHej        jI        ZJd ZK ejL        dejM        N                     ejL        dd          d                    ZOejP        ZPejM        N                    eOd          ZQ ejL        dejR                  ZS ejL        deS          ZT ejL        deT          ZUejM        V                    eQ          reejM        V                    ejR                  sFdejW        vr=dejW        vr4dejW        vr+eHX                    d            ejY        eQejR                    ejL        dejM        N                    ejZ        d                    Z[dZ\ e            j]        Z^dD ]'Z_ ejL        e_           ej`        d e_ d!ea           (d"Zbd#ZcejW        d                    d$d%          e                                e?v Zfefrd&nd'ZgegZhejW        d                    d(d          , ej`        d)ea           ejW        d                    d(d          ZhejW        d                    d*eh          Zhehd+z   Ziehd,z   Zj	 drd-ekd.ekd/eekedf         d0eek         fd1Zld2 Zm e6d3d45          dsd/eekef         d6ee         fd7            Znd8 Zodsd9eeekdf         d6ekfd:Zpd;eek         d<eek         d6eek         fd=Zq	 	 	 	 	 	 	 	 	 	 	 	 	 	 dtd-eekejr        f         dAekd/eeekejr        f                  dBesdCees         dDeeekekf                  dEeeesekf                  d0eek         dFesdGekdHeek         d9eeekeekekf         f                  dIesdJesdKesdLeek         d6eek         f"dMZt	 	 	 	 	 	 	 	 dudNeekejr        f         dAekd/eeekejr        f                  dBesdCees         dDeeekekf                  dEeeesekf                  d0eek         dFesdGekfdOZudsdPZv	 	 	 dvd>dddQdNeekejr        f         dAekd0eek         dDeeekekf                  dEeeesekf                  dFesd/eekedf         dHeek         fdRZw G dS dT          ZxdUdVdWZydXeezekf         fdYZ{	 	 	 	 	 	 	 	 	 	 dwdZZ|dsd[Z}d\ Z~	 	 	 dxd]ekd^eeek                  dEeek         d_esfd`Zda Zdb ZdvdcZ G dd de          ZejM        N                    eUdf          ZejM                            e          sdZnO ee          5 Z	  eze                                          Zn# e$ r dZY nw xY wddd           n# 1 swxY w Y   ejM        V                    eU          o e ej        eU                    dk    Zedk     rer eK            reHX                    dg           neHX                    dh           	 eUejR        k    r eeUeU           n
 e             nc# e$ r[ZdiN                     ej        ej                            ZeH                    dje diej        jG         dke dl           Y dZ[ndZ[ww xY wedk     rt	  ej        eUd@m            eedn          5 Ze                    do           ddd           dS # 1 swxY w Y   dS # e$ r eHX                    dpeU dq           Y dS w xY wdS )yz?
Hub utilities: utilities related to download and cache models
    N)futures)Path)DictListOptionalTupleUnion)urlparse)uuid4)_CACHED_NO_EXISTCommitOperationAdd	ModelCardModelCardData	constantscreate_branchcreate_commitcreate_repoget_hf_file_metadatahf_hub_download
hf_hub_urltry_to_load_from_cache)REGEX_COMMIT_HASHhttp_get)EntryNotFoundErrorGatedRepoErrorHfHubHTTPErrorHFValidationErrorLocalEntryNotFoundErrorOfflineModeIsEnabledRepositoryNotFoundErrorRevisionNotFoundErrorbuild_hf_headersget_sessionhf_raise_for_statussend_telemetry)_deprecate_method)	HTTPError   )__version__logging)working_or_temp_dir)ENV_VARS_TRUE_VALUES_tf_version_torch_versionis_tf_availableis_torch_availableis_training_run_on_sagemaker)tqdmc                      t           S N)_is_offline_mode     R/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/utils/hub.pyis_offline_moder9   T   s    r7   
TORCH_HOMEXDG_CACHE_HOMEz~/.cachetorchtransformersPYTORCH_PRETRAINED_BERT_CACHEPYTORCH_TRANSFORMERS_CACHETRANSFORMERS_CACHEa  In Transformers v4.22.0, the default path to cache downloaded models changed from '~/.cache/torch/transformers' to '~/.cache/huggingface/hub'. Since you don't seem to have overridden and '~/.cache/torch/transformers' is a directory that exists, we're moving it to '~/.cache/huggingface/hub' to avoid redownloading models you have already in the cache. You should only see this message once.HF_MODULES_CACHEmodulestransformers_modules)r>   r?   r@   zUsing `zQ` is deprecated and will be removed in v5 of Transformers. Use `HF_HOME` instead.z3https://s3.amazonaws.com/models.huggingface.co/bertzhttps://cdn.huggingface.coHUGGINGFACE_CO_STAGINGNOzhttps://hub-ci.huggingface.cozhttps://huggingface.coHUGGINGFACE_CO_RESOLVE_ENDPOINTzUsing the environment variable `HUGGINGFACE_CO_RESOLVE_ENDPOINT` is deprecated and will be removed in Transformers v5. Use `HF_ENDPOINT` instead.HF_ENDPOINTz)/{model_id}/resolve/{revision}/{filename}z/api/telemetry/examplespath_or_repo_idfull_filename	cache_dirrevisionc                 J    t          | |||          }||t          k    r|S d S )NrJ   rK   )r   r   )rH   rI   rJ   rK   resolved_files        r8   _get_cache_file_to_returnrO      s8     +?MU^iqrrrM ]6F%F%F4r7   c                 2    t          |           }|j        dv S )N)httphttps)r
   scheme)url_or_filenameparseds     r8   is_remote_urlrV      s    o&&F=---r7   z4.39.0zBThis method is outdated and does not support the new cache system.)versionmessagereturnc                    | t           } n$t          | t                    rt          |           } t          j                            |           sg S g }t	          j        |           D ]}|                    d          rt          j        	                    | |          }t          |d          5 }t          j        |          }|d         }|d         }|                    d          rMt          j                            |                    d                    dz  }|                    |||f           ddd           n# 1 swxY w Y   |S )	a  
    Returns a list of tuples representing model binaries that are cached locally. Each tuple has shape `(model_url,
    etag, size_MB)`. Filenames in `cache_dir` are use to get the metadata for each model, only urls ending with *.bin*
    are added.

    Args:
        cache_dir (`Union[str, Path]`, *optional*):
            The cache directory to search for models within. Will default to the transformers cache if unset.

    Returns:
        List[Tuple]: List of tuples each with shape `(model_url, etag, size_MB)`
    N.jsonutf-8encodingurletagz.bing    .A)r@   
isinstancer   strospathisdirlistdirendswithjoinopenjsonloadgetsizestripappend)	rJ   cached_modelsfile	meta_path	meta_filemetadatar_   r`   size_MBs	            r8   get_cached_modelsru      ss    &			It	$	$ #	NN	7==## 	M
9%% 	? 	?==!! 	?Y55Ii'222 ?i9Y//uo'<<'' ? gooioog.F.FGG#MG!((#tW)=>>>? ? ? ? ? ? ? ? ? ? ? ? ? ? ? s   .BEE	E	c            	      v   	 t          j        t          j        d                                                   } | d         }| d                             d          d         }n# t          $ r d }d }Y nw xY wt	          j        t          j        dd                    }d|v rdnd	}d
t          j        v r-t          j        d
                              d          d         nd }t          j        dd           t          j        dd           t          j        dd          t          j        dd          ||||d}|S )NECS_CONTAINER_METADATA_URIImage:r(   SM_FRAMEWORK_PARAMSz{}*sagemaker_distributed_dataparallel_enabledTFTRAINING_JOB_ARN   SM_FRAMEWORK_MODULE
AWS_REGIONSM_NUM_GPUSr   SM_NUM_CPUS)sm_framework	sm_regionsm_number_gpusm_number_cpusm_distributed_trainingsm_deep_learning_containersm_deep_learning_container_tagsm_account_id)	requestsgetrc   environrj   split	Exceptionloadsgetenv)instance_datadlc_container_useddlc_tagsagemaker_paramsruns_distributed_training
account_idsagemaker_objects          r8   define_sagemaker_informationr      sJ    RZ0L%MNNSSUU*73(..s33A6   ! z"),A4"H"HII(TXh(h(hns@RVXV`@`@`-..44S99!<<fjJ 	"7>>Y|T22=!44=!44#<&8*1#	 	 s   AA" "A32A3
user_agentc                    dt            dt          j                                        d          dt           }t                      r|dt           z  }t                      r|dt           z  }t          j
        r|dz   S t                      rC|dd                    d	 t                                                      D                       z   z  }t          j                            d
d                                          t&          v r|dz  }t)          | t*                    r8|dd                    d |                                 D                       z   z  }nt)          | t,                    r|d| z   z  }|S )zF
    Formats a user-agent string with basic info about a request.
    ztransformers/z	; python/r   z; session_id/z; torch/z; tensorflow/z; telemetry/offz; c              3   *   K   | ]\  }}| d | V  dS /Nr6   .0kvs      r8   	<genexpr>z"http_user_agent.<locals>.<genexpr>   s0      ]]da!zzazz]]]]]]r7   TRANSFORMERS_IS_CI z; is_ci/truec              3   *   K   | ]\  }}| d | V  dS r   r6   r   s      r8   r   z"http_user_agent.<locals>.<genexpr>   s0      IIda!zzazzIIIIIIr7   )r)   sysrW   r   
SESSION_IDr0   r.   r/   r-   r   HF_HUB_DISABLE_TELEMETRYr1   rh   r   itemsrc   r   r   upperr,   ra   dictrb   )r   uas     r8   http_user_agentr      s~    
a	`	`s{/@/@/B/B1/E	`	`T^	`	`B *
)))) ,
+k+++) &%%%#%% ^
dTYY]]6R6T6T6Z6Z6\6\]]]]]]]	z~~*B//5577;OOO
n*d##  
dTYYIIj6F6F6H6HIIIIIII	J	$	$  
dZIr7   rN   commit_hashc                     | ||S t          t          |                                                     } t          j        d|           }|dS |                                d         }t          j        |          r|ndS )zP
    Extracts the commit hash from a resolved filename toward a cache file.
    Nzsnapshots/([^/]+)/r   )rb   r   as_posixresearchgroupsr   match)rN   r   r   s      r8   extract_commit_hashr      s~      7]++446677MY,m<<F~t--//!$K+1+>>H;;DHr7   Fr   Tfilenameforce_downloadresume_downloadproxiestokenlocal_files_only	subfolder	repo_type _raise_exceptions_for_gated_repo%_raise_exceptions_for_missing_entries'_raise_exceptions_for_connection_errors_commit_hashc                    |                     dd          }|-t          j        dt                     |t	          d          |}t                      r|st                              d           d}|	d}	t          |           } t          j
                            |	|          }t          j
                            |           rt          j
                            t          j
                            | |	          |          }t          j
                            |          s(|r$|d|	 d	fvrt          |  d
| d|  d| d          dS |S |t          }t!          |t"                    rt          |          }|=|s;t%          | ||||
          }|%|t&          ur|S |sdS t          d| d|  d          t)          |          }	 t+          | |t-          |	          dk    rdn|	|
||||||||          }n# t.          $ rE}t1          | |||          }||s|cY d}~S t          d|  dt          |                     |d}~wt2          $ r}t          |  d          |d}~wt4          $ r}t          | d|  d          |d}~wt6          $ rC}t1          | |||          }||r|s|cY d}~S t          dt8           d|  d| d          |d}~wt:          $ r<}|sY d}~dS |d}|d|	 d	fv rY d}~dS t          |  d
| d|  d| d          |d}~wt<          $ r7}t1          | |||          }||s|cY d}~S t          d|  d|           d}~wt>          $ r}t          d |  d!          |d}~ww xY w|S )"a
  
    Tries to locate a file in a local folder and repo, downloads and cache it if necessary.

    Args:
        path_or_repo_id (`str` or `os.PathLike`):
            This can be either:

            - a string, the *model id* of a model repo on huggingface.co.
            - a path to a *directory* potentially containing the file.
        filename (`str`):
            The name of the file to locate in `path_or_repo`.
        cache_dir (`str` or `os.PathLike`, *optional*):
            Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
            cache should not be used.
        force_download (`bool`, *optional*, defaults to `False`):
            Whether or not to force to (re-)download the configuration files and override the cached versions if they
            exist.
        resume_download:
            Deprecated and ignored. All downloads are now resumed by default when possible.
            Will be removed in v5 of Transformers.
        proxies (`Dict[str, str]`, *optional*):
            A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
            'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
        token (`str` or *bool*, *optional*):
            The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
            when running `huggingface-cli login` (stored in `~/.huggingface`).
        revision (`str`, *optional*, defaults to `"main"`):
            The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
            git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
            identifier allowed by git.
        local_files_only (`bool`, *optional*, defaults to `False`):
            If `True`, will only try to load the tokenizer configuration from local files.
        subfolder (`str`, *optional*, defaults to `""`):
            In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
            specify the folder name here.
        repo_type (`str`, *optional*):
            Specify the repo type (useful when downloading from a space for instance).

    <Tip>

    Passing `token=True` is required when you want to use a private model.

    </Tip>

    Returns:
        `Optional[str]`: Returns the resolved file (to the cache folder if downloaded from a repo).

    Examples:

    ```python
    # Download a model weight from the Hub and cache it.
    model_weights_file = cached_file("google-bert/bert-base-uncased", "pytorch_model.bin")
    ```
    use_auth_tokenNrThe `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.V`token` and `use_auth_token` are both specified. Please set only the argument `token`.z+Offline mode: forcing local_files_only=TrueTr   zconfig.jsonz/config.json& does not appear to have a file named z#. Checkout 'https://huggingface.co/z/tree/z' for available files.)rJ   rK   r   zCould not locate z inside .r   )
r   r   rK   rJ   r   r   r   r   r   r   z`You are trying to access a gated repo.
Make sure to have access to it at https://huggingface.co/z.
a   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 either by logging in with `huggingface-cli login` or by passing `token=<your_token>` 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/' for available revisions.We couldn't connect to 'zL' to load this file, 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.
Checkout your internet connection or see how to run the library in offline mode at 'https://huggingface.co/docs/transformers/installation#offline-mode'.mainz:There was a specific connection error when trying to load z:
zIncorrect path_or_model_id: 'zY'. Please provide either the path to a local folder or the repo_id of a model on the Hub.) popwarningswarnFutureWarning
ValueErrorr9   loggerinforb   rc   rd   rh   re   isfileEnvironmentErrorr@   ra   r   r   r   r   r   lenr   rO   r    r!   r   rF   r   r'   r   )rH   r   rJ   r   r   r   r   rK   r   r   r   r   r   r   r   r   deprecated_kwargsr   rI   rN   eerrs                         r8   cached_filer     s   R '**+;TBBN! A	
 	
 	
 uvvv   !1  ABBB	/**OGLLH55M	w}}_%% 
RW\\/9%M%MxXXw~~m,, 	4 -\eYsYsYsIt9t9t&& g gm g g/>g gFNg g g  
 t&	)T"" #	NN	.]i,bk
 
 
 $$444$$: ft&'d='d'dRa'd'd'deee ,,JF'!)nn11ddy!)+-
 
 
    1/=R[]eff$,L$       C&5C C:=a&&C C
 
 	 #    # # #
 

 	 !    S S'6S S S
 
 		
 #   1/=R[]eff%8 &: & !      U'F U U/>U UU U U
 

 	  
 
 
4 	44444H)'A'A'ABBB44444 _ _m _ _'6_ _>F_ _ _
 
 	  w w w1/=R[]eff$,S$       u\kuupsuuvvv    WO  W  W  W
 
	 s   0G9 9
M:IM: #IM:I##M:0JM:K,M:2KM:L&L9LM:"M9M:?MM:!M55M:path_or_repoc
                     |
                     dd          }|-t          j        dt                     |t	          d          |}t          | |||||||||	ddd          S )a  
    Tries to locate a file in a local folder and repo, downloads and cache it if necessary.

    Args:
        path_or_repo (`str` or `os.PathLike`):
            This can be either:

            - a string, the *model id* of a model repo on huggingface.co.
            - a path to a *directory* potentially containing the file.
        filename (`str`):
            The name of the file to locate in `path_or_repo`.
        cache_dir (`str` or `os.PathLike`, *optional*):
            Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
            cache should not be used.
        force_download (`bool`, *optional*, defaults to `False`):
            Whether or not to force to (re-)download the configuration files and override the cached versions if they
            exist.
        resume_download:
            Deprecated and ignored. All downloads are now resumed by default when possible.
            Will be removed in v5 of Transformers.
        proxies (`Dict[str, str]`, *optional*):
            A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
            'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
        token (`str` or *bool*, *optional*):
            The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
            when running `huggingface-cli login` (stored in `~/.huggingface`).
        revision (`str`, *optional*, defaults to `"main"`):
            The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
            git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
            identifier allowed by git.
        local_files_only (`bool`, *optional*, defaults to `False`):
            If `True`, will only try to load the tokenizer configuration from local files.
        subfolder (`str`, *optional*, defaults to `""`):
            In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
            specify the folder name here.

    <Tip>

    Passing `token=True` is required when you want to use a private model.

    </Tip>

    Returns:
        `Optional[str]`: Returns the resolved file (to the cache folder if downloaded from a repo) or `None` if the
        file does not exist.

    Examples:

    ```python
    # Download a tokenizer configuration from huggingface.co and cache.
    tokenizer_config = get_file_from_repo("google-bert/bert-base-uncased", "tokenizer_config.json")
    # This model does not have a tokenizer config so the result will be None.
    tokenizer_config = get_file_from_repo("FacebookAI/xlm-roberta-base", "tokenizer_config.json")
    ```
    r   Nr   r   F)rH   r   rJ   r   r   r   r   rK   r   r   r   r   r   )r   r   r   r   r   r   )r   r   rJ   r   r   r   r   rK   r   r   r   r   s               r8   get_file_from_repor     s    H '**+;TBBN! A	
 	
 	
 uvvv$%'))..305   r7   c                     t          j        d|  dt                     t          j                    \  }}t          j        |d          5 }t          | ||           ddd           n# 1 swxY w Y   |S )aw  
    Downloads a given url in a temporary file. This function is not safe to use in multiple processes. Its only use is
    for deprecated behavior allowing to download config/models with a single url instead of using the Hub.

    Args:
        url (`str`): The url of the file to download.
        proxies (`Dict[str, str]`, *optional*):
            A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
            'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.

    Returns:
        `str`: The location of the temporary file where the url was downloaded.
    z5Using `from_pretrained` with the url of a file (here aY  ) is deprecated and won't be possible anymore in v5 of Transformers. You should host your file on the Hub (hf.co) instead and use the repository ID. Note that this is not compatible with the caching system (your file will be downloaded at each execution) or multiple processes (each process will download the file in a different temporary file).wb)r   N)r   r   r   tempfilemkstemprc   fdopenr   )r_   r   tmp_fdtmp_filefs        r8   download_urlr   >  s     M	c 	c 	c 	c 	    '))FH	64	 	  *Aa))))* * * * * * * * * * * * * * *Os   
A))A-0A-)r   rJ   r   c                   |                     dd          }	|	-t          j        dt                     |t	          d          |	}t
          j                            |           r=t
          j                            t
          j        	                    | |                    S t          | ||||          }
t          |
t                    }|r|S 	 t                                          t          | |||          t!          |t#                                d|d	
          }nX# t$          j        j        t$          j        j        f$ r  t$          j        j        t$          j        j        t0          f$ r |cY S w xY w	 t3          |           dS # t4          $ r5}t6                              |           t;          |  d|  d          |d}~wt<          $ r2}t6                              |           t;          |  d          |d}~wt>          $ r5}t6                              |           t;          | d|  d          |d}~wt@          $ r Y dS t$          j!        $ r |cY S w xY w)a  
    Checks if a repo contains a given file without downloading it. Works for remote repos and local folders.

    If offline mode is enabled, checks if the file exists in the cache.

    <Tip warning={false}>

    This function will raise an error if the repository `path_or_repo` is not valid or if `revision` does not exist for
    this repo, but will return False for regular connection errors.

    </Tip>
    r   Nr   r   )repo_idr   rK   r   rJ   )r   rK   r   )r   r   F
   )headersallow_redirectsr   timeoutTzN is a gated repository. Make sure to request access at https://huggingface.co/z and pass a token having permission to this repo either by logging in with `huggingface-cli login` or by passing `token=<your_token>`.zE is not a local folder or a valid repository name on 'https://hf.co'.r   r   )"r   r   r   r   r   rc   rd   re   r   rh   r   ra   rb   r#   headr   r"   r   r   
exceptionsSSLError
ProxyErrorConnectionErrorTimeoutr   r$   r   r   errorr   r    r!   r   r'   )r   r   rK   r   r   r   rJ   r   r   r   cached_pathhas_file_in_cacheresponser   s                 r8   has_filer   Y  s   0 '**+;TBBN! A	
 	
 	
 uvvv 
w}}\"" Dw~~bgll<BBCCC )  K #;44  !  !==%%|hU^___$5_=N=NOOO! & 
 
 ((*=*HI   +# ! ! !
 !   !!H%%%t   Q Z Z&2Z Z Z
 
 		
 #   Qbbb
 
	 !   Q t tKWt t t
 
 	    uu ! ! !    !sP   AD# #AE87E8<F 
I!0GI!-HI!0H>>I!I! I!c                      e Zd ZdZ	 	 	 	 ddedee         deeeef                  dee         dee         defd	Zd
eee	j
        f         fdZ	 	 	 	 	 dd
eee	j
        f         dedeeef         dee         deeeef                  dededefdZ	 	 	 	 	 	 	 	 	 	 ddedee         dee         dee         deeeef                  deeeef                  dededededeee                  defdZdS )PushToHubMixinzW
    A Mixin containing the functionality to push a model or tokenizer to the hub.
    Nr   privater   repo_urlorganizationrY   c                 b   |Ct          j        d           |t          d          |                    t           dd          }|Ot          j        d           |                    |          s&d|v r|                    d          d         }| d| }t          |||d	          }|j        S )
z
        Create the repo if needed, cleans up repo_id with deprecated kwargs `repo_url` and `organization`, retrieves
        the token.
        NzgThe `repo_url` argument is deprecated and will be removed in v5 of Transformers. Use `repo_id` instead.zT`repo_id` and `repo_url` are both specified. Please set only the argument `repo_id`.r   r   zThe `organization` argument is deprecated and will be removed in v5 of Transformers. Set your organization directly in the `repo_id` passed instead (`repo_id={organization}/{model_id}`).T)r   r   r   exist_ok)	r   r   r   replacerF   
startswithr   r   r   )selfr   r   r   r   r   r_   s          r8   _create_repozPushToHubMixin._create_repo  s     M   " j   &&*I'L'L'LbQQG#Mo   %%l33 6'>>%mmC004G)55G55'RVWWW{r7   working_dirc                 D    fdt          j                  D             S )zS
        Returns the list of files with their last modification timestamp.
        c           	          i | ]@}|t           j                            t           j                            |                    AS r6   rc   rd   getmtimerh   r   r   r  s     r8   
<dictcomp>z8PushToHubMixin._get_files_timestamps.<locals>.<dictcomp>  s;    ccca27##BGLLa$@$@AAcccr7   )rc   rf   )r  r  s    `r8   _get_files_timestampsz$PushToHubMixin._get_files_timestamps  s+     dccc2:VaKbKbccccr7   Ffiles_timestampscommit_message	create_prrK   commit_descriptionc	                    |dd| j         j        v rd}nSd| j         j        v rd}nBd| j         j        v rd}n1d| j         j        v rd	}n d
| j         j        v rd}nd| j         j         }fdt          j                  D             }	fd|	D             }	g }
|	D ]}t          j                            t          j                            |                    rt          j        t          j                            |                    D ]c}|
                    t          t          j                            ||          t          j                            ||                               d|
                    t          t          j                            |          |                     |U|	                    d          s@	 t          |||d           n+# t          $ r}|j        j        dk    r|rn Y d}~nd}~ww xY wt                              d| dd                    |	                      t!          ||
|||||          S )zh
        Uploads all modified files in `working_dir` to `repo_id`, based on `files_timestamps`.
        NModelzUpload modelConfigzUpload config	TokenizerzUpload tokenizerFeatureExtractorzUpload feature extractor	ProcessorzUpload processorzUpload c                     g | ]O}|vsGt           j                            t           j                            |                    |         k    M|PS r6   r  )r   r   r  r  s     r8   
<listcomp>z9PushToHubMixin._upload_modified_files.<locals>.<listcomp>  sa     
 
 
(((BG,<,<RW\\+WX=Y=Y,Z,Z]mno]p,p,p ,p,p,pr7   c                    g | ]~}t           j                            t           j                            |                    s=t           j                            t           j                            |                    ||S r6   )rc   rd   r   rh   re   r  s     r8   r  z9PushToHubMixin._upload_modified_files.<locals>.<listcomp>  sy     
 
 
w~~bgll;::;;
 @Bw}}RW\\ZeghMiMi?j?j

 
 
r7   )path_or_fileobjpath_in_repozrefs/prT)r   branchr   r   i  z!Uploading the following files to : ,)r   
operationsr  r  r   r  rK   )	__class____name__rc   rf   rd   re   rh   rn   r   r   r   r   r   status_coder   r   r   )r  r  r   r  r  r   r  rK   r  modified_filesr  rp   r   r   s    ` `          r8   _upload_modified_filesz%PushToHubMixin._upload_modified_files  s    !$.111!/T^444!0 777!3#t~'>>>!; 777!3!D4>+B!D!D
 
 
 
 
Z,,
 
 

 
 
 
#
 
 
 
" 	 	Dw}}RW\\+t<<== BGLLd$C$CDD  A%%*,.GLLdA,N,N]_]d]i]ijnpq]r]r      !!&rw||KQU7V7Veijjj    (;(;I(F(F	gheVZ[[[[[!   :)S00Y0  DDDD 	]]]388NC[C[]]^^^!)1
 
 
 	
s   G# #
H-HH5GBTuse_temp_dirmax_shard_sizesafe_serializationtagsc                    |                     dd          }|                     dd          }|-t          j        dt                     |t	          d          |}|                     dd          }|t          j        dt                     |t	          d	          t
          j                            |          r-|                    t
          j        j	                  d
         }|}n9|}|                    d          d
         }n|                    d          d
         }|                     dd          }|                     dd          }| 
                    |||||          }t          ||||          }| t
          j                            |           }t          ||          5 }|                     |          }|                     |||           |                    t
          j                            |d                     |                     |||||||	|
          cddd           S # 1 swxY w Y   dS )u
  
        Upload the {object_files} to the 🤗 Model Hub.

        Parameters:
            repo_id (`str`):
                The name of the repository you want to push your {object} to. It should contain your organization name
                when pushing to a given organization.
            use_temp_dir (`bool`, *optional*):
                Whether or not to use a temporary directory to store the files saved before they are pushed to the Hub.
                Will default to `True` if there is no directory named like `repo_id`, `False` otherwise.
            commit_message (`str`, *optional*):
                Message to commit while pushing. Will default to `"Upload {object}"`.
            private (`bool`, *optional*):
                Whether or not the repository created should be private.
            token (`bool` or `str`, *optional*):
                The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
                when running `huggingface-cli login` (stored in `~/.huggingface`). Will default to `True` if `repo_url`
                is not specified.
            max_shard_size (`int` or `str`, *optional*, defaults to `"5GB"`):
                Only applicable for models. The maximum size for a checkpoint before being sharded. Checkpoints shard
                will then be each of size lower than this size. If expressed as a string, needs to be digits followed
                by a unit (like `"5MB"`). We default it to `"5GB"` so that users can easily load models on free-tier
                Google Colab instances without any CPU OOM issues.
            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 in safetensors format for safer serialization.
            revision (`str`, *optional*):
                Branch to push the uploaded files to.
            commit_description (`str`, *optional*):
                The description of the commit that will be created
            tags (`List[str]`, *optional*):
                List of tags to push on the Hub.

        Examples:

        ```python
        from transformers import {object_class}

        {object} = {object_class}.from_pretrained("google-bert/bert-base-cased")

        # Push the {object} to your namespace with the name "my-finetuned-bert".
        {object}.push_to_hub("my-finetuned-bert")

        # Push the {object} to an organization with the name "my-finetuned-bert".
        {object}.push_to_hub("huggingface/my-finetuned-bert")
        ```
        r   Nignore_metadata_errorsFr   r   repo_path_or_namezpThe `repo_path_or_name` argument is deprecated and will be removed in v5 of Transformers. Use `repo_id` instead.z]`repo_id` and `repo_path_or_name` are both specified. Please set only the argument `repo_id`.r   r   r   r   )r   r   r   r   r   r)  )r  r$  )r%  r&  z	README.md)r  r   r  rK   r  )r   r   r   r   r   rc   rd   re   r   sepr  create_and_tag_model_cardr+   r
  save_pretrainedsaverh   r"  )r  r   r$  r  r   r   r%  r  r&  rK   r  r'  r   r   r)  r*  r  r   r   
model_cardwork_dirr  s                         r8   push_to_hubzPushToHubMixin.push_to_hub<  s   ~ +../?FF!2!6!67OQV!W!W%M E     l   #E-112EtLL( M%  
 " s   w}}.// 5!--44R8% ,%mmC004 "--,,R0K %((T::(,,^TBB##WEHS_ $ 
 

 /T?U
 
 

 !w}}[999L [|TTT 	X`#99(CC   .]o ppp OOBGLL;??@@@.. -#!#5 / 	 		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   0A=H::H>H>)NNNN)NNFNN)
NNNNr#  FTNNN)r  
__module____qualname____doc__rb   r   boolr	   r  rc   PathLiker
  r   floatr"  intr   r2  r6   r7   r8   r   r     se         #',0"&&*! !! $! dCi()	!
 3-! sm! 
! ! ! !FdsBK7G1H d d d d )-,0"&M
 M
3+,M
 M
 sEz*	M

 !M
 dCi()M
 M
 M
  M
 M
 M
 M
d (,(,"&,049#'"&$(G GG tnG !	G
 $G dCi()G !sCx1G G !G G  G tCy!G 
G G G G G Gr7   r   pytorch)	frameworkc                &   t                      rdS | |d}|D ]}d |j                                        D             }d|v r2|d         }t          j                            |          s|d         |d<   d|v r|d         |d<   kd|v rd|                     dd	                              d
d	                              dd	          }|                    dd	          }| d|d          |d<   t          ddt          t          |                     dS )a  
    Sends telemetry that helps tracking the examples use.

    Args:
        example_name (`str`): The name of the example.
        *example_args (dataclasses or `argparse.ArgumentParser`): The arguments to the script. This function will only
            try to extract the model and dataset name from those. Nothing else is tracked.
        framework (`str`, *optional*, defaults to `"pytorch"`): The framework for the example.
    N)exampler;  c                 H    i | ]\  }}|                     d           ||| S )_)r   r   s      r8   r	  z*send_example_telemetry.<locals>.<dictcomp>  s6    jjjAallSVFWFWj\]\i1\i\i\ir7   model_name_or_path
model_namedataset_name	task_nametf_r   flax_run__no_trainer-examplesr=   )topiclibrary_namelibrary_versionr   )
r9   __dict__r   rc   rd   re   r   r%   r)   r   )example_namer;  example_argsdataargsargs_as_dictrA  script_names           r8   send_example_telemetryrT    s[     #)<<D P Pjj)<)<)>)>jjj<//%&:;J7==,, H%12F%G\"\))#/#?D  L((&..ub99AA'2NNVVW]_abbK%--mR@@K&1#O#OL4M#O#OD  ~{_nos_t_t     r7   sizec                    t          | t                    r| S |                                                     d          rt          | dd                   dz  S |                                                     d          rt          | dd                   dz  S |                                                     d          rt          | dd                   dz  S |                                                     d	          r6t          | dd
                   dz  }|                     d          r|dz  n|S |                                                     d          r6t          | dd
                   dz  }|                     d          r|dz  n|S |                                                     d          r6t          | dd
                   dz  }|                     d          r|dz  n|S t	          d          )a'  
    Converts a size expressed as a string with digits an unit (like `"5MB"`) to an integer (in bytes).

    Args:
        size (`int` or `str`): The size to convert. Will be directly returned if an `int`.

    Example:
    ```py
    >>> convert_file_size_to_int("1MiB")
    1048576
    ```
    GIBNi   @MIBi   KIBi   GBi ʚ;b   MBi@B KBi  zR`size` is not in a valid format. Use an integer followed by the unit, e.g., '5GB'.)ra   r9  r   rg   r   )rU  int_sizes     r8   convert_file_size_to_intrb    s    $ zz||U## (49~~''zz||U## (49~~''zz||U## (49~~''zz||T"" AtCRCy>>U+ $c 2 2@x1}}@zz||T"" AtCRCy>>U+ $c 2 2@x1}}@zz||T"" AtCRCy>>U+ $c 2 2@x1}}@
i
j
jjr7   c                 h   
 ddl }|                    dd          }|-t          j        dt                     |t          d          |}t          j                            |          st          d| d  d          t          |d	          5 } |j
        |                                          }ddd           n# 1 swxY w Y   t          t          |d
                                                             }|d         }t          |d
                                                   |d<   |d
                                         |d
<   t          j                                       r 
fd|D             }||fS g }t'           |d         ||          }|du p|}t)          |d|           D ]{}	 t+           |||||||||	
|          }nG# t,          $ r t/            d| d          t0          $ r t/          dt2           d| d          w xY w|                    |           |||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).
    r   Nr   r   r   zCan't find a checkpoint index (z) in r   r
weight_maprs   all_checkpoint_keysc                 R    g | ]#}t           j                            |          $S r6   )rc   rd   rh   )r   r   pretrained_model_name_or_pathr   s     r8   r  z.get_checkpoint_shard_files.<locals>.<listcomp><  s.    nnnYZ27<<(EyRSTTnnnr7   r   rM   zDownloading shards)descdisable)
rJ   r   r   r   r   r   r   rK   r   r   r   z5 which is required according to the checkpoint index.r   z
' to load z?. You should try again after checking your internet connection.)rj   r   r   r   r   r   rc   rd   r   ri   r   readsortedsetvalueslistkeyscopyre   r   r2   r   r   r   r'   rF   rn   )rh  index_filenamerJ   r   r   r   r   r   r   rK   r   r   r   rj   r   r   indexshard_filenamessharded_metadatacached_filenames
last_shardshow_progress_barshard_filenamecached_filenames   `         `             r8   get_checkpoint_shard_filesr{  
  s3   2 KKK&**+;TBBN! A	
 	
 	
 uvvv7>>.)) rp>ppPmpppqqq	nc	"	" %a
16688$$% % % % % % % % % % % % % % % S|!4!;!;!=!=>>??OZ(.253F3K3K3M3M.N.N*+%*<%8%=%=%?%?\" 
w}}233 1nnnnn^mnnn 000  (%r':iZf  J #d*<n5IWhShiii 1 1	)-#- /!1%!#)  OO  " 	 	 	"0 > >Xf > > >    	 	 	"B+J B BVd B B B  	 	0000---s   #C  CC7GAHc                 &   | t           } nt          |           } t          j                            |           sg S g }t          j        |           D ]}t          j                            | | d          }t          j                            |          sEt          |d          5 }t          j
        |          }|d         }|d                             dd          }|                    |||d	           ddd           n# 1 swxY w Y   |S )
zH
    Returns a list for all files cached with appropriate metadata.
    Nr[   r\   r]   r_   r`   "r   )rp   r_   r`   )r@   rb   rc   rd   re   rf   rh   r   ri   rj   rk   r   rn   )rJ   cached_filesrp   rq   rr   rs   r_   r`   s           r8   get_all_cached_filesr  m  sY    &			NN	7==## 	L
9%% 	J 	JGLLtNNN;;	w~~i(( 	)g... 	J)y++H5/CF#++C44Dc4 H HIII		J 	J 	J 	J 	J 	J 	J 	J 	J 	J 	J 	J 	J 	J 	J s   'ADD		D		c                     t          j        d|           }|dS |                                \  }}}d                    dg|                    d          z             }|||dS )z?
    Extract repo_name, revision and filename from an url.
    z3^https://huggingface\.co/(.*)/resolve/([^/]*)/(.*)$Nz--modelsr   )reporK   r   )r   r   r   rh   r   )r_   r   r  rK   r   
cache_repos         r8   extract_info_from_urlr    sf     YMsSSF~t%}}D(HH:

3788JH(KKKr7   r   r'  r)  c                 J   	 t          j        | ||          }n=# t          $ r0 d}t          |g n|d          }t          j        ||          }Y nw xY w|J|j        j        g |j        _        |D ]/}||j        j        vr|j        j                            |           0|S )ae  
    Creates or loads an existing model card and tags it.

    Args:
        repo_id (`str`):
            The repo_id where to look for the model card.
        tags (`List[str]`, *optional*):
            The list of tags to add in the model card
        token (`str`, *optional*):
            Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to the stored token.
        ignore_metadata_errors (`str`):
            If True, errors while parsing the metadata section will be ignored. Some information might be lost during
            the process. Use it at your own risk.
    r+  u   This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.Nr=   )r'  rK  )model_description)r   rk   r   r   from_templaterP  r'  rn   )r   r'  r   r)  r0  r  	card_data	model_tags           r8   r-  r-    s    (]^G5Qghhh

 ] ] ] e!T\rrtR`aaa	,YJ[\\\


	] ?'#%JO  	7 	7I
 444$++I666s    7AAc                     | |  d|  dfD ]5}t           j                            |          rt          j        |           6dS )z>
    Remove, if they exist, file, file.json and file.lock
    r[   z.lockN)rc   rd   r   remove)rp   r   s     r8   clean_files_forr    sT     tNNNtNNN3  7>>! 	IaLLL r7   c                    t          j        |d           t          j        t           j                            |d          d           ||k    r^t           j                            |d|          }t	          |d          5 }|                    |           ddd           n# 1 swxY w Y   t          j        t           j                            |d          d           t           j                            |d|          }t          j        | |           t          j        t           j                            |d          d           t          j        t           j                            |d|          d           t           j                            |d||          }	t          j	        
                    ||	           t          |            dS )zQ
    Move file to repo following the new huggingface hub cache organization.
    Tr   refswNblobs	snapshots)rc   makedirsrd   rh   ri   writeshutilmovehuggingface_hubfile_download_create_relative_symlinkr  )
rp   r  r   rK   r`   r   ref_pathr   	blob_pathpointer_paths
             r8   move_to_new_cacher    s    Kt$$$$ KT6**T::::;7<<fh77(C   	!AGGK   	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! KT7++d;;;;T7D11I
Ki    KT;//$????KT;<<tLLLL7<<k;IIL!::9lSSSDs   B$$B(+B(c           	         |t           }| Zt          t                     j        dz  }t          j                            t          |                    rt          |          } n|} t          |           }t          	                    dt          |           d           i }t          |          D ]#}|                    d          }||vr+	 t          ||          ||<   n# t          j        $ r Y Cw xY w||         j        ||         j        }	}||	f|d         |k    r4t%          t          j                            | |d                              t)          |          }
|
t          j                            ||
d	                   }t+          t          j                            | |d                   ||
d
         |
d         ||	           %d S )Nr=   )rJ   zMoving z files to the new cache systemr_   )r   r`   rp   r  r   rK   )rp   r  r   rK   r`   r   )r@   r   parentrc   rd   re   rb   r  r   r   r   r2   r   r   r   r'   r`   r   r  rh   r  r  )rJ   new_cache_dirr   	old_cacher~  hub_metadata	file_infor_   r`   r   url_infor  s               r8   
move_cacher    s   *+,,3nD	7==Y(( 	&III%I')<<<L
KKK#l++KKKLLLL,'' 
 
	mmE""l""$8E$J$J$JS!!%    )-2L4E4Qk<;.V$$BGLLIf4EFFGGG(--w||M8F+;<<i6):;;j)j)#	
 	
 	
 	
 	
/
 
s   C$$C65C6c                   N    e Zd ZdZd	deej                 ddfdZd Zd Z	d
dZ
dS )PushInProgresszj
    Internal class to keep track of a push in progress (which might contain multiple `Future` jobs).
    NjobsrY   c                     |g n|| _         d S r4   r  )r  r  s     r8   __init__zPushInProgress.__init__  s    ,BBD			r7   c                 >    t          d | j        D                       S )Nc              3   >   K   | ]}|                                 V  d S r4   )doner   jobs     r8   r   z)PushInProgress.is_done.<locals>.<genexpr>  s*      33#388::333333r7   )allr  r  s    r8   is_donezPushInProgress.is_done  s!    33333333r7   c                 8    t          j        | j                   d S r4   )r   waitr  r  s    r8   wait_until_donezPushInProgress.wait_until_done  s    TYr7   c                 2    d | j         D             | _         d S )Nc                 b    g | ],}|                                 |                                *|-S r6   )cancelr  r  s     r8   r  z)PushInProgress.cancel.<locals>.<listcomp>  sH     
 
 
JJLL	
 %(HHJJ	

 
 
r7   r  r  s    r8   r  zPushInProgress.cancel  s(    
 
y
 
 
			r7   r4   )rY   N)r  r3  r4  r5  r   r   Futurer  r  r  r  r6   r7   r8   r  r    s~         1 1Xgn5 1 1 1 1 14 4 4     
 
 
 
 
 
r7   r  zversion.txtau  You are offline and the cache for model files in Transformers v4.22.0 has been updated while your local cache seems to be the one of a previous version. It is very likely that all your calls to any `from_pretrained()` method will fail. Remove the offline mode and enable internet connection to have your cache be updated automatically, then you can go back to offline mode.zThe cache for model files in Transformers v4.22.0 has been updated. Migrating your old cache. This is a one-time only operation. You can interrupt this and resume the migration later on by calling `transformers.utils.move_cache()`.
z5There was a problem when trying to move your cache:

r  z

Please file an issue at https://github.com/huggingface/transformers/issues/new/choose and copy paste this whole message and we will do our best to help.r  r  1z?There was a problem when trying to write in your cache folder (zV). You should set the environment variable TRANSFORMERS_CACHE to a writable directory.)NNr4   )NFNNNNFr   NNTTTN)NFNNNNFr   )NNN)
NFNNFNNNr   N)NNF)r5  rj   rc   r   r  r   r   	tracebackr   
concurrentr   pathlibr   typingr   r   r   r   r	   urllib.parser
   uuidr   r  r   r   r   r   r   r   r   r   r   r   r   r   r   huggingface_hub.file_downloadr   r   huggingface_hub.utilsr   r   r   r   r   r   r    r!   r"   r#   r$   r%   "huggingface_hub.utils._deprecationr&   requests.exceptionsr'   r   r)   r*   genericr+   import_utilsr,   r-   r.   r/   r0   r1   r2   
get_loggerr  r   HF_HUB_OFFLINEr5   r9   r   rd   rh   torch_cache_homedefault_cache_pathold_default_cache_pathHF_HUB_CACHEr>   r?   r@   re   r   warningr  HF_HOMErA    TRANSFORMERS_DYNAMIC_MODULE_NAMEhexr   keyr   r   S3_BUCKET_PREFIXCLOUDFRONT_DISTRIB_PREFIXr   r   _staging_mode_default_endpointrF   HUGGINGFACE_CO_PREFIX!HUGGINGFACE_CO_EXAMPLES_TELEMETRYrb   rO   rV   ru   r   r   r   r7  r6  r   r   r   r   r   rT  r9  rb  r{  r  r  r-  r  r  r  r  cache_version_filer   cache_versionri   r   rk  r   r   rf   cache_is_not_emptyr   r   	format_tb__traceback__tracer   r  r  r  r6   r7   r8   <module>r     s     				 				  



                   5 5 5 5 5 5 5 5 5 5 5 5 5 5 ! ! ! ! ! !                                       F E E E E E E E                            A @ @ @ @ @ ) ) ) ) ) ) " " " " " " " " ( ( ( ( ( (                      
	H	%	%",;    29\27<<		BRT^8_8_ah+i+ijj 1 &6GG  !*	*I9Ka b b &RY'CEbcc RY35OPP  GMM())@GMM)011@ 	(rz99$BJ66BJ..
NN	'   FK&	(>???29/i>OQZ1[1[\\ #9  UWW[
 a 
 
Cry~~!lclll	
 	
 	
 I 8 
7>>DDFFJ^^7Db33Jb "3 :>>3T::FHM	6  
 ')jnn5VX\&]&]#"$*..@_"`"` 7:ee $CF_$_ ! sw ),9>sD$9Objknbo   . . . 8-qrrr   sDy!1  T%[       sr F  4 dCo 6 #    .Ix} I8C= IU]^aUb I I I I" 48 &*(,(,""#7;-12648"&!J J3+,JJ c2;./0J 	J
 d^J d38n%J E$)$%J smJ J J }J sDcN234J '+J ,0J .2J  3-!J$ c]%J J J Jh 48 &*(,(,""\ \R[()\\ c2;./0\ 	\
 d^\ d38n%\ E$)$%\ sm\ \ \ \ \ \~   < #(,(,c! #(,#c! c! c!R[()c!c! smc! d38n%	c!
 E$)$%c! c! S$_%c! }c! c! c! c!LD D D D D D D DN CL          Fk5c? k k k kH 
]. ]. ]. ].F   4	L 	L 	L !%#(	% %%
49
% C=% !	% % % %P    4,
 ,
 ,
 ,
^
 
 
 
 
 
 
 
. W\\"4mDD 	w~~()) MM	 	!	! Q	CMMMM 	 	 	MMM	               W]]#566b33zrzJ\?]?];^;^ab;b 1+ 
Y	
 	
 	
 	
 	1	
 	
 	


!777J)+=>>>>JLLL 
 
 
		-)-ao>>??7e 7 7q{Oc 7 7gh 7 7 7	
 	
 	
 	
 	
 	
 	
 	

 1
&6666T$c** 	aGGCLLL	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 
 
 
SN` S S S	
 	
 	
 	
 	
 	

 s   WV=<W=WWWWWW"Y9 9[>A[[#\1 \$\1 $\((\1 +\(,\1 1]]