text stringlengths 1 1.02k | class_index int64 0 305 | source stringclasses 77
values |
|---|---|---|
class EvalResult:
"""
Flattened representation of individual evaluation results found in model-index of Model Cards.
For more information on the model-index spec, see https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1. | 0 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
Args:
task_type (`str`):
The task identifier. Example: "image-classification".
dataset_type (`str`):
The dataset identifier. Example: "common_voice". Use dataset id from https://hf.co/datasets.
dataset_name (`str`):
A pretty name for the dataset. Example: "Com... | 0 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
dataset_split (`str`, *optional*):
The split used in `load_dataset()`. Example: "test".
dataset_revision (`str`, *optional*):
The revision (AKA Git Sha) of the dataset used in `load_dataset()`.
Example: 5503434ddd753f426f4b38109466949a1217c2bb
dataset_args (`Dict[str,... | 0 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
The arguments passed during `Metric.compute()`. Example for `bleu`: max_order: 4
verified (`bool`, *optional*):
Indicates whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. Automatically computed by Hugging Face,... | 0 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
# Required
# The task identifier
# Example: automatic-speech-recognition
task_type: str
# The dataset identifier
# Example: common_voice. Use dataset id from https://hf.co/datasets
dataset_type: str
# A pretty name for the dataset.
# Example: Common Voice (French)
dataset_name: st... | 0 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
# The split used in `load_dataset()`.
# Example: test
dataset_split: Optional[str] = None
# The revision (AKA Git Sha) of the dataset used in `load_dataset()`.
# Example: 5503434ddd753f426f4b38109466949a1217c2bb
dataset_revision: Optional[str] = None
# The arguments passed during `Metric.compu... | 0 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
# Indicates whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. Automatically computed by Hugging Face, do not set.
verified: Optional[bool] = None
# A JSON Web Token that is used to verify whether the metrics originate from... | 0 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
@property
def unique_identifier(self) -> tuple:
"""Returns a tuple that uniquely identifies this evaluation."""
return (
self.task_type,
self.dataset_type,
self.dataset_config,
self.dataset_split,
self.dataset_revision,
)
def i... | 0 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
def __post_init__(self) -> None:
if self.source_name is not None and self.source_url is None:
raise ValueError("If `source_name` is provided, `source_url` must also be provided.") | 0 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
class CardData:
"""Structure containing metadata from a RepoCard.
[`CardData`] is the parent class of [`ModelCardData`] and [`DatasetCardData`].
Metadata can be exported as a dictionary or YAML. Export can be customized to alter the representation of the data
(example: flatten evaluation results). `Ca... | 1 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
def _to_dict(self, data_dict):
"""Use this method in child classes to alter the dict representation of the data. Alter the dict in-place.
Args:
data_dict (`dict`): The raw dict representation of the card data.
"""
pass
def to_yaml(self, line_break=None, original_order: ... | 1 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
def __repr__(self):
return repr(self.__dict__)
def __str__(self):
return self.to_yaml()
def get(self, key: str, default: Any = None) -> Any:
"""Get value for a given metadata key."""
return self.__dict__.get(key, default)
def pop(self, key: str, default: Any = None) -> Any... | 1 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
class ModelCardData(CardData):
"""Model Card Metadata that is used by Hugging Face Hub when included at the top of your README.md | 2 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
Args:
base_model (`str` or `List[str]`, *optional*):
The identifier of the base model from which the model derives. This is applicable for example if your model is a
fine-tune or adapter of an existing model. The value must be the ID of a model on the Hub (or a list of IDs
if... | 2 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
Language of model's training data or metadata. It must be an ISO 639-1, 639-2 or
639-3 code (two/three letters), or a special value like "code", "multilingual". Defaults to `None`.
library_name (`str`, *optional*):
Name of library used by this model. Example: keras or any library from
... | 2 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
Link to the license of this model. Defaults to None. To be used in conjunction with `license_name`.
Common licenses (Apache-2.0, MIT, CC-BY-SA-4.0) do not need a link. In that case, use `license` instead.
metrics (`List[str]`, *optional*):
List of metrics used to evaluate this model. Sho... | 2 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
List of tags to add to your model that can be used when filtering on the Hugging
Face Hub. Defaults to None.
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 o... | 2 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
Example:
```python
>>> from huggingface_hub import ModelCardData
>>> card_data = ModelCardData(
... language="en",
... license="mit",
... library_name="timm",
... tags=['image-classification', 'resnet'],
... )
>>> card_data.to_dict(... | 2 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
def __init__(
self,
*,
base_model: Optional[Union[str, List[str]]] = None,
datasets: Optional[Union[str, List[str]]] = None,
eval_results: Optional[List[EvalResult]] = None,
language: Optional[Union[str, List[str]]] = None,
library_name: Optional[str] = None,
... | 2 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
self.model_name = model_name
self.pipeline_tag = pipeline_tag
self.tags = _to_unique_list(tags) | 2 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
model_index = kwargs.pop("model-index", None)
if model_index:
try:
model_name, eval_results = model_index_to_eval_results(model_index)
self.model_name = model_name
self.eval_results = eval_results
except (KeyError, TypeError) as error:
... | 2 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
if self.eval_results:
if isinstance(self.eval_results, EvalResult):
self.eval_results = [self.eval_results]
if self.model_name is None:
raise ValueError("Passing `eval_results` requires `model_name` to be set.")
def _to_dict(self, data_dict):
"""Forma... | 2 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
class DatasetCardData(CardData):
"""Dataset Card Metadata that is used by Hugging Face Hub when included at the top of your README.md | 3 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
Args:
language (`List[str]`, *optional*):
Language of dataset's data or metadata. It must be an ISO 639-1, 639-2 or
639-3 code (two/three letters), or a special value like "code", "multilingual".
license (`Union[str, List[str]]`, *optional*):
License(s) of this datase... | 3 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
Options are: 'monolingual', 'multilingual', 'translation', 'other'.
size_categories (`Union[str, List[str]]`, *optional*):
The number of examples in the dataset. Options are: 'n<1K', '1K<n<10K', '10K<n<100K',
'100K<n<1M', '1M<n<10M', '10M<n<100M', '100M<n<1B', '1B<n<10B', '10B<n<100B', '... | 3 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
A more human-readable name for the dataset. (ex. "Cats vs. Dogs")
train_eval_index (`Dict`, *optional*):
A dictionary that describes the necessary spec for doing evaluation on the Hub.
If not provided, it will be gathered from the 'train-eval-index' key of the kwargs.
config_name... | 3 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
def __init__(
self,
*,
language: Optional[Union[str, List[str]]] = None,
license: Optional[Union[str, List[str]]] = None,
annotations_creators: Optional[Union[str, List[str]]] = None,
language_creators: Optional[Union[str, List[str]]] = None,
multilinguality: Opti... | 3 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
self.license = license
self.multilinguality = multilinguality
self.size_categories = size_categories
self.source_datasets = source_datasets
self.task_categories = task_categories
self.task_ids = task_ids
self.paperswithcode_id = paperswithcode_id
self.pretty_name ... | 3 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
# TODO - maybe handle this similarly to EvalResult?
self.train_eval_index = train_eval_index or kwargs.pop("train-eval-index", None)
super().__init__(**kwargs)
def _to_dict(self, data_dict):
data_dict["train-eval-index"] = data_dict.pop("train_eval_index") | 3 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
class SpaceCardData(CardData):
"""Space Card Metadata that is used by Hugging Face Hub when included at the top of your README.md
To get an exhaustive reference of Spaces configuration, please visit https://huggingface.co/docs/hub/spaces-config-reference#spaces-configuration-reference. | 4 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
Args:
title (`str`, *optional*)
Title of the Space.
sdk (`str`, *optional*)
SDK of the Space (one of `gradio`, `streamlit`, `docker`, or `static`).
sdk_version (`str`, *optional*)
Version of the used SDK (if Gradio/Streamlit sdk).
python_version (`str`... | 4 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
ID of the original Space if this is a duplicated Space.
models (List[`str`], *optional*)
List of models related to this Space. Should be a dataset ID found on https://hf.co/models.
datasets (`List[str]`, *optional*)
List of datasets related to this Space. Should be a dataset ID f... | 4 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
Example:
```python
>>> from huggingface_hub import SpaceCardData
>>> card_data = SpaceCardData(
... title="Dreambooth Training",
... license="mit",
... sdk="gradio",
... duplicated_from="multimodalart/dreambooth-training"
... )
>>> ... | 4 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
def __init__(
self,
*,
title: Optional[str] = None,
sdk: Optional[str] = None,
sdk_version: Optional[str] = None,
python_version: Optional[str] = None,
app_file: Optional[str] = None,
app_port: Optional[int] = None,
license: Optional[str] = None,
... | 4 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py |
class BaseModel: # type: ignore [no-redef]
def __init__(self, *args, **kwargs) -> None:
raise ImportError(
"You must have `pydantic` installed to use `WebhookPayload`. This is an optional dependency that"
" should be installed separately. Please run `pip install --up... | 5 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py |
class ObjectId(BaseModel):
id: str | 6 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py |
class WebhookPayloadUrl(BaseModel):
web: str
api: Optional[str] = None | 7 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py |
class WebhookPayloadMovedTo(BaseModel):
name: str
owner: ObjectId | 8 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py |
class WebhookPayloadWebhook(ObjectId):
version: SupportedWebhookVersion | 9 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py |
class WebhookPayloadEvent(BaseModel):
action: WebhookEvent_T
scope: str | 10 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py |
class WebhookPayloadDiscussionChanges(BaseModel):
base: str
mergeCommitId: Optional[str] = None | 11 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py |
class WebhookPayloadComment(ObjectId):
author: ObjectId
hidden: bool
content: Optional[str] = None
url: WebhookPayloadUrl | 12 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py |
class WebhookPayloadDiscussion(ObjectId):
num: int
author: ObjectId
url: WebhookPayloadUrl
title: str
isPullRequest: bool
status: DiscussionStatus_T
changes: Optional[WebhookPayloadDiscussionChanges] = None
pinned: Optional[bool] = None | 13 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py |
class WebhookPayloadRepo(ObjectId):
owner: ObjectId
head_sha: Optional[str] = None
name: str
private: bool
subdomain: Optional[str] = None
tags: Optional[List[str]] = None
type: Literal["dataset", "model", "space"]
url: WebhookPayloadUrl | 14 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py |
class WebhookPayloadUpdatedRef(BaseModel):
ref: str
oldSha: Optional[str] = None
newSha: Optional[str] = None | 15 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py |
class WebhookPayload(BaseModel):
event: WebhookPayloadEvent
repo: WebhookPayloadRepo
discussion: Optional[WebhookPayloadDiscussion] = None
comment: Optional[WebhookPayloadComment] = None
webhook: WebhookPayloadWebhook
movedTo: Optional[WebhookPayloadMovedTo] = None
updatedRefs: Optional[List... | 16 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py |
class MixinInfo:
model_card_template: str
model_card_data: ModelCardData
repo_url: Optional[str] = None
docs_url: Optional[str] = None | 17 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
class ModelHubMixin:
"""
A generic mixin to integrate ANY machine learning framework with the Hub.
To integrate your framework, your model class must inherit from this class. Custom logic for saving/loading models
have to be overwritten in [`_from_pretrained`] and [`_save_pretrained`]. [`PyTorchModelH... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
Args:
repo_url (`str`, *optional*):
URL of the library repository. Used to generate model card.
docs_url (`str`, *optional*):
URL of the library documentation. Used to generate model card.
model_card_template (`str`, *optional*):
Template of the model card. Us... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
E.g: "coqui-public-model-license".
license_link (`str`, *optional*):
URL to the license of the library integrating ModelHubMixin. Used to generate model card.
Only used if `license` is set to `other` and `license_name` is set.
E.g: "https://coqui.ai/cpml".
pipeline_ta... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
Example:
```python
>>> from huggingface_hub import ModelHubMixin | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
# Inherit from ModelHubMixin
>>> class MyCustomModel(
... ModelHubMixin,
... library_name="my-library",
... tags=["x-custom-tag", "arxiv:2304.12244"],
... repo_url="https://github.com/huggingface/my-cool-library",
... docs_url="https://huggingface.co/docs/... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
... resume_download: Optional[bool] = None,
... proxies: Optional[Dict] = None,
... token: Optional[Union[str, bool]] = None,
... cache_dir: Optional[Union[str, Path]] = None,
... local_files_only: bool = False,
... revision: Optional[str] = None,
... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
>>> model = MyCustomModel(size=256, device="gpu")
# Save model weights to local directory
>>> model.save_pretrained("my-awesome-model")
# Push model weights to the Hub
>>> model.push_to_hub("my-awesome-model")
# Download and initialize weights from the Hub
>>> reloaded_model = MyCustomModel.f... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
_hub_mixin_config: Optional[Union[dict, "DataclassInstance"]] = None
# ^ optional config attribute automatically set in `from_pretrained`
_hub_mixin_info: MixinInfo
# ^ information about the library integrating ModelHubMixin (used to generate model card)
_hub_mixin_inject_config: bool # whether `_from_... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
def __init_subclass__(
cls,
*,
# Generic info for model card
repo_url: Optional[str] = None,
docs_url: Optional[str] = None,
# Model card template
model_card_template: str = DEFAULT_MODEL_CARD,
# Model card metadata
language: Optional[List[str]] = ... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
super().__init_subclass__() | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
# Will be reused when creating modelcard
tags = tags or []
tags.append("model_hub_mixin")
# Initialize MixinInfo if not existent
info = MixinInfo(model_card_template=model_card_template, model_card_data=ModelCardData())
# If parent class has a MixinInfo, inherit from it as a co... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
# Update MixinInfo with metadata
if model_card_template is not None and model_card_template != DEFAULT_MODEL_CARD:
info.model_card_template = model_card_template
if repo_url is not None:
info.repo_url = repo_url
if docs_url is not None:
info.docs_url = docs_ur... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
info.model_card_data.tags.extend(tags)
else:
info.model_card_data.tags = tags | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
info.model_card_data.tags = sorted(set(info.model_card_data.tags))
# Handle encoders/decoders for args
cls._hub_mixin_coders = coders or {}
cls._hub_mixin_jsonable_custom_types = tuple(cls._hub_mixin_coders.keys())
# Inspect __init__ signature to handle config
cls._hub_mixin_in... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
3 cases:
- If `self._hub_mixin_config` is already set, do nothing.
- If `config` is passed as a dataclass, set it as `self._hub_mixin_config`.
- Otherwise, build `self._hub_mixin_config` from default values and passed values.
"""
instance = super().__new__(cls)
# If `con... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
# Otherwise, build config from default + passed values
init_config = {
# default values
**cls._hub_mixin_jsonable_default_values,
# passed values
**{
key: cls._encode_arg(value) # Encode custom types as jsonable value
for key, valu... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
@classmethod
def _is_jsonable(cls, value: Any) -> bool:
"""Check if a value is JSON serializable."""
if isinstance(value, cls._hub_mixin_jsonable_custom_types):
return True
return is_jsonable(value)
@classmethod
def _encode_arg(cls, arg: Any) -> Any:
"""Encode an... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
@classmethod
def _decode_arg(cls, expected_type: Type[ARGS_T], value: Any) -> Optional[ARGS_T]:
"""Decode a JSON serializable value into an argument."""
if is_simple_optional_type(expected_type):
if value is None:
return None
expected_type = unwrap_simple_opti... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
def save_pretrained(
self,
save_directory: Union[str, Path],
*,
config: Optional[Union[dict, "DataclassInstance"]] = None,
repo_id: Optional[str] = None,
push_to_hub: bool = False,
model_card_kwargs: Optional[Dict[str, Any]] = None,
**push_to_hub_kwargs,
... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
Args:
save_directory (`str` or `Path`):
Path to directory in which the model weights and configuration will be saved.
config (`dict` or `DataclassInstance`, *optional*):
Model configuration specified as a key/value dictionary or a dataclass instance.
p... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
`str` or `None`: url of the commit on the Hub if `push_to_hub=True`, `None` otherwise.
"""
save_directory = Path(save_directory)
save_directory.mkdir(parents=True, exist_ok=True) | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
# Remove config.json if already exists. After `_save_pretrained` we don't want to overwrite config.json
# as it might have been saved by the custom `_save_pretrained` already. However we do want to overwrite
# an existing config.json if it was not saved by `_save_pretrained`.
config_path = save_... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
# save model card
model_card_path = save_directory / "README.md"
model_card_kwargs = model_card_kwargs if model_card_kwargs is not None else {}
if not model_card_path.exists(): # do not overwrite if already exists
self.generate_model_card(**model_card_kwargs).save(save_directory / "... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
def _save_pretrained(self, save_directory: Path) -> None:
"""
Overwrite this method in subclass to define how to save your model.
Check out our [integration guide](../guides/integrations) for instructions.
Args:
save_directory (`str` or `Path`):
Path to direc... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
Args:
pretrained_model_name_or_path (`str`, `Path`):
- Either the `model_id` (string) of a model hosted on the Hub, e.g. `bigscience/bloom`.
- Or a path to a `directory` containing model weights saved using
[`~transformers.PreTrainedModel.save_pretrained`]... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
'http://hostname': 'foo.bar:4012'}`. The proxies are used on every request.
token (`str` or `bool`, *optional*):
The token to use as HTTP bearer authorization for remote files. By default, it will use the token
cached when running `huggingface-cli login`.
cache_di... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
config_file = os.path.join(model_id, constants.CONFIG_NAME)
else:
logger.warning(f"{constants.CONFIG_NAME} not found in {Path(model_id).resolve()}")
else:
try:
config_file = hf_hub_download(
repo_id=model_id,
filenam... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
# Read config
config = None
if config_file is not None:
with open(config_file, "r", encoding="utf-8") as f:
config = json.load(f)
# Decode custom types in config
for key, value in config.items():
if key in cls._hub_mixin_init_parameter... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
# Check if `config` argument was passed at init
if "config" in cls._hub_mixin_init_parameters and "config" not in model_kwargs:
# Decode `config` argument if it was passed
config_annotation = cls._hub_mixin_init_parameters["config"].annotation
config = cls._de... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
# Finally, also inject if `_from_pretrained` expects it
if cls._hub_mixin_inject_config and "config" not in model_kwargs:
model_kwargs["config"] = config
instance = cls._from_pretrained(
model_id=str(model_id),
revision=revision,
cache_dir=cache_d... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
@classmethod
def _from_pretrained(
cls: Type[T],
*,
model_id: str,
revision: Optional[str],
cache_dir: Optional[Union[str, Path]],
force_download: bool,
proxies: Optional[Dict],
resume_download: Optional[bool],
local_files_only: bool,
t... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
Args:
model_id (`str`):
ID of the model to load from the Huggingface Hub (e.g. `bigscience/bloom`).
revision (`str`, *optional*):
Revision of the model on the Hub. Can be a branch name, a git tag or any commit id. Defaults to the
latest commit on `... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
cache_dir (`str`, `Path`, *optional*):
Path to the folder where cached files are stored.
local_files_only (`bool`, *optional*, defaults to `False`):
If `True`, avoid downloading the file and return the path to the local cached file if it exists.
model_kwargs:
... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
@validate_hf_hub_args
def push_to_hub(
self,
repo_id: str,
*,
config: Optional[Union[dict, "DataclassInstance"]] = None,
commit_message: str = "Push model using huggingface_hub.",
private: Optional[bool] = None,
token: Optional[str] = None,
branch: Opt... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
Args:
repo_id (`str`):
ID of the repository to push to (example: `"username/my-model"`).
config (`dict` or `DataclassInstance`, *optional*):
Model configuration specified as a key/value dictionary or a dataclass instance.
commit_message (`str`, *option... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
Whether or not to create a Pull Request from `branch` with that commit. Defaults to `False`.
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... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
Returns:
The url of the commit of your model in the given repository.
"""
api = HfApi(token=token)
repo_id = api.create_repo(repo_id=repo_id, private=private, exist_ok=True).repo_id
# Push the files to the repo in a single commit
with SoftTemporaryDirectory() as tmp:... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
def generate_model_card(self, *args, **kwargs) -> ModelCard:
card = ModelCard.from_template(
card_data=self._hub_mixin_info.model_card_data,
template_str=self._hub_mixin_info.model_card_template,
repo_url=self._hub_mixin_info.repo_url,
docs_url=self._hub_mixin_inf... | 18 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
class PyTorchModelHubMixin(ModelHubMixin):
"""
Implementation of [`ModelHubMixin`] to provide model Hub upload/download capabilities to PyTorch models. The model
is set in evaluation mode by default using `model.eval()` (dropout modules are deactivated). To train the model,
you should first set it back ... | 19 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
>>> class MyModel(
... nn.Module,
... PyTorchModelHubMixin,
... library_name="keras-nlp",
... repo_url="https://github.com/keras-team/keras-nlp",
... docs_url="https://keras.io/keras_nlp/",
... # ^ optional metadata to generate model card
... ... | 19 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
# Download and initialize weights from the Hub
>>> model = MyModel.from_pretrained("username/my-awesome-model")
>>> model.hidden_size
256
```
"""
def __init_subclass__(cls, *args, tags: Optional[List[str]] = None, **kwargs) -> None:
tags = tags or []
tags.append("pytorch_model_h... | 19 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
@classmethod
def _from_pretrained(
cls,
*,
model_id: str,
revision: Optional[str],
cache_dir: Optional[Union[str, Path]],
force_download: bool,
proxies: Optional[Dict],
resume_download: Optional[bool],
local_files_only: bool,
token: Uni... | 19 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
revision=revision,
cache_dir=cache_dir,
force_download=force_download,
proxies=proxies,
resume_download=resume_download,
token=token,
local_files_only=local_files_only,
)
... | 19 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
@classmethod
def _load_as_pickle(cls, model: T, model_file: str, map_location: str, strict: bool) -> T:
state_dict = torch.load(model_file, map_location=torch.device(map_location), weights_only=True)
model.load_state_dict(state_dict, strict=strict) # type: ignore
model.eval() # type: ignor... | 19 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
@classmethod
def _load_as_safetensor(cls, model: T, model_file: str, map_location: str, strict: bool) -> T:
if packaging.version.parse(safetensors.__version__) < packaging.version.parse("0.4.3"): # type: ignore [attr-defined]
load_model_as_safetensor(model, model_file, strict=strict) # type: i... | 19 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
safetensors.torch.load_model(model, model_file, strict=strict, device=map_location) # type: ignore [arg-type]
return model | 19 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py |
class WebhooksServer:
"""
The [`WebhooksServer`] class lets you create an instance of a Gradio app that can receive Huggingface webhooks.
These webhooks can be registered using the [`~WebhooksServer.add_webhook`] decorator. Webhook endpoints are added to
the app as a POST endpoint to the FastAPI router.... | 20 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_server.py |
You must have `gradio` installed to use `WebhooksServer` (`pip install --upgrade gradio`).
</Tip>
Args:
ui (`gradio.Blocks`, optional):
A Gradio UI instance to be used as the Space landing page. If `None`, a UI displaying instructions
about the configured webhooks is created.
... | 20 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_server.py |
@app.add_webhook("/say_hello")
async def hello(payload: WebhookPayload):
return {"message": "hello"}
app.launch()
```
"""
def __new__(cls, *args, **kwargs) -> "WebhooksServer":
if not is_gradio_available():
raise ImportError(
"You must ha... | 20 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_server.py |
self.webhook_secret = webhook_secret or os.getenv("WEBHOOK_SECRET")
self.registered_webhooks: Dict[str, Callable] = {}
_warn_on_empty_secret(self.webhook_secret)
def add_webhook(self, path: Optional[str] = None) -> Callable:
"""
Decorator to add a webhook to the [`WebhooksServer`] s... | 20 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_server.py |
@app.add_webhook
async def trigger_training(payload: WebhookPayload):
if payload.repo.type == "dataset" and payload.event.action == "update":
# Trigger a training job if a dataset is updated
...
app.launch()
```
"""
... | 20 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_server.py |
def launch(self, prevent_thread_lock: bool = False, **launch_kwargs: Any) -> None:
"""Launch the Gradio app and register webhooks to the underlying FastAPI server.
Input parameters are forwarded to Gradio when launching the app.
"""
ui = self._ui or self._get_default_ui()
# Sta... | 20 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_server.py |
# Print instructions and block main thread
space_host = os.environ.get("SPACE_HOST")
url = "https://" + space_host if space_host is not None else (ui.share_url or ui.local_url)
url = url.strip("/")
message = "\nWebhooks are correctly setup and ready to use:"
message += "\n" + "\n... | 20 | /Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_server.py |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 10