U
    ”Ê¹jsA  ã                   @   sÜ  d dl Z d dlZd dlmZ d dlmZ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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 d	dlmZ e e¡Z d)e!e!dœdd„Z"d*e!e!e!dœdd„Z#dZ$deƒ › deƒ › deƒ › d�Z%edœdd„Z&edœdd„Z'd+ee!ef ee	e!ef  dœdd „Z(ed,e!ee! d!œd"d#„ƒZ)ed$dddddddddd%œ
e!e!ee* ee! ee+ ee! ee* eee
e! e!f  eee
e! e!f  eee
e! e!f  ee! d&œd'd(„ƒZ,dS )-é    N)ÚPath)ÚDEFAULT_PROTOCOLÚPicklingError)ÚAnyÚDictÚListÚOptionalÚUnion)Úversion)Ú	constantsÚsnapshot_download)ÚHfApi)ÚSoftTemporaryDirectoryÚget_fastai_versionÚget_fastcore_versionÚget_python_versioné   )ÚloggingÚvalidate_hf_hub_args)Ú_PY_VERSIONú2.4ú1.3.27)Úfastai_min_versionÚfastcore_min_versionc              
   C   sž   t ƒ p
tƒ dkr6td| › d|› dtƒ › dt ƒ › d�	ƒ‚t tƒ ¡}t t ƒ ¡}|t | ¡k rttd| › dtƒ › d	�ƒ‚|t |¡k rštd
|› dt ƒ › d�ƒ‚dS )a-  
    Checks that the installed fastai and fastcore versions are compatible for pickle serialization.

    Args:
        fastai_min_version (`str`, *optional*):
            The minimum fastai version supported.
        fastcore_min_version (`str`, *optional*):
            The minimum fastcore version supported.

    > [!TIP]
    > Raises the following error:
    >
    >     - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
    >       if the fastai or fastcore libraries are not available or are of an invalid version.
    zN/Azfastai>=z and fastcore>=z' are required. Currently using fastai==z and fastcore==Ú.zD`push_to_hub_fastai` and `from_pretrained_fastai` require a fastai>=z+ version, but you are using fastai version zA which is incompatible. Upgrade with `pip install fastai==2.5.6`.zF`push_to_hub_fastai` and `from_pretrained_fastai` require a fastcore>=ú- version, but you are using fastcore version zD which is incompatible. Upgrade with `pip install fastcore==1.3.27`.N)r   r   ÚImportErrorr
   ÚVersion)r   r   Zcurrent_fastai_versionZcurrent_fastcore_version© r   ú[/var/www/html/bwave/python/venv/lib/python3.8/site-packages/huggingface_hub/fastai_utils.pyÚ_check_fastai_fastcore_versions   s     ÿÿÿr    )Ústorage_folderr   r   c                 C   sˆ  zddl }W n tk
r(   tdƒ‚Y nX tj | › d�¡sJt d¡ dS | | › d�¡}d| 	¡ krtt d¡ dS |d }d| 	¡ kr–t d	¡ dS |d }d
d„ |D ƒ}t
|ƒdkrÄt d¡ nLt|d ƒ d¡d }|dk�rt |¡t |¡k �rtd|› d|› d�ƒ‚dd„ |D ƒ}	t
|	ƒdk�r8t d¡ nLt|	d ƒ d¡d }
|
dk�r„t |
¡t |¡k �r„td|› d|
› d�ƒ‚dS )að  
    Checks that the `pyproject.toml` file in the directory `storage_folder` has fastai and fastcore versions
    that are compatible with `from_pretrained_fastai` and `push_to_hub_fastai`. If `pyproject.toml` does not exist
    or does not contain versions for fastai and fastcore, then it logs a warning.

    Args:
        storage_folder (`str`):
            Folder to look for the `pyproject.toml` file.
        fastai_min_version (`str`, *optional*):
            The minimum fastai version supported.
        fastcore_min_version (`str`, *optional*):
            The minimum fastcore version supported.

    > [!TIP]
    > Raises the following errors:
    >
    >     - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
    >       if the `toml` module is not installed.
    >     - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
    >       if the `pyproject.toml` indicates a lower than minimum supported version of fastai or fastcore.
    r   Nzn`push_to_hub_fastai` and `from_pretrained_fastai` require the toml module. Install it with `pip install toml`.z/pyproject.tomlzàThere is no `pyproject.toml` in the repository that contains the fastai `Learner`. The `pyproject.toml` would allow us to verify that your fastai and fastcore versions are compatible with those of the model you want to load.zbuild-systemzúThere is no `build-system` section in the pyproject.toml of the repository that contains the fastai `Learner`. The `build-system` would allow us to verify that your fastai and fastcore versions are compatible with those of the model you want to load.ÚrequireszòThere is no `requires` section in the pyproject.toml of the repository that contains the fastai `Learner`. The `requires` would allow us to verify that your fastai and fastcore versions are compatible with those of the model you want to load.c                 S   s   g | ]}|  d ¡r|‘qS )Úfastai©Ú
startswith©Ú.0Zpckr   r   r   Ú
<listcomp>Œ   s     
 z=_check_fastai_fastcore_pyproject_versions.<locals>.<listcomp>zPThe repository does not have a fastai version specified in the `pyproject.toml`.ú=é   Ú z*`from_pretrained_fastai` requires fastai>=z$ version but the model to load uses z which is incompatible.c                 S   s   g | ]}|  d ¡r|‘qS )Zfastcorer$   r&   r   r   r   r(   ™   s     
 zRThe repository does not have a fastcore version specified in the `pyproject.toml`.z,`from_pretrained_fastai` requires fastcore>=r   )ÚtomlÚModuleNotFoundErrorr   ÚosÚpathÚisfileÚloggerÚwarningÚloadÚkeysÚlenÚstrÚ	partitionr
   r   )r!   r   r   r,   Úpyproject_tomlZbuild_system_tomlZpackage_versionsZfastai_packagesZfastai_versionZfastcore_packagesZfastcore_versionr   r   r   Ú)_check_fastai_fastcore_pyproject_versionsH   sP    ÿ
ÿÿÿ ÿ ÿr9   u   ---
tags:
- fastai
---

# Amazing!

ðŸ¥³ Congratulations on hosting your fastai model on the Hugging Face Hub!

# Some next steps
1. Fill out this model card with more information (see the template below and the [documentation here](https://huggingface.co/docs/hub/model-repos))!

2. Create a demo in Gradio or Streamlit using ðŸ¤— Spaces ([documentation here](https://huggingface.co/docs/hub/spaces)).

3. Join the fastai community on the [Fastai Discord](https://discord.com/invite/YKrxeNn)!

Greetings fellow fastlearner ðŸ¤�! Don't forget to delete this content from your model card.


---


# Model card

## Model description
More information needed

## Intended uses & limitations
More information needed

## Training and evaluation data
More information needed
zB[build-system]
requires = ["setuptools>=40.8.0", "wheel", "python=z", "fastai=z", "fastcore=z6"]
build-backend = "setuptools.build_meta:__legacy__"
)Úrepo_dirc              	   C   s8   | d }|  ¡ s4|jddd��}| t¡ W 5 Q R X dS )z‹
    Creates a model card for the repository.

    Args:
        repo_dir (`Path`):
            Directory where model card is created.
    z	README.mdÚwúutf-8©ÚencodingN)ÚexistsÚopenÚwriteÚREADME_TEMPLATE)r:   Zreadme_pathÚfr   r   r   Ú_create_model_cardÏ   s    rD   c              	   C   s8   | d }|  ¡ s4|jddd��}| t¡ W 5 Q R X dS )z—
    Creates a `pyproject.toml` for the repository.

    Args:
        repo_dir (`Path`):
            Directory where `pyproject.toml` is created.
    zpyproject.tomlr;   r<   r=   N)r?   r@   rA   ÚPYPROJECT_TEMPLATE)r:   Zpyproject_pathrC   r   r   r   Ú_create_model_pyprojectÞ   s    rF   )Úsave_directoryÚconfigc              	   C   sÐ   t ƒ  tj|dd� |dk	rlt|tƒs:tdt|ƒ› d�ƒ‚tj |t	j
¡}t|dƒ�}t ||¡ W 5 Q R X tt|ƒƒ tt|ƒƒ t|ƒ| _tj|dd� z| jdtd� W n tk
rÊ   td	ƒ‚Y nX dS )
aú  
    Saves a fastai learner to `save_directory` in pickle format using the default pickle protocol for the version of python used.

    Args:
        learner (`Learner`):
            The `fastai.Learner` you'd like to save.
        save_directory (`str` or `Path`):
            Specific directory in which you want to save the fastai learner.
        config (`dict`, *optional*):
            Configuration object. Will be uploaded as a .json file. Example: 'https://huggingface.co/espejelomar/fastai-pet-breeds-classification/blob/main/config.json'.

    > [!TIP]
    > Raises the following error:
    >
    >     - [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError)
    >       if the config file provided is not a dictionary.
    T)Úexist_okNz(Provided config should be a dict. Got: 'ú'r;   ú	model.pkl)ÚfnameZpickle_protocolzÀYou are using a lambda function, i.e., an anonymous function. `pickle` cannot pickle function objects and requires that all functions have names. One possible solution is to name the function.)r    r.   ÚmakedirsÚ
isinstanceÚdictÚRuntimeErrorÚtyper/   Újoinr   ZCONFIG_NAMEr@   ÚjsonÚdumprD   r   rF   Zexportr   r   )ÚlearnerrG   rH   r/   rC   r   r   r   Ú_save_pretrained_fastaií   s*    

þ
ÿrV   )Úrepo_idÚrevisionc                 C   sP   t ƒ  tj | ¡s&t| |dtƒ d�}n| }t|ƒ ddlm} |tj 	|d¡ƒS )ap  
    Load pretrained fastai model from the Hub or from a local directory.

    Args:
        repo_id (`str`):
            The location where the pickled fastai.Learner is. It can be either of the two:
                - Hosted on the Hugging Face Hub. E.g.: 'espejelomar/fatai-pet-breeds-classification' or 'distilgpt2'.
                  You can add a `revision` by appending `@` at the end of `repo_id`. E.g.: `dbmdz/bert-base-german-cased@main`.
                  Revision is the specific model version to use. Since we use a git-based system for storing models and other
                  artifacts on the Hugging Face Hub, it can be a branch name, a tag name, or a commit id.
                - Hosted locally. `repo_id` would be a directory containing the pickle and a pyproject.toml
                  indicating the fastai and fastcore versions used to build the `fastai.Learner`. E.g.: `./my_model_directory/`.
        revision (`str`, *optional*):
            Revision at which the repo's files are downloaded. See documentation of `snapshot_download`.

    Returns:
        The `fastai.Learner` model in the `repo_id` repo.
    r#   )rW   rX   Zlibrary_nameZlibrary_versionr   )Úload_learnerrK   )
r    r.   r/   Úisdirr   r   r9   Zfastai.learnerrY   rR   )rW   rX   r!   rY   r   r   r   Úfrom_pretrained_fastai"  s    ür[   z(Push FastAI model using huggingface_hub.)
Úcommit_messageÚprivateÚtokenrH   ÚbranchÚ	create_prÚallow_patternsÚignore_patternsÚdelete_patternsÚapi_endpoint)rW   r\   r]   r^   rH   r_   r`   ra   rb   rc   rd   c                C   sx   t ƒ  t|d�}|j|||dd�j}tƒ �D}t|ƒ| }t| ||d� |j||||||||	|
d�	W  5 Q R £ S Q R X dS )a½	  
    Upload learner checkpoint files to the Hub.

    Use `allow_patterns` and `ignore_patterns` to precisely filter which files should be pushed to the hub. Use
    `delete_patterns` to delete existing remote files in the same commit. See [`upload_folder`] reference for more
    details.

    Args:
        learner (`Learner`):
            The `fastai.Learner' you'd like to push to the Hub.
        repo_id (`str`):
            The repository id for your model in Hub in the format of "namespace/repo_name". The namespace can be your individual account or an organization to which you have write access (for example, 'stanfordnlp/stanza-de').
        commit_message (`str`, *optional*):
            Message to commit while pushing. Will default to :obj:`"add model"`.
        private (`bool`, *optional*):
            Whether or not the repository created should be private.
            If `None` (default), will default to been public except if the organization's default is private.
        token (`str`, *optional*):
            The Hugging Face account token to use as HTTP bearer authorization for remote files. If :obj:`None`, the token will be asked by a prompt.
        config (`dict`, *optional*):
            Configuration object to be saved alongside the model weights.
        branch (`str`, *optional*):
            The git branch on which to push the model. This defaults to
            the default branch as specified in your repository, which
            defaults to `"main"`.
        create_pr (`boolean`, *optional*):
            Whether or not to create a Pull Request from `branch` with that commit.
            Defaults to `False`.
        api_endpoint (`str`, *optional*):
            The API endpoint to use when pushing the model to the hub.
        allow_patterns (`List[str]` or `str`, *optional*):
            If provided, only files matching at least one pattern are pushed.
        ignore_patterns (`List[str]` or `str`, *optional*):
            If provided, files matching any of the patterns are not pushed.
        delete_patterns (`List[str]` or `str`, *optional*):
            If provided, remote files matching any of the patterns will be deleted from the repo.

    Returns:
        The url of the commit of your model in the given repository.

    > [!TIP]
    > Raises the following error:
    >
    >     - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
    >       if the user is not log on to the Hugging Face Hub.
    )ZendpointT)rW   r^   r]   rI   )rH   )	rW   r^   Zfolder_pathr\   rX   r`   ra   rb   rc   N)r    r   Zcreate_reporW   r   r   rV   Zupload_folder)rU   rW   r\   r]   r^   rH   r_   r`   ra   rb   rc   rd   ÚapiÚtmpZ
saved_pathr   r   r   Úpush_to_hub_fastaiO  s"    >
÷rg   )r   r   )r   r   )N)N)-rS   r.   Úpathlibr   Úpickler   r   Útypingr   r   r   r   r	   Ú	packagingr
   Zhuggingface_hubr   r   Zhuggingface_hub.hf_apir   Zhuggingface_hub.utilsr   r   r   r   Úutilsr   r   Zutils._runtimer   Z
get_loggerÚ__name__r1   r6   r    r9   rB   rE   rD   rF   rV   r[   ÚboolrO   rg   r   r   r   r   Ú<module>   sŠ   
  þþ1  ýý_"ÿÿÿ ý
ý5 þþ,óó