huggingface-hub API Reference
Full documentation for huggingface-hub (1.26.0)
huggingface-hub.ASYNC_CLIENT_FACTORY_T
Python Library Documentation: _CallableGenericAlias in module collections.abc
class Callable(builtins.object)
| Methods defined here:
|
| __call__(self, *args, **kwds)
| Call self as a function.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__ = _CallableGenericAlias(args)
| Represent `Callable[argtypes, resulttype]`.
|
| This sets ``__args__`` to a tuple containing the flattened ``argtypes``
| followed by ``resulttype``.
|
| Example: ``Callable[[int, str], float]`` sets ``__args__`` to
| ``(int, str, float)``.
|
| __subclasshook__(C)
| Abstract classes can override this to customize issubclass().
|
| This is invoked early on by abc.ABCMeta.__subclasscheck__().
| It should return True, False or NotImplemented. If it returns
| NotImplemented, the normal algorithm is used. Otherwise, it
| overrides the normal algorithm (and the outcome is cached).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__call__'})
huggingface-hub.Agent
Python Library Documentation: class Agent in module huggingface_hub.inference._mcp.agent class Agent(huggingface_hub.inference._mcp.mcp_client.MCPClient) | Agent(*, model: 'Optional[str]' = None, servers: 'Iterable[ServerConfig]', provider: 'Optional[PROVIDER_OR_POLICY_T]' = None, base_url: 'Optional[str]' = None, api_key: 'Optional[str]' = None, prompt: 'Optional[str]' = None) | | Implementation of a Simple Agent, which is a simple while loop built right on top of an [`MCPClient`]. | | > [!WARNING] | > This class is experimental and might be subject to breaking changes in the future without prior notice. | | Args: | model (`str`, *optional*): | The model to run inference with. Can be a model id hosted on the Hugging Face Hub, e.g. `meta-llama/Meta-Llama-3-8B-Instruct` | or a URL to a deployed Inference Endpoint or other local or remote endpoint. | servers (`Iterable[dict]`): | MCP servers to connect to. Each server is a dictionary containing a `type` key and a `config` key. The `type` key can be `"stdio"` or `"sse"`, and the `config` key is a dictionary of arguments for the server. | provider (`str`, *optional*): | Name of the provider to use for inference. Defaults to "auto" i.e. the first of the providers available for the model, sorted by the user's order in https://hf.co/settings/inference-providers. | If model is a URL or `base_url` is passed, then `provider` is not used. | base_url (`str`, *optional*): | The base URL to run inference. Defaults to None. | api_key (`str`, *optional*): | Token to use for authentication. Will default to the locally Hugging Face saved token if not provided. You can also use your own provider API key to interact directly with the provider's service. | prompt (`str`, *optional*): | The system prompt to use for the agent. Defaults to the default system prompt in `constants.py`. | | Method resolution order: | Agent | huggingface_hub.inference._mcp.mcp_client.MCPClient | builtins.object | | Methods defined here: | | __init__(self, *, model: 'Optional[str]' = None, servers: 'Iterable[ServerConfig]', provider: 'Optional[PROVIDER_OR_POLICY_T]' = None, base_url: 'Optional[str]' = None, api_key: 'Optional[str]' = None, prompt: 'Optional[str]' = None) | Initialize self. See help(type(self)) for accurate signature. | | async load_tools(self) -> 'None' | | async run(self, user_input: 'str', *, abort_event: 'Optional[asyncio.Event]' = None) -> 'AsyncGenerator[Union[ChatCompletionStreamOutput, ChatCompletionInputMessage], None]' | Run the agent with the given user input. | | Args: | user_input (`str`): | The user input to run the agent with. | abort_event (`asyncio.Event`, *optional*): | An event that can be used to abort the agent. If the event is set, the agent will stop running. | | ---------------------------------------------------------------------- | Methods inherited from huggingface_hub.inference._mcp.mcp_client.MCPClient: | | async __aenter__(self) | Enter the context manager | | async __aexit__(self, exc_type, exc_val, exc_tb) | Exit the context manager | | async add_mcp_server(self, type: Literal['stdio', 'sse', 'http'], **params: Any) | Connect to an MCP server | | Args: | type (`str`): | Type of the server to connect to. Can be one of: | - "stdio": Standard input/output server (local) | - "sse": Server-sent events (SSE) server | - "http": StreamableHTTP server | **params (`dict[str, Any]`): | Server parameters that can be either: | - For stdio servers: | - command (str): The command to run the MCP server | - args (list[str], optional): Arguments for the command | - env (dict[str, str], optional): Environment variables for the command | - cwd (Union[str, Path, None], optional): Working directory for the command | - allowed_tools (list[str], optional): List of tool names to allow from this server | - For SSE servers: | - url (str): The URL of the SSE server | - headers (dict[str, Any], optional): Headers for the SSE connection | - timeout (float, optional): Connection timeout | - sse_read_timeout (float, optional): SSE read timeout | - allowed_tools (list[str], optional): List of tool names to allow from this server | - For StreamableHTTP servers: | - url (str): The URL of the StreamableHTTP server | - headers (dict[str, Any], optional): Headers for the StreamableHTTP connection | - timeout (timedelta, optional): Connection timeout | - sse_read_timeout (timedelta, optional): SSE read timeout | - terminate_on_close (bool, optional): Whether to terminate on close | - allowed_tools (list[str], optional): List of tool names to allow from this server | | async cleanup(self) | Clean up resources | | async process_single_turn_with_tools(self, messages: list[typing.Union[dict, huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputMessage]], exit_loop_tools: Optional[list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputTool]] = None, exit_if_first_chunk_no_tool: bool = False) -> AsyncIterable[Union[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutput, huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputMessage]] | Process a query using `self.model` and available tools, yielding chunks and tool outputs. | | Args: | messages (`list[dict]`): | List of message objects representing the conversation history | exit_loop_tools (`list[ChatCompletionInputTool]`, *optional*): | List of tools that should exit the generator when called | exit_if_first_chunk_no_tool (`bool`, *optional*): | Exit if no tool is present in the first chunks. Default to False. | | Yields: | [`ChatCompletionStreamOutput`] chunks or [`ChatCompletionInputMessage`] objects | | ---------------------------------------------------------------------- | Data descriptors inherited from huggingface_hub.inference._mcp.mcp_client.MCPClient: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
huggingface-hub.AsyncInferenceClient
Python Library Documentation: class AsyncInferenceClient in module huggingface_hub.inference._generated._async_client
class AsyncInferenceClient(builtins.object)
| AsyncInferenceClient(model: str | None = None, *, provider: Union[Literal['cerebras', 'cohere', 'deepinfra', 'fal-ai', 'featherless-ai', 'fireworks-ai', 'groq', 'hf-inference', 'novita', 'nscale', 'openai', 'ovhcloud', 'publicai', 'replicate', 'scaleway', 'together', 'wavespeed', 'zai-org'], Literal['auto'], NoneType] = None, token: str | None = None, timeout: float | None = None, headers: dict[str, str] | None = None, cookies: dict[str, str] | None = None, bill_to: str | None = None, base_url: str | None = None, api_key: str | None = None) -> None
|
| Initialize a new Inference Client.
|
| [`InferenceClient`] aims to provide a unified experience to perform inference. The client can be used
| seamlessly with either the (free) Inference API, self-hosted Inference Endpoints, or third-party Inference Providers.
|
| Args:
| model (`str`, `optional`):
| The model to run inference with. Can be a model id hosted on the Hugging Face Hub, e.g. `meta-llama/Meta-Llama-3-8B-Instruct`
| or a URL to a deployed Inference Endpoint. Defaults to None, in which case a recommended model is
| automatically selected for the task.
| Note: for better compatibility with OpenAI's client, `model` has been aliased as `base_url`. Those 2
| arguments are mutually exclusive. If a URL is passed as `model` or `base_url` for chat completion, the `(/v1)/chat/completions` suffix path will be appended to the URL.
| provider (`str`, *optional*):
| Name of the provider to use for inference. Can be `"cerebras"`, `"cohere"`, `"deepinfra"`, `"fal-ai"`, `"featherless-ai"`, `"fireworks-ai"`, `"groq"`, `"hf-inference"`, `"novita"`, `"nscale"`, `"openai"`, `"ovhcloud"`, `"publicai"`, `"replicate"`, `"scaleway"`, `"together"`, `"wavespeed"` or `"zai-org"`.
| Defaults to "auto": automatic routing, which defaults to "fastest" provider; you can
| switch to "cheapest" or "preferred" provider order at https://hf.co/settings/inference-providers.
| If model is a URL or `base_url` is passed, then `provider` is not used.
| token (`str`, *optional*):
| Hugging Face token. Will default to the locally saved token if not provided.
| Note: for better compatibility with OpenAI's client, `token` has been aliased as `api_key`. Those 2
| arguments are mutually exclusive and have the exact same behavior.
| timeout (`float`, `optional`):
| The maximum number of seconds to wait for a response from the server. Defaults to None, meaning it will loop until the server is available.
| headers (`dict[str, str]`, `optional`):
| Additional headers to send to the server. By default only the authorization and user-agent headers are sent.
| Values in this dictionary will override the default values.
| bill_to (`str`, `optional`):
| The billing account to use for the requests. By default the requests are billed on the user's account.
| Requests can only be billed to an organization the user is a member of, and which has subscribed to Enterprise Hub.
| cookies (`dict[str, str]`, `optional`):
| Additional cookies to send to the server.
| base_url (`str`, `optional`):
| Base URL to run inference. This is a duplicated argument from `model` to make [`InferenceClient`]
| follow the same pattern as `openai.OpenAI` client. Cannot be used if `model` is set. Defaults to None.
| api_key (`str`, `optional`):
| Token to use for authentication. This is a duplicated argument from `token` to make [`InferenceClient`]
| follow the same pattern as `openai.OpenAI` client. Cannot be used if `token` is set. Defaults to None.
|
| Methods defined here:
|
| async __aenter__(self)
|
| async __aexit__(self, exc_type, exc_value, traceback)
|
| __init__(self, model: str | None = None, *, provider: Union[Literal['cerebras', 'cohere', 'deepinfra', 'fal-ai', 'featherless-ai', 'fireworks-ai', 'groq', 'hf-inference', 'novita', 'nscale', 'openai', 'ovhcloud', 'publicai', 'replicate', 'scaleway', 'together', 'wavespeed', 'zai-org'], Literal['auto'], NoneType] = None, token: str | None = None, timeout: float | None = None, headers: dict[str, str] | None = None, cookies: dict[str, str] | None = None, bill_to: str | None = None, base_url: str | None = None, api_key: str | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| async audio_classification(self, audio: Union[bytes, BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], *, model: str | None = None, top_k: int | None = None, function_to_apply: Optional[ForwardRef('AudioClassificationOutputTransform')] = None) -> list[huggingface_hub.inference._generated.types.audio_classification.AudioClassificationOutputElement]
| Perform audio classification on the provided audio content.
|
| Args:
| audio (Union[str, Path, bytes, BinaryIO]):
| The audio content to classify. It can be raw audio bytes, a local audio file, or a URL pointing to an
| audio file.
| model (`str`, *optional*):
| The model to use for audio classification. Can be a model ID hosted on the Hugging Face Hub
| or a URL to a deployed Inference Endpoint. If not provided, the default recommended model for
| audio classification will be used.
| top_k (`int`, *optional*):
| When specified, limits the output to the top K most probable classes.
| function_to_apply (`"AudioClassificationOutputTransform"`, *optional*):
| The function to apply to the model outputs in order to retrieve the scores.
|
| Returns:
| `list[AudioClassificationOutputElement]`: List of [`AudioClassificationOutputElement`] items containing the predicted labels and their confidence.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
| >>> await client.audio_classification("audio.flac")
| [
| AudioClassificationOutputElement(score=0.4976358711719513, label='hap'),
| AudioClassificationOutputElement(score=0.3677836060523987, label='neu'),
| ...
| ]
| ```
|
| async audio_to_audio(self, audio: Union[bytes, BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], *, model: str | None = None) -> list[huggingface_hub.inference._generated.types.audio_to_audio.AudioToAudioOutputElement]
| Performs multiple tasks related to audio-to-audio depending on the model (eg: speech enhancement, source separation).
|
| Args:
| audio (Union[str, Path, bytes, BinaryIO]):
| The audio content for the model. It can be raw audio bytes, a local audio file, or a URL pointing to an
| audio file.
| model (`str`, *optional*):
| The model can be any model which takes an audio file and returns another audio file. Can be a model ID hosted on the Hugging Face Hub
| or a URL to a deployed Inference Endpoint. If not provided, the default recommended model for
| audio_to_audio will be used.
|
| Returns:
| `list[AudioToAudioOutputElement]`: A list of [`AudioToAudioOutputElement`] items containing audios label, content-type, and audio content in blob.
|
| Raises:
| `InferenceTimeoutError`:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
| >>> audio_output = await client.audio_to_audio("audio.flac")
| >>> async for i, item in enumerate(audio_output):
| >>> with open(f"output_{i}.flac", "wb") as f:
| f.write(item.blob)
| ```
|
| async automatic_speech_recognition(self, audio: Union[bytes, BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], *, model: str | None = None, extra_body: dict | None = None) -> huggingface_hub.inference._generated.types.automatic_speech_recognition.AutomaticSpeechRecognitionOutput
| Perform automatic speech recognition (ASR or audio-to-text) on the given audio content.
|
| Args:
| audio (Union[str, Path, bytes, BinaryIO]):
| The content to transcribe. It can be raw audio bytes, local audio file, or a URL to an audio file.
| model (`str`, *optional*):
| The model to use for ASR. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. If not provided, the default recommended model for ASR will be used.
| extra_body (`dict`, *optional*):
| Additional provider-specific parameters to pass to the model. Refer to the provider's documentation
| for supported parameters.
| Returns:
| [`AutomaticSpeechRecognitionOutput`]: An item containing the transcribed text and optionally the timestamp chunks.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
| >>> await client.automatic_speech_recognition("hello_world.flac").text
| "hello world"
| ```
|
| async chat_completion(self, messages: list[dict | huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputMessage], *, model: str | None = None, stream: bool = False, frequency_penalty: float | None = None, logit_bias: list[float] | None = None, logprobs: bool | None = None, max_tokens: int | None = None, n: int | None = None, presence_penalty: float | None = None, response_format: Union[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputResponseFormatText, huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputResponseFormatJSONSchema, huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputResponseFormatJSONObject, NoneType] = None, seed: int | None = None, stop: list[str] | None = None, stream_options: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputStreamOptions | None = None, temperature: float | None = None, tool_choice: Union[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputToolChoiceClass, ForwardRef('ChatCompletionInputToolChoiceEnum'), NoneType] = None, tool_prompt: str | None = None, tools: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputTool] | None = None, top_logprobs: int | None = None, top_p: float | None = None, extra_body: dict | None = None) -> Union[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionOutput, AsyncIterable[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutput]]
| A method for completing conversations using a specified language model.
|
| > [!TIP]
| > The `client.chat_completion` method is aliased as `client.chat.completions.create` for compatibility with OpenAI's client.
| > Inputs and outputs are strictly the same and using either syntax will yield the same results.
| > Check out the [Inference guide](https://huggingface.co/docs/huggingface_hub/guides/inference#openai-compatibility)
| > for more details about OpenAI's compatibility.
|
| > [!TIP]
| > You can pass provider-specific parameters to the model by using the `extra_body` argument.
|
| Args:
| messages (List of [`ChatCompletionInputMessage`]):
| Conversation history consisting of roles and content pairs.
| model (`str`, *optional*):
| The model to use for chat-completion. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. If not provided, the default recommended model for chat-based text-generation will be used.
| See https://huggingface.co/tasks/text-generation for more details.
| If `model` is a model ID, it is passed to the server as the `model` parameter. If you want to define a
| custom URL while setting `model` in the request payload, you must set `base_url` when initializing [`InferenceClient`].
| frequency_penalty (`float`, *optional*):
| Penalizes new tokens based on their existing frequency
| in the text so far. Range: [-2.0, 2.0]. Defaults to 0.0.
| logit_bias (`list[float]`, *optional*):
| Adjusts the likelihood of specific tokens appearing in the generated output.
| logprobs (`bool`, *optional*):
| Whether to return log probabilities of the output tokens or not. If true, returns the log
| probabilities of each output token returned in the content of message.
| max_tokens (`int`, *optional*):
| Maximum number of tokens allowed in the response. Defaults to 100.
| n (`int`, *optional*):
| The number of completions to generate for each prompt.
| presence_penalty (`float`, *optional*):
| Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the
| text so far, increasing the model's likelihood to talk about new topics.
| response_format ([`ChatCompletionInputGrammarType`], *optional*):
| Grammar constraints. Can be either a JSONSchema or a regex.
| seed (Optional[`int`], *optional*):
| Seed for reproducible control flow. Defaults to None.
| stop (`list[str]`, *optional*):
| Up to four strings which trigger the end of the response.
| Defaults to None.
| stream (`bool`, *optional*):
| Enable realtime streaming of responses. Defaults to False.
| stream_options ([`ChatCompletionInputStreamOptions`], *optional*):
| Options for streaming completions.
| temperature (`float`, *optional*):
| Controls randomness of the generations. Lower values ensure
| less random completions. Range: [0, 2]. Defaults to 1.0.
| top_logprobs (`int`, *optional*):
| An integer between 0 and 5 specifying the number of most likely tokens to return at each token
| position, each with an associated log probability. logprobs must be set to true if this parameter is
| used.
| top_p (`float`, *optional*):
| Fraction of the most likely next words to sample from.
| Must be between 0 and 1. Defaults to 1.0.
| tool_choice ([`ChatCompletionInputToolChoiceClass`] or [`ChatCompletionInputToolChoiceEnum`], *optional*):
| The tool to use for the completion. Defaults to "auto".
| tool_prompt (`str`, *optional*):
| A prompt to be appended before the tools.
| tools (List of [`ChatCompletionInputTool`], *optional*):
| A list of tools the model may call. Currently, only functions are supported as a tool. Use this to
| provide a list of functions the model may generate JSON inputs for.
| extra_body (`dict`, *optional*):
| Additional provider-specific parameters to pass to the model. Refer to the provider's documentation
| for supported parameters.
| Returns:
| [`ChatCompletionOutput`] or Iterable of [`ChatCompletionStreamOutput`]:
| Generated text returned from the server:
| - if `stream=False`, the generated text is returned as a [`ChatCompletionOutput`] (default).
| - if `stream=True`, the generated text is returned token by token as a sequence of [`ChatCompletionStreamOutput`].
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
|
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> messages = [{"role": "user", "content": "What is the capital of France?"}]
| >>> client = AsyncInferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
| >>> await client.chat_completion(messages, max_tokens=100)
| ChatCompletionOutput(
| choices=[
| ChatCompletionOutputComplete(
| finish_reason='eos_token',
| index=0,
| message=ChatCompletionOutputMessage(
| role='assistant',
| content='The capital of France is Paris.',
| name=None,
| tool_calls=None
| ),
| logprobs=None
| )
| ],
| created=1719907176,
| id='',
| model='meta-llama/Meta-Llama-3-8B-Instruct',
| object='text_completion',
| system_fingerprint='2.0.4-sha-f426a33',
| usage=ChatCompletionOutputUsage(
| completion_tokens=8,
| prompt_tokens=17,
| total_tokens=25
| )
| )
| ```
|
| Example using streaming:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> messages = [{"role": "user", "content": "What is the capital of France?"}]
| >>> client = AsyncInferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
| >>> async for token in await client.chat_completion(messages, max_tokens=10, stream=True):
| ... print(token)
| ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content='The', role='assistant'), index=0, finish_reason=None)], created=1710498504)
| ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content=' capital', role='assistant'), index=0, finish_reason=None)], created=1710498504)
| (...)
| ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content=' may', role='assistant'), index=0, finish_reason=None)], created=1710498504)
| ```
|
| Example using OpenAI's syntax:
| ```py
| # Must be run in an async context
| # instead of `from openai import OpenAI`
| from huggingface_hub import AsyncInferenceClient
|
| # instead of `client = OpenAI(...)`
| client = AsyncInferenceClient(
| base_url=...,
| api_key=...,
| )
|
| output = await client.chat.completions.create(
| model="meta-llama/Meta-Llama-3-8B-Instruct",
| messages=[
| {"role": "system", "content": "You are a helpful assistant."},
| {"role": "user", "content": "Count to 10"},
| ],
| stream=True,
| max_tokens=1024,
| )
|
| for chunk in output:
| print(chunk.choices[0].delta.content)
| ```
|
| Example using a third-party provider directly with extra (provider-specific) parameters. Usage will be billed on your Together AI account.
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient(
| ... provider="together", # Use Together AI provider
| ... api_key="<together_api_key>", # Pass your Together API key directly
| ... )
| >>> client.chat_completion(
| ... model="meta-llama/Meta-Llama-3-8B-Instruct",
| ... messages=[{"role": "user", "content": "What is the capital of France?"}],
| ... extra_body={"safety_model": "Meta-Llama/Llama-Guard-7b"},
| ... )
| ```
|
| Example using a third-party provider through Hugging Face Routing. Usage will be billed on your Hugging Face account.
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient(
| ... provider="novita", # Use Novita provider
| ... api_key="hf_...", # Pass your HF token
| ... )
| >>> client.chat_completion(
| ... model="meta-llama/Meta-Llama-3-8B-Instruct",
| ... messages=[{"role": "user", "content": "What is the capital of France?"}],
| ... )
| ```
|
| Example using Image + Text as input:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
|
| # provide a remote URL
| >>> image_url ="https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
| # or a base64-encoded image
| >>> image_path = "/path/to/image.jpeg"
| >>> with open(image_path, "rb") as f:
| ... base64_image = base64.b64encode(f.read()).decode("utf-8")
| >>> image_url = f"data:image/jpeg;base64,{base64_image}"
|
| >>> client = AsyncInferenceClient("meta-llama/Llama-3.2-11B-Vision-Instruct")
| >>> output = await client.chat.completions.create(
| ... messages=[
| ... {
| ... "role": "user",
| ... "content": [
| ... {
| ... "type": "image_url",
| ... "image_url": {"url": image_url},
| ... },
| ... {
| ... "type": "text",
| ... "text": "Describe this image in one sentence.",
| ... },
| ... ],
| ... },
| ... ],
| ... )
| >>> output
| The image depicts the iconic Statue of Liberty situated in New York Harbor, New York, on a clear day.
| ```
|
| Example using tools:
| ```py
| # Must be run in an async context
| >>> client = AsyncInferenceClient("meta-llama/Meta-Llama-3-70B-Instruct")
| >>> messages = [
| ... {
| ... "role": "system",
| ... "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.",
| ... },
| ... {
| ... "role": "user",
| ... "content": "What's the weather like the next 3 days in San Francisco, CA?",
| ... },
| ... ]
| >>> tools = [
| ... {
| ... "type": "function",
| ... "function": {
| ... "name": "get_current_weather",
| ... "description": "Get the current weather",
| ... "parameters": {
| ... "type": "object",
| ... "properties": {
| ... "location": {
| ... "type": "string",
| ... "description": "The city and state, e.g. San Francisco, CA",
| ... },
| ... "format": {
| ... "type": "string",
| ... "enum": ["celsius", "fahrenheit"],
| ... "description": "The temperature unit to use. Infer this from the users location.",
| ... },
| ... },
| ... "required": ["location", "format"],
| ... },
| ... },
| ... },
| ... {
| ... "type": "function",
| ... "function": {
| ... "name": "get_n_day_weather_forecast",
| ... "description": "Get an N-day weather forecast",
| ... "parameters": {
| ... "type": "object",
| ... "properties": {
| ... "location": {
| ... "type": "string",
| ... "description": "The city and state, e.g. San Francisco, CA",
| ... },
| ... "format": {
| ... "type": "string",
| ... "enum": ["celsius", "fahrenheit"],
| ... "description": "The temperature unit to use. Infer this from the users location.",
| ... },
| ... "num_days": {
| ... "type": "integer",
| ... "description": "The number of days to forecast",
| ... },
| ... },
| ... "required": ["location", "format", "num_days"],
| ... },
| ... },
| ... },
| ... ]
|
| >>> response = await client.chat_completion(
| ... model="meta-llama/Meta-Llama-3-70B-Instruct",
| ... messages=messages,
| ... tools=tools,
| ... tool_choice="auto",
| ... max_tokens=500,
| ... )
| >>> response.choices[0].message.tool_calls[0].function
| ChatCompletionOutputFunctionDefinition(
| arguments={
| 'location': 'San Francisco, CA',
| 'format': 'fahrenheit',
| 'num_days': 3
| },
| name='get_n_day_weather_forecast',
| description=None
| )
| ```
|
| Example using response_format:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient("meta-llama/Meta-Llama-3-70B-Instruct")
| >>> messages = [
| ... {
| ... "role": "user",
| ... "content": "I saw a puppy a cat and a raccoon during my bike ride in the park. What did I see and when?",
| ... },
| ... ]
| >>> response_format = {
| ... "type": "json",
| ... "value": {
| ... "properties": {
| ... "location": {"type": "string"},
| ... "activity": {"type": "string"},
| ... "animals_seen": {"type": "integer", "minimum": 1, "maximum": 5},
| ... "animals": {"type": "array", "items": {"type": "string"}},
| ... },
| ... "required": ["location", "activity", "animals_seen", "animals"],
| ... },
| ... }
| >>> response = await client.chat_completion(
| ... messages=messages,
| ... response_format=response_format,
| ... max_tokens=500,
| ... )
| >>> response.choices[0].message.content
| '{
|
| "activity": "bike ride",
| "animals": ["puppy", "cat", "raccoon"],
| "animals_seen": 3,
| "location": "park"}'
| ```
|
| async close(self)
| Close the client.
|
| This method is automatically called when using the client as a context manager.
|
| async document_question_answering(self, image: Union[bytes, BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], question: str, *, model: str | None = None, doc_stride: int | None = None, handle_impossible_answer: bool | None = None, lang: str | None = None, max_answer_len: int | None = None, max_question_len: int | None = None, max_seq_len: int | None = None, top_k: int | None = None, word_boxes: list[list[float] | str] | None = None) -> list[huggingface_hub.inference._generated.types.document_question_answering.DocumentQuestionAnsweringOutputElement]
| Answer questions on document images.
|
| Args:
| image (`Union[str, Path, bytes, BinaryIO]`):
| The input image for the context. It can be raw bytes, an image file, or a URL to an online image.
| question (`str`):
| Question to be answered.
| model (`str`, *optional*):
| The model to use for the document question answering task. Can be a model ID hosted on the Hugging Face Hub or a URL to
| a deployed Inference Endpoint. If not provided, the default recommended document question answering model will be used.
| Defaults to None.
| doc_stride (`int`, *optional*):
| If the words in the document are too long to fit with the question for the model, it will be split in
| several chunks with some overlap. This argument controls the size of that overlap.
| handle_impossible_answer (`bool`, *optional*):
| Whether to accept impossible as an answer
| lang (`str`, *optional*):
| Language to use while running OCR. Defaults to english.
| max_answer_len (`int`, *optional*):
| The maximum length of predicted answers (e.g., only answers with a shorter length are considered).
| max_question_len (`int`, *optional*):
| The maximum length of the question after tokenization. It will be truncated if needed.
| max_seq_len (`int`, *optional*):
| The maximum length of the total sentence (context + question) in tokens of each chunk passed to the
| model. The context will be split in several chunks (using doc_stride as overlap) if needed.
| top_k (`int`, *optional*):
| The number of answers to return (will be chosen by order of likelihood). Can return less than top_k
| answers if there are not enough options available within the context.
| word_boxes (`list[Union[list[float], str`, *optional*):
| A list of words and bounding boxes (normalized 0->1000). If provided, the inference will skip the OCR
| step and use the provided bounding boxes instead.
| Returns:
| `list[DocumentQuestionAnsweringOutputElement]`: a list of [`DocumentQuestionAnsweringOutputElement`] items containing the predicted label, associated probability, word ids, and page number.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
| >>> await client.document_question_answering(image="https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png", question="What is the invoice number?")
| [DocumentQuestionAnsweringOutputElement(answer='us-001', end=16, score=0.9999666213989258, start=16)]
| ```
|
| async feature_extraction(self, text: str | list[str], *, normalize: bool | None = None, prompt_name: str | None = None, truncate: bool | None = None, truncation_direction: Optional[Literal['left', 'right']] = None, dimensions: int | None = None, encoding_format: Optional[Literal['float', 'base64']] = None, model: str | None = None) -> 'np.ndarray'
| Generate embeddings for a given text or batch of texts.
|
| Args:
| text (`str` or `list[str]`):
| The text or list of texts to embed.
| model (`str`, *optional*):
| The model to use for the feature extraction task. Can be a model ID hosted on the Hugging Face Hub or a URL to
| a deployed Inference Endpoint. If not provided, the default recommended feature extraction model will be used.
| Defaults to None.
| normalize (`bool`, *optional*):
| Whether to normalize the embeddings or not.
| Only available on server powered by Text-Embedding-Inference.
| prompt_name (`str`, *optional*):
| The name of the prompt that should be used by for encoding. If not set, no prompt will be applied.
| Must be a key in the `Sentence Transformers` configuration `prompts` dictionary.
| For example if ``prompt_name`` is "query" and the ``prompts`` is {"query": "query: ",...},
| then the sentence "What is the capital of France?" will be encoded as "query: What is the capital of France?"
| because the prompt text will be prepended before any text to encode.
| truncate (`bool`, *optional*):
| Whether to truncate the embeddings or not.
| Only available on server powered by Text-Embedding-Inference.
| truncation_direction (`Literal["left", "right"]`, *optional*):
| Which side of the input should be truncated when `truncate=True` is passed.
| dimensions (`int`, *optional*):
| The number of dimensions the resulting output embeddings should have.
| Only available on OpenAI-compatible embedding endpoints.
| encoding_format (`Literal["float", "base64"]`, *optional*):
| The format of the output embeddings. Either "float" or "base64".
| Only available on OpenAI-compatible embedding endpoints.
|
| Returns:
| `np.ndarray`: The embedding representing the input text(s) as a float32 numpy array.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
| >>> await client.feature_extraction("Hi, who are you?")
| array([[ 2.424802 , 2.93384 , 1.1750331 , ..., 1.240499, -0.13776633, -0.7889173 ],
| [-0.42943227, -0.6364878 , -1.693462 , ..., 0.41978157, -2.4336355 , 0.6162071 ],
| ...,
| [ 0.28552425, -0.928395 , -1.2077185 , ..., 0.76810825, -2.1069427 , 0.6236161 ]], dtype=float32)
| ```
|
| async fill_mask(self, text: str, *, model: str | None = None, targets: list[str] | None = None, top_k: int | None = None) -> list[huggingface_hub.inference._generated.types.fill_mask.FillMaskOutputElement]
| Fill in a hole with a missing word (token to be precise).
|
| Args:
| text (`str`):
| a string to be filled from, must contain the [MASK] token (check model card for exact name of the mask).
| model (`str`, *optional*):
| The model to use for the fill mask task. Can be a model ID hosted on the Hugging Face Hub or a URL to
| a deployed Inference Endpoint. If not provided, the default recommended fill mask model will be used.
| targets (`list[str`, *optional*):
| When passed, the model will limit the scores to the passed targets instead of looking up in the whole
| vocabulary. If the provided targets are not in the model vocab, they will be tokenized and the first
| resulting token will be used (with a warning, and that might be slower).
| top_k (`int`, *optional*):
| When passed, overrides the number of predictions to return.
| Returns:
| `list[FillMaskOutputElement]`: a list of [`FillMaskOutputElement`] items containing the predicted label, associated
| probability, token reference, and completed text.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
| >>> await client.fill_mask("The goal of life is <mask>.")
| [
| FillMaskOutputElement(score=0.06897063553333282, token=11098, token_str=' happiness', sequence='The goal of life is happiness.'),
| FillMaskOutputElement(score=0.06554922461509705, token=45075, token_str=' immortality', sequence='The goal of life is immortality.')
| ]
| ```
|
| async get_endpoint_info(self, *, model: str | None = None) -> dict[str, typing.Any]
| Get information about the deployed endpoint.
|
| This endpoint is only available on endpoints powered by Text-Generation-Inference (TGI) or Text-Embedding-Inference (TEI).
| Endpoints powered by `transformers` return an empty payload.
|
| Args:
| model (`str`, *optional*):
| The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
|
| Returns:
| `dict[str, Any]`: Information about the endpoint.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient("meta-llama/Meta-Llama-3-70B-Instruct")
| >>> await client.get_endpoint_info()
| {
| 'model_id': 'meta-llama/Meta-Llama-3-70B-Instruct',
| 'model_sha': None,
| 'model_dtype': 'torch.float16',
| 'model_device_type': 'cuda',
| 'model_pipeline_tag': None,
| 'max_concurrent_requests': 128,
| 'max_best_of': 2,
| 'max_stop_sequences': 4,
| 'max_input_length': 8191,
| 'max_total_tokens': 8192,
| 'waiting_served_ratio': 0.3,
| 'max_batch_total_tokens': 1259392,
| 'max_waiting_tokens': 20,
| 'max_batch_size': None,
| 'validation_workers': 32,
| 'max_client_batch_size': 4,
| 'version': '2.0.2',
| 'sha': 'dccab72549635c7eb5ddb17f43f0b7cdff07c214',
| 'docker_label': 'sha-dccab72'
| }
| ```
|
| async health_check(self, model: str | None = None) -> bool
| Check the health of the deployed endpoint.
|
| Health check is only available with Inference Endpoints powered by Text-Generation-Inference (TGI) or Text-Embedding-Inference (TEI).
|
| Args:
| model (`str`, *optional*):
| URL of the Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
|
| Returns:
| `bool`: True if everything is working fine.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient("https://jzgu0buei5.us-east-1.aws.endpoints.huggingface.cloud")
| >>> await client.health_check()
| True
| ```
|
| async image_classification(self, image: Union[bytes, BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], *, model: str | None = None, function_to_apply: Optional[ForwardRef('ImageClassificationOutputTransform')] = None, top_k: int | None = None) -> list[huggingface_hub.inference._generated.types.image_classification.ImageClassificationOutputElement]
| Perform image classification on the given image using the specified model.
|
| Args:
| image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`):
| The image to classify. It can be raw bytes, an image file, a URL to an online image, or a PIL Image.
| model (`str`, *optional*):
| The model to use for image classification. Can be a model ID hosted on the Hugging Face Hub or a URL to a
| deployed Inference Endpoint. If not provided, the default recommended model for image classification will be used.
| function_to_apply (`"ImageClassificationOutputTransform"`, *optional*):
| The function to apply to the model outputs in order to retrieve the scores.
| top_k (`int`, *optional*):
| When specified, limits the output to the top K most probable classes.
| Returns:
| `list[ImageClassificationOutputElement]`: a list of [`ImageClassificationOutputElement`] items containing the predicted label and associated probability.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
| >>> await client.image_classification("https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg")
| [ImageClassificationOutputElement(label='Blenheim spaniel', score=0.9779096841812134), ...]
| ```
|
| async image_segmentation(self, image: Union[bytes, BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], *, model: str | None = None, mask_threshold: float | None = None, overlap_mask_area_threshold: float | None = None, subtask: Optional[ForwardRef('ImageSegmentationSubtask')] = None, threshold: float | None = None) -> list[huggingface_hub.inference._generated.types.image_segmentation.ImageSegmentationOutputElement]
| Perform image segmentation on the given image using the specified model.
|
| > [!WARNING]
| > You must have `PIL` installed if you want to work with images (`pip install Pillow`).
|
| Args:
| image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`):
| The image to segment. It can be raw bytes, an image file, a URL to an online image, or a PIL Image.
| model (`str`, *optional*):
| The model to use for image segmentation. Can be a model ID hosted on the Hugging Face Hub or a URL to a
| deployed Inference Endpoint. If not provided, the default recommended model for image segmentation will be used.
| mask_threshold (`float`, *optional*):
| Threshold to use when turning the predicted masks into binary values.
| overlap_mask_area_threshold (`float`, *optional*):
| Mask overlap threshold to eliminate small, disconnected segments.
| subtask (`"ImageSegmentationSubtask"`, *optional*):
| Segmentation task to be performed, depending on model capabilities.
| threshold (`float`, *optional*):
| Probability threshold to filter out predicted masks.
| Returns:
| `list[ImageSegmentationOutputElement]`: A list of [`ImageSegmentationOutputElement`] items containing the segmented masks and associated attributes.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
| >>> await client.image_segmentation("cat.jpg")
| [ImageSegmentationOutputElement(score=0.989008, label='LABEL_184', mask=<PIL.PngImagePlugin.PngImageFile image mode=L size=400x300 at 0x7FDD2B129CC0>), ...]
| ```
|
| async image_to_image(self, image: Union[bytes, BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], prompt: str | None = None, *, negative_prompt: str | None = None, num_inference_steps: int | None = None, guidance_scale: float | None = None, model: str | None = None, target_size: huggingface_hub.inference._generated.types.image_to_image.ImageToImageTargetSize | None = None, **kwargs) -> 'Image'
| Perform image-to-image translation using a specified model.
|
| > [!WARNING]
| > You must have `PIL` installed if you want to work with images (`pip install Pillow`).
|
| Args:
| image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`):
| The input image for translation. It can be raw bytes, an image file, a URL to an online image, or a PIL Image.
| prompt (`str`, *optional*):
| The text prompt to guide the image generation.
| negative_prompt (`str`, *optional*):
| One prompt to guide what NOT to include in image generation.
| num_inference_steps (`int`, *optional*):
| For diffusion models. The number of denoising steps. More denoising steps usually lead to a higher
| quality image at the expense of slower inference.
| guidance_scale (`float`, *optional*):
| For diffusion models. A higher guidance scale value encourages the model to generate images closely
| linked to the text prompt at the expense of lower image quality.
| model (`str`, *optional*):
| The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
| target_size (`ImageToImageTargetSize`, *optional*):
| The size in pixels of the output image. This parameter is only supported by some providers and for
| specific models. It will be ignored when unsupported.
|
| Returns:
| `Image`: The translated image.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
| >>> image = await client.image_to_image("cat.jpg", prompt="turn the cat into a tiger")
| >>> image.save("tiger.jpg")
| ```
|
| async image_to_text(self, image: Union[bytes, BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], *, model: str | None = None) -> huggingface_hub.inference._generated.types.image_to_text.ImageToTextOutput
| Takes an input image and return text.
|
| Models can have very different outputs depending on your use case (image captioning, optical character recognition
| (OCR), Pix2Struct, etc.). Please have a look to the model card to learn more about a model's specificities.
|
| Args:
| image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`):
| The input image to caption. It can be raw bytes, an image file, a URL to an online image, or a PIL Image.
| model (`str`, *optional*):
| The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
|
| Returns:
| [`ImageToTextOutput`]: The generated text.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
| >>> await client.image_to_text("cat.jpg")
| 'a cat standing in a grassy field '
| >>> await client.image_to_text("https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg")
| 'a dog laying on the grass next to a flower pot '
| ```
|
| async image_to_video(self, image: Union[bytes, BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], *, model: str | None = None, prompt: str | None = None, negative_prompt: str | None = None, num_frames: float | None = None, num_inference_steps: int | None = None, guidance_scale: float | None = None, seed: int | None = None, target_size: huggingface_hub.inference._generated.types.image_to_video.ImageToVideoTargetSize | None = None, **kwargs) -> bytes
| Generate a video from an input image.
|
| Args:
| image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`):
| The input image to generate a video from. It can be raw bytes, an image file, a URL to an online image, or a PIL Image.
| model (`str`, *optional*):
| The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
| prompt (`str`, *optional*):
| The text prompt to guide the video generation.
| negative_prompt (`str`, *optional*):
| One prompt to guide what NOT to include in video generation.
| num_frames (`float`, *optional*):
| The num_frames parameter determines how many video frames are generated.
| num_inference_steps (`int`, *optional*):
| For diffusion models. The number of denoising steps. More denoising steps usually lead to a higher
| quality image at the expense of slower inference.
| guidance_scale (`float`, *optional*):
| For diffusion models. A higher guidance scale value encourages the model to generate videos closely
| linked to the text prompt at the expense of lower image quality.
| seed (`int`, *optional*):
| The seed to use for the video generation.
| target_size (`ImageToVideoTargetSize`, *optional*):
| The size in pixel of the output video frames.
| num_inference_steps (`int`, *optional*):
| The number of denoising steps. More denoising steps usually lead to a higher quality video at the
| expense of slower inference.
| seed (`int`, *optional*):
| Seed for the random number generator.
|
| Returns:
| `bytes`: The generated video.
|
| Examples:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
| >>> video = await client.image_to_video("cat.jpg", model="Wan-AI/Wan2.2-I2V-A14B", prompt="turn the cat into a tiger")
| >>> with open("tiger.mp4", "wb") as f:
| ... f.write(video)
| ```
|
| async object_detection(self, image: Union[bytes, BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], *, model: str | None = None, threshold: float | None = None) -> list[huggingface_hub.inference._generated.types.object_detection.ObjectDetectionOutputElement]
| Perform object detection on the given image using the specified model.
|
| > [!WARNING]
| > You must have `PIL` installed if you want to work with images (`pip install Pillow`).
|
| Args:
| image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`):
| The image to detect objects on. It can be raw bytes, an image file, a URL to an online image, or a PIL Image.
| model (`str`, *optional*):
| The model to use for object detection. Can be a model ID hosted on the Hugging Face Hub or a URL to a
| deployed Inference Endpoint. If not provided, the default recommended model for object detection (DETR) will be used.
| threshold (`float`, *optional*):
| The probability necessary to make a prediction.
| Returns:
| `list[ObjectDetectionOutputElement]`: A list of [`ObjectDetectionOutputElement`] items containing the bounding boxes and associated attributes.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
| `ValueError`:
| If the request output is not a List.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
| >>> await client.object_detection("people.jpg")
| [ObjectDetectionOutputElement(score=0.9486683011054993, label='person', box=ObjectDetectionBoundingBox(xmin=59, ymin=39, xmax=420, ymax=510)), ...]
| ```
|
| async question_answering(self, question: str, context: str, *, model: str | None = None, align_to_words: bool | None = None, doc_stride: int | None = None, handle_impossible_answer: bool | None = None, max_answer_len: int | None = None, max_question_len: int | None = None, max_seq_len: int | None = None, top_k: int | None = None) -> huggingface_hub.inference._generated.types.question_answering.QuestionAnsweringOutputElement | list[huggingface_hub.inference._generated.types.question_answering.QuestionAnsweringOutputElement]
| Retrieve the answer to a question from a given text.
|
| Args:
| question (`str`):
| Question to be answered.
| context (`str`):
| The context of the question.
| model (`str`):
| The model to use for the question answering task. Can be a model ID hosted on the Hugging Face Hub or a URL to
| a deployed Inference Endpoint.
| align_to_words (`bool`, *optional*):
| Attempts to align the answer to real words. Improves quality on space separated languages. Might hurt
| on non-space-separated languages (like Japanese or Chinese)
| doc_stride (`int`, *optional*):
| If the context is too long to fit with the question for the model, it will be split in several chunks
| with some overlap. This argument controls the size of that overlap.
| handle_impossible_answer (`bool`, *optional*):
| Whether to accept impossible as an answer.
| max_answer_len (`int`, *optional*):
| The maximum length of predicted answers (e.g., only answers with a shorter length are considered).
| max_question_len (`int`, *optional*):
| The maximum length of the question after tokenization. It will be truncated if needed.
| max_seq_len (`int`, *optional*):
| The maximum length of the total sentence (context + question) in tokens of each chunk passed to the
| model. The context will be split in several chunks (using docStride as overlap) if needed.
| top_k (`int`, *optional*):
| The number of answers to return (will be chosen by order of likelihood). Note that we return less than
| topk answers if there are not enough options available within the context.
|
| Returns:
| Union[`QuestionAnsweringOutputElement`, list[`QuestionAnsweringOutputElement`]]:
| When top_k is 1 or not provided, it returns a single `QuestionAnsweringOutputElement`.
| When top_k is greater than 1, it returns a list of `QuestionAnsweringOutputElement`.
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
| >>> await client.question_answering(question="What's my name?", context="My name is Clara and I live in Berkeley.")
| QuestionAnsweringOutputElement(answer='Clara', end=16, score=0.9326565265655518, start=11)
| ```
|
| async sentence_similarity(self, sentence: str, other_sentences: list[str], *, model: str | None = None) -> list[float]
| Compute the semantic similarity between a sentence and a list of other sentences by comparing their embeddings.
|
| Args:
| sentence (`str`):
| The main sentence to compare to others.
| other_sentences (`list[str]`):
| The list of sentences to compare to.
| model (`str`, *optional*):
| The model to use for the sentence similarity task. Can be a model ID hosted on the Hugging Face Hub or a URL to
| a deployed Inference Endpoint. If not provided, the default recommended sentence similarity model will be used.
| Defaults to None.
|
| Returns:
| `list[float]`: The embedding representing the input text.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
| >>> await client.sentence_similarity(
| ... "Machine learning is so easy.",
| ... other_sentences=[
| ... "Deep learning is so straightforward.",
| ... "This is so difficult, like rocket science.",
| ... "I can't believe how much I struggled with this.",
| ... ],
| ... )
| [0.7785726189613342, 0.45876261591911316, 0.2906220555305481]
| ```
|
| async summarization(self, text: str, *, model: str | None = None, clean_up_tokenization_spaces: bool | None = None, generate_parameters: dict[str, typing.Any] | None = None, truncation: Optional[ForwardRef('SummarizationTruncationStrategy')] = None) -> huggingface_hub.inference._generated.types.summarization.SummarizationOutput
| Generate a summary of a given text using a specified model.
|
| Args:
| text (`str`):
| The input text to summarize.
| model (`str`, *optional*):
| The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. If not provided, the default recommended model for summarization will be used.
| clean_up_tokenization_spaces (`bool`, *optional*):
| Whether to clean up the potential extra spaces in the text output.
| generate_parameters (`dict[str, Any]`, *optional*):
| Additional parametrization of the text generation algorithm.
| truncation (`"SummarizationTruncationStrategy"`, *optional*):
| The truncation strategy to use.
| Returns:
| [`SummarizationOutput`]: The generated summary text.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
| >>> await client.summarization("The Eiffel tower...")
| SummarizationOutput(generated_text="The Eiffel tower is one of the most famous landmarks in the world....")
| ```
|
| async table_question_answering(self, table: dict[str, typing.Any], query: str, *, model: str | None = None, padding: Optional[ForwardRef('Padding')] = None, sequential: bool | None = None, truncation: bool | None = None) -> huggingface_hub.inference._generated.types.table_question_answering.TableQuestionAnsweringOutputElement
| Retrieve the answer to a question from information given in a table.
|
| Args:
| table (`str`):
| A table of data represented as a dict of lists where entries are headers and the lists are all the
| values, all lists must have the same size.
| query (`str`):
| The query in plain text that you want to ask the table.
| model (`str`):
| The model to use for the table-question-answering task. Can be a model ID hosted on the Hugging Face
| Hub or a URL to a deployed Inference Endpoint.
| padding (`"Padding"`, *optional*):
| Activates and controls padding.
| sequential (`bool`, *optional*):
| Whether to do inference sequentially or as a batch. Batching is faster, but models like SQA require the
| inference to be done sequentially to extract relations within sequences, given their conversational
| nature.
| truncation (`bool`, *optional*):
| Activates and controls truncation.
|
| Returns:
| [`TableQuestionAnsweringOutputElement`]: a table question answering output containing the answer, coordinates, cells and the aggregator used.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
| >>> query = "How many stars does the transformers repository have?"
| >>> table = {"Repository": ["Transformers", "Datasets", "Tokenizers"], "Stars": ["36542", "4512", "3934"]}
| >>> await client.table_question_answering(table, query, model="google/tapas-base-finetuned-wtq")
| TableQuestionAnsweringOutputElement(answer='36542', coordinates=[[0, 1]], cells=['36542'], aggregator='AVERAGE')
| ```
|
| async tabular_classification(self, table: dict[str, typing.Any], *, model: str | None = None) -> list[str]
| Classifying a target category (a group) based on a set of attributes.
|
| Args:
| table (`dict[str, Any]`):
| Set of attributes to classify.
| model (`str`, *optional*):
| The model to use for the tabular classification task. Can be a model ID hosted on the Hugging Face Hub or a URL to
| a deployed Inference Endpoint. If not provided, the default recommended tabular classification model will be used.
| Defaults to None.
|
| Returns:
| `List`: a list of labels, one per row in the initial table.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
| >>> table = {
| ... "fixed_acidity": ["7.4", "7.8", "10.3"],
| ... "volatile_acidity": ["0.7", "0.88", "0.32"],
| ... "citric_acid": ["0", "0", "0.45"],
| ... "residual_sugar": ["1.9", "2.6", "6.4"],
| ... "chlorides": ["0.076", "0.098", "0.073"],
| ... "free_sulfur_dioxide": ["11", "25", "5"],
| ... "total_sulfur_dioxide": ["34", "67", "13"],
| ... "density": ["0.9978", "0.9968", "0.9976"],
| ... "pH": ["3.51", "3.2", "3.23"],
| ... "sulphates": ["0.56", "0.68", "0.82"],
| ... "alcohol": ["9.4", "9.8", "12.6"],
| ... }
| >>> await client.tabular_classification(table=table, model="julien-c/wine-quality")
| ["5", "5", "5"]
| ```
|
| async tabular_regression(self, table: dict[str, typing.Any], *, model: str | None = None) -> list[float]
| Predicting a numerical target value given a set of attributes/features in a table.
|
| Args:
| table (`dict[str, Any]`):
| Set of attributes stored in a table. The attributes used to predict the target can be both numerical and categorical.
| model (`str`, *optional*):
| The model to use for the tabular regression task. Can be a model ID hosted on the Hugging Face Hub or a URL to
| a deployed Inference Endpoint. If not provided, the default recommended tabular regression model will be used.
| Defaults to None.
|
| Returns:
| `List`: a list of predicted numerical target values.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
| >>> table = {
| ... "Height": ["11.52", "12.48", "12.3778"],
| ... "Length1": ["23.2", "24", "23.9"],
| ... "Length2": ["25.4", "26.3", "26.5"],
| ... "Length3": ["30", "31.2", "31.1"],
| ... "Species": ["Bream", "Bream", "Bream"],
| ... "Width": ["4.02", "4.3056", "4.6961"],
| ... }
| >>> await client.tabular_regression(table, model="scikit-learn/Fish-Weight")
| [110, 120, 130]
| ```
|
| async text_classification(self, text: str, *, model: str | None = None, top_k: int | None = None, function_to_apply: Optional[ForwardRef('TextClassificationOutputTransform')] = None) -> list[huggingface_hub.inference._generated.types.text_classification.TextClassificationOutputElement]
| Perform text classification (e.g. sentiment-analysis) on the given text.
|
| Args:
| text (`str`):
| A string to be classified.
| model (`str`, *optional*):
| The model to use for the text classification task. Can be a model ID hosted on the Hugging Face Hub or a URL to
| a deployed Inference Endpoint. If not provided, the default recommended text classification model will be used.
| Defaults to None.
| top_k (`int`, *optional*):
| When specified, limits the output to the top K most probable classes.
| function_to_apply (`"TextClassificationOutputTransform"`, *optional*):
| The function to apply to the model outputs in order to retrieve the scores.
|
| Returns:
| `list[TextClassificationOutputElement]`: a list of [`TextClassificationOutputElement`] items containing the predicted label and associated probability.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
| >>> await client.text_classification("I like you")
| [
| TextClassificationOutputElement(label='POSITIVE', score=0.9998695850372314),
| TextClassificationOutputElement(label='NEGATIVE', score=0.0001304351753788069),
| ]
| ```
|
| async text_generation(self, prompt: str, *, details: bool | None = None, stream: bool | None = None, model: str | None = None, adapter_id: str | None = None, best_of: int | None = None, decoder_input_details: bool | None = None, do_sample: bool | None = None, frequency_penalty: float | None = None, grammar: huggingface_hub.inference._generated.types.text_generation.TextGenerationInputGrammarType | None = None, max_new_tokens: int | None = None, repetition_penalty: float | None = None, return_full_text: bool | None = None, seed: int | None = None, stop: list[str] | None = None, stop_sequences: list[str] | None = None, temperature: float | None = None, top_k: int | None = None, top_n_tokens: int | None = None, top_p: float | None = None, truncate: int | None = None, typical_p: float | None = None, watermark: bool | None = None) -> Union[str, huggingface_hub.inference._generated.types.text_generation.TextGenerationOutput, AsyncIterable[str], AsyncIterable[huggingface_hub.inference._generated.types.text_generation.TextGenerationStreamOutput]]
| Given a prompt, generate the following text.
|
| > [!TIP]
| > If you want to generate a response from chat messages, you should use the [`InferenceClient.chat_completion`] method.
| > It accepts a list of messages instead of a single text prompt and handles the chat templating for you.
|
| Args:
| prompt (`str`):
| Input text.
| details (`bool`, *optional*):
| By default, text_generation returns a string. Pass `details=True` if you want a detailed output (tokens,
| probabilities, seed, finish reason, etc.). Only available for models running on with the
| `text-generation-inference` backend.
| stream (`bool`, *optional*):
| By default, text_generation returns the full generated text. Pass `stream=True` if you want a stream of
| tokens to be returned. Only available for models running on with the `text-generation-inference`
| backend.
| model (`str`, *optional*):
| The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
| adapter_id (`str`, *optional*):
| Lora adapter id.
| best_of (`int`, *optional*):
| Generate best_of sequences and return the one if the highest token logprobs.
| decoder_input_details (`bool`, *optional*):
| Return the decoder input token logprobs and ids. You must set `details=True` as well for it to be taken
| into account. Defaults to `False`.
| do_sample (`bool`, *optional*):
| Activate logits sampling
| frequency_penalty (`float`, *optional*):
| Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in
| the text so far, decreasing the model's likelihood to repeat the same line verbatim.
| grammar ([`TextGenerationInputGrammarType`], *optional*):
| Grammar constraints. Can be either a JSONSchema or a regex.
| max_new_tokens (`int`, *optional*):
| Maximum number of generated tokens. Defaults to 100.
| repetition_penalty (`float`, *optional*):
| The parameter for repetition penalty. 1.0 means no penalty. See [this
| paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
| return_full_text (`bool`, *optional*):
| Whether to prepend the prompt to the generated text
| seed (`int`, *optional*):
| Random sampling seed
| stop (`list[str]`, *optional*):
| Stop generating tokens if a member of `stop` is generated.
| stop_sequences (`list[str]`, *optional*):
| Deprecated argument. Use `stop` instead.
| temperature (`float`, *optional*):
| The value used to module the logits distribution.
| top_n_tokens (`int`, *optional*):
| Return information about the `top_n_tokens` most likely tokens at each generation step, instead of
| just the sampled token.
| top_k (`int`, *optional`):
| The number of highest probability vocabulary tokens to keep for top-k-filtering.
| top_p (`float`, *optional`):
| If set to < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or
| higher are kept for generation.
| truncate (`int`, *optional`):
| Truncate inputs tokens to the given size.
| typical_p (`float`, *optional`):
| Typical Decoding mass
| See [Typical Decoding for Natural Language Generation](https://arxiv.org/abs/2202.00666) for more information
| watermark (`bool`, *optional*):
| Watermarking with [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226)
|
| Returns:
| `Union[str, TextGenerationOutput, AsyncIterable[str], AsyncIterable[TextGenerationStreamOutput]]`:
| Generated text returned from the server:
| - if `stream=False` and `details=False`, the generated text is returned as a `str` (default)
| - if `stream=True` and `details=False`, the generated text is returned token by token as a `AsyncIterable[str]`
| - if `stream=False` and `details=True`, the generated text is returned with more details as a [`~huggingface_hub.TextGenerationOutput`]
| - if `details=True` and `stream=True`, the generated text is returned token by token as a iterable of [`~huggingface_hub.TextGenerationStreamOutput`]
|
| Raises:
| `ValidationError`:
| If input values are not valid. No HTTP call is made to the server.
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
|
| # Case 1: generate text
| >>> await client.text_generation("The huggingface_hub library is ", max_new_tokens=12)
| '100% open source and built to be easy to use.'
|
| # Case 2: iterate over the generated tokens. Useful for large generation.
| >>> async for token in await client.text_generation("The huggingface_hub library is ", max_new_tokens=12, stream=True):
| ... print(token)
| 100
| %
| open
| source
| and
| built
| to
| be
| easy
| to
| use
| .
|
| # Case 3: get more details about the generation process.
| >>> await client.text_generation("The huggingface_hub library is ", max_new_tokens=12, details=True)
| TextGenerationOutput(
| generated_text='100% open source and built to be easy to use.',
| details=TextGenerationDetails(
| finish_reason='length',
| generated_tokens=12,
| seed=None,
| prefill=[
| TextGenerationPrefillOutputToken(id=487, text='The', logprob=None),
| TextGenerationPrefillOutputToken(id=53789, text=' hugging', logprob=-13.171875),
| (...)
| TextGenerationPrefillOutputToken(id=204, text=' ', logprob=-7.0390625)
| ],
| tokens=[
| TokenElement(id=1425, text='100', logprob=-1.0175781, special=False),
| TokenElement(id=16, text='%', logprob=-0.0463562, special=False),
| (...)
| TokenElement(id=25, text='.', logprob=-0.5703125, special=False)
| ],
| best_of_sequences=None
| )
| )
|
| # Case 4: iterate over the generated tokens with more details.
| # Last object is more complete, containing the full generated text and the finish reason.
| >>> async for details in await client.text_generation("The huggingface_hub library is ", max_new_tokens=12, details=True, stream=True):
| ... print(details)
| ...
| TextGenerationStreamOutput(token=TokenElement(id=1425, text='100', logprob=-1.0175781, special=False), generated_text=None, details=None)
| TextGenerationStreamOutput(token=TokenElement(id=16, text='%', logprob=-0.0463562, special=False), generated_text=None, details=None)
| TextGenerationStreamOutput(token=TokenElement(id=1314, text=' open', logprob=-1.3359375, special=False), generated_text=None, details=None)
| TextGenerationStreamOutput(token=TokenElement(id=3178, text=' source', logprob=-0.28100586, special=False), generated_text=None, details=None)
| TextGenerationStreamOutput(token=TokenElement(id=273, text=' and', logprob=-0.5961914, special=False), generated_text=None, details=None)
| TextGenerationStreamOutput(token=TokenElement(id=3426, text=' built', logprob=-1.9423828, special=False), generated_text=None, details=None)
| TextGenerationStreamOutput(token=TokenElement(id=271, text=' to', logprob=-1.4121094, special=False), generated_text=None, details=None)
| TextGenerationStreamOutput(token=TokenElement(id=314, text=' be', logprob=-1.5224609, special=False), generated_text=None, details=None)
| TextGenerationStreamOutput(token=TokenElement(id=1833, text=' easy', logprob=-2.1132812, special=False), generated_text=None, details=None)
| TextGenerationStreamOutput(token=TokenElement(id=271, text=' to', logprob=-0.08520508, special=False), generated_text=None, details=None)
| TextGenerationStreamOutput(token=TokenElement(id=745, text=' use', logprob=-0.39453125, special=False), generated_text=None, details=None)
| TextGenerationStreamOutput(token=TokenElement(
| id=25,
| text='.',
| logprob=-0.5703125,
| special=False),
| generated_text='100% open source and built to be easy to use.',
| details=TextGenerationStreamOutputStreamDetails(finish_reason='length', generated_tokens=12, seed=None)
| )
|
| # Case 5: generate constrained output using grammar
| >>> response = await client.text_generation(
| ... prompt="I saw a puppy a cat and a raccoon during my bike ride in the park",
| ... model="HuggingFaceH4/zephyr-orpo-141b-A35b-v0.1",
| ... max_new_tokens=100,
| ... repetition_penalty=1.3,
| ... grammar={
| ... "type": "json",
| ... "value": {
| ... "properties": {
| ... "location": {"type": "string"},
| ... "activity": {"type": "string"},
| ... "animals_seen": {"type": "integer", "minimum": 1, "maximum": 5},
| ... "animals": {"type": "array", "items": {"type": "string"}},
| ... },
| ... "required": ["location", "activity", "animals_seen", "animals"],
| ... },
| ... },
| ... )
| >>> json.loads(response)
| {
| "activity": "bike riding",
| "animals": ["puppy", "cat", "raccoon"],
| "animals_seen": 3,
| "location": "park"
| }
| ```
|
| async text_to_image(self, prompt: str, *, negative_prompt: str | None = None, height: int | None = None, width: int | None = None, num_inference_steps: int | None = None, guidance_scale: float | None = None, model: str | None = None, scheduler: str | None = None, seed: int | None = None, extra_body: dict[str, typing.Any] | None = None) -> 'Image'
| Generate an image based on a given text using a specified model.
|
| > [!WARNING]
| > You must have `PIL` installed if you want to work with images (`pip install Pillow`).
|
| > [!TIP]
| > You can pass provider-specific parameters to the model by using the `extra_body` argument.
|
| Args:
| prompt (`str`):
| The prompt to generate an image from.
| negative_prompt (`str`, *optional*):
| One prompt to guide what NOT to include in image generation.
| height (`int`, *optional*):
| The height in pixels of the output image
| width (`int`, *optional*):
| The width in pixels of the output image
| num_inference_steps (`int`, *optional*):
| The number of denoising steps. More denoising steps usually lead to a higher quality image at the
| expense of slower inference.
| guidance_scale (`float`, *optional*):
| A higher guidance scale value encourages the model to generate images closely linked to the text
| prompt, but values too high may cause saturation and other artifacts.
| model (`str`, *optional*):
| The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. If not provided, the default recommended text-to-image model will be used.
| Defaults to None.
| scheduler (`str`, *optional*):
| Override the scheduler with a compatible one.
| seed (`int`, *optional*):
| Seed for the random number generator.
| extra_body (`dict[str, Any]`, *optional*):
| Additional provider-specific parameters to pass to the model. Refer to the provider's documentation
| for supported parameters.
|
| Returns:
| `Image`: The generated image.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
|
| >>> image = await client.text_to_image("An astronaut riding a horse on the moon.")
| >>> image.save("astronaut.png")
|
| >>> image = await client.text_to_image(
| ... "An astronaut riding a horse on the moon.",
| ... negative_prompt="low resolution, blurry",
| ... model="stabilityai/stable-diffusion-2-1",
| ... )
| >>> image.save("better_astronaut.png")
| ```
| Example using a third-party provider directly. Usage will be billed on your fal.ai account.
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient(
| ... provider="fal-ai", # Use fal.ai provider
| ... api_key="fal-ai-api-key", # Pass your fal.ai API key
| ... )
| >>> image = client.text_to_image(
| ... "A majestic lion in a fantasy forest",
| ... model="black-forest-labs/FLUX.1-schnell",
| ... )
| >>> image.save("lion.png")
| ```
|
| Example using a third-party provider through Hugging Face Routing. Usage will be billed on your Hugging Face account.
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient(
| ... provider="replicate", # Use replicate provider
| ... api_key="hf_...", # Pass your HF token
| ... )
| >>> image = client.text_to_image(
| ... "An astronaut riding a horse on the moon.",
| ... model="black-forest-labs/FLUX.1-dev",
| ... )
| >>> image.save("astronaut.png")
| ```
|
| Example using Replicate provider with extra parameters
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient(
| ... provider="replicate", # Use replicate provider
| ... api_key="hf_...", # Pass your HF token
| ... )
| >>> image = client.text_to_image(
| ... "An astronaut riding a horse on the moon.",
| ... model="black-forest-labs/FLUX.1-schnell",
| ... extra_body={"output_quality": 100},
| ... )
| >>> image.save("astronaut.png")
| ```
|
| async text_to_speech(self, text: str, *, model: str | None = None, do_sample: bool | None = None, early_stopping: Union[bool, ForwardRef('TextToSpeechEarlyStoppingEnum'), NoneType] = None, epsilon_cutoff: float | None = None, eta_cutoff: float | None = None, max_length: int | None = None, max_new_tokens: int | None = None, min_length: int | None = None, min_new_tokens: int | None = None, num_beam_groups: int | None = None, num_beams: int | None = None, penalty_alpha: float | None = None, temperature: float | None = None, top_k: int | None = None, top_p: float | None = None, typical_p: float | None = None, use_cache: bool | None = None, extra_body: dict[str, typing.Any] | None = None) -> bytes
| Synthesize an audio of a voice pronouncing a given text.
|
| > [!TIP]
| > You can pass provider-specific parameters to the model by using the `extra_body` argument.
|
| Args:
| text (`str`):
| The text to synthesize.
| model (`str`, *optional*):
| The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. If not provided, the default recommended text-to-speech model will be used.
| Defaults to None.
| do_sample (`bool`, *optional*):
| Whether to use sampling instead of greedy decoding when generating new tokens.
| early_stopping (`Union[bool, "TextToSpeechEarlyStoppingEnum"]`, *optional*):
| Controls the stopping condition for beam-based methods.
| epsilon_cutoff (`float`, *optional*):
| If set to float strictly between 0 and 1, only tokens with a conditional probability greater than
| epsilon_cutoff will be sampled. In the paper, suggested values range from 3e-4 to 9e-4, depending on
| the size of the model. See [Truncation Sampling as Language Model
| Desmoothing](https://hf.co/papers/2210.15191) for more details.
| eta_cutoff (`float`, *optional*):
| Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to float strictly
| between 0 and 1, a token is only considered if it is greater than either eta_cutoff or sqrt(eta_cutoff)
| * exp(-entropy(softmax(next_token_logits))). The latter term is intuitively the expected next token
| probability, scaled by sqrt(eta_cutoff). In the paper, suggested values range from 3e-4 to 2e-3,
| depending on the size of the model. See [Truncation Sampling as Language Model
| Desmoothing](https://hf.co/papers/2210.15191) for more details.
| max_length (`int`, *optional*):
| The maximum length (in tokens) of the generated text, including the input.
| max_new_tokens (`int`, *optional*):
| The maximum number of tokens to generate. Takes precedence over max_length.
| min_length (`int`, *optional*):
| The minimum length (in tokens) of the generated text, including the input.
| min_new_tokens (`int`, *optional*):
| The minimum number of tokens to generate. Takes precedence over min_length.
| num_beam_groups (`int`, *optional*):
| Number of groups to divide num_beams into in order to ensure diversity among different groups of beams.
| See [this paper](https://hf.co/papers/1610.02424) for more details.
| num_beams (`int`, *optional*):
| Number of beams to use for beam search.
| penalty_alpha (`float`, *optional*):
| The value balances the model confidence and the degeneration penalty in contrastive search decoding.
| temperature (`float`, *optional*):
| The value used to modulate the next token probabilities.
| top_k (`int`, *optional*):
| The number of highest probability vocabulary tokens to keep for top-k-filtering.
| top_p (`float`, *optional*):
| If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to
| top_p or higher are kept for generation.
| typical_p (`float`, *optional*):
| Local typicality measures how similar the conditional probability of predicting a target token next is
| to the expected conditional probability of predicting a random token next, given the partial text
| already generated. If set to float < 1, the smallest set of the most locally typical tokens with
| probabilities that add up to typical_p or higher are kept for generation. See [this
| paper](https://hf.co/papers/2202.00666) for more details.
| use_cache (`bool`, *optional*):
| Whether the model should use the past last key/values attentions to speed up decoding
| extra_body (`dict[str, Any]`, *optional*):
| Additional provider-specific parameters to pass to the model. Refer to the provider's documentation
| for supported parameters.
| Returns:
| `bytes`: The generated audio.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from pathlib import Path
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
|
| >>> audio = await client.text_to_speech("Hello world")
| >>> Path("hello_world.flac").write_bytes(audio)
| ```
|
| Example using a third-party provider directly. Usage will be billed on your Replicate account.
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient(
| ... provider="replicate",
| ... api_key="your-replicate-api-key", # Pass your Replicate API key directly
| ... )
| >>> audio = client.text_to_speech(
| ... text="Hello world",
| ... model="OuteAI/OuteTTS-0.3-500M",
| ... )
| >>> Path("hello_world.flac").write_bytes(audio)
| ```
|
| Example using a third-party provider through Hugging Face Routing. Usage will be billed on your Hugging Face account.
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient(
| ... provider="replicate",
| ... api_key="hf_...", # Pass your HF token
| ... )
| >>> audio =client.text_to_speech(
| ... text="Hello world",
| ... model="OuteAI/OuteTTS-0.3-500M",
| ... )
| >>> Path("hello_world.flac").write_bytes(audio)
| ```
| Example using Replicate provider with extra parameters
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient(
| ... provider="replicate", # Use replicate provider
| ... api_key="hf_...", # Pass your HF token
| ... )
| >>> audio = client.text_to_speech(
| ... "Hello, my name is Kororo, an awesome text-to-speech model.",
| ... model="hexgrad/Kokoro-82M",
| ... extra_body={"voice": "af_nicole"},
| ... )
| >>> Path("hello.flac").write_bytes(audio)
| ```
|
| Example music-gen using "YuE-s1-7B-anneal-en-cot" on fal.ai
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> lyrics = '''
| ... [verse]
| ... In the town where I was born
| ... Lived a man who sailed to sea
| ... And he told us of his life
| ... In the land of submarines
| ... So we sailed on to the sun
| ... 'Til we found a sea of green
| ... And we lived beneath the waves
| ... In our yellow submarine
|
| ... [chorus]
| ... We all live in a yellow submarine
| ... Yellow submarine, yellow submarine
| ... We all live in a yellow submarine
| ... Yellow submarine, yellow submarine
| ... '''
| >>> genres = "pavarotti-style tenor voice"
| >>> client = InferenceClient(
| ... provider="fal-ai",
| ... model="m-a-p/YuE-s1-7B-anneal-en-cot",
| ... api_key=...,
| ... )
| >>> audio = client.text_to_speech(lyrics, extra_body={"genres": genres})
| >>> with open("output.mp3", "wb") as f:
| ... f.write(audio)
| ```
|
| async text_to_video(self, prompt: str, *, model: str | None = None, guidance_scale: float | None = None, negative_prompt: list[str] | None = None, num_frames: float | None = None, num_inference_steps: int | None = None, seed: int | None = None, extra_body: dict[str, typing.Any] | None = None) -> bytes
| Generate a video based on a given text.
|
| > [!TIP]
| > You can pass provider-specific parameters to the model by using the `extra_body` argument.
|
| Args:
| prompt (`str`):
| The prompt to generate a video from.
| model (`str`, *optional*):
| The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. If not provided, the default recommended text-to-video model will be used.
| Defaults to None.
| guidance_scale (`float`, *optional*):
| A higher guidance scale value encourages the model to generate videos closely linked to the text
| prompt, but values too high may cause saturation and other artifacts.
| negative_prompt (`list[str]`, *optional*):
| One or several prompt to guide what NOT to include in video generation.
| num_frames (`float`, *optional*):
| The num_frames parameter determines how many video frames are generated.
| num_inference_steps (`int`, *optional*):
| The number of denoising steps. More denoising steps usually lead to a higher quality video at the
| expense of slower inference.
| seed (`int`, *optional*):
| Seed for the random number generator.
| extra_body (`dict[str, Any]`, *optional*):
| Additional provider-specific parameters to pass to the model. Refer to the provider's documentation
| for supported parameters.
|
| Returns:
| `bytes`: The generated video.
|
| Example:
|
| Example using a third-party provider directly. Usage will be billed on your fal.ai account.
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient(
| ... provider="fal-ai", # Using fal.ai provider
| ... api_key="fal-ai-api-key", # Pass your fal.ai API key
| ... )
| >>> video = client.text_to_video(
| ... "A majestic lion running in a fantasy forest",
| ... model="tencent/HunyuanVideo",
| ... )
| >>> with open("lion.mp4", "wb") as file:
| ... file.write(video)
| ```
|
| Example using a third-party provider through Hugging Face Routing. Usage will be billed on your Hugging Face account.
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient(
| ... provider="replicate", # Using replicate provider
| ... api_key="hf_...", # Pass your HF token
| ... )
| >>> video = client.text_to_video(
| ... "A cat running in a park",
| ... model="genmo/mochi-1-preview",
| ... )
| >>> with open("cat.mp4", "wb") as file:
| ... file.write(video)
| ```
|
| async token_classification(self, text: str, *, model: str | None = None, aggregation_strategy: Optional[ForwardRef('TokenClassificationAggregationStrategy')] = None, ignore_labels: list[str] | None = None, stride: int | None = None) -> list[huggingface_hub.inference._generated.types.token_classification.TokenClassificationOutputElement]
| Perform token classification on the given text.
| Usually used for sentence parsing, either grammatical, or Named Entity Recognition (NER) to understand keywords contained within text.
|
| Args:
| text (`str`):
| A string to be classified.
| model (`str`, *optional*):
| The model to use for the token classification task. Can be a model ID hosted on the Hugging Face Hub or a URL to
| a deployed Inference Endpoint. If not provided, the default recommended token classification model will be used.
| Defaults to None.
| aggregation_strategy (`"TokenClassificationAggregationStrategy"`, *optional*):
| The strategy used to fuse tokens based on model predictions
| ignore_labels (`list[str`, *optional*):
| A list of labels to ignore
| stride (`int`, *optional*):
| The number of overlapping tokens between chunks when splitting the input text.
|
| Returns:
| `list[TokenClassificationOutputElement]`: List of [`TokenClassificationOutputElement`] items containing the entity group, confidence score, word, start and end index.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
| >>> await client.token_classification("My name is Sarah Jessica Parker but you can call me Jessica")
| [
| TokenClassificationOutputElement(
| entity_group='PER',
| score=0.9971321225166321,
| word='Sarah Jessica Parker',
| start=11,
| end=31,
| ),
| TokenClassificationOutputElement(
| entity_group='PER',
| score=0.9773476123809814,
| word='Jessica',
| start=52,
| end=59,
| )
| ]
| ```
|
| async translation(self, text: str, *, model: str | None = None, src_lang: str | None = None, tgt_lang: str | None = None, clean_up_tokenization_spaces: bool | None = None, truncation: Optional[ForwardRef('TranslationTruncationStrategy')] = None, generate_parameters: dict[str, typing.Any] | None = None) -> huggingface_hub.inference._generated.types.translation.TranslationOutput
| Convert text from one language to another.
|
| Check out https://huggingface.co/tasks/translation for more information on how to choose the best model for
| your specific use case. Source and target languages usually depend on the model.
| However, it is possible to specify source and target languages for certain models. If you are working with one of these models,
| you can use `src_lang` and `tgt_lang` arguments to pass the relevant information.
|
| Args:
| text (`str`):
| A string to be translated.
| model (`str`, *optional*):
| The model to use for the translation task. Can be a model ID hosted on the Hugging Face Hub or a URL to
| a deployed Inference Endpoint. If not provided, the default recommended translation model will be used.
| Defaults to None.
| src_lang (`str`, *optional*):
| The source language of the text. Required for models that can translate from multiple languages.
| tgt_lang (`str`, *optional*):
| Target language to translate to. Required for models that can translate to multiple languages.
| clean_up_tokenization_spaces (`bool`, *optional*):
| Whether to clean up the potential extra spaces in the text output.
| truncation (`"TranslationTruncationStrategy"`, *optional*):
| The truncation strategy to use.
| generate_parameters (`dict[str, Any]`, *optional*):
| Additional parametrization of the text generation algorithm.
|
| Returns:
| [`TranslationOutput`]: The generated translated text.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
| `ValueError`:
| If only one of the `src_lang` and `tgt_lang` arguments are provided.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
| >>> await client.translation("My name is Wolfgang and I live in Berlin")
| 'Mein Name ist Wolfgang und ich lebe in Berlin.'
| >>> await client.translation("My name is Wolfgang and I live in Berlin", model="Helsinki-NLP/opus-mt-en-fr")
| TranslationOutput(translation_text='Je m'appelle Wolfgang et je vis à Berlin.')
| ```
|
| Specifying languages:
| ```py
| >>> client.translation("My name is Sarah Jessica Parker but you can call me Jessica", model="facebook/mbart-large-50-many-to-many-mmt", src_lang="en_XX", tgt_lang="fr_XX")
| "Mon nom est Sarah Jessica Parker mais vous pouvez m'appeler Jessica"
| ```
|
| async visual_question_answering(self, image: Union[bytes, BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], question: str, *, model: str | None = None, top_k: int | None = None) -> list[huggingface_hub.inference._generated.types.visual_question_answering.VisualQuestionAnsweringOutputElement]
| Answering open-ended questions based on an image.
|
| Args:
| image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`):
| The input image for the context. It can be raw bytes, an image file, a URL to an online image, or a PIL Image.
| question (`str`):
| Question to be answered.
| model (`str`, *optional*):
| The model to use for the visual question answering task. Can be a model ID hosted on the Hugging Face Hub or a URL to
| a deployed Inference Endpoint. If not provided, the default recommended visual question answering model will be used.
| Defaults to None.
| top_k (`int`, *optional*):
| The number of answers to return (will be chosen by order of likelihood). Note that we return less than
| topk answers if there are not enough options available within the context.
| Returns:
| `list[VisualQuestionAnsweringOutputElement]`: a list of [`VisualQuestionAnsweringOutputElement`] items containing the predicted label and associated probability.
|
| Raises:
| `InferenceTimeoutError`:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
| >>> await client.visual_question_answering(
| ... image="https://huggingface.co/datasets/mishig/sample_images/resolve/main/tiger.jpg",
| ... question="What is the animal doing?"
| ... )
| [
| VisualQuestionAnsweringOutputElement(score=0.778609573841095, answer='laying down'),
| VisualQuestionAnsweringOutputElement(score=0.6957435607910156, answer='sitting'),
| ]
| ```
|
| async zero_shot_classification(self, text: str, candidate_labels: list[str], *, multi_label: bool | None = False, hypothesis_template: str | None = None, model: str | None = None) -> list[huggingface_hub.inference._generated.types.zero_shot_classification.ZeroShotClassificationOutputElement]
| Provide as input a text and a set of candidate labels to classify the input text.
|
| Args:
| text (`str`):
| The input text to classify.
| candidate_labels (`list[str]`):
| The set of possible class labels to classify the text into.
| labels (`list[str]`, *optional*):
| (deprecated) List of strings. Each string is the verbalization of a possible label for the input text.
| multi_label (`bool`, *optional*):
| Whether multiple candidate labels can be true. If false, the scores are normalized such that the sum of
| the label likelihoods for each sequence is 1. If true, the labels are considered independent and
| probabilities are normalized for each candidate.
| hypothesis_template (`str`, *optional*):
| The sentence used in conjunction with `candidate_labels` to attempt the text classification by
| replacing the placeholder with the candidate labels.
| model (`str`, *optional*):
| The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. This parameter overrides the model defined at the instance level. If not provided, the default recommended zero-shot classification model will be used.
|
|
| Returns:
| `list[ZeroShotClassificationOutputElement]`: List of [`ZeroShotClassificationOutputElement`] items containing the predicted labels and their confidence.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example with `multi_label=False`:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
| >>> text = (
| ... "A new model offers an explanation for how the Galilean satellites formed around the solar system's"
| ... "largest world. Konstantin Batygin did not set out to solve one of the solar system's most puzzling"
| ... " mysteries when he went for a run up a hill in Nice, France."
| ... )
| >>> labels = ["space & cosmos", "scientific discovery", "microbiology", "robots", "archeology"]
| >>> await client.zero_shot_classification(text, labels)
| [
| ZeroShotClassificationOutputElement(label='scientific discovery', score=0.7961668968200684),
| ZeroShotClassificationOutputElement(label='space & cosmos', score=0.18570658564567566),
| ZeroShotClassificationOutputElement(label='microbiology', score=0.00730885099619627),
| ZeroShotClassificationOutputElement(label='archeology', score=0.006258360575884581),
| ZeroShotClassificationOutputElement(label='robots', score=0.004559356719255447),
| ]
| >>> await client.zero_shot_classification(text, labels, multi_label=True)
| [
| ZeroShotClassificationOutputElement(label='scientific discovery', score=0.9829297661781311),
| ZeroShotClassificationOutputElement(label='space & cosmos', score=0.755190908908844),
| ZeroShotClassificationOutputElement(label='microbiology', score=0.0005462635890580714),
| ZeroShotClassificationOutputElement(label='archeology', score=0.00047131875180639327),
| ZeroShotClassificationOutputElement(label='robots', score=0.00030448526376858354),
| ]
| ```
|
| Example with `multi_label=True` and a custom `hypothesis_template`:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
| >>> await client.zero_shot_classification(
| ... text="I really like our dinner and I'm very happy. I don't like the weather though.",
| ... labels=["positive", "negative", "pessimistic", "optimistic"],
| ... multi_label=True,
| ... hypothesis_template="This text is {} towards the weather"
| ... )
| [
| ZeroShotClassificationOutputElement(label='negative', score=0.9231801629066467),
| ZeroShotClassificationOutputElement(label='pessimistic', score=0.8760990500450134),
| ZeroShotClassificationOutputElement(label='optimistic', score=0.0008674879791215062),
| ZeroShotClassificationOutputElement(label='positive', score=0.0005250611575320363)
| ]
| ```
|
| async zero_shot_image_classification(self, image: Union[bytes, BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], candidate_labels: list[str], *, model: str | None = None, hypothesis_template: str | None = None, labels: list[str] = None) -> list[huggingface_hub.inference._generated.types.zero_shot_image_classification.ZeroShotImageClassificationOutputElement]
| Provide input image and text labels to predict text labels for the image.
|
| Args:
| image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`):
| The input image to caption. It can be raw bytes, an image file, a URL to an online image, or a PIL Image.
| candidate_labels (`list[str]`):
| The candidate labels for this image
| labels (`list[str]`, *optional*):
| (deprecated) List of string possible labels. There must be at least 2 labels.
| model (`str`, *optional*):
| The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. This parameter overrides the model defined at the instance level. If not provided, the default recommended zero-shot image classification model will be used.
| hypothesis_template (`str`, *optional*):
| The sentence used in conjunction with `candidate_labels` to attempt the image classification by
| replacing the placeholder with the candidate labels.
|
| Returns:
| `list[ZeroShotImageClassificationOutputElement]`: List of [`ZeroShotImageClassificationOutputElement`] items containing the predicted labels and their confidence.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| # Must be run in an async context
| >>> from huggingface_hub import AsyncInferenceClient
| >>> client = AsyncInferenceClient()
|
| >>> await client.zero_shot_image_classification(
| ... "https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg",
| ... labels=["dog", "cat", "horse"],
| ... )
| [ZeroShotImageClassificationOutputElement(label='dog', score=0.956),...]
| ```
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| chat
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'provider': typing.Union[typing.Literal['cerebras',...
huggingface-hub.AudioClassificationInput
Python Library Documentation: class AudioClassificationInput in module huggingface_hub.inference._generated.types.audio_classification
class AudioClassificationInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| AudioClassificationInput(inputs: str, parameters: huggingface_hub.inference._generated.types.audio_classification.AudioClassificationParameters | None = None) -> None
|
| Inputs for Audio Classification inference
|
| Method resolution order:
| AudioClassificationInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: str, parameters: huggingface_hub.inference._generated.types.audio_classification.AudioClassificationParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'str'>, 'parameters': huggingface_...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.AudioClassificationOutputElement
Python Library Documentation: class AudioClassificationOutputElement in module huggingface_hub.inference._generated.types.audio_classification
class AudioClassificationOutputElement(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| AudioClassificationOutputElement(label: str, score: float) -> None
|
| Outputs for Audio Classification inference
|
| Method resolution order:
| AudioClassificationOutputElement
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, label: str, score: float) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'label': <class 'str'>, 'score': <class 'float'>}
|
| __dataclass_fields__ = {'label': Field(name='label',type=<class 'str'>...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('label', 'score')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.AudioClassificationOutputTransform
Python Library Documentation: _LiteralGenericAlias in module typing
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
huggingface-hub.AudioClassificationParameters
Python Library Documentation: class AudioClassificationParameters in module huggingface_hub.inference._generated.types.audio_classification
class AudioClassificationParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| AudioClassificationParameters(function_to_apply: Optional[ForwardRef('AudioClassificationOutputTransform')] = None, top_k: int | None = None) -> None
|
| Additional inference parameters for Audio Classification
|
| Method resolution order:
| AudioClassificationParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, function_to_apply: Optional[ForwardRef('AudioClassificationOutputTransform')] = None, top_k: int | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'function_to_apply': typing.Optional[ForwardRef('Au...
|
| __dataclass_fields__ = {'function_to_apply': Field(name='function_to_a...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('function_to_apply', 'top_k')
|
| function_to_apply = None
|
| top_k = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.AudioToAudioInput
Python Library Documentation: class AudioToAudioInput in module huggingface_hub.inference._generated.types.audio_to_audio
class AudioToAudioInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| AudioToAudioInput(inputs: Any) -> None
|
| Inputs for Audio to Audio inference
|
| Method resolution order:
| AudioToAudioInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: Any) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': typing.Any}
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=typing.Any,...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs',)
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.AudioToAudioOutputElement
Python Library Documentation: class AudioToAudioOutputElement in module huggingface_hub.inference._generated.types.audio_to_audio
class AudioToAudioOutputElement(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| AudioToAudioOutputElement(blob: Any, content_type: str, label: str) -> None
|
| Outputs of inference for the Audio To Audio task
| A generated audio file with its label.
|
| Method resolution order:
| AudioToAudioOutputElement
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, blob: Any, content_type: str, label: str) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'blob': typing.Any, 'content_type': <class 'str'>, ...
|
| __dataclass_fields__ = {'blob': Field(name='blob',type=typing.Any,defa...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('blob', 'content_type', 'label')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.AutomaticSpeechRecognitionEarlyStoppingEnum
Python Library Documentation: _LiteralGenericAlias in module typing
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
huggingface-hub.AutomaticSpeechRecognitionGenerationParameters
Python Library Documentation: class AutomaticSpeechRecognitionGenerationParameters in module huggingface_hub.inference._generated.types.automatic_speech_recognition
class AutomaticSpeechRecognitionGenerationParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| AutomaticSpeechRecognitionGenerationParameters(do_sample: bool | None = None, early_stopping: Union[bool, ForwardRef('AutomaticSpeechRecognitionEarlyStoppingEnum'), NoneType] = None, epsilon_cutoff: float | None = None, eta_cutoff: float | None = None, max_length: int | None = None, max_new_tokens: int | None = None, min_length: int | None = None, min_new_tokens: int | None = None, num_beam_groups: int | None = None, num_beams: int | None = None, penalty_alpha: float | None = None, temperature: float | None = None, top_k: int | None = None, top_p: float | None = None, typical_p: float | None = None, use_cache: bool | None = None) -> None
|
| Parametrization of the text generation process
|
| Method resolution order:
| AutomaticSpeechRecognitionGenerationParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, do_sample: bool | None = None, early_stopping: Union[bool, ForwardRef('AutomaticSpeechRecognitionEarlyStoppingEnum'), NoneType] = None, epsilon_cutoff: float | None = None, eta_cutoff: float | None = None, max_length: int | None = None, max_new_tokens: int | None = None, min_length: int | None = None, min_new_tokens: int | None = None, num_beam_groups: int | None = None, num_beams: int | None = None, penalty_alpha: float | None = None, temperature: float | None = None, top_k: int | None = None, top_p: float | None = None, typical_p: float | None = None, use_cache: bool | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'do_sample': bool | None, 'early_stopping': typing....
|
| __dataclass_fields__ = {'do_sample': Field(name='do_sample',type=bool ...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('do_sample', 'early_stopping', 'epsilon_cutoff', 'et...
|
| do_sample = None
|
| early_stopping = None
|
| epsilon_cutoff = None
|
| eta_cutoff = None
|
| max_length = None
|
| max_new_tokens = None
|
| min_length = None
|
| min_new_tokens = None
|
| num_beam_groups = None
|
| num_beams = None
|
| penalty_alpha = None
|
| temperature = None
|
| top_k = None
|
| top_p = None
|
| typical_p = None
|
| use_cache = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.AutomaticSpeechRecognitionInput
Python Library Documentation: class AutomaticSpeechRecognitionInput in module huggingface_hub.inference._generated.types.automatic_speech_recognition
class AutomaticSpeechRecognitionInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| AutomaticSpeechRecognitionInput(inputs: str, parameters: huggingface_hub.inference._generated.types.automatic_speech_recognition.AutomaticSpeechRecognitionParameters | None = None) -> None
|
| Inputs for Automatic Speech Recognition inference
|
| Method resolution order:
| AutomaticSpeechRecognitionInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: str, parameters: huggingface_hub.inference._generated.types.automatic_speech_recognition.AutomaticSpeechRecognitionParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'str'>, 'parameters': huggingface_...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.AutomaticSpeechRecognitionOutput
Python Library Documentation: class AutomaticSpeechRecognitionOutput in module huggingface_hub.inference._generated.types.automatic_speech_recognition
class AutomaticSpeechRecognitionOutput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| AutomaticSpeechRecognitionOutput(text: str, chunks: list[huggingface_hub.inference._generated.types.automatic_speech_recognition.AutomaticSpeechRecognitionOutputChunk] | None = None) -> None
|
| Outputs of inference for the Automatic Speech Recognition task
|
| Method resolution order:
| AutomaticSpeechRecognitionOutput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, text: str, chunks: list[huggingface_hub.inference._generated.types.automatic_speech_recognition.AutomaticSpeechRecognitionOutputChunk] | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'chunks': list[huggingface_hub.inference._generated...
|
| __dataclass_fields__ = {'chunks': Field(name='chunks',type=list[huggin...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('text', 'chunks')
|
| chunks = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.AutomaticSpeechRecognitionOutputChunk
Python Library Documentation: class AutomaticSpeechRecognitionOutputChunk in module huggingface_hub.inference._generated.types.automatic_speech_recognition
class AutomaticSpeechRecognitionOutputChunk(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| AutomaticSpeechRecognitionOutputChunk(text: str, timestamp: list[float]) -> None
|
| AutomaticSpeechRecognitionOutputChunk(text: str, timestamp: list[float])
|
| Method resolution order:
| AutomaticSpeechRecognitionOutputChunk
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, text: str, timestamp: list[float]) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'text': <class 'str'>, 'timestamp': list[float]}
|
| __dataclass_fields__ = {'text': Field(name='text',type=<class 'str'>,d...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('text', 'timestamp')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.AutomaticSpeechRecognitionParameters
Python Library Documentation: class AutomaticSpeechRecognitionParameters in module huggingface_hub.inference._generated.types.automatic_speech_recognition
class AutomaticSpeechRecognitionParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| AutomaticSpeechRecognitionParameters(generation_parameters: huggingface_hub.inference._generated.types.automatic_speech_recognition.AutomaticSpeechRecognitionGenerationParameters | None = None, return_timestamps: bool | None = None) -> None
|
| Additional inference parameters for Automatic Speech Recognition
|
| Method resolution order:
| AutomaticSpeechRecognitionParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, generation_parameters: huggingface_hub.inference._generated.types.automatic_speech_recognition.AutomaticSpeechRecognitionGenerationParameters | None = None, return_timestamps: bool | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'generation_parameters': huggingface_hub.inference....
|
| __dataclass_fields__ = {'generation_parameters': Field(name='generatio...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('generation_parameters', 'return_timestamps')
|
| generation_parameters = None
|
| return_timestamps = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.BucketFile
Python Library Documentation: class BucketFile in module huggingface_hub._buckets
class BucketFile(builtins.object)
| BucketFile(**kwargs)
|
| Contains information about a file in a bucket on the Hub. This object is returned by [`list_bucket_tree`].
|
| Similar to [`RepoFile`] but for files in buckets.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'mtime': datetime.datetime | None, 'path': <class '...
|
| __dataclass_fields__ = {'mtime': Field(name='mtime',type=datetime.date...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('type', 'path', 'size', 'xet_hash', 'mtime', 'upload...
huggingface-hub.BucketFileMetadata
Python Library Documentation: class BucketFileMetadata in module huggingface_hub._buckets
class BucketFileMetadata(builtins.object)
| BucketFileMetadata(size: int, xet_file_data: huggingface_hub.utils._xet.XetFileData) -> None
|
| Data structure containing information about a file in a bucket.
|
| Returned by [`get_bucket_file_metadata`].
|
| Args:
| size (`int`):
| Size of the file in bytes.
| xet_file_data (`XetFileData`):
| Xet information for the file (hash and refresh route).
|
| Methods defined here:
|
| __delattr__(self, name)
| Implement delattr(self, name).
|
| __eq__(self, other)
| Return self==value.
|
| __hash__(self)
| Return hash(self).
|
| __init__(self, size: int, xet_file_data: huggingface_hub.utils._xet.XetFileData) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| __setattr__(self, name, value)
| Implement setattr(self, name, value).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'size': <class 'int'>, 'xet_file_data': <class 'hug...
|
| __dataclass_fields__ = {'size': Field(name='size',type=<class 'int'>,d...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __match_args__ = ('size', 'xet_file_data')
huggingface-hub.BucketFolder
Python Library Documentation: class BucketFolder in module huggingface_hub._buckets
class BucketFolder(builtins.object)
| BucketFolder(**kwargs)
|
| Contains information about a directory in a bucket on the Hub. This object is returned by [`list_bucket_tree`].
|
| Similar to [`RepoFolder`] but for directories in buckets.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'path': <class 'str'>, 'type': typing.Literal['dire...
|
| __dataclass_fields__ = {'path': Field(name='path',type=<class 'str'>,d...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('type', 'path', 'uploaded_at')
huggingface-hub.BucketInfo
Python Library Documentation: class BucketInfo in module huggingface_hub._buckets
class BucketInfo(builtins.object)
| BucketInfo(**kwargs)
|
| Contains information about a bucket on the Hub. This object is returned by [`bucket_info`] and [`list_buckets`].
|
| Attributes:
| id (`str`):
| ID of the bucket.
| private (`bool`):
| Is the bucket private.
| created_at (`datetime`):
| Date of creation of the bucket on the Hub.
| size (`int`):
| Size of the bucket in bytes.
| total_files (`int`):
| Total number of files in the bucket.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'created_at': <class 'datetime.datetime'>, 'id': <c...
|
| __dataclass_fields__ = {'created_at': Field(name='created_at',type=<cl...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('id', 'private', 'created_at', 'size', 'total_files'...
huggingface-hub.BucketUrl
Python Library Documentation: class BucketUrl in module huggingface_hub._buckets
class BucketUrl(builtins.object)
| BucketUrl(url: str, endpoint: str = '') -> None
|
| Describes a bucket URL on the Hub.
|
| `BucketUrl` is returned by [`create_bucket`]. At initialization, the URL is parsed to populate properties:
| - endpoint (`str`)
| - namespace (`str`)
| - bucket_id (`str`)
| - url (`str`)
| - uri (`HfUri`)
|
| Args:
| url (`str`):
| String value of the bucket url.
| endpoint (`str`, *optional*):
| Endpoint of the Hub. Defaults to <https://huggingface.co>.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, url: str, endpoint: str = '') -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __post_init__(self) -> None
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'bucket_id': <class 'str'>, 'endpoint': <class 'str...
|
| __dataclass_fields__ = {'bucket_id': Field(name='bucket_id',type=<clas...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('url', 'endpoint')
|
| endpoint = ''
huggingface-hub.CLIENT_FACTORY_T
Python Library Documentation: _CallableGenericAlias in module collections.abc
class Callable(builtins.object)
| Methods defined here:
|
| __call__(self, *args, **kwds)
| Call self as a function.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__ = _CallableGenericAlias(args)
| Represent `Callable[argtypes, resulttype]`.
|
| This sets ``__args__`` to a tuple containing the flattened ``argtypes``
| followed by ``resulttype``.
|
| Example: ``Callable[[int, str], float]`` sets ``__args__`` to
| ``(int, str, float)``.
|
| __subclasshook__(C)
| Abstract classes can override this to customize issubclass().
|
| This is invoked early on by abc.ABCMeta.__subclasscheck__().
| It should return True, False or NotImplemented. If it returns
| NotImplemented, the normal algorithm is used. Otherwise, it
| overrides the normal algorithm (and the outcome is cached).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__call__'})
huggingface-hub.CONFIG_NAME
Error rendering doc: No Python documentation found for 'config.json'. Use help() to get the interactive help utility. Use help(str) for help on the str class.
huggingface-hub.CacheNotFound
Python Library Documentation: class CacheNotFound in module huggingface_hub.errors
class CacheNotFound(builtins.Exception)
| CacheNotFound(msg: str, cache_dir: str | pathlib.Path, *args, **kwargs)
|
| Exception thrown when the Huggingface cache is not found.
|
| Method resolution order:
| CacheNotFound
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, msg: str, cache_dir: str | pathlib.Path, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'cache_dir': str | pathlib.Path}
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
huggingface-hub.CachedFileInfo
Python Library Documentation: class CachedFileInfo in module huggingface_hub.utils._cache_manager
class CachedFileInfo(builtins.object)
| CachedFileInfo(file_name: str, file_path: pathlib.Path, blob_path: pathlib.Path, size_on_disk: int, blob_last_accessed: float, blob_last_modified: float) -> None
|
| Frozen data structure holding information about a single cached file.
|
| Args:
| file_name (`str`):
| Name of the file. Example: `config.json`.
| file_path (`Path`):
| Path of the file in the `snapshots` directory. The file path is a symlink
| referring to a blob in the `blobs` folder.
| blob_path (`Path`):
| Path of the blob file. This is equivalent to `file_path.resolve()`.
| size_on_disk (`int`):
| Size of the blob file in bytes.
| blob_last_accessed (`float`):
| Timestamp of the last time the blob file has been accessed (from any
| revision).
| blob_last_modified (`float`):
| Timestamp of the last time the blob file has been modified/created.
|
| > [!WARNING]
| > `blob_last_accessed` and `blob_last_modified` reliability can depend on the OS you
| > are using. See [python documentation](https://docs.python.org/3/library/os.html#os.stat_result)
| > for more details.
|
| Methods defined here:
|
| __delattr__(self, name)
| Implement delattr(self, name).
|
| __eq__(self, other)
| Return self==value.
|
| __hash__(self)
| Return hash(self).
|
| __init__(self, file_name: str, file_path: pathlib.Path, blob_path: pathlib.Path, size_on_disk: int, blob_last_accessed: float, blob_last_modified: float) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| __setattr__(self, name, value)
| Implement setattr(self, name, value).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| blob_last_accessed_str
| (property) Timestamp of the last time the blob file has been accessed (from any
| revision), returned as a human-readable string.
|
| Example: "2 weeks ago".
|
| blob_last_modified_str
| (property) Timestamp of the last time the blob file has been modified, returned
| as a human-readable string.
|
| Example: "2 weeks ago".
|
| size_on_disk_str
| (property) Size of the blob file as a human-readable string.
|
| Example: "42.2K".
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'blob_last_accessed': <class 'float'>, 'blob_last_m...
|
| __dataclass_fields__ = {'blob_last_accessed': Field(name='blob_last_ac...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __match_args__ = ('file_name', 'file_path', 'blob_path', 'size_on_disk...
huggingface-hub.CachedIncompleteFileInfo
Python Library Documentation: class CachedIncompleteFileInfo in module huggingface_hub.utils._cache_manager
class CachedIncompleteFileInfo(builtins.object)
| CachedIncompleteFileInfo(file_path: pathlib.Path, size_on_disk: int) -> None
|
| Frozen data structure holding information about a single incomplete download.
|
| Interrupted downloads leave `<cache>/<repo>/blobs/<etag>.incomplete` files behind.
| These are not part of any committed revision, so they are surfaced separately by
| [`scan_cache_dir`].
|
| Args:
| file_path (`Path`):
| Path of the `.incomplete` file in the `blobs` folder.
| size_on_disk (`int`):
| Size of the partially-downloaded file in bytes.
|
| Methods defined here:
|
| __delattr__(self, name)
| Implement delattr(self, name).
|
| __eq__(self, other)
| Return self==value.
|
| __hash__(self)
| Return hash(self).
|
| __init__(self, file_path: pathlib.Path, size_on_disk: int) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| __setattr__(self, name, value)
| Implement setattr(self, name, value).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'file_path': <class 'pathlib.Path'>, 'size_on_disk'...
|
| __dataclass_fields__ = {'file_path': Field(name='file_path',type=<clas...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __match_args__ = ('file_path', 'size_on_disk')
huggingface-hub.CachedRepoInfo
Python Library Documentation: class CachedRepoInfo in module huggingface_hub.utils._cache_manager
class CachedRepoInfo(builtins.object)
| CachedRepoInfo(repo_id: str, repo_type: Literal['model', 'dataset', 'space'], repo_path: pathlib.Path, size_on_disk: int, nb_files: int, revisions: frozenset[huggingface_hub.utils._cache_manager.CachedRevisionInfo], last_accessed: float, last_modified: float) -> None
|
| Frozen data structure holding information about a cached repository.
|
| Args:
| repo_id (`str`):
| Repo id of the repo on the Hub. Example: `"google/fleurs"`.
| repo_type (`Literal["dataset", "model", "space"]`):
| Type of the cached repo.
| repo_path (`Path`):
| Local path to the cached repo.
| size_on_disk (`int`):
| Sum of the blob file sizes in the cached repo.
| nb_files (`int`):
| Total number of blob files in the cached repo.
| revisions (`frozenset[CachedRevisionInfo]`):
| Set of [`~CachedRevisionInfo`] describing all revisions cached in the repo.
| last_accessed (`float`):
| Timestamp of the last time a blob file of the repo has been accessed.
| last_modified (`float`):
| Timestamp of the last time a blob file of the repo has been modified/created.
|
| > [!WARNING]
| > `size_on_disk` is not necessarily the sum of all revisions sizes because of
| > duplicated files. Besides, only blobs are taken into account, not the (negligible)
| > size of folders and symlinks.
|
| > [!WARNING]
| > `last_accessed` and `last_modified` reliability can depend on the OS you are using.
| > See [python documentation](https://docs.python.org/3/library/os.html#os.stat_result)
| > for more details.
|
| Methods defined here:
|
| __delattr__(self, name)
| Implement delattr(self, name).
|
| __eq__(self, other)
| Return self==value.
|
| __hash__(self)
| Return hash(self).
|
| __init__(self, repo_id: str, repo_type: Literal['model', 'dataset', 'space'], repo_path: pathlib.Path, size_on_disk: int, nb_files: int, revisions: frozenset[huggingface_hub.utils._cache_manager.CachedRevisionInfo], last_accessed: float, last_modified: float) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| __setattr__(self, name, value)
| Implement setattr(self, name, value).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| cache_id
| Canonical `type/id` identifier used across cache tooling.
|
| last_accessed_str
| (property) Last time a blob file of the repo has been accessed, returned as a
| human-readable string.
|
| Example: "2 weeks ago".
|
| last_modified_str
| (property) Last time a blob file of the repo has been modified, returned as a
| human-readable string.
|
| Example: "2 weeks ago".
|
| refs
| (property) Mapping between `refs` and revision data structures.
|
| size_on_disk_str
| (property) Sum of the blob file sizes as a human-readable string.
|
| Example: "42.2K".
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'last_accessed': <class 'float'>, 'last_modified': ...
|
| __dataclass_fields__ = {'last_accessed': Field(name='last_accessed',ty...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __match_args__ = ('repo_id', 'repo_type', 'repo_path', 'size_on_disk',...
huggingface-hub.CachedRevisionInfo
Python Library Documentation: class CachedRevisionInfo in module huggingface_hub.utils._cache_manager
class CachedRevisionInfo(builtins.object)
| CachedRevisionInfo(commit_hash: str, snapshot_path: pathlib.Path, size_on_disk: int, files: frozenset[huggingface_hub.utils._cache_manager.CachedFileInfo], refs: frozenset[str], last_modified: float) -> None
|
| Frozen data structure holding information about a revision.
|
| A revision correspond to a folder in the `snapshots` folder and is populated with
| the exact tree structure as the repo on the Hub but contains only symlinks. A
| revision can be either referenced by 1 or more `refs` or be "detached" (no refs).
|
| Args:
| commit_hash (`str`):
| Hash of the revision (unique).
| Example: `"9338f7b671827df886678df2bdd7cc7b4f36dffd"`.
| snapshot_path (`Path`):
| Path to the revision directory in the `snapshots` folder. It contains the
| exact tree structure as the repo on the Hub.
| files: (`frozenset[CachedFileInfo]`):
| Set of [`~CachedFileInfo`] describing all files contained in the snapshot.
| refs (`frozenset[str]`):
| Set of `refs` pointing to this revision. If the revision has no `refs`, it
| is considered detached.
| Example: `{"main", "2.4.0"}` or `{"refs/pr/1"}`.
| size_on_disk (`int`):
| Sum of the blob file sizes that are symlink-ed by the revision.
| last_modified (`float`):
| Timestamp of the last time the revision has been created/modified.
|
| > [!WARNING]
| > `last_accessed` cannot be determined correctly on a single revision as blob files
| > are shared across revisions.
|
| > [!WARNING]
| > `size_on_disk` is not necessarily the sum of all file sizes because of possible
| > duplicated files. Besides, only blobs are taken into account, not the (negligible)
| > size of folders and symlinks.
|
| Methods defined here:
|
| __delattr__(self, name)
| Implement delattr(self, name).
|
| __eq__(self, other)
| Return self==value.
|
| __hash__(self)
| Return hash(self).
|
| __init__(self, commit_hash: str, snapshot_path: pathlib.Path, size_on_disk: int, files: frozenset[huggingface_hub.utils._cache_manager.CachedFileInfo], refs: frozenset[str], last_modified: float) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| __setattr__(self, name, value)
| Implement setattr(self, name, value).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| last_modified_str
| (property) Timestamp of the last time the revision has been modified, returned
| as a human-readable string.
|
| Example: "2 weeks ago".
|
| nb_files
| (property) Total number of files in the revision.
|
| size_on_disk_str
| (property) Sum of the blob file sizes as a human-readable string.
|
| Example: "42.2K".
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'commit_hash': <class 'str'>, 'files': frozenset[hu...
|
| __dataclass_fields__ = {'commit_hash': Field(name='commit_hash',type=<...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __match_args__ = ('commit_hash', 'snapshot_path', 'size_on_disk', 'fil...
huggingface-hub.CardData
Python Library Documentation: class CardData in module huggingface_hub.repocard_data
class CardData(builtins.object)
| CardData(ignore_metadata_errors: bool = False, **kwargs)
|
| 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). `CardData` behaves as a dictionary (can get, pop, set values) but do not
| inherit from `dict` to allow this export step.
|
| Methods defined here:
|
| __contains__(self, key: str) -> bool
| Check if a given metadata key is set.
|
| __eq__(self, other)
| Return self==value.
|
| __getitem__(self, key: str) -> Any
| Get value for a given metadata key.
|
| __init__(self, ignore_metadata_errors: bool = False, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __len__(self) -> int
| Return the number of metadata keys set.
|
| __repr__(self)
| Return repr(self).
|
| __setitem__(self, key: str, value: Any) -> None
| Set value for a given metadata key.
|
| __str__(self)
| Return str(self).
|
| get(self, key: str, default: Any = None) -> Any
| Get value for a given metadata key.
|
| pop(self, key: str, default: Any = None) -> Any
| Pop value for a given metadata key.
|
| to_dict(self)
| Converts CardData to a dict.
|
| Returns:
| `dict`: CardData represented as a dictionary ready to be dumped to a YAML
| block for inclusion in a README.md file.
|
| to_yaml(self, line_break=None, original_order: list[str] | None = None) -> str
| Dumps CardData to a YAML block for inclusion in a README.md file.
|
| Args:
| line_break (str, *optional*):
| The line break to use when dumping to yaml.
| original_order (`list[str]`, *optional*):
| If provided, reorder the metadata fields to match this list before dumping.
| Any keys not in `original_order` are appended after the listed keys, preserving
| their existing relative order. Useful for round-tripping a YAML block without
| shuffling its keys.
|
| Returns:
| `str`: CardData represented as a YAML block.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __dataclass_fields__ = {}
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ()
huggingface-hub.ChatCompletionInput
Python Library Documentation: class ChatCompletionInput in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionInput(messages: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputMessage], frequency_penalty: float | None = None, logit_bias: list[float] | None = None, logprobs: bool | None = None, max_tokens: int | None = None, model: str | None = None, n: int | None = None, presence_penalty: float | None = None, response_format: Union[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputResponseFormatText, huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputResponseFormatJSONSchema, huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputResponseFormatJSONObject, NoneType] = None, seed: int | None = None, stop: list[str] | None = None, stream: bool | None = None, stream_options: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputStreamOptions | None = None, temperature: float | None = None, tool_choice: Union[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputToolChoiceClass, ForwardRef('ChatCompletionInputToolChoiceEnum'), NoneType] = None, tool_prompt: str | None = None, tools: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputTool] | None = None, top_logprobs: int | None = None, top_p: float | None = None) -> None
|
| Chat Completion Input.
| Auto-generated from TGI specs.
| For more details, check out
| https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tgi-import.ts.
|
| Method resolution order:
| ChatCompletionInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, messages: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputMessage], frequency_penalty: float | None = None, logit_bias: list[float] | None = None, logprobs: bool | None = None, max_tokens: int | None = None, model: str | None = None, n: int | None = None, presence_penalty: float | None = None, response_format: Union[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputResponseFormatText, huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputResponseFormatJSONSchema, huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputResponseFormatJSONObject, NoneType] = None, seed: int | None = None, stop: list[str] | None = None, stream: bool | None = None, stream_options: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputStreamOptions | None = None, temperature: float | None = None, tool_choice: Union[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputToolChoiceClass, ForwardRef('ChatCompletionInputToolChoiceEnum'), NoneType] = None, tool_prompt: str | None = None, tools: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputTool] | None = None, top_logprobs: int | None = None, top_p: float | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'frequency_penalty': float | None, 'logit_bias': li...
|
| __dataclass_fields__ = {'frequency_penalty': Field(name='frequency_pen...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('messages', 'frequency_penalty', 'logit_bias', 'logp...
|
| frequency_penalty = None
|
| logit_bias = None
|
| logprobs = None
|
| max_tokens = None
|
| model = None
|
| n = None
|
| presence_penalty = None
|
| response_format = None
|
| seed = None
|
| stop = None
|
| stream = None
|
| stream_options = None
|
| temperature = None
|
| tool_choice = None
|
| tool_prompt = None
|
| tools = None
|
| top_logprobs = None
|
| top_p = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionInputFunctionDefinition
Python Library Documentation: class ChatCompletionInputFunctionDefinition in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionInputFunctionDefinition(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionInputFunctionDefinition(name: str, parameters: Any, description: str | None = None) -> None
|
| ChatCompletionInputFunctionDefinition(name: str, parameters: Any, description: str | None = None)
|
| Method resolution order:
| ChatCompletionInputFunctionDefinition
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, name: str, parameters: Any, description: str | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'description': str | None, 'name': <class 'str'>, '...
|
| __dataclass_fields__ = {'description': Field(name='description',type=s...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('name', 'parameters', 'description')
|
| description = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionInputFunctionName
Python Library Documentation: class ChatCompletionInputFunctionName in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionInputFunctionName(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionInputFunctionName(name: str) -> None
|
| ChatCompletionInputFunctionName(name: str)
|
| Method resolution order:
| ChatCompletionInputFunctionName
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, name: str) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'name': <class 'str'>}
|
| __dataclass_fields__ = {'name': Field(name='name',type=<class 'str'>,d...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('name',)
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionInputGrammarType
Python Library Documentation: _UnionGenericAlias in module typing
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
huggingface-hub.ChatCompletionInputJSONSchema
Python Library Documentation: class ChatCompletionInputJSONSchema in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionInputJSONSchema(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionInputJSONSchema(name: str, description: str | None = None, schema: dict[str, object] | None = None, strict: bool | None = None) -> None
|
| ChatCompletionInputJSONSchema(name: str, description: str | None = None, schema: dict[str, object] | None = None, strict: bool | None = None)
|
| Method resolution order:
| ChatCompletionInputJSONSchema
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, name: str, description: str | None = None, schema: dict[str, object] | None = None, strict: bool | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'description': str | None, 'name': <class 'str'>, '...
|
| __dataclass_fields__ = {'description': Field(name='description',type=s...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('name', 'description', 'schema', 'strict')
|
| description = None
|
| schema = None
|
| strict = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionInputMessage
Python Library Documentation: class ChatCompletionInputMessage in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionInputMessage(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionInputMessage(role: str, content: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputMessageChunk] | str | None = None, name: str | None = None, tool_calls: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputToolCall] | None = None) -> None
|
| ChatCompletionInputMessage(role: str, content: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputMessageChunk] | str | None = None, name: str | None = None, tool_calls: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputToolCall] | None = None)
|
| Method resolution order:
| ChatCompletionInputMessage
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, role: str, content: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputMessageChunk] | str | None = None, name: str | None = None, tool_calls: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputToolCall] | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'content': list[huggingface_hub.inference._generate...
|
| __dataclass_fields__ = {'content': Field(name='content',type=list[hugg...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('role', 'content', 'name', 'tool_calls')
|
| content = None
|
| name = None
|
| tool_calls = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionInputMessageChunk
Python Library Documentation: class ChatCompletionInputMessageChunk in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionInputMessageChunk(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionInputMessageChunk(type: 'ChatCompletionInputMessageChunkType', image_url: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputURL | None = None, text: str | None = None) -> None
|
| ChatCompletionInputMessageChunk(type: 'ChatCompletionInputMessageChunkType', image_url: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputURL | None = None, text: str | None = None)
|
| Method resolution order:
| ChatCompletionInputMessageChunk
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, type: 'ChatCompletionInputMessageChunkType', image_url: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputURL | None = None, text: str | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'image_url': huggingface_hub.inference._generated.t...
|
| __dataclass_fields__ = {'image_url': Field(name='image_url',type=huggi...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('type', 'image_url', 'text')
|
| image_url = None
|
| text = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionInputMessageChunkType
Python Library Documentation: _LiteralGenericAlias in module typing
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
huggingface-hub.ChatCompletionInputResponseFormatJSONObject
Python Library Documentation: class ChatCompletionInputResponseFormatJSONObject in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionInputResponseFormatJSONObject(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionInputResponseFormatJSONObject(type: Literal['json_object']) -> None
|
| ChatCompletionInputResponseFormatJSONObject(type: Literal['json_object'])
|
| Method resolution order:
| ChatCompletionInputResponseFormatJSONObject
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, type: Literal['json_object']) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'type': typing.Literal['json_object']}
|
| __dataclass_fields__ = {'type': Field(name='type',type=typing.Literal[...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('type',)
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionInputResponseFormatJSONSchema
Python Library Documentation: class ChatCompletionInputResponseFormatJSONSchema in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionInputResponseFormatJSONSchema(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionInputResponseFormatJSONSchema(type: Literal['json_schema'], json_schema: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputJSONSchema) -> None
|
| ChatCompletionInputResponseFormatJSONSchema(type: Literal['json_schema'], json_schema: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputJSONSchema)
|
| Method resolution order:
| ChatCompletionInputResponseFormatJSONSchema
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, type: Literal['json_schema'], json_schema: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputJSONSchema) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'json_schema': <class 'huggingface_hub.inference._g...
|
| __dataclass_fields__ = {'json_schema': Field(name='json_schema',type=<...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('type', 'json_schema')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionInputResponseFormatText
Python Library Documentation: class ChatCompletionInputResponseFormatText in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionInputResponseFormatText(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionInputResponseFormatText(type: Literal['text']) -> None
|
| ChatCompletionInputResponseFormatText(type: Literal['text'])
|
| Method resolution order:
| ChatCompletionInputResponseFormatText
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, type: Literal['text']) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'type': typing.Literal['text']}
|
| __dataclass_fields__ = {'type': Field(name='type',type=typing.Literal[...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('type',)
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionInputStreamOptions
Python Library Documentation: class ChatCompletionInputStreamOptions in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionInputStreamOptions(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionInputStreamOptions(include_usage: bool | None = None) -> None
|
| ChatCompletionInputStreamOptions(include_usage: bool | None = None)
|
| Method resolution order:
| ChatCompletionInputStreamOptions
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, include_usage: bool | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'include_usage': bool | None}
|
| __dataclass_fields__ = {'include_usage': Field(name='include_usage',ty...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('include_usage',)
|
| include_usage = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionInputTool
Python Library Documentation: class ChatCompletionInputTool in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionInputTool(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionInputTool(function: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputFunctionDefinition, type: str) -> None
|
| ChatCompletionInputTool(function: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputFunctionDefinition, type: str)
|
| Method resolution order:
| ChatCompletionInputTool
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, function: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputFunctionDefinition, type: str) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'function': <class 'huggingface_hub.inference._gene...
|
| __dataclass_fields__ = {'function': Field(name='function',type=<class ...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('function', 'type')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionInputToolCall
Python Library Documentation: class ChatCompletionInputToolCall in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionInputToolCall(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionInputToolCall(function: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputFunctionDefinition, id: str, type: str) -> None
|
| ChatCompletionInputToolCall(function: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputFunctionDefinition, id: str, type: str)
|
| Method resolution order:
| ChatCompletionInputToolCall
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, function: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputFunctionDefinition, id: str, type: str) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'function': <class 'huggingface_hub.inference._gene...
|
| __dataclass_fields__ = {'function': Field(name='function',type=<class ...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('function', 'id', 'type')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionInputToolChoiceClass
Python Library Documentation: class ChatCompletionInputToolChoiceClass in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionInputToolChoiceClass(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionInputToolChoiceClass(function: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputFunctionName) -> None
|
| ChatCompletionInputToolChoiceClass(function: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputFunctionName)
|
| Method resolution order:
| ChatCompletionInputToolChoiceClass
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, function: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputFunctionName) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'function': <class 'huggingface_hub.inference._gene...
|
| __dataclass_fields__ = {'function': Field(name='function',type=<class ...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('function',)
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionInputToolChoiceEnum
Python Library Documentation: _LiteralGenericAlias in module typing
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
huggingface-hub.ChatCompletionInputURL
Python Library Documentation: class ChatCompletionInputURL in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionInputURL(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionInputURL(url: str) -> None
|
| ChatCompletionInputURL(url: str)
|
| Method resolution order:
| ChatCompletionInputURL
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, url: str) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'url': <class 'str'>}
|
| __dataclass_fields__ = {'url': Field(name='url',type=<class 'str'>,def...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('url',)
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionOutput
Python Library Documentation: class ChatCompletionOutput in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionOutput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionOutput(choices: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionOutputComplete], created: int, id: str, model: str, system_fingerprint: str, usage: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionOutputUsage) -> None
|
| Chat Completion Output.
| Auto-generated from TGI specs.
| For more details, check out
| https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tgi-import.ts.
|
| Method resolution order:
| ChatCompletionOutput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, choices: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionOutputComplete], created: int, id: str, model: str, system_fingerprint: str, usage: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionOutputUsage) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'choices': list[huggingface_hub.inference._generate...
|
| __dataclass_fields__ = {'choices': Field(name='choices',type=list[hugg...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('choices', 'created', 'id', 'model', 'system_fingerp...
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionOutputComplete
Python Library Documentation: class ChatCompletionOutputComplete in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionOutputComplete(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionOutputComplete(finish_reason: str, index: int, message: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionOutputMessage, logprobs: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionOutputLogprobs | None = None) -> None
|
| ChatCompletionOutputComplete(finish_reason: str, index: int, message: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionOutputMessage, logprobs: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionOutputLogprobs | None = None)
|
| Method resolution order:
| ChatCompletionOutputComplete
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, finish_reason: str, index: int, message: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionOutputMessage, logprobs: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionOutputLogprobs | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'finish_reason': <class 'str'>, 'index': <class 'in...
|
| __dataclass_fields__ = {'finish_reason': Field(name='finish_reason',ty...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('finish_reason', 'index', 'message', 'logprobs')
|
| logprobs = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionOutputFunctionDefinition
Python Library Documentation: class ChatCompletionOutputFunctionDefinition in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionOutputFunctionDefinition(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionOutputFunctionDefinition(arguments: str, name: str, description: str | None = None) -> None
|
| ChatCompletionOutputFunctionDefinition(arguments: str, name: str, description: str | None = None)
|
| Method resolution order:
| ChatCompletionOutputFunctionDefinition
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, arguments: str, name: str, description: str | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'arguments': <class 'str'>, 'description': str | No...
|
| __dataclass_fields__ = {'arguments': Field(name='arguments',type=<clas...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('arguments', 'name', 'description')
|
| description = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionOutputLogprob
Python Library Documentation: class ChatCompletionOutputLogprob in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionOutputLogprob(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionOutputLogprob(logprob: float, token: str, top_logprobs: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionOutputTopLogprob]) -> None
|
| ChatCompletionOutputLogprob(logprob: float, token: str, top_logprobs: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionOutputTopLogprob])
|
| Method resolution order:
| ChatCompletionOutputLogprob
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, logprob: float, token: str, top_logprobs: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionOutputTopLogprob]) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'logprob': <class 'float'>, 'token': <class 'str'>,...
|
| __dataclass_fields__ = {'logprob': Field(name='logprob',type=<class 'f...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('logprob', 'token', 'top_logprobs')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionOutputLogprobs
Python Library Documentation: class ChatCompletionOutputLogprobs in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionOutputLogprobs(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionOutputLogprobs(content: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionOutputLogprob]) -> None
|
| ChatCompletionOutputLogprobs(content: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionOutputLogprob])
|
| Method resolution order:
| ChatCompletionOutputLogprobs
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, content: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionOutputLogprob]) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'content': list[huggingface_hub.inference._generate...
|
| __dataclass_fields__ = {'content': Field(name='content',type=list[hugg...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('content',)
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionOutputMessage
Python Library Documentation: class ChatCompletionOutputMessage in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionOutputMessage(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionOutputMessage(role: str, content: str | None = None, reasoning: str | None = None, tool_call_id: str | None = None, tool_calls: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionOutputToolCall] | None = None) -> None
|
| ChatCompletionOutputMessage(role: str, content: str | None = None, reasoning: str | None = None, tool_call_id: str | None = None, tool_calls: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionOutputToolCall] | None = None)
|
| Method resolution order:
| ChatCompletionOutputMessage
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, role: str, content: str | None = None, reasoning: str | None = None, tool_call_id: str | None = None, tool_calls: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionOutputToolCall] | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'content': str | None, 'reasoning': str | None, 'ro...
|
| __dataclass_fields__ = {'content': Field(name='content',type=str | Non...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('role', 'content', 'reasoning', 'tool_call_id', 'too...
|
| content = None
|
| reasoning = None
|
| tool_call_id = None
|
| tool_calls = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionOutputToolCall
Python Library Documentation: class ChatCompletionOutputToolCall in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionOutputToolCall(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionOutputToolCall(function: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionOutputFunctionDefinition, id: str, type: str) -> None
|
| ChatCompletionOutputToolCall(function: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionOutputFunctionDefinition, id: str, type: str)
|
| Method resolution order:
| ChatCompletionOutputToolCall
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, function: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionOutputFunctionDefinition, id: str, type: str) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'function': <class 'huggingface_hub.inference._gene...
|
| __dataclass_fields__ = {'function': Field(name='function',type=<class ...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('function', 'id', 'type')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionOutputTopLogprob
Python Library Documentation: class ChatCompletionOutputTopLogprob in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionOutputTopLogprob(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionOutputTopLogprob(logprob: float, token: str) -> None
|
| ChatCompletionOutputTopLogprob(logprob: float, token: str)
|
| Method resolution order:
| ChatCompletionOutputTopLogprob
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, logprob: float, token: str) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'logprob': <class 'float'>, 'token': <class 'str'>}
|
| __dataclass_fields__ = {'logprob': Field(name='logprob',type=<class 'f...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('logprob', 'token')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionOutputUsage
Python Library Documentation: class ChatCompletionOutputUsage in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionOutputUsage(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionOutputUsage(completion_tokens: int, prompt_tokens: int, total_tokens: int) -> None
|
| ChatCompletionOutputUsage(completion_tokens: int, prompt_tokens: int, total_tokens: int)
|
| Method resolution order:
| ChatCompletionOutputUsage
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, completion_tokens: int, prompt_tokens: int, total_tokens: int) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'completion_tokens': <class 'int'>, 'prompt_tokens'...
|
| __dataclass_fields__ = {'completion_tokens': Field(name='completion_to...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('completion_tokens', 'prompt_tokens', 'total_tokens'...
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionStreamOutput
Python Library Documentation: class ChatCompletionStreamOutput in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionStreamOutput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionStreamOutput(choices: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutputChoice], created: int, id: str, model: str, system_fingerprint: str, usage: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutputUsage | None = None) -> None
|
| Chat Completion Stream Output.
| Auto-generated from TGI specs.
| For more details, check out
| https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tgi-import.ts.
|
| Method resolution order:
| ChatCompletionStreamOutput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, choices: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutputChoice], created: int, id: str, model: str, system_fingerprint: str, usage: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutputUsage | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'choices': list[huggingface_hub.inference._generate...
|
| __dataclass_fields__ = {'choices': Field(name='choices',type=list[hugg...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('choices', 'created', 'id', 'model', 'system_fingerp...
|
| usage = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionStreamOutputChoice
Python Library Documentation: class ChatCompletionStreamOutputChoice in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionStreamOutputChoice(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionStreamOutputChoice(delta: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutputDelta, index: int, finish_reason: str | None = None, logprobs: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutputLogprobs | None = None) -> None
|
| ChatCompletionStreamOutputChoice(delta: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutputDelta, index: int, finish_reason: str | None = None, logprobs: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutputLogprobs | None = None)
|
| Method resolution order:
| ChatCompletionStreamOutputChoice
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, delta: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutputDelta, index: int, finish_reason: str | None = None, logprobs: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutputLogprobs | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'delta': <class 'huggingface_hub.inference._generat...
|
| __dataclass_fields__ = {'delta': Field(name='delta',type=<class 'huggi...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('delta', 'index', 'finish_reason', 'logprobs')
|
| finish_reason = None
|
| logprobs = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionStreamOutputDelta
Python Library Documentation: class ChatCompletionStreamOutputDelta in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionStreamOutputDelta(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionStreamOutputDelta(role: str, content: str | None = None, reasoning: str | None = None, tool_call_id: str | None = None, tool_calls: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutputDeltaToolCall] | None = None) -> None
|
| ChatCompletionStreamOutputDelta(role: str, content: str | None = None, reasoning: str | None = None, tool_call_id: str | None = None, tool_calls: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutputDeltaToolCall] | None = None)
|
| Method resolution order:
| ChatCompletionStreamOutputDelta
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, role: str, content: str | None = None, reasoning: str | None = None, tool_call_id: str | None = None, tool_calls: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutputDeltaToolCall] | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'content': str | None, 'reasoning': str | None, 'ro...
|
| __dataclass_fields__ = {'content': Field(name='content',type=str | Non...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('role', 'content', 'reasoning', 'tool_call_id', 'too...
|
| content = None
|
| reasoning = None
|
| tool_call_id = None
|
| tool_calls = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionStreamOutputDeltaToolCall
Python Library Documentation: class ChatCompletionStreamOutputDeltaToolCall in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionStreamOutputDeltaToolCall(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionStreamOutputDeltaToolCall(function: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutputFunction, id: str, index: int, type: str) -> None
|
| ChatCompletionStreamOutputDeltaToolCall(function: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutputFunction, id: str, index: int, type: str)
|
| Method resolution order:
| ChatCompletionStreamOutputDeltaToolCall
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, function: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutputFunction, id: str, index: int, type: str) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'function': <class 'huggingface_hub.inference._gene...
|
| __dataclass_fields__ = {'function': Field(name='function',type=<class ...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('function', 'id', 'index', 'type')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionStreamOutputFunction
Python Library Documentation: class ChatCompletionStreamOutputFunction in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionStreamOutputFunction(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionStreamOutputFunction(arguments: str, name: str | None = None) -> None
|
| ChatCompletionStreamOutputFunction(arguments: str, name: str | None = None)
|
| Method resolution order:
| ChatCompletionStreamOutputFunction
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, arguments: str, name: str | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'arguments': <class 'str'>, 'name': str | None}
|
| __dataclass_fields__ = {'arguments': Field(name='arguments',type=<clas...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('arguments', 'name')
|
| name = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionStreamOutputLogprob
Python Library Documentation: class ChatCompletionStreamOutputLogprob in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionStreamOutputLogprob(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionStreamOutputLogprob(logprob: float, token: str, top_logprobs: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutputTopLogprob]) -> None
|
| ChatCompletionStreamOutputLogprob(logprob: float, token: str, top_logprobs: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutputTopLogprob])
|
| Method resolution order:
| ChatCompletionStreamOutputLogprob
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, logprob: float, token: str, top_logprobs: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutputTopLogprob]) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'logprob': <class 'float'>, 'token': <class 'str'>,...
|
| __dataclass_fields__ = {'logprob': Field(name='logprob',type=<class 'f...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('logprob', 'token', 'top_logprobs')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionStreamOutputLogprobs
Python Library Documentation: class ChatCompletionStreamOutputLogprobs in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionStreamOutputLogprobs(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionStreamOutputLogprobs(content: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutputLogprob]) -> None
|
| ChatCompletionStreamOutputLogprobs(content: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutputLogprob])
|
| Method resolution order:
| ChatCompletionStreamOutputLogprobs
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, content: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutputLogprob]) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'content': list[huggingface_hub.inference._generate...
|
| __dataclass_fields__ = {'content': Field(name='content',type=list[hugg...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('content',)
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionStreamOutputTopLogprob
Python Library Documentation: class ChatCompletionStreamOutputTopLogprob in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionStreamOutputTopLogprob(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionStreamOutputTopLogprob(logprob: float, token: str) -> None
|
| ChatCompletionStreamOutputTopLogprob(logprob: float, token: str)
|
| Method resolution order:
| ChatCompletionStreamOutputTopLogprob
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, logprob: float, token: str) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'logprob': <class 'float'>, 'token': <class 'str'>}
|
| __dataclass_fields__ = {'logprob': Field(name='logprob',type=<class 'f...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('logprob', 'token')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ChatCompletionStreamOutputUsage
Python Library Documentation: class ChatCompletionStreamOutputUsage in module huggingface_hub.inference._generated.types.chat_completion
class ChatCompletionStreamOutputUsage(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ChatCompletionStreamOutputUsage(completion_tokens: int, prompt_tokens: int, total_tokens: int) -> None
|
| ChatCompletionStreamOutputUsage(completion_tokens: int, prompt_tokens: int, total_tokens: int)
|
| Method resolution order:
| ChatCompletionStreamOutputUsage
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, completion_tokens: int, prompt_tokens: int, total_tokens: int) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'completion_tokens': <class 'int'>, 'prompt_tokens'...
|
| __dataclass_fields__ = {'completion_tokens': Field(name='completion_to...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('completion_tokens', 'prompt_tokens', 'total_tokens'...
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.Collection
Python Library Documentation: class Collection in module huggingface_hub.hf_api
class Collection(builtins.object)
| Collection(**kwargs) -> 'None'
|
| Contains information about a Collection on the Hub.
|
| Attributes:
| slug (`str`):
| Slug of the collection. E.g. `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
| title (`str`):
| Title of the collection. E.g. `"Recent models"`.
| owner (`str`):
| Owner of the collection. E.g. `"TheBloke"`.
| items (`list[CollectionItem]`):
| List of items in the collection.
| last_updated (`datetime`):
| Date of the last update of the collection.
| position (`int`):
| Position of the collection in the list of collections of the owner.
| private (`bool`):
| Whether the collection is private or not.
| theme (`str`):
| Theme of the collection. E.g. `"green"`.
| upvotes (`int`):
| Number of upvotes of the collection.
| description (`str`, *optional*):
| Description of the collection, as plain text.
| url (`str`):
| (property) URL of the collection on the Hub.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, **kwargs) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| url
| Returns the URL of the collection on the Hub.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'description': 'str | None', 'items': 'list[Collect...
|
| __dataclass_fields__ = {'description': Field(name='description',type='...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('slug', 'title', 'owner', 'items', 'last_updated', '...
|
| description = None
huggingface-hub.CollectionItem
Python Library Documentation: class CollectionItem in module huggingface_hub.hf_api
class CollectionItem(builtins.object)
| CollectionItem(_id: 'str', id: 'str', type: 'CollectionItemType_T', position: 'int', note: 'dict | None' = None, **kwargs) -> 'None'
|
| Contains information about an item of a Collection (model, dataset, Space, paper, collection or bucket).
|
| Attributes:
| item_object_id (`str`):
| Unique ID of the item in the collection.
| item_id (`str`):
| ID of the underlying object on the Hub. Can be either a repo_id, a paper id, a collection slug
| or a bucket id.
| e.g. `"jbilcke-hf/ai-comic-factory"`, `"2307.09288"`, `"celinah/cerebras-function-calling-682607169c35fbfa98b30b9a"`.
| item_type (`str`):
| Type of the underlying object. Can be one of `"model"`, `"dataset"`, `"space"`, `"paper"`, `"collection"`
| or `"bucket"`.
| position (`int`):
| Position of the item in the collection.
| note (`str`, *optional*):
| Note associated with the item, as plain text.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, _id: 'str', id: 'str', type: 'CollectionItemType_T', position: 'int', note: 'dict | None' = None, **kwargs) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'item_id': 'str', 'item_object_id': 'str', 'item_ty...
|
| __dataclass_fields__ = {'item_id': Field(name='item_id',type='str',def...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('item_object_id', 'item_id', 'item_type', 'position'...
|
| note = None
huggingface-hub.CommitInfo
Python Library Documentation: class CommitInfo in module huggingface_hub.hf_api
class CommitInfo(builtins.str)
| CommitInfo(*args, commit_url: 'str', **kwargs)
|
| Data structure containing information about a newly created commit.
|
| Returned by any method that creates a commit on the Hub: [`create_commit`], [`upload_file`], [`upload_folder`],
| [`delete_file`], [`delete_folder`]. It inherits from `str` for backward compatibility but using methods specific
| to `str` is deprecated.
|
| Attributes:
| commit_url (`str`):
| Url where to find the commit.
|
| commit_message (`str`):
| The summary (first line) of the commit that has been created.
|
| commit_description (`str`):
| Description of the commit that has been created. Can be empty.
|
| oid (`str`):
| Commit hash id. Example: `"91c54ad1727ee830252e457677f467be0bfd8a57"`.
|
| pr_url (`str`, *optional*):
| Url to the PR that has been created, if any. Populated when `create_pr=True`
| is passed.
|
| pr_revision (`str`, *optional*):
| Revision of the PR that has been created, if any. Populated when
| `create_pr=True` is passed. Example: `"refs/pr/1"`.
|
| pr_num (`int`, *optional*):
| Number of the PR discussion that has been created, if any. Populated when
| `create_pr=True` is passed. Can be passed as `discussion_num` in
| [`get_discussion_details`]. Example: `1`.
|
| repo_url (`RepoUrl`):
| Repo URL of the commit containing info like repo_id, repo_type, etc.
|
| Method resolution order:
| CommitInfo
| builtins.str
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, commit_url: 'str', commit_message: 'str', commit_description: 'str', oid: 'str', _endpoint: 'str | None' = None, pr_url: 'str | None' = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __post_init__(self)
| Populate pr-related fields after initialization.
|
| See https://docs.python.org/3.10/library/dataclasses.html#post-init-processing.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(cls, *args, commit_url: 'str', **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_endpoint': 'str | None', 'commit_description': 's...
|
| __dataclass_fields__ = {'_endpoint': Field(name='_endpoint',type='str ...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('commit_url', 'commit_message', 'commit_description'...
|
| pr_url = None
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.str:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __format__(self, format_spec, /)
| Return a formatted version of the string as described by format_spec.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(...)
|
| __gt__(self, value, /)
| Return self>value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __sizeof__(self, /)
| Return the size of the string in memory, in bytes.
|
| __str__(self, /)
| Return str(self).
|
| capitalize(self, /)
| Return a capitalized version of the string.
|
| More specifically, make the first character have upper case and the rest lower
| case.
|
| casefold(self, /)
| Return a version of the string suitable for caseless comparisons.
|
| center(self, width, fillchar=' ', /)
| Return a centered string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| count(...)
| S.count(sub[, start[, end]]) -> int
|
| Return the number of non-overlapping occurrences of substring sub in
| string S[start:end]. Optional arguments start and end are
| interpreted as in slice notation.
|
| encode(self, /, encoding='utf-8', errors='strict')
| Encode the string using the codec registered for encoding.
|
| encoding
| The encoding in which to encode the string.
| errors
| The error handling scheme to use for encoding errors.
| The default is 'strict' meaning that encoding errors raise a
| UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
| 'xmlcharrefreplace' as well as any other name registered with
| codecs.register_error that can handle UnicodeEncodeErrors.
|
| endswith(...)
| S.endswith(suffix[, start[, end]]) -> bool
|
| Return True if S ends with the specified suffix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| suffix can also be a tuple of strings to try.
|
| expandtabs(self, /, tabsize=8)
| Return a copy where all tab characters are expanded using spaces.
|
| If tabsize is not given, a tab size of 8 characters is assumed.
|
| find(...)
| S.find(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| format(...)
| S.format(*args, **kwargs) -> str
|
| Return a formatted version of S, using substitutions from args and kwargs.
| The substitutions are identified by braces ('{' and '}').
|
| format_map(...)
| S.format_map(mapping) -> str
|
| Return a formatted version of S, using substitutions from mapping.
| The substitutions are identified by braces ('{' and '}').
|
| index(...)
| S.index(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| isalnum(self, /)
| Return True if the string is an alpha-numeric string, False otherwise.
|
| A string is alpha-numeric if all characters in the string are alpha-numeric and
| there is at least one character in the string.
|
| isalpha(self, /)
| Return True if the string is an alphabetic string, False otherwise.
|
| A string is alphabetic if all characters in the string are alphabetic and there
| is at least one character in the string.
|
| isascii(self, /)
| Return True if all characters in the string are ASCII, False otherwise.
|
| ASCII characters have code points in the range U+0000-U+007F.
| Empty string is ASCII too.
|
| isdecimal(self, /)
| Return True if the string is a decimal string, False otherwise.
|
| A string is a decimal string if all characters in the string are decimal and
| there is at least one character in the string.
|
| isdigit(self, /)
| Return True if the string is a digit string, False otherwise.
|
| A string is a digit string if all characters in the string are digits and there
| is at least one character in the string.
|
| isidentifier(self, /)
| Return True if the string is a valid Python identifier, False otherwise.
|
| Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
| such as "def" or "class".
|
| islower(self, /)
| Return True if the string is a lowercase string, False otherwise.
|
| A string is lowercase if all cased characters in the string are lowercase and
| there is at least one cased character in the string.
|
| isnumeric(self, /)
| Return True if the string is a numeric string, False otherwise.
|
| A string is numeric if all characters in the string are numeric and there is at
| least one character in the string.
|
| isprintable(self, /)
| Return True if the string is printable, False otherwise.
|
| A string is printable if all of its characters are considered printable in
| repr() or if it is empty.
|
| isspace(self, /)
| Return True if the string is a whitespace string, False otherwise.
|
| A string is whitespace if all characters in the string are whitespace and there
| is at least one character in the string.
|
| istitle(self, /)
| Return True if the string is a title-cased string, False otherwise.
|
| In a title-cased string, upper- and title-case characters may only
| follow uncased characters and lowercase characters only cased ones.
|
| isupper(self, /)
| Return True if the string is an uppercase string, False otherwise.
|
| A string is uppercase if all cased characters in the string are uppercase and
| there is at least one cased character in the string.
|
| join(self, iterable, /)
| Concatenate any number of strings.
|
| The string whose method is called is inserted in between each given string.
| The result is returned as a new string.
|
| Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
|
| ljust(self, width, fillchar=' ', /)
| Return a left-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| lower(self, /)
| Return a copy of the string converted to lowercase.
|
| lstrip(self, chars=None, /)
| Return a copy of the string with leading whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| partition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string. If the separator is found,
| returns a 3-tuple containing the part before the separator, the separator
| itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing the original string
| and two empty strings.
|
| removeprefix(self, prefix, /)
| Return a str with the given prefix string removed if present.
|
| If the string starts with the prefix string, return string[len(prefix):].
| Otherwise, return a copy of the original string.
|
| removesuffix(self, suffix, /)
| Return a str with the given suffix string removed if present.
|
| If the string ends with the suffix string and that suffix is not empty,
| return string[:-len(suffix)]. Otherwise, return a copy of the original
| string.
|
| replace(self, old, new, count=-1, /)
| Return a copy with all occurrences of substring old replaced by new.
|
| count
| Maximum number of occurrences to replace.
| -1 (the default value) means replace all occurrences.
|
| If the optional argument count is given, only the first count occurrences are
| replaced.
|
| rfind(...)
| S.rfind(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| rindex(...)
| S.rindex(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| rjust(self, width, fillchar=' ', /)
| Return a right-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| rpartition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string, starting at the end. If
| the separator is found, returns a 3-tuple containing the part before the
| separator, the separator itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing two empty strings
| and the original string.
|
| rsplit(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the end of the string and works to the front.
|
| rstrip(self, chars=None, /)
| Return a copy of the string with trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| split(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the front of the string and works to the end.
|
| Note, str.split() is mainly useful for data that has been intentionally
| delimited. With natural text that includes punctuation, consider using
| the regular expression module.
|
| splitlines(self, /, keepends=False)
| Return a list of the lines in the string, breaking at line boundaries.
|
| Line breaks are not included in the resulting list unless keepends is given and
| true.
|
| startswith(...)
| S.startswith(prefix[, start[, end]]) -> bool
|
| Return True if S starts with the specified prefix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| prefix can also be a tuple of strings to try.
|
| strip(self, chars=None, /)
| Return a copy of the string with leading and trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| swapcase(self, /)
| Convert uppercase characters to lowercase and lowercase characters to uppercase.
|
| title(self, /)
| Return a version of the string where each word is titlecased.
|
| More specifically, words start with uppercased characters and all remaining
| cased characters have lower case.
|
| translate(self, table, /)
| Replace each character in the string using the given translation table.
|
| table
| Translation table, which must be a mapping of Unicode ordinals to
| Unicode ordinals, strings, or None.
|
| The table must implement lookup/indexing via __getitem__, for instance a
| dictionary or list. If this operation raises LookupError, the character is
| left untouched. Characters mapped to None are deleted.
|
| upper(self, /)
| Return a copy of the string converted to uppercase.
|
| zfill(self, width, /)
| Pad a numeric string with zeros on the left, to fill a field of the given width.
|
| The string is never truncated.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.str:
|
| maketrans(...)
| Return a translation table usable for str.translate().
|
| If there is only one argument, it must be a dictionary mapping Unicode
| ordinals (integers) or characters to Unicode ordinals, strings or None.
| Character keys will be then converted to ordinals.
| If there are two arguments, they must be strings of equal length, and
| in the resulting dictionary, each character in x will be mapped to the
| character at the same position in y. If there is a third argument, it
| must be a string, whose characters will be mapped to None in the result.
huggingface-hub.CommitOperation
Python Library Documentation: _UnionGenericAlias in module typing
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
huggingface-hub.CommitOperationAdd
Python Library Documentation: class CommitOperationAdd in module huggingface_hub._commit_api
class CommitOperationAdd(builtins.object)
| CommitOperationAdd(path_in_repo: str, path_or_fileobj: str | pathlib.Path | bytes | typing.BinaryIO) -> None
|
| Data structure holding necessary info to upload a file to a repository on the Hub.
|
| Args:
| path_in_repo (`str`):
| Relative filepath in the repo, for example: `"checkpoints/1fec34a/weights.bin"`
| path_or_fileobj (`str`, `Path`, `bytes`, or `BinaryIO`):
| Either:
| - a path to a local file (as `str` or `pathlib.Path`) to upload
| - a buffer of bytes (`bytes`) holding the content of the file to upload
| - a "file object" (subclass of `io.BufferedIOBase`), typically obtained
| with `open(path, "rb")`. It must support `seek()` and `tell()` methods.
|
| Raises:
| [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| If `path_or_fileobj` is not one of `str`, `Path`, `bytes` or `io.BufferedIOBase`.
| [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| If `path_or_fileobj` is a `str` or `Path` but not a path to an existing file.
| [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| If `path_or_fileobj` is a `io.BufferedIOBase` but it doesn't support both
| `seek()` and `tell()`.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, path_in_repo: str, path_or_fileobj: str | pathlib.Path | bytes | typing.BinaryIO) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __post_init__(self) -> None
| Validates `path_or_fileobj` and compute `upload_info`.
|
| __repr__(self)
| Return repr(self).
|
| as_file(self, with_tqdm: bool = False) -> collections.abc.Iterator[typing.BinaryIO]
| A context manager that yields a file-like object allowing to read the underlying
| data behind `path_or_fileobj`.
|
| Args:
| with_tqdm (`bool`, *optional*, defaults to `False`):
| If True, iterating over the file object will display a progress bar. Only
| works if the file-like object is a path to a file. Pure bytes and buffers
| are not supported.
|
| Example:
|
| ```python
| >>> operation = CommitOperationAdd(
| ... path_in_repo="remote/dir/weights.h5",
| ... path_or_fileobj="./local/weights.h5",
| ... )
| CommitOperationAdd(path_in_repo='remote/dir/weights.h5', path_or_fileobj='./local/weights.h5')
|
| >>> with operation.as_file() as file:
| ... content = file.read()
|
| >>> with operation.as_file(with_tqdm=True) as file:
| ... while True:
| ... data = file.read(1024)
| ... if not data:
| ... break
| config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s]
|
| >>> with operation.as_file(with_tqdm=True) as file:
| ... httpx.put(..., data=file)
| config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s]
| ```
|
| b64content(self) -> bytes
| The base64-encoded content of `path_or_fileobj`
|
| Returns: `bytes`
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_is_committed': <class 'bool'>, '_is_uploaded': <c...
|
| __dataclass_fields__ = {'_is_committed': Field(name='_is_committed',ty...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('path_in_repo', 'path_or_fileobj')
huggingface-hub.CommitOperationCopy
Python Library Documentation: class CommitOperationCopy in module huggingface_hub._commit_api
class CommitOperationCopy(builtins.object)
| CommitOperationCopy(src_path_in_repo: str, path_in_repo: str, src_revision: str | None = None, src_repo_id: str | None = None, src_repo_type: str | None = None, _src_oid: str | None = None, _dest_oid: str | None = None, _is_duplicated: bool = False) -> None
|
| Data structure holding necessary info to copy a file in a repository on the Hub.
|
| Both LFS files and regular files are supported. LFS files are copied server-side while regular files are
| downloaded and re-uploaded as part of the commit.
|
| Cross-repository copies are supported by setting `src_repo_id` and `src_repo_type`. For cross-repo LFS copies,
| the LFS objects are duplicated to the destination repository before the commit is created. This is handled
| automatically by [`create_commit`]. Note that cross-repository copies only work within the same
| [storage region](https://huggingface.co/docs/hub/storage-regions); copying across regions is not supported.
|
| Note: you can combine a [`CommitOperationCopy`] and a [`CommitOperationDelete`] to rename an LFS file on the Hub.
|
| Args:
| src_path_in_repo (`str`):
| Relative filepath in the repo of the file to be copied, e.g. `"checkpoints/1fec34a/weights.bin"`.
| path_in_repo (`str`):
| Relative filepath in the repo where to copy the file, e.g. `"checkpoints/1fec34a/weights_copy.bin"`.
| src_revision (`str`, *optional*):
| The git revision of the file to be copied. Can be any valid git revision.
| Default to the target commit revision.
| src_repo_id (`str`, *optional*):
| The source repository to copy from (e.g. `"username/source-model"`).
| Default to the destination repository (intra-repo copy).
| src_repo_type (`str`, *optional*):
| The type of the source repository (`"model"`, `"dataset"` or `"space"`).
| Required when `src_repo_id` is set.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, src_path_in_repo: str, path_in_repo: str, src_revision: str | None = None, src_repo_id: str | None = None, src_repo_type: str | None = None, _src_oid: str | None = None, _dest_oid: str | None = None, _is_duplicated: bool = False) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __post_init__(self)
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_dest_oid': str | None, '_is_duplicated': <class '...
|
| __dataclass_fields__ = {'_dest_oid': Field(name='_dest_oid',type=str |...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('src_path_in_repo', 'path_in_repo', 'src_revision', ...
|
| src_repo_id = None
|
| src_repo_type = None
|
| src_revision = None
huggingface-hub.CommitOperationDelete
Python Library Documentation: class CommitOperationDelete in module huggingface_hub._commit_api
class CommitOperationDelete(builtins.object)
| CommitOperationDelete(path_in_repo: str, is_folder: Union[bool, Literal['auto']] = 'auto') -> None
|
| Data structure holding necessary info to delete a file or a folder from a repository
| on the Hub.
|
| Args:
| path_in_repo (`str`):
| Relative filepath in the repo, for example: `"checkpoints/1fec34a/weights.bin"`
| for a file or `"checkpoints/1fec34a/"` for a folder.
| is_folder (`bool` or `Literal["auto"]`, *optional*)
| Whether the Delete Operation applies to a folder or not. If "auto", the path
| type (file or folder) is guessed automatically by looking if path ends with
| a "/" (folder) or not (file). To explicitly set the path type, you can set
| `is_folder=True` or `is_folder=False`.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, path_in_repo: str, is_folder: Union[bool, Literal['auto']] = 'auto') -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __post_init__(self)
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'is_folder': typing.Union[bool, typing.Literal['aut...
|
| __dataclass_fields__ = {'is_folder': Field(name='is_folder',type=typin...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('path_in_repo', 'is_folder')
|
| is_folder = 'auto'
huggingface-hub.CommitScheduler
Python Library Documentation: class CommitScheduler in module huggingface_hub._commit_scheduler
class CommitScheduler(builtins.object)
| CommitScheduler(*, repo_id: str, folder_path: str | pathlib.Path, every: int | float = 5, path_in_repo: str | None = None, repo_type: str | None = None, revision: str | None = None, private: bool | None = None, token: str | None = None, allow_patterns: list[str] | str | None = None, ignore_patterns: list[str] | str | None = None, squash_history: bool = False, hf_api: Optional[ForwardRef('HfApi')] = None) -> None
|
| Scheduler to upload a local folder to the Hub at regular intervals (e.g. push to hub every 5 minutes).
|
| The recommended way to use the scheduler is to use it as a context manager. This ensures that the scheduler is
| properly stopped and the last commit is triggered when the script ends. The scheduler can also be stopped manually
| with the `stop` method. Checkout the [upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#scheduled-uploads)
| to learn more about how to use it.
|
| Args:
| repo_id (`str`):
| The id of the repo to commit to.
| folder_path (`str` or `Path`):
| Path to the local folder to upload regularly.
| every (`int` or `float`, *optional*):
| The number of minutes between each commit. Defaults to 5 minutes.
| path_in_repo (`str`, *optional*):
| Relative path of the directory in the repo, for example: `"checkpoints/"`. Defaults to the root folder
| of the repository.
| repo_type (`str`, *optional*):
| The type of the repo to commit to. Defaults to `model`.
| revision (`str`, *optional*):
| The revision of the repo to commit to. Defaults to `main`.
| private (`bool`, *optional*):
| Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
| token (`str`, *optional*):
| The token to use to commit to the repo. Defaults to the token saved on the machine.
| allow_patterns (`list[str]` or `str`, *optional*):
| If provided, only files matching at least one pattern are uploaded.
| ignore_patterns (`list[str]` or `str`, *optional*):
| If provided, files matching any of the patterns are not uploaded.
| squash_history (`bool`, *optional*):
| Whether to squash the history of the repo after each commit. Defaults to `False`. Squashing commits is
| useful to avoid degraded performances on the repo when it grows too large.
| hf_api (`HfApi`, *optional*):
| The [`HfApi`] client to use to commit to the Hub. Can be set with custom settings (user agent, token,...).
|
| Example:
| ```py
| >>> from pathlib import Path
| >>> from huggingface_hub import CommitScheduler
|
| # Scheduler uploads every 10 minutes
| >>> csv_path = Path("watched_folder/data.csv")
| >>> CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path=csv_path.parent, every=10)
|
| >>> with csv_path.open("a") as f:
| ... f.write("first line")
|
| # Some time later (...)
| >>> with csv_path.open("a") as f:
| ... f.write("second line")
| ```
|
| Example using a context manager:
| ```py
| >>> from pathlib import Path
| >>> from huggingface_hub import CommitScheduler
|
| >>> with CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path="watched_folder", every=10) as scheduler:
| ... csv_path = Path("watched_folder/data.csv")
| ... with csv_path.open("a") as f:
| ... f.write("first line")
| ... (...)
| ... with csv_path.open("a") as f:
| ... f.write("second line")
|
| # Scheduler is now stopped and last commit have been triggered
| ```
|
| Methods defined here:
|
| __enter__(self) -> 'CommitScheduler'
|
| __exit__(self, exc_type, exc_value, traceback) -> None
|
| __init__(self, *, repo_id: str, folder_path: str | pathlib.Path, every: int | float = 5, path_in_repo: str | None = None, repo_type: str | None = None, revision: str | None = None, private: bool | None = None, token: str | None = None, allow_patterns: list[str] | str | None = None, ignore_patterns: list[str] | str | None = None, squash_history: bool = False, hf_api: Optional[ForwardRef('HfApi')] = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| push_to_hub(self) -> huggingface_hub.hf_api.CommitInfo | None
| Push folder to the Hub and return the commit info.
|
| > [!WARNING]
| > This method is not meant to be called directly. It is run in the background by the scheduler, respecting a
| > queue mechanism to avoid concurrent commits. Making a direct call to the method might lead to concurrency
| > issues.
|
| The default behavior of `push_to_hub` is to assume an append-only folder. It lists all files in the folder and
| uploads only changed files. If no changes are found, the method returns without committing anything. If you want
| to change this behavior, you can inherit from [`CommitScheduler`] and override this method. This can be useful
| for example to compress data together in a single file before committing. For more details and examples, check
| out our [integration guide](https://huggingface.co/docs/huggingface_hub/main/en/guides/upload#scheduled-uploads).
|
| stop(self) -> None
| Stop the scheduler.
|
| A stopped scheduler cannot be restarted. Mostly for tests purposes.
|
| trigger(self) -> concurrent.futures._base.Future
| Trigger a `push_to_hub` and return a future.
|
| This method is automatically called every `every` minutes. You can also call it manually to trigger a commit
| immediately, without waiting for the next scheduled commit.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
huggingface-hub.CorruptedCacheException
Python Library Documentation: class CorruptedCacheException in module huggingface_hub.errors class CorruptedCacheException(builtins.Exception) | Exception for any unexpected structure in the Huggingface cache-system. | | Method resolution order: | CorruptedCacheException | builtins.Exception | builtins.BaseException | builtins.object | | Data descriptors defined here: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.Exception: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
huggingface-hub.DDUFEntry
Python Library Documentation: class DDUFEntry in module huggingface_hub.serialization._dduf
class DDUFEntry(builtins.object)
| DDUFEntry(filename: str, length: int, offset: int, dduf_path: pathlib.Path) -> None
|
| Object representing a file entry in a DDUF file.
|
| See [`read_dduf_file`] for how to read a DDUF file.
|
| Attributes:
| filename (str):
| The name of the file in the DDUF archive.
| offset (int):
| The offset of the file in the DDUF archive.
| length (int):
| The length of the file in the DDUF archive.
| dduf_path (str):
| The path to the DDUF archive (for internal use).
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, filename: str, length: int, offset: int, dduf_path: pathlib.Path) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| as_mmap(self) -> collections.abc.Generator[bytes, None, None]
| Open the file as a memory-mapped file.
|
| Useful to load safetensors directly from the file.
|
| Example:
| ```py
| >>> import safetensors.torch
| >>> with entry.as_mmap() as mm:
| ... tensors = safetensors.torch.load(mm)
| ```
|
| read_text(self, encoding: str = 'utf-8') -> str
| Read the file as text.
|
| Useful for '.txt' and '.json' entries.
|
| Example:
| ```py
| >>> import json
| >>> index = json.loads(entry.read_text())
| ```
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'dduf_path': <class 'pathlib.Path'>, 'filename': <c...
|
| __dataclass_fields__ = {'dduf_path': Field(name='dduf_path',type=<clas...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('filename', 'length', 'offset', 'dduf_path')
huggingface-hub.DatasetCard
Python Library Documentation: class DatasetCard in module huggingface_hub.repocard
class DatasetCard(RepoCard)
| DatasetCard(content: str, ignore_metadata_errors: bool = False)
|
| Method resolution order:
| DatasetCard
| RepoCard
| builtins.object
|
| Class methods defined here:
|
| from_template(card_data: huggingface_hub.repocard_data.DatasetCardData, template_path: str | None = None, template_str: str | None = None, **template_kwargs)
| Initialize a DatasetCard from a template. By default, it uses the default template, which can be found here:
| https://github.com/huggingface/huggingface_hub/blob/main/src/huggingface_hub/templates/datasetcard_template.md
|
| Templates are Jinja2 templates that can be customized by passing keyword arguments.
|
| Args:
| card_data (`huggingface_hub.DatasetCardData`):
| A huggingface_hub.DatasetCardData instance containing the metadata you want to include in the YAML
| header of the dataset card on the Hugging Face Hub.
| template_path (`str`, *optional*):
| A path to a markdown file with optional Jinja template variables that can be filled
| in with `template_kwargs`. Defaults to the default template.
| template_str (`str`, *optional*):
| A raw Jinja template string with optional variables. Used when neither `template_path`
| nor the default template is appropriate. Ignored if `template_path` is also provided.
|
| Returns:
| [`huggingface_hub.DatasetCard`]: A DatasetCard instance with the specified card data and content from the
| template.
|
| Example:
| ```python
| >>> from huggingface_hub import DatasetCard, DatasetCardData
|
| >>> # Using the Default Template
| >>> card_data = DatasetCardData(
| ... language='en',
| ... license='mit',
| ... annotations_creators='crowdsourced',
| ... task_categories=['text-classification'],
| ... task_ids=['sentiment-classification', 'text-scoring'],
| ... multilinguality='monolingual',
| ... pretty_name='My Text Classification Dataset',
| ... )
| >>> card = DatasetCard.from_template(
| ... card_data,
| ... pretty_name=card_data.pretty_name,
| ... )
|
| >>> # Using a Custom Template
| >>> card_data = DatasetCardData(
| ... language='en',
| ... license='mit',
| ... )
| >>> card = DatasetCard.from_template(
| ... card_data=card_data,
| ... template_path='./src/huggingface_hub/templates/datasetcard_template.md',
| ... custom_template_var='custom value', # will be replaced in template if it exists
| ... )
|
| ```
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| card_data_class = <class 'huggingface_hub.repocard_data.DatasetCardDat...
| Dataset Card Metadata that is used by Hugging Face Hub when included at the top of your README.md
|
| 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 dataset. Example: apache-2.0 or any license from
| https://huggingface.co/docs/hub/repositories-licenses.
| annotations_creators (`Union[str, list[str]]`, *optional*):
| How the annotations for the dataset were created.
| Options are: 'found', 'crowdsourced', 'expert-generated', 'machine-generated', 'no-annotation', 'other'.
| language_creators (`Union[str, list[str]]`, *optional*):
| How the text-based data in the dataset was created.
| Options are: 'found', 'crowdsourced', 'expert-generated', 'machine-generated', 'other'
| multilinguality (`Union[str, list[str]]`, *optional*):
| Whether the dataset is multilingual.
| 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', '100B<n<1T', 'n>1T', and 'other'.
| source_datasets (`list[str]]`, *optional*):
| Indicates whether the dataset is an original dataset or extended from another existing dataset.
| Options are: 'original' and 'extended'.
| task_categories (`Union[str, list[str]]`, *optional*):
| What categories of task does the dataset support?
| task_ids (`Union[str, list[str]]`, *optional*):
| What specific tasks does the dataset support?
| paperswithcode_id (`str`, *optional*):
| ID of the dataset on PapersWithCode.
| pretty_name (`str`, *optional*):
| 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_names (`Union[str, list[str]]`, *optional*):
| A list of the available dataset configs for the dataset.
|
|
| default_template_path = WindowsPath('C:/Users/Youse/AppData/Local/Prog...
|
| repo_type = 'dataset'
|
| ----------------------------------------------------------------------
| Methods inherited from RepoCard:
|
| __init__(self, content: str, ignore_metadata_errors: bool = False)
| Initialize a RepoCard from string content. The content should be a
| Markdown file with a YAML block at the beginning and a Markdown body.
|
| Args:
| content (`str`): The content of the Markdown file.
|
| Example:
| ```python
| >>> from huggingface_hub.repocard import RepoCard
| >>> text = '''
| ... ---
| ... language: en
| ... license: mit
| ... ---
| ...
| ... # My repo
| ... '''
| >>> card = RepoCard(text)
| >>> card.data.to_dict()
| {'language': 'en', 'license': 'mit'}
| >>> card.text
| '\n# My repo\n'
|
| ```
| > [!TIP]
| > Raises the following error:
| >
| > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| > when the content of the repo card metadata is not a dictionary.
|
| __str__(self)
| Return str(self).
|
| push_to_hub(self, repo_id: str, token: str | None = None, repo_type: str | None = None, commit_message: str | None = None, commit_description: str | None = None, revision: str | None = None, create_pr: bool | None = None, parent_commit: str | None = None)
| Push a RepoCard to a Hugging Face Hub repo.
|
| Args:
| repo_id (`str`):
| The repo ID of the Hugging Face Hub repo to push to. Example: "nateraw/food".
| token (`str`, *optional*):
| Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to
| the stored token.
| repo_type (`str`, *optional*, defaults to "model"):
| The type of Hugging Face repo to push to. Options are "model", "dataset", and "space". If this
| function is called by a child class, it will default to the child class's `repo_type`.
| commit_message (`str`, *optional*):
| The summary / title / first line of the generated commit.
| commit_description (`str`, *optional*)
| The description of the generated commit.
| revision (`str`, *optional*):
| The git revision to commit from. Defaults to the head of the `"main"` branch.
| create_pr (`bool`, *optional*):
| Whether or not to create a Pull Request with this commit. Defaults to `False`.
| parent_commit (`str`, *optional*):
| The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
| If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
| If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
| Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
| especially useful if the repo is updated / committed too concurrently.
| Returns:
| `str`: URL of the commit which updated the card metadata.
|
| save(self, filepath: pathlib.Path | str)
| Save a RepoCard to a file.
|
| Args:
| filepath (`Union[Path, str]`): Filepath to the markdown file to save.
|
| Example:
| ```python
| >>> from huggingface_hub.repocard import RepoCard
| >>> card = RepoCard("---\nlanguage: en\n---\n# This is a test repo card")
| >>> card.save("/tmp/test.md")
|
| ```
|
| validate(self, repo_type: str | None = None)
| Validates card against Hugging Face Hub's card validation logic.
| Using this function requires access to the internet, so it is only called
| internally by [`huggingface_hub.repocard.RepoCard.push_to_hub`].
|
| Args:
| repo_type (`str`, *optional*, defaults to "model"):
| The type of Hugging Face repo to push to. Options are "model", "dataset", and "space".
| If this function is called from a child class, the default will be the child class's `repo_type`.
|
| > [!TIP]
| > Raises the following errors:
| >
| > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| > if the card fails validation checks.
| > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
| > if the request to the Hub API fails for any other reason.
|
| ----------------------------------------------------------------------
| Class methods inherited from RepoCard:
|
| load(repo_id_or_path: str | pathlib.Path, repo_type: str | None = None, token: str | None = None, ignore_metadata_errors: bool = False)
| Initialize a RepoCard from a Hugging Face Hub repo's README.md or a local filepath.
|
| Args:
| repo_id_or_path (`Union[str, Path]`):
| The repo ID associated with a Hugging Face Hub repo or a local filepath.
| repo_type (`str`, *optional*):
| The type of Hugging Face repo to push to. Defaults to None, which will use "model". Other options
| are "dataset" and "space". Not used when loading from a local filepath. If this is called from a child
| class, the default value will be the child class's `repo_type`.
| 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.
|
| Returns:
| [`huggingface_hub.repocard.RepoCard`]: The RepoCard (or subclass) initialized from the repo's
| README.md file or filepath.
|
| Example:
| ```python
| >>> from huggingface_hub.repocard import RepoCard
| >>> card = RepoCard.load("nateraw/food")
| >>> assert card.data.tags == ["generated_from_trainer", "image-classification", "pytorch"]
|
| ```
|
| ----------------------------------------------------------------------
| Data descriptors inherited from RepoCard:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| content
| The content of the RepoCard, including the YAML block and the Markdown body.
huggingface-hub.DatasetCardData
Python Library Documentation: class DatasetCardData in module huggingface_hub.repocard_data
class DatasetCardData(CardData)
| DatasetCardData(*, language: str | list[str] | None = None, license: str | list[str] | None = None, annotations_creators: str | list[str] | None = None, language_creators: str | list[str] | None = None, multilinguality: str | list[str] | None = None, size_categories: str | list[str] | None = None, source_datasets: list[str] | None = None, task_categories: str | list[str] | None = None, task_ids: str | list[str] | None = None, paperswithcode_id: str | None = None, pretty_name: str | None = None, train_eval_index: dict | None = None, config_names: str | list[str] | None = None, ignore_metadata_errors: bool = False, **kwargs)
|
| Dataset Card Metadata that is used by Hugging Face Hub when included at the top of your README.md
|
| 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 dataset. Example: apache-2.0 or any license from
| https://huggingface.co/docs/hub/repositories-licenses.
| annotations_creators (`Union[str, list[str]]`, *optional*):
| How the annotations for the dataset were created.
| Options are: 'found', 'crowdsourced', 'expert-generated', 'machine-generated', 'no-annotation', 'other'.
| language_creators (`Union[str, list[str]]`, *optional*):
| How the text-based data in the dataset was created.
| Options are: 'found', 'crowdsourced', 'expert-generated', 'machine-generated', 'other'
| multilinguality (`Union[str, list[str]]`, *optional*):
| Whether the dataset is multilingual.
| 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', '100B<n<1T', 'n>1T', and 'other'.
| source_datasets (`list[str]]`, *optional*):
| Indicates whether the dataset is an original dataset or extended from another existing dataset.
| Options are: 'original' and 'extended'.
| task_categories (`Union[str, list[str]]`, *optional*):
| What categories of task does the dataset support?
| task_ids (`Union[str, list[str]]`, *optional*):
| What specific tasks does the dataset support?
| paperswithcode_id (`str`, *optional*):
| ID of the dataset on PapersWithCode.
| pretty_name (`str`, *optional*):
| 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_names (`Union[str, list[str]]`, *optional*):
| A list of the available dataset configs for the dataset.
|
| Method resolution order:
| DatasetCardData
| CardData
| builtins.object
|
| Methods defined here:
|
| __init__(self, *, language: str | list[str] | None = None, license: str | list[str] | None = None, annotations_creators: str | list[str] | None = None, language_creators: str | list[str] | None = None, multilinguality: str | list[str] | None = None, size_categories: str | list[str] | None = None, source_datasets: list[str] | None = None, task_categories: str | list[str] | None = None, task_ids: str | list[str] | None = None, paperswithcode_id: str | None = None, pretty_name: str | None = None, train_eval_index: dict | None = None, config_names: str | list[str] | None = None, ignore_metadata_errors: bool = False, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from CardData:
|
| __contains__(self, key: str) -> bool
| Check if a given metadata key is set.
|
| __eq__(self, other)
| Return self==value.
|
| __getitem__(self, key: str) -> Any
| Get value for a given metadata key.
|
| __len__(self) -> int
| Return the number of metadata keys set.
|
| __repr__(self)
| Return repr(self).
|
| __setitem__(self, key: str, value: Any) -> None
| Set value for a given metadata key.
|
| __str__(self)
| Return str(self).
|
| get(self, key: str, default: Any = None) -> Any
| Get value for a given metadata key.
|
| pop(self, key: str, default: Any = None) -> Any
| Pop value for a given metadata key.
|
| to_dict(self)
| Converts CardData to a dict.
|
| Returns:
| `dict`: CardData represented as a dictionary ready to be dumped to a YAML
| block for inclusion in a README.md file.
|
| to_yaml(self, line_break=None, original_order: list[str] | None = None) -> str
| Dumps CardData to a YAML block for inclusion in a README.md file.
|
| Args:
| line_break (str, *optional*):
| The line break to use when dumping to yaml.
| original_order (`list[str]`, *optional*):
| If provided, reorder the metadata fields to match this list before dumping.
| Any keys not in `original_order` are appended after the listed keys, preserving
| their existing relative order. Useful for round-tripping a YAML block without
| shuffling its keys.
|
| Returns:
| `str`: CardData represented as a YAML block.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from CardData:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from CardData:
|
| __dataclass_fields__ = {}
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ()
huggingface-hub.DatasetInfo
Python Library Documentation: class DatasetInfo in module huggingface_hub.hf_api
class DatasetInfo(builtins.object)
| DatasetInfo(**kwargs)
|
| Contains information about a dataset on the Hub. This object is returned by [`dataset_info`] and [`list_datasets`].
|
| > [!TIP]
| > Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made.
| > In general, the more specific the query, the more information is returned. On the contrary, when listing datasets
| > using [`list_datasets`] only a subset of the attributes are returned.
|
| Attributes:
| id (`str`):
| ID of dataset.
| author (`str`):
| Author of the dataset.
| card_data (`DatasetCardData`, *optional*):
| Dataset Card Metadata as a [`huggingface_hub.repocard_data.DatasetCardData`] object.
| citation (`str`, *optional*):
| Citation information for the dataset.
| created_at (`datetime`, *optional*):
| Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`,
| corresponding to the date when we began to store creation dates.
| description (`str`, *optional*):
| Description of the dataset.
| disabled (`bool`, *optional*):
| Is the repo disabled.
| downloads (`int`):
| Number of downloads of the dataset over the last 30 days.
| downloads_all_time (`int`):
| Cumulated number of downloads of the dataset since its creation.
| gated (`Literal["auto", "manual", False]`, *optional*):
| Is the repo gated.
| If so, whether there is manual or automatic approval.
| last_modified (`datetime`, *optional*):
| Date of last commit to the repo.
| likes (`int`):
| Number of likes of the dataset.
| main_size (`int`, *optional*):
| Size in bytes of the main branch of the dataset.
| paperswithcode_id (`str`, *optional*):
| Papers with code ID of the dataset.
| private (`bool`):
| Is the repo private.
| resource_group (`dict`, *optional*):
| Resource group information for the dataset.
| sha (`str`):
| Repo SHA at this particular revision.
| siblings (`list[RepoSibling]`):
| List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the dataset.
| tags (`list[str]`):
| List of tags of the dataset.
| trending_score (`int`, *optional*):
| Trending score of the dataset.
| used_storage (`int`, *optional*):
| Size in bytes of the dataset on the Hub.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'author': 'str | None', 'card_data': 'DatasetCardDa...
|
| __dataclass_fields__ = {'author': Field(name='author',type='str | None...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('id', 'author', 'card_data', 'citation', 'created_at...
huggingface-hub.DatasetLeaderboardEntry
Python Library Documentation: class DatasetLeaderboardEntry in module huggingface_hub.hf_api
class DatasetLeaderboardEntry(builtins.object)
| DatasetLeaderboardEntry(**kwargs) -> 'None'
|
| Contains information about a single entry in a dataset leaderboard on the Hub.
|
| A leaderboard ranks models based on their evaluation scores on a given benchmark dataset.
| This object is returned by [`get_dataset_leaderboard`]. To get evaluation results for a
| specific model across benchmarks, see [`ModelInfo.eval_results`] (via [`model_info`] with
| `expand=["evalResults"]`) and [`EvalResultEntry`].
|
| Attributes:
| rank (`int`):
| Rank of the model on the leaderboard (1-indexed).
| model_id (`str`):
| ID of the model (e.g. `"meta-llama/Llama-3-8b"`).
| value (`float`):
| Evaluation score value.
| filename (`str`):
| Name of the result file containing the evaluation data.
| verified (`bool`):
| Whether the result has been verified.
| source (`dict[str, Any]`, *optional*):
| Information about the source of the evaluation result. Contains keys like
| `"url"`, `"name"`, and `"isExternal"`. Not all entries have a source.
| author (`User` or `Organization`):
| The model author, parsed based on the `"type"` field in the API response.
| pull_request (`int`, *optional*):
| Pull request number associated with the leaderboard entry, if any.
| notes (`str`, *optional*):
| Notes associated with the leaderboard entry, if any.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, **kwargs) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'author': 'User | Organization', 'filename': 'str',...
|
| __dataclass_fields__ = {'author': Field(name='author',type='User | Org...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('rank', 'model_id', 'value', 'filename', 'verified',...
|
| notes = None
|
| pull_request = None
huggingface-hub.DeleteCacheStrategy
Python Library Documentation: class DeleteCacheStrategy in module huggingface_hub.utils._cache_manager
class DeleteCacheStrategy(builtins.object)
| DeleteCacheStrategy(expected_freed_size: int, blobs: frozenset[pathlib.Path], refs: frozenset[pathlib.Path], repos: frozenset[pathlib.Path], snapshots: frozenset[pathlib.Path]) -> None
|
| Frozen data structure holding the strategy to delete cached revisions.
|
| This object is not meant to be instantiated programmatically but to be returned by
| [`~utils.HFCacheInfo.delete_revisions`]. See documentation for usage example.
|
| Args:
| expected_freed_size (`float`):
| Expected freed size once strategy is executed.
| blobs (`frozenset[Path]`):
| Set of blob file paths to be deleted.
| refs (`frozenset[Path]`):
| Set of reference file paths to be deleted.
| repos (`frozenset[Path]`):
| Set of entire repo paths to be deleted.
| snapshots (`frozenset[Path]`):
| Set of snapshots to be deleted (directory of symlinks).
|
| Methods defined here:
|
| __delattr__(self, name)
| Implement delattr(self, name).
|
| __eq__(self, other)
| Return self==value.
|
| __hash__(self)
| Return hash(self).
|
| __init__(self, expected_freed_size: int, blobs: frozenset[pathlib.Path], refs: frozenset[pathlib.Path], repos: frozenset[pathlib.Path], snapshots: frozenset[pathlib.Path]) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| __setattr__(self, name, value)
| Implement setattr(self, name, value).
|
| execute(self) -> None
| Execute the defined strategy.
|
| > [!WARNING]
| > If this method is interrupted, the cache might get corrupted. Deletion order is
| > implemented so that references and symlinks are deleted before the actual blob
| > files.
|
| > [!WARNING]
| > This method is irreversible. If executed, cached files are erased and must be
| > downloaded again.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| expected_freed_size_str
| (property) Expected size that will be freed as a human-readable string.
|
| Example: "42.2K".
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'blobs': frozenset[pathlib.Path], 'expected_freed_s...
|
| __dataclass_fields__ = {'blobs': Field(name='blobs',type=frozenset[pat...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __match_args__ = ('expected_freed_size', 'blobs', 'refs', 'repos', 'sn...
huggingface-hub.DepthEstimationInput
Python Library Documentation: class DepthEstimationInput in module huggingface_hub.inference._generated.types.depth_estimation
class DepthEstimationInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| DepthEstimationInput(inputs: Any, parameters: dict[str, typing.Any] | None = None) -> None
|
| Inputs for Depth Estimation inference
|
| Method resolution order:
| DepthEstimationInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: Any, parameters: dict[str, typing.Any] | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': typing.Any, 'parameters': dict[str, typin...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=typing.Any,...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.DepthEstimationOutput
Python Library Documentation: class DepthEstimationOutput in module huggingface_hub.inference._generated.types.depth_estimation
class DepthEstimationOutput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| DepthEstimationOutput(depth: Any, predicted_depth: Any) -> None
|
| Outputs of inference for the Depth Estimation task
|
| Method resolution order:
| DepthEstimationOutput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, depth: Any, predicted_depth: Any) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'depth': typing.Any, 'predicted_depth': typing.Any}
|
| __dataclass_fields__ = {'depth': Field(name='depth',type=typing.Any,de...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('depth', 'predicted_depth')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.Discussion
Python Library Documentation: class Discussion in module huggingface_hub.community
class Discussion(builtins.object)
| Discussion(title: str, status: Literal['open', 'closed', 'merged', 'draft'], num: int, repo_id: str, repo_type: str, author: str, is_pull_request: bool, created_at: datetime.datetime, endpoint: str) -> None
|
| A Discussion or Pull Request on the Hub.
|
| This dataclass is not intended to be instantiated directly.
|
| Attributes:
| title (`str`):
| The title of the Discussion / Pull Request
| status (`str`):
| The status of the Discussion / Pull Request.
| It must be one of:
| * `"open"`
| * `"closed"`
| * `"merged"` (only for Pull Requests )
| * `"draft"` (only for Pull Requests )
| num (`int`):
| The number of the Discussion / Pull Request.
| repo_id (`str`):
| The id (`"{namespace}/{repo_name}"`) of the repo on which
| the Discussion / Pull Request was open.
| repo_type (`str`):
| The type of the repo on which the Discussion / Pull Request was open.
| Possible values are: `"model"`, `"dataset"`, `"space"`.
| author (`str`):
| The username of the Discussion / Pull Request author.
| Can be `"deleted"` if the user has been deleted since.
| is_pull_request (`bool`):
| Whether or not this is a Pull Request.
| created_at (`datetime`):
| The `datetime` of creation of the Discussion / Pull Request.
| endpoint (`str`):
| Endpoint of the Hub. Default is https://huggingface.co.
| git_reference (`str`, *optional*):
| (property) Git reference to which changes can be pushed if this is a Pull Request, `None` otherwise.
| url (`str`):
| (property) URL of the discussion on the Hub.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, title: str, status: Literal['open', 'closed', 'merged', 'draft'], num: int, repo_id: str, repo_type: str, author: str, is_pull_request: bool, created_at: datetime.datetime, endpoint: str) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| git_reference
| If this is a Pull Request , returns the git reference to which changes can be pushed.
| Returns `None` otherwise.
|
| url
| Returns the URL of the discussion on the Hub.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'author': <class 'str'>, 'created_at': <class 'date...
|
| __dataclass_fields__ = {'author': Field(name='author',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('title', 'status', 'num', 'repo_id', 'repo_type', 'a...
huggingface-hub.DiscussionComment
Python Library Documentation: class DiscussionComment in module huggingface_hub.community
class DiscussionComment(DiscussionEvent)
| DiscussionComment(id: str, type: str, created_at: datetime.datetime, author: str, _event: dict, content: str, edited: bool, hidden: bool) -> None
|
| A comment in a Discussion / Pull Request.
|
| Subclass of [`DiscussionEvent`].
|
|
| Attributes:
| id (`str`):
| The ID of the event. An hexadecimal string.
| type (`str`):
| The type of the event.
| created_at (`datetime`):
| A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime)
| object holding the creation timestamp for the event.
| author (`str`):
| The username of the Discussion / Pull Request author.
| Can be `"deleted"` if the user has been deleted since.
| content (`str`):
| The raw markdown content of the comment. Mentions, links and images are not rendered.
| edited (`bool`):
| Whether or not this comment has been edited.
| hidden (`bool`):
| Whether or not this comment has been hidden.
|
| Method resolution order:
| DiscussionComment
| DiscussionEvent
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, id: str, type: str, created_at: datetime.datetime, author: str, _event: dict, content: str, edited: bool, hidden: bool) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| edit_history
| The edit history of the comment
|
| last_edited_at
| The last edit time, as a `datetime` object.
|
| last_edited_by
| The last edit time, as a `datetime` object.
|
| number_of_edits
|
| rendered
| The rendered comment, as a HTML string
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'content': <class 'str'>, 'edited': <class 'bool'>,...
|
| __dataclass_fields__ = {'_event': Field(name='_event',type=<class 'dic...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('id', 'type', 'created_at', 'author', '_event', 'con...
|
| ----------------------------------------------------------------------
| Data descriptors inherited from DiscussionEvent:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
huggingface-hub.DiscussionCommit
Python Library Documentation: class DiscussionCommit in module huggingface_hub.community
class DiscussionCommit(DiscussionEvent)
| DiscussionCommit(id: str, type: str, created_at: datetime.datetime, author: str, _event: dict, summary: str, oid: str) -> None
|
| A commit in a Pull Request.
|
| Subclass of [`DiscussionEvent`].
|
| Attributes:
| id (`str`):
| The ID of the event. An hexadecimal string.
| type (`str`):
| The type of the event.
| created_at (`datetime`):
| A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime)
| object holding the creation timestamp for the event.
| author (`str`):
| The username of the Discussion / Pull Request author.
| Can be `"deleted"` if the user has been deleted since.
| summary (`str`):
| The summary of the commit.
| oid (`str`):
| The OID / SHA of the commit, as a hexadecimal string.
|
| Method resolution order:
| DiscussionCommit
| DiscussionEvent
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, id: str, type: str, created_at: datetime.datetime, author: str, _event: dict, summary: str, oid: str) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'oid': <class 'str'>, 'summary': <class 'str'>}
|
| __dataclass_fields__ = {'_event': Field(name='_event',type=<class 'dic...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('id', 'type', 'created_at', 'author', '_event', 'sum...
|
| ----------------------------------------------------------------------
| Data descriptors inherited from DiscussionEvent:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
huggingface-hub.DiscussionEvent
Python Library Documentation: class DiscussionEvent in module huggingface_hub.community
class DiscussionEvent(builtins.object)
| DiscussionEvent(id: str, type: str, created_at: datetime.datetime, author: str, _event: dict) -> None
|
| An event in a Discussion or Pull Request.
|
| Use concrete classes:
| * [`DiscussionComment`]
| * [`DiscussionStatusChange`]
| * [`DiscussionCommit`]
| * [`DiscussionTitleChange`]
|
| Attributes:
| id (`str`):
| The ID of the event. An hexadecimal string.
| type (`str`):
| The type of the event.
| created_at (`datetime`):
| A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime)
| object holding the creation timestamp for the event.
| author (`str`):
| The username of the Discussion / Pull Request author.
| Can be `"deleted"` if the user has been deleted since.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, id: str, type: str, created_at: datetime.datetime, author: str, _event: dict) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_event': <class 'dict'>, 'author': <class 'str'>, ...
|
| __dataclass_fields__ = {'_event': Field(name='_event',type=<class 'dic...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('id', 'type', 'created_at', 'author', '_event')
huggingface-hub.DiscussionStatusChange
Python Library Documentation: class DiscussionStatusChange in module huggingface_hub.community
class DiscussionStatusChange(DiscussionEvent)
| DiscussionStatusChange(id: str, type: str, created_at: datetime.datetime, author: str, _event: dict, new_status: str) -> None
|
| A change of status in a Discussion / Pull Request.
|
| Subclass of [`DiscussionEvent`].
|
| Attributes:
| id (`str`):
| The ID of the event. An hexadecimal string.
| type (`str`):
| The type of the event.
| created_at (`datetime`):
| A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime)
| object holding the creation timestamp for the event.
| author (`str`):
| The username of the Discussion / Pull Request author.
| Can be `"deleted"` if the user has been deleted since.
| new_status (`str`):
| The status of the Discussion / Pull Request after the change.
| It can be one of:
| * `"open"`
| * `"closed"`
| * `"merged"` (only for Pull Requests )
|
| Method resolution order:
| DiscussionStatusChange
| DiscussionEvent
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, id: str, type: str, created_at: datetime.datetime, author: str, _event: dict, new_status: str) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'new_status': <class 'str'>}
|
| __dataclass_fields__ = {'_event': Field(name='_event',type=<class 'dic...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('id', 'type', 'created_at', 'author', '_event', 'new...
|
| ----------------------------------------------------------------------
| Data descriptors inherited from DiscussionEvent:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
huggingface-hub.DiscussionTitleChange
Python Library Documentation: class DiscussionTitleChange in module huggingface_hub.community
class DiscussionTitleChange(DiscussionEvent)
| DiscussionTitleChange(id: str, type: str, created_at: datetime.datetime, author: str, _event: dict, old_title: str, new_title: str) -> None
|
| A rename event in a Discussion / Pull Request.
|
| Subclass of [`DiscussionEvent`].
|
| Attributes:
| id (`str`):
| The ID of the event. An hexadecimal string.
| type (`str`):
| The type of the event.
| created_at (`datetime`):
| A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime)
| object holding the creation timestamp for the event.
| author (`str`):
| The username of the Discussion / Pull Request author.
| Can be `"deleted"` if the user has been deleted since.
| old_title (`str`):
| The previous title for the Discussion / Pull Request.
| new_title (`str`):
| The new title.
|
| Method resolution order:
| DiscussionTitleChange
| DiscussionEvent
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, id: str, type: str, created_at: datetime.datetime, author: str, _event: dict, old_title: str, new_title: str) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'new_title': <class 'str'>, 'old_title': <class 'st...
|
| __dataclass_fields__ = {'_event': Field(name='_event',type=<class 'dic...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('id', 'type', 'created_at', 'author', '_event', 'old...
|
| ----------------------------------------------------------------------
| Data descriptors inherited from DiscussionEvent:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
huggingface-hub.DiscussionWithDetails
Python Library Documentation: class DiscussionWithDetails in module huggingface_hub.community
class DiscussionWithDetails(Discussion)
| DiscussionWithDetails(title: str, status: Literal['open', 'closed', 'merged', 'draft'], num: int, repo_id: str, repo_type: str, author: str, is_pull_request: bool, created_at: datetime.datetime, endpoint: str, events: list['DiscussionEvent'], conflicting_files: list[str] | bool | None, target_branch: str | None, merge_commit_oid: str | None, diff: str | None) -> None
|
| Subclass of [`Discussion`].
|
| Attributes:
| title (`str`):
| The title of the Discussion / Pull Request
| status (`str`):
| The status of the Discussion / Pull Request.
| It can be one of:
| * `"open"`
| * `"closed"`
| * `"merged"` (only for Pull Requests )
| * `"draft"` (only for Pull Requests )
| num (`int`):
| The number of the Discussion / Pull Request.
| repo_id (`str`):
| The id (`"{namespace}/{repo_name}"`) of the repo on which
| the Discussion / Pull Request was open.
| repo_type (`str`):
| The type of the repo on which the Discussion / Pull Request was open.
| Possible values are: `"model"`, `"dataset"`, `"space"`.
| author (`str`):
| The username of the Discussion / Pull Request author.
| Can be `"deleted"` if the user has been deleted since.
| is_pull_request (`bool`):
| Whether or not this is a Pull Request.
| created_at (`datetime`):
| The `datetime` of creation of the Discussion / Pull Request.
| events (`list` of [`DiscussionEvent`])
| The list of [`DiscussionEvents`] in this Discussion or Pull Request.
| conflicting_files (`Union[list[str], bool, None]`, *optional*):
| A list of conflicting files if this is a Pull Request.
| `None` if `self.is_pull_request` is `False`.
| `True` if there are conflicting files but the list can't be retrieved.
| target_branch (`str`, *optional*):
| The branch into which changes are to be merged if this is a
| Pull Request . `None` if `self.is_pull_request` is `False`.
| merge_commit_oid (`str`, *optional*):
| If this is a merged Pull Request , this is set to the OID / SHA of
| the merge commit, `None` otherwise.
| diff (`str`, *optional*):
| The git diff if this is a Pull Request , `None` otherwise.
| endpoint (`str`):
| Endpoint of the Hub. Default is https://huggingface.co.
| git_reference (`str`, *optional*):
| (property) Git reference to which changes can be pushed if this is a Pull Request, `None` otherwise.
| url (`str`):
| (property) URL of the discussion on the Hub.
|
| Method resolution order:
| DiscussionWithDetails
| Discussion
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, title: str, status: Literal['open', 'closed', 'merged', 'draft'], num: int, repo_id: str, repo_type: str, author: str, is_pull_request: bool, created_at: datetime.datetime, endpoint: str, events: list['DiscussionEvent'], conflicting_files: list[str] | bool | None, target_branch: str | None, merge_commit_oid: str | None, diff: str | None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'conflicting_files': list[str] | bool | None, 'diff...
|
| __dataclass_fields__ = {'author': Field(name='author',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('title', 'status', 'num', 'repo_id', 'repo_type', 'a...
|
| ----------------------------------------------------------------------
| Readonly properties inherited from Discussion:
|
| git_reference
| If this is a Pull Request , returns the git reference to which changes can be pushed.
| Returns `None` otherwise.
|
| url
| Returns the URL of the discussion on the Hub.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Discussion:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
huggingface-hub.DocumentQuestionAnsweringInput
Python Library Documentation: class DocumentQuestionAnsweringInput in module huggingface_hub.inference._generated.types.document_question_answering
class DocumentQuestionAnsweringInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| DocumentQuestionAnsweringInput(inputs: huggingface_hub.inference._generated.types.document_question_answering.DocumentQuestionAnsweringInputData, parameters: huggingface_hub.inference._generated.types.document_question_answering.DocumentQuestionAnsweringParameters | None = None) -> None
|
| Inputs for Document Question Answering inference
|
| Method resolution order:
| DocumentQuestionAnsweringInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: huggingface_hub.inference._generated.types.document_question_answering.DocumentQuestionAnsweringInputData, parameters: huggingface_hub.inference._generated.types.document_question_answering.DocumentQuestionAnsweringParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'huggingface_hub.inference._genera...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'hug...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.DocumentQuestionAnsweringInputData
Python Library Documentation: class DocumentQuestionAnsweringInputData in module huggingface_hub.inference._generated.types.document_question_answering
class DocumentQuestionAnsweringInputData(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| DocumentQuestionAnsweringInputData(image: Any, question: str) -> None
|
| One (document, question) pair to answer
|
| Method resolution order:
| DocumentQuestionAnsweringInputData
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, image: Any, question: str) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'image': typing.Any, 'question': <class 'str'>}
|
| __dataclass_fields__ = {'image': Field(name='image',type=typing.Any,de...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('image', 'question')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.DocumentQuestionAnsweringOutputElement
Python Library Documentation: class DocumentQuestionAnsweringOutputElement in module huggingface_hub.inference._generated.types.document_question_answering
class DocumentQuestionAnsweringOutputElement(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| DocumentQuestionAnsweringOutputElement(answer: str, end: int, score: float, start: int) -> None
|
| Outputs of inference for the Document Question Answering task
|
| Method resolution order:
| DocumentQuestionAnsweringOutputElement
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, answer: str, end: int, score: float, start: int) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'answer': <class 'str'>, 'end': <class 'int'>, 'sco...
|
| __dataclass_fields__ = {'answer': Field(name='answer',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('answer', 'end', 'score', 'start')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.DocumentQuestionAnsweringParameters
Python Library Documentation: class DocumentQuestionAnsweringParameters in module huggingface_hub.inference._generated.types.document_question_answering
class DocumentQuestionAnsweringParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| DocumentQuestionAnsweringParameters(doc_stride: int | None = None, handle_impossible_answer: bool | None = None, lang: str | None = None, max_answer_len: int | None = None, max_question_len: int | None = None, max_seq_len: int | None = None, top_k: int | None = None, word_boxes: list[list[float] | str] | None = None) -> None
|
| Additional inference parameters for Document Question Answering
|
| Method resolution order:
| DocumentQuestionAnsweringParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, doc_stride: int | None = None, handle_impossible_answer: bool | None = None, lang: str | None = None, max_answer_len: int | None = None, max_question_len: int | None = None, max_seq_len: int | None = None, top_k: int | None = None, word_boxes: list[list[float] | str] | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'doc_stride': int | None, 'handle_impossible_answer...
|
| __dataclass_fields__ = {'doc_stride': Field(name='doc_stride',type=int...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('doc_stride', 'handle_impossible_answer', 'lang', 'm...
|
| doc_stride = None
|
| handle_impossible_answer = None
|
| lang = None
|
| max_answer_len = None
|
| max_question_len = None
|
| max_seq_len = None
|
| top_k = None
|
| word_boxes = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.DryRunFileInfo
Python Library Documentation: class DryRunFileInfo in module huggingface_hub.file_download
class DryRunFileInfo(builtins.object)
| DryRunFileInfo(commit_hash: str, file_size: int, filename: str, local_path: str, is_cached: bool, will_download: bool) -> None
|
| Information returned when performing a dry run of a file download.
|
| Returned by [`hf_hub_download`] when `dry_run=True`.
|
| Args:
| commit_hash (`str`):
| The commit_hash related to the file.
| file_size (`int`):
| Size of the file. In case of an LFS file, contains the size of the actual LFS file, not the pointer.
| filename (`str`):
| Name of the file in the repo.
| is_cached (`bool`):
| Whether the file is already cached locally.
| will_download (`bool`):
| Whether the file will be downloaded if `hf_hub_download` is called with `dry_run=False`.
| In practice, will_download is `True` if the file is not cached or if `force_download=True`.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, commit_hash: str, file_size: int, filename: str, local_path: str, is_cached: bool, will_download: bool) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'commit_hash': <class 'str'>, 'file_size': <class '...
|
| __dataclass_fields__ = {'commit_hash': Field(name='commit_hash',type=<...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('commit_hash', 'file_size', 'filename', 'local_path'...
huggingface-hub.EvalResult
Python Library Documentation: class EvalResult in module huggingface_hub.repocard_data
class EvalResult(builtins.object)
| EvalResult(task_type: str, dataset_type: str, dataset_name: str, metric_type: str, metric_value: Any, task_name: str | None = None, dataset_config: str | None = None, dataset_split: str | None = None, dataset_revision: str | None = None, dataset_args: dict[str, typing.Any] | None = None, metric_name: str | None = None, metric_config: str | None = None, metric_args: dict[str, typing.Any] | None = None, verified: bool | None = None, verify_token: str | None = None, source_name: str | None = None, source_url: str | None = None) -> None
|
| 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.
|
| 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: "Common Voice (French)".
| metric_type (`str`):
| The metric identifier. Example: "wer". Use metric id from https://hf.co/metrics.
| metric_value (`Any`):
| The metric value. Example: 0.9 or "20.0 ± 1.2".
| task_name (`str`, *optional*):
| A pretty name for the task. Example: "Speech Recognition".
| dataset_config (`str`, *optional*):
| The name of the dataset configuration used in `load_dataset()`.
| Example: fr in `load_dataset("common_voice", "fr")`. See the `datasets` docs for more info:
| https://hf.co/docs/datasets/package_reference/loading_methods#datasets.load_dataset.name
| 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, Any]`, *optional*):
| The arguments passed during `Metric.compute()`. Example for `bleu`: `{"max_order": 4}`
| metric_name (`str`, *optional*):
| A pretty name for the metric. Example: "Test WER".
| metric_config (`str`, *optional*):
| The name of the metric configuration used in `load_metric()`.
| Example: bleurt-large-512 in `load_metric("bleurt", "bleurt-large-512")`.
| See the `datasets` docs for more info: https://huggingface.co/docs/datasets/v2.1.0/en/loading#load-configurations
| metric_args (`dict[str, Any]`, *optional*):
| 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, do not set.
| verify_token (`str`, *optional*):
| A JSON Web Token that is used to verify whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not.
| source_name (`str`, *optional*):
| The name of the source of the evaluation result. Example: "Open LLM Leaderboard".
| source_url (`str`, *optional*):
| The URL of the source of the evaluation result. Example: "https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard".
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, task_type: str, dataset_type: str, dataset_name: str, metric_type: str, metric_value: Any, task_name: str | None = None, dataset_config: str | None = None, dataset_split: str | None = None, dataset_revision: str | None = None, dataset_args: dict[str, typing.Any] | None = None, metric_name: str | None = None, metric_config: str | None = None, metric_args: dict[str, typing.Any] | None = None, verified: bool | None = None, verify_token: str | None = None, source_name: str | None = None, source_url: str | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __post_init__(self) -> None
|
| __repr__(self)
| Return repr(self).
|
| is_equal_except_value(self, other: 'EvalResult') -> bool
| Return True if `self` and `other` describe exactly the same metric but with a
| different value.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| unique_identifier
| Returns a tuple that uniquely identifies this evaluation.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'dataset_args': dict[str, typing.Any] | None, 'data...
|
| __dataclass_fields__ = {'dataset_args': Field(name='dataset_args',type...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('task_type', 'dataset_type', 'dataset_name', 'metric...
|
| dataset_args = None
|
| dataset_config = None
|
| dataset_revision = None
|
| dataset_split = None
|
| metric_args = None
|
| metric_config = None
|
| metric_name = None
|
| source_name = None
|
| source_url = None
|
| task_name = None
|
| verified = None
|
| verify_token = None
huggingface-hub.EvalResultEntry
Python Library Documentation: class EvalResultEntry in module huggingface_hub._eval_results
class EvalResultEntry(builtins.object)
| EvalResultEntry(dataset_id: str, task_id: str, value: Any, dataset_revision: str | None = None, verify_token: str | None = None, date: str | None = None, source_url: str | None = None, source_name: str | None = None, source_user: str | None = None, source_org: str | None = None, notes: str | None = None) -> None
|
| Evaluation result entry for the `.eval_results/*.yaml` format.
|
| Represents evaluation scores stored in model repos that automatically appear on
| the model page and the benchmark dataset's leaderboard.
|
| For the legacy `model-index` format in `README.md`, use [`EvalResult`] instead.
|
| See https://huggingface.co/docs/hub/eval-results for more details.
|
| Args:
| dataset_id (`str`):
| Benchmark dataset ID from the Hub. Example: "cais/hle", "Idavidrein/gpqa".
| task_id (`str`):
| Task identifier within the benchmark. Example: "gpqa_diamond".
| value (`Any`):
| The metric value. Example: 20.90.
| dataset_revision (`str`, *optional*):
| Git SHA of the benchmark dataset.
| verify_token (`str`, *optional*):
| A signature that can be used to prove that evaluation is provably auditable and reproducible.
| date (`str`, *optional*):
| When the evaluation was run (ISO-8601 datetime). Defaults to git commit time.
| source_url (`str`, *optional*):
| Link to the evaluation source (e.g., https://huggingface.co/spaces/SaylorTwift/smollm3-mmlu-pro). Required if `source_name`, `source_user`, or `source_org` is provided.
| source_name (`str`, *optional*):
| Display name for the source. Example: "Eval Logs".
| source_user (`str`, *optional*):
| HF user name for attribution. Example: "celinah".
| source_org (`str`, *optional*):
| HF org name for attribution. Example: "cais".
| notes (`str`, *optional*):
| Details about the evaluation setup. Example: "tools", "no-tools", "chain-of-thought".
|
| Example:
| ```python
| >>> from huggingface_hub import EvalResultEntry
| >>> # Minimal example with required fields only
| >>> result = EvalResultEntry(
| ... dataset_id="Idavidrein/gpqa",
| ... task_id="gpqa_diamond",
| ... value=0.412,
| ... )
| >>> # Full example with all fields
| >>> result = EvalResultEntry(
| ... dataset_id="cais/hle",
| ... task_id="default",
| ... value=20.90,
| ... dataset_revision="5503434ddd753f426f4b38109466949a1217c2bb",
| ... verify_token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
| ... date="2025-01-15T10:30:00Z",
| ... source_url="https://huggingface.co/datasets/cais/hle",
| ... source_name="CAIS HLE",
| ... source_org="cais",
| ... notes="no-tools",
| ... )
|
| ```
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, dataset_id: str, task_id: str, value: Any, dataset_revision: str | None = None, verify_token: str | None = None, date: str | None = None, source_url: str | None = None, source_name: str | None = None, source_user: str | None = None, source_org: str | None = None, notes: str | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __post_init__(self) -> None
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'dataset_id': <class 'str'>, 'dataset_revision': st...
|
| __dataclass_fields__ = {'dataset_id': Field(name='dataset_id',type=<cl...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('dataset_id', 'task_id', 'value', 'dataset_revision'...
|
| dataset_revision = None
|
| date = None
|
| notes = None
|
| source_name = None
|
| source_org = None
|
| source_url = None
|
| source_user = None
|
| verify_token = None
huggingface-hub.FLAX_WEIGHTS_NAME
Error rendering doc: No Python documentation found for 'flax_model.msgpack'. Use help() to get the interactive help utility. Use help(str) for help on the str class.
huggingface-hub.FeatureExtractionInput
Python Library Documentation: class FeatureExtractionInput in module huggingface_hub.inference._generated.types.feature_extraction
class FeatureExtractionInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| FeatureExtractionInput(inputs: list[str] | str, normalize: bool | None = None, prompt_name: str | None = None, truncate: bool | None = None, truncation_direction: Optional[ForwardRef('FeatureExtractionInputTruncationDirection')] = None) -> None
|
| Feature Extraction Input.
| Auto-generated from TEI specs.
| For more details, check out
| https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tei-import.ts.
|
| Method resolution order:
| FeatureExtractionInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: list[str] | str, normalize: bool | None = None, prompt_name: str | None = None, truncate: bool | None = None, truncation_direction: Optional[ForwardRef('FeatureExtractionInputTruncationDirection')] = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': list[str] | str, 'normalize': bool | None...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=list[str] |...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'normalize', 'prompt_name', 'truncate', 't...
|
| normalize = None
|
| prompt_name = None
|
| truncate = None
|
| truncation_direction = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.FeatureExtractionInputTruncationDirection
Python Library Documentation: _LiteralGenericAlias in module typing
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
huggingface-hub.FillMaskInput
Python Library Documentation: class FillMaskInput in module huggingface_hub.inference._generated.types.fill_mask
class FillMaskInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| FillMaskInput(inputs: str, parameters: huggingface_hub.inference._generated.types.fill_mask.FillMaskParameters | None = None) -> None
|
| Inputs for Fill Mask inference
|
| Method resolution order:
| FillMaskInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: str, parameters: huggingface_hub.inference._generated.types.fill_mask.FillMaskParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'str'>, 'parameters': huggingface_...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.FillMaskOutputElement
Python Library Documentation: class FillMaskOutputElement in module huggingface_hub.inference._generated.types.fill_mask
class FillMaskOutputElement(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| FillMaskOutputElement(score: float, sequence: str, token: int, token_str: Any, fill_mask_output_token_str: str | None = None) -> None
|
| Outputs of inference for the Fill Mask task
|
| Method resolution order:
| FillMaskOutputElement
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, score: float, sequence: str, token: int, token_str: Any, fill_mask_output_token_str: str | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'fill_mask_output_token_str': str | None, 'score': ...
|
| __dataclass_fields__ = {'fill_mask_output_token_str': Field(name='fill...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('score', 'sequence', 'token', 'token_str', 'fill_mas...
|
| fill_mask_output_token_str = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.FillMaskParameters
Python Library Documentation: class FillMaskParameters in module huggingface_hub.inference._generated.types.fill_mask
class FillMaskParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| FillMaskParameters(targets: list[str] | None = None, top_k: int | None = None) -> None
|
| Additional inference parameters for Fill Mask
|
| Method resolution order:
| FillMaskParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, targets: list[str] | None = None, top_k: int | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'targets': list[str] | None, 'top_k': int | None}
|
| __dataclass_fields__ = {'targets': Field(name='targets',type=list[str]...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('targets', 'top_k')
|
| targets = None
|
| top_k = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.GitCommitInfo
Python Library Documentation: class GitCommitInfo in module huggingface_hub.hf_api
class GitCommitInfo(builtins.object)
| GitCommitInfo(commit_id: 'str', authors: 'list[str]', created_at: 'datetime', title: 'str', message: 'str', formatted_title: 'str | None', formatted_message: 'str | None') -> None
|
| Contains information about a git commit for a repo on the Hub. Check out [`list_repo_commits`] for more details.
|
| Attributes:
| commit_id (`str`):
| OID of the commit (e.g. `"e7da7f221d5bf496a48136c0cd264e630fe9fcc8"`)
| authors (`list[str]`):
| List of authors of the commit.
| created_at (`datetime`):
| Datetime when the commit was created.
| title (`str`):
| Title of the commit. This is a free-text value entered by the authors.
| message (`str`):
| Description of the commit. This is a free-text value entered by the authors.
| formatted_title (`str`):
| Title of the commit formatted as HTML. Only returned if `formatted=True` is set.
| formatted_message (`str`):
| Description of the commit formatted as HTML. Only returned if `formatted=True` is set.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, commit_id: 'str', authors: 'list[str]', created_at: 'datetime', title: 'str', message: 'str', formatted_title: 'str | None', formatted_message: 'str | None') -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'authors': 'list[str]', 'commit_id': 'str', 'create...
|
| __dataclass_fields__ = {'authors': Field(name='authors',type='list[str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('commit_id', 'authors', 'created_at', 'title', 'mess...
huggingface-hub.GitRefInfo
Python Library Documentation: class GitRefInfo in module huggingface_hub.hf_api
class GitRefInfo(builtins.object)
| GitRefInfo(name: 'str', ref: 'str', target_commit: 'str') -> None
|
| Contains information about a git reference for a repo on the Hub.
|
| Attributes:
| name (`str`):
| Name of the reference (e.g. tag name or branch name).
| ref (`str`):
| Full git ref on the Hub (e.g. `"refs/heads/main"` or `"refs/tags/v1.0"`).
| target_commit (`str`):
| OID of the target commit for the ref (e.g. `"e7da7f221d5bf496a48136c0cd264e630fe9fcc8"`)
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, name: 'str', ref: 'str', target_commit: 'str') -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'name': 'str', 'ref': 'str', 'target_commit': 'str'...
|
| __dataclass_fields__ = {'name': Field(name='name',type='str',default=<...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('name', 'ref', 'target_commit')
huggingface-hub.GitRefs
Python Library Documentation: class GitRefs in module huggingface_hub.hf_api
class GitRefs(builtins.object)
| GitRefs(branches: 'list[GitRefInfo]', converts: 'list[GitRefInfo]', tags: 'list[GitRefInfo]', pull_requests: 'list[GitRefInfo] | None' = None) -> None
|
| Contains information about all git references for a repo on the Hub.
|
| Object is returned by [`list_repo_refs`].
|
| Attributes:
| branches (`list[GitRefInfo]`):
| A list of [`GitRefInfo`] containing information about branches on the repo.
| converts (`list[GitRefInfo]`):
| A list of [`GitRefInfo`] containing information about "convert" refs on the repo.
| Converts are refs used (internally) to push preprocessed data in Dataset repos.
| tags (`list[GitRefInfo]`):
| A list of [`GitRefInfo`] containing information about tags on the repo.
| pull_requests (`list[GitRefInfo]`, *optional*):
| A list of [`GitRefInfo`] containing information about pull requests on the repo.
| Only returned if `include_prs=True` is set.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, branches: 'list[GitRefInfo]', converts: 'list[GitRefInfo]', tags: 'list[GitRefInfo]', pull_requests: 'list[GitRefInfo] | None' = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'branches': 'list[GitRefInfo]', 'converts': 'list[G...
|
| __dataclass_fields__ = {'branches': Field(name='branches',type='list[G...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('branches', 'converts', 'tags', 'pull_requests')
|
| pull_requests = None
huggingface-hub.HFCacheInfo
Python Library Documentation: class HFCacheInfo in module huggingface_hub.utils._cache_manager
class HFCacheInfo(builtins.object)
| HFCacheInfo(size_on_disk: int, repos: frozenset[huggingface_hub.utils._cache_manager.CachedRepoInfo], incomplete_files: frozenset[huggingface_hub.utils._cache_manager.CachedIncompleteFileInfo], warnings: list[huggingface_hub.errors.CorruptedCacheException]) -> None
|
| Frozen data structure holding information about the entire cache-system.
|
| This data structure is returned by [`scan_cache_dir`] and is immutable.
|
| Args:
| size_on_disk (`int`):
| Sum of all valid repo sizes in the cache-system.
| repos (`frozenset[CachedRepoInfo]`):
| Set of [`~CachedRepoInfo`] describing all valid cached repos found on the
| cache-system while scanning.
| incomplete_files (`frozenset[CachedIncompleteFileInfo]`):
| Set of [`~CachedIncompleteFileInfo`] describing orphaned `*.incomplete`
| files left behind by interrupted downloads.
| warnings (`list[CorruptedCacheException]`):
| List of [`~CorruptedCacheException`] that occurred while scanning the cache.
| Those exceptions are captured so that the scan can continue. Corrupted repos
| are skipped from the scan.
|
| > [!WARNING]
| > Here `size_on_disk` is equal to the sum of all repo sizes (only blobs). However if
| > some cached repos are corrupted, their sizes are not taken into account.
|
| Methods defined here:
|
| __delattr__(self, name)
| Implement delattr(self, name).
|
| __eq__(self, other)
| Return self==value.
|
| __hash__(self)
| Return hash(self).
|
| __init__(self, size_on_disk: int, repos: frozenset[huggingface_hub.utils._cache_manager.CachedRepoInfo], incomplete_files: frozenset[huggingface_hub.utils._cache_manager.CachedIncompleteFileInfo], warnings: list[huggingface_hub.errors.CorruptedCacheException]) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| __setattr__(self, name, value)
| Implement setattr(self, name, value).
|
| delete_revisions(self, *revisions: str) -> huggingface_hub.utils._cache_manager.DeleteCacheStrategy
| Prepare the strategy to delete one or more revisions cached locally.
|
| Input revisions can be any revision hash. If a revision hash is not found in the
| local cache, a warning is thrown but no error is raised. Revisions can be from
| different cached repos since hashes are unique across repos,
|
| Examples:
| ```py
| >>> from huggingface_hub import scan_cache_dir
| >>> cache_info = scan_cache_dir()
| >>> delete_strategy = cache_info.delete_revisions(
| ... "81fd1d6e7847c99f5862c9fb81387956d99ec7aa"
| ... )
| >>> print(f"Will free {delete_strategy.expected_freed_size_str}.")
| Will free 7.9K.
| >>> delete_strategy.execute()
| Cache deletion done. Saved 7.9K.
| ```
|
| ```py
| >>> from huggingface_hub import scan_cache_dir
| >>> scan_cache_dir().delete_revisions(
| ... "81fd1d6e7847c99f5862c9fb81387956d99ec7aa",
| ... "e2983b237dccf3ab4937c97fa717319a9ca1a96d",
| ... "6c0e6080953db56375760c0471a8c5f2929baf11",
| ... ).execute()
| Cache deletion done. Saved 8.6G.
| ```
|
| > [!WARNING]
| > `delete_revisions` returns a [`~utils.DeleteCacheStrategy`] object that needs to
| > be executed. The [`~utils.DeleteCacheStrategy`] is not meant to be modified but
| > allows having a dry run before actually executing the deletion.
|
| export_as_table(self, *, verbosity: int = 0) -> str
| Generate a table from the [`HFCacheInfo`] object.
|
| Pass `verbosity=0` to get a table with a single row per repo, with columns
| "repo_id", "repo_type", "size_on_disk", "nb_files", "last_accessed", "last_modified", "refs", "local_path".
|
| Pass `verbosity=1` to get a table with a row per repo and revision (thus multiple rows can appear for a single repo), with columns
| "repo_id", "repo_type", "revision", "size_on_disk", "nb_files", "last_modified", "refs", "local_path".
|
| Example:
| ```py
| >>> from huggingface_hub.utils import scan_cache_dir
|
| >>> hf_cache_info = scan_cache_dir()
| HFCacheInfo(...)
|
| >>> print(hf_cache_info.export_as_table())
| REPO ID REPO TYPE SIZE ON DISK NB FILES LAST_ACCESSED LAST_MODIFIED REFS LOCAL PATH
| --------------------------------------------------- --------- ------------ -------- ------------- ------------- ---- --------------------------------------------------------------------------------------------------
| roberta-base model 2.7M 5 1 day ago 1 week ago main ~/.cache/huggingface/hub/models--roberta-base
| suno/bark model 8.8K 1 1 week ago 1 week ago main ~/.cache/huggingface/hub/models--suno--bark
| t5-base model 893.8M 4 4 days ago 7 months ago main ~/.cache/huggingface/hub/models--t5-base
| t5-large model 3.0G 4 5 weeks ago 5 months ago main ~/.cache/huggingface/hub/models--t5-large
|
| >>> print(hf_cache_info.export_as_table(verbosity=1))
| REPO ID REPO TYPE REVISION SIZE ON DISK NB FILES LAST_MODIFIED REFS LOCAL PATH
| --------------------------------------------------- --------- ---------------------------------------- ------------ -------- ------------- ---- -----------------------------------------------------------------------------------------------------------------------------------------------------
| roberta-base model e2da8e2f811d1448a5b465c236feacd80ffbac7b 2.7M 5 1 week ago main ~/.cache/huggingface/hub/models--roberta-base/snapshots/e2da8e2f811d1448a5b465c236feacd80ffbac7b
| suno/bark model 70a8a7d34168586dc5d028fa9666aceade177992 8.8K 1 1 week ago main ~/.cache/huggingface/hub/models--suno--bark/snapshots/70a8a7d34168586dc5d028fa9666aceade177992
| t5-base model a9723ea7f1b39c1eae772870f3b547bf6ef7e6c1 893.8M 4 7 months ago main ~/.cache/huggingface/hub/models--t5-base/snapshots/a9723ea7f1b39c1eae772870f3b547bf6ef7e6c1
| t5-large model 150ebc2c4b72291e770f58e6057481c8d2ed331a 3.0G 4 5 months ago main ~/.cache/huggingface/hub/models--t5-large/snapshots/150ebc2c4b72291e770f58e6057481c8d2ed331a
| ```
|
| Args:
| verbosity (`int`, *optional*):
| The verbosity level. Defaults to 0.
|
| Returns:
| `str`: The table as a string.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| incomplete_size_on_disk
| (property) Sum of all incomplete download sizes in bytes.
|
| size_on_disk_str
| (property) Sum of all valid repo sizes in the cache-system as a human-readable
| string.
|
| Example: "42.2K".
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'incomplete_files': frozenset[huggingface_hub.utils...
|
| __dataclass_fields__ = {'incomplete_files': Field(name='incomplete_fil...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __match_args__ = ('size_on_disk', 'repos', 'incomplete_files', 'warnin...
huggingface-hub.HFSummaryWriter
Error rendering doc: initialization of _pywrap_checkpoint_reader raised unreported exception
huggingface-hub.HUGGINGFACE_CO_URL_HOME
Error rendering doc: No Python documentation found for 'https://huggingface.co/'. Use help() to get the interactive help utility. Use help(str) for help on the str class.
huggingface-hub.HUGGINGFACE_CO_URL_TEMPLATE
Error rendering doc: No Python documentation found for 'https://huggingface.co/{repo_id}/resolve/{revision}/{filename}'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.
huggingface-hub.HfApi
Python Library Documentation: class HfApi in module huggingface_hub.hf_api
class HfApi(builtins.object)
| HfApi(endpoint: 'str | None' = None, token: 'str | bool | None' = None, library_name: 'str | None' = None, library_version: 'str | None' = None, user_agent: 'dict | str | None' = None, headers: 'dict[str, str] | None' = None) -> 'None'
|
| Client to interact with the Hugging Face Hub via HTTP.
|
| The client is initialized with some high-level settings used in all requests
| made to the Hub (HF endpoint, authentication, user agents...). Using the `HfApi`
| client is preferred but not mandatory as all of its public methods are exposed
| directly at the root of `huggingface_hub`.
|
| Args:
| endpoint (`str`, *optional*):
| Endpoint of the Hub. Defaults to <https://huggingface.co>.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| library_name (`str`, *optional*):
| The name of the library that is making the HTTP request. Will be added to
| the user-agent header. Example: `"transformers"`.
| library_version (`str`, *optional*):
| The version of the library that is making the HTTP request. Will be added
| to the user-agent header. Example: `"4.24.0"`.
| user_agent (`str`, `dict`, *optional*):
| The user agent info in the form of a dictionary or a single string. It will
| be completed with information about the installed packages.
| headers (`dict`, *optional*):
| Additional headers to be sent with each request. Example: `{"X-My-Header": "value"}`.
| Headers passed here are taking precedence over the default headers.
|
| Methods defined here:
|
| __init__(self, endpoint: 'str | None' = None, token: 'str | bool | None' = None, library_name: 'str | None' = None, library_version: 'str | None' = None, user_agent: 'dict | str | None' = None, headers: 'dict[str, str] | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| accept_access_request(self, repo_id: 'str', user: 'str', *, repo_type: 'str | None' = None, token: 'bool | str | None' = None) -> 'None'
| Accept an access request from a user for a given gated repo.
|
| Once the request is accepted, the user will be able to download any file of the repo and access the community
| tab. If the approval mode is automatic, you don't have to accept requests manually. An accepted request can be
| cancelled or rejected at any time using [`cancel_access_request`] and [`reject_access_request`].
|
| For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
|
| Args:
| repo_id (`str`):
| The id of the repo to accept access request for.
| user (`str`):
| The username of the user which access request should be accepted.
| repo_type (`str`, *optional*):
| The type of the repo to accept access request for. Must be one of `model`, `dataset` or `space`.
| Defaults to `model`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Raises:
| [`HfHubHTTPError`]:
| HTTP 400 if the repo is not gated.
| [`HfHubHTTPError`]:
| HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
| or `admin` role in the organization the repo belongs to or if you passed a `read` token.
| [`HfHubHTTPError`]:
| HTTP 404 if the user does not exist on the Hub.
| [`HfHubHTTPError`]:
| HTTP 404 if the user access request cannot be found.
| [`HfHubHTTPError`]:
| HTTP 404 if the user access request is already in the accepted list.
|
| add_collection_item(self, collection_slug: 'str', item_id: 'str', item_type: 'CollectionItemType_T', *, note: 'str | None' = None, exists_ok: 'bool' = False, token: 'bool | str | None' = None) -> 'Collection'
| Add an item to a collection on the Hub.
|
| Args:
| collection_slug (`str`):
| Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
| item_id (`str`):
| Id of the item to add to the collection. Use the repo_id for repos/spaces/datasets,
| the paper id for papers, the slug of another collection (e.g. `"moonshotai/kimi-k2"`)
| or a bucket id (e.g. `"namespace/bucket-name"`).
| item_type (`str`):
| Type of the item to add. Can be one of `"model"`, `"dataset"`, `"space"`, `"paper"`, `"collection"`
| or `"bucket"`.
| note (`str`, *optional*):
| A note to attach to the item in the collection. The maximum size for a note is 500 characters.
| exists_ok (`bool`, *optional*):
| If `True`, do not raise an error if item already exists.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns: [`Collection`]
|
| Raises:
| [`HfHubHTTPError`]:
| HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
| or `admin` role in the organization the repo belongs to or if you passed a `read` token.
| [`HfHubHTTPError`]:
| HTTP 404 if the item you try to add to the collection does not exist on the Hub.
| [`HfHubHTTPError`]:
| HTTP 409 if the item you try to add to the collection is already in the collection (and exists_ok=False)
|
| Example:
|
| ```py
| >>> from huggingface_hub import add_collection_item
| >>> collection = add_collection_item(
| ... collection_slug="davanstrien/climate-64f99dc2a5067f6b65531bab",
| ... item_id="pierre-loic/climate-news-articles",
| ... item_type="dataset"
| ... )
| >>> collection.items[-1].item_id
| "pierre-loic/climate-news-articles"
| # ^item got added to the collection on last position
|
| # Add item with a note
| >>> add_collection_item(
| ... collection_slug="davanstrien/climate-64f99dc2a5067f6b65531bab",
| ... item_id="datasets/climate_fever",
| ... item_type="dataset"
| ... note="This dataset adopts the FEVER methodology that consists of 1,535 real-world claims regarding climate-change collected on the internet."
| ... )
| (...)
| ```
|
| add_space_secret(self, repo_id: 'str', key: 'str', value: 'str', *, description: 'str | None' = None, token: 'bool | str | None' = None) -> 'None'
| Adds or updates a secret in a Space.
|
| Secrets allow to set secret keys or tokens to a Space without hardcoding them.
| For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
|
| Args:
| repo_id (`str`):
| ID of the repo to update. Example: `"bigcode/in-the-stack"`.
| key (`str`):
| Secret key. Example: `"GITHUB_API_KEY"`
| value (`str`):
| Secret value. Example: `"your_github_api_key"`.
| description (`str`, *optional*):
| Secret description. Example: `"Github API key to access the Github API"`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| add_space_variable(self, repo_id: 'str', key: 'str', value: 'str', *, description: 'str | None' = None, token: 'bool | str | None' = None) -> 'dict[str, SpaceVariable]'
| Adds or updates a variable in a Space.
|
| Variables allow to set environment variables to a Space without hardcoding them.
| For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables
|
| Args:
| repo_id (`str`):
| ID of the repo to update. Example: `"bigcode/in-the-stack"`.
| key (`str`):
| Variable key. Example: `"MODEL_REPO_ID"`
| value (`str`):
| Variable value. Example: `"the_model_repo_id"`.
| description (`str`):
| Description of the variable. Example: `"Model Repo ID of the implemented model"`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| auth_check(self, repo_id: 'str', *, repo_type: 'str | None' = None, token: 'bool | str | None' = None, write: 'bool' = False) -> 'None'
| Check if the provided user token has access to a specific repository on the Hugging Face Hub.
|
| This method verifies whether the user, authenticated via the provided token, has access to the specified
| repository. If the repository is not found or if the user lacks the required permissions to access it,
| the method raises an appropriate exception.
|
| Args:
| repo_id (`str`):
| The repository to check for access. Format should be `"user/repo_name"`.
| Example: `"user/my-cool-model"`.
|
| repo_type (`str`, *optional*):
| The type of the repository. Should be one of `"model"`, `"dataset"`, or `"space"`.
| If not specified, the default is `"model"`.
|
| token (`Union[bool, str, None]`, *optional*):
| A valid user access token. If not provided, the locally saved token will be used, which is the
| recommended authentication method. Set to `False` to disable authentication.
| Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
|
| write (`bool`, *optional*):
| If `True`, checks whether the user has content write permission on the repository.
| If `False` (default), only checks for read access.
|
| Raises:
| [`~utils.RepositoryNotFoundError`]:
| Raised if the repository does not exist, is private, or the user does not have access. This can
| occur if the `repo_id` or `repo_type` is incorrect or if the repository is private but the user
| is not authenticated.
|
| [`~utils.GatedRepoError`]:
| Raised if the repository exists but is gated and the user is not authorized to access it.
|
| Example:
| Check if the user has access to a repository:
|
| ```python
| >>> from huggingface_hub import auth_check
| >>> from huggingface_hub.utils import GatedRepoError, RepositoryNotFoundError
|
| try:
| auth_check("user/my-cool-model")
| except GatedRepoError:
| # Handle gated repository error
| print("You do not have permission to access this gated repository.")
| except RepositoryNotFoundError:
| # Handle repository not found error
| print("The repository was not found or you do not have access.")
| ```
|
| In this example:
| - If the user has access, the method completes successfully.
| - If the repository is gated or does not exist, appropriate exceptions are raised, allowing the user
| to handle them accordingly.
|
| batch_bucket_files(self, bucket_id: 'str', *, add: 'list[tuple[str | Path | bytes, str]] | None' = None, copy: 'list[tuple[str, str, str, str]] | None' = None, delete: 'list[str] | None' = None, token: 'str | bool | None' = None)
| Add, copy, and/or delete files in a bucket.
|
| This is a non-transactional operation. If an error occurs in the process, some files may have been uploaded,
| copied, or deleted while others haven't.
|
| Args:
| bucket_id (`str`):
| The ID of the bucket (e.g. `"username/my-bucket"`).
| add (`list` of `tuple`, *optional*):
| Files to upload. Each element is a `(source, destination)` tuple where `source` is a path to a local
| file (`str` or `Path`) or raw `bytes` content, and `destination` is the path in the bucket.
| copy (`list` of `tuple`, *optional*):
| Files to copy by xet hash. Each element is a `(source_repo_type, source_repo_id, xet_hash,
| destination)` tuple where:
| - `source_repo_type` is the type of the source repository: `"model"`, `"dataset"`, `"space"`, or
| `"bucket"`.
| - `source_repo_id` is the ID of the source repository or bucket (e.g. `"username/my-model"`).
| - `xet_hash` is the xet hash of the file to copy.
| - `destination` is the destination path in the bucket.
| This is a server-side operation — no data is downloaded or re-uploaded.
| delete (`list` of `str`, *optional*):
| Paths of files to delete from the bucket.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Example:
| ```python
| >>> from huggingface_hub import batch_bucket_files
|
| # Upload files
| >>> batch_bucket_files(
| ... "username/my-bucket",
| ... add=[
| ... ("./model.safetensors", "models/model.safetensors"),
| ... (b'{{"key": "value"}}', "config.json"),
| ... ],
| ... )
|
| # Copy xet files from another bucket or repo (server-side, no data transfer)
| >>> batch_bucket_files(
| ... "username/my-bucket",
| ... copy=[
| ... ("bucket", "username/source-bucket", "<xethash_1>", "models/model.safetensors"),
| ... ("model", "username/my-model", "<xethash_2>", "models/config.safetensors"),
| ... ],
| ... )
|
| # Delete files
| >>> batch_bucket_files("username/my-bucket", delete=["old-model.bin"])
|
| # Upload and delete in one batch
| >>> batch_bucket_files(
| ... "username/my-bucket",
| ... add=[("./new.txt", "new.txt")],
| ... delete=["old.txt"],
| ... )
| ```
|
| bucket_info(self, bucket_id: 'str', *, token: 'bool | str | None' = None) -> 'BucketInfo'
| Get information about a specific bucket on the Hub.
|
| Args:
| bucket_id (`str`):
| The ID of the bucket (e.g. `"username/my-bucket"`).
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`BucketInfo`]: The bucket information.
|
| Raises:
| [`~errors.BucketNotFoundError`]: If the bucket cannot be found. This may be because it doesn't exist,
| or because it is set to `private` and you do not have access.
|
| Example:
| ```python
| >>> from huggingface_hub import bucket_info
| >>> info = bucket_info(bucket_id="Wauplin/first-bucket")
| >>> info.id
| 'Wauplin/first-bucket'
| >>> info.private
| False
| >>> info.created_at
| datetime.datetime(2026, 2, 6, 17, 37, 57, tzinfo=datetime.timezone.utc)
| >>> info.size
| 551879671
| >>> info.total_files
| 12
| ```
|
| cancel_access_request(self, repo_id: 'str', user: 'str', *, repo_type: 'str | None' = None, token: 'bool | str | None' = None) -> 'None'
| Cancel an access request from a user for a given gated repo.
|
| A cancelled request will go back to the pending list and the user will lose access to the repo.
|
| For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
|
| Args:
| repo_id (`str`):
| The id of the repo to cancel access request for.
| user (`str`):
| The username of the user which access request should be cancelled.
| repo_type (`str`, *optional*):
| The type of the repo to cancel access request for. Must be one of `model`, `dataset` or `space`.
| Defaults to `model`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Raises:
| [`HfHubHTTPError`]:
| HTTP 400 if the repo is not gated.
| [`HfHubHTTPError`]:
| HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
| or `admin` role in the organization the repo belongs to or if you passed a `read` token.
| [`HfHubHTTPError`]:
| HTTP 404 if the user does not exist on the Hub.
| [`HfHubHTTPError`]:
| HTTP 404 if the user access request cannot be found.
| [`HfHubHTTPError`]:
| HTTP 404 if the user access request is already in the pending list.
|
| cancel_job(self, *, job_id: 'str', namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'None'
| Cancel a compute Job on Hugging Face infrastructure.
|
| Args:
| job_id (`str`):
| ID of the Job.
|
| namespace (`str`, *optional*):
| The namespace where the Job is running. Defaults to the current user's namespace.
|
| token `(Union[bool, str, None]`, *optional*):
| A valid user access token. If not provided, the locally saved token will be used, which is the
| recommended authentication method. Set to `False` to disable authentication.
| Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
|
| change_discussion_status(self, repo_id: 'str', discussion_num: 'int', new_status: "Literal['open', 'closed']", *, token: 'bool | str | None' = None, comment: 'str | None' = None, repo_type: 'str | None' = None) -> 'DiscussionStatusChange'
| Closes or re-opens a Discussion or Pull Request.
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated
| by a `/`.
| discussion_num (`int`):
| The number of the Discussion or Pull Request . Must be a strictly positive integer.
| new_status (`str`):
| The new status for the discussion, either `"open"` or `"closed"`.
| comment (`str`, *optional*):
| An optional comment to post with the status change.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if uploading to a dataset or
| space, `None` or `"model"` if uploading to a model. Default is
| `None`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`DiscussionStatusChange`]: the status change event
|
|
| Examples:
| ```python
| >>> new_title = "New title, fixing a typo"
| >>> HfApi().rename_discussion(
| ... repo_id="username/repo_name",
| ... discussion_num=34
| ... new_title=new_title
| ... )
| # DiscussionStatusChange(id='deadbeef0000000', type='status-change', ...)
|
| ```
|
| > [!TIP]
| > Raises the following errors:
| >
| > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
| > if the HuggingFace API returned an error
| > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| > if some parameter value is invalid
| > - [`~utils.RepositoryNotFoundError`]
| > If the repository to download from cannot be found. This may be because it doesn't exist,
| > or because it is set to `private` and you do not have access.
|
| comment_discussion(self, repo_id: 'str', discussion_num: 'int', comment: 'str', *, token: 'bool | str | None' = None, repo_type: 'str | None' = None) -> 'DiscussionComment'
| Creates a new comment on the given Discussion.
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated
| by a `/`.
| discussion_num (`int`):
| The number of the Discussion or Pull Request . Must be a strictly positive integer.
| comment (`str`):
| The content of the comment to create. Comments support markdown formatting.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if uploading to a dataset or
| space, `None` or `"model"` if uploading to a model. Default is
| `None`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`DiscussionComment`]: the newly created comment
|
|
| Examples:
| ```python
|
| >>> comment = """
| ... Hello @otheruser!
| ...
| ... # This is a title
| ...
| ... **This is bold**, *this is italic* and ~this is strikethrough~
| ... And [this](http://url) is a link
| ... """
|
| >>> HfApi().comment_discussion(
| ... repo_id="username/repo_name",
| ... discussion_num=34
| ... comment=comment
| ... )
| # DiscussionComment(id='deadbeef0000000', type='comment', ...)
|
| ```
|
| > [!TIP]
| > Raises the following errors:
| >
| > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
| > if the HuggingFace API returned an error
| > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| > if some parameter value is invalid
| > - [`~utils.RepositoryNotFoundError`]
| > If the repository to download from cannot be found. This may be because it doesn't exist,
| > or because it is set to `private` and you do not have access.
|
| copy_files(self, source: 'str', destination: 'str', *, token: 'str | bool | None' = None) -> 'None'
| Copy files between locations on the Hub.
|
| Copy files from a bucket or repository (model, dataset, space) to a bucket or another repository.
| Both individual files and entire folders are supported.
|
| When copying folders, a trailing `/` on the source path uses rsync-style semantics: copy the *contents*
| of the folder into the destination, without nesting the source folder itself. Without a trailing `/`,
| the source folder is nested inside the destination (like `cp -r`).
|
| When copying from a repository to a bucket, `.gitattributes` files are automatically excluded since they
| are git-specific metadata and not relevant in a bucket context.
|
| Repo-to-repo copies use [`CommitOperationCopy`] under the hood and create a commit on the destination
| repository. Bucket-to-repo copies are not supported.
|
| > [!WARNING]
| > Server-side copies only work within the same [storage region](https://huggingface.co/docs/hub/storage-regions).
|
| Args:
| source (`str`):
| Source location as an `hf://` URI. Can be a bucket path (e.g. `"hf://buckets/my-bucket/path/to/file"`)
| or a repo path (e.g. `"hf://username/my-model/weights.bin"`, `"hf://datasets/username/my-dataset/data/"`).
| destination (`str`):
| Destination location as an `hf://` URI pointing to a bucket (e.g. `"hf://buckets/my-bucket/target/path"`)
| or a repository (e.g. `"hf://username/my-model/target/path"`).
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Raises:
| [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError):
| If source/destination URIs are invalid or if copying from a bucket to a repo.
|
| Example:
| ```python
| >>> from huggingface_hub import copy_files
|
| # Copy a single file between buckets
| >>> copy_files("hf://buckets/my-bucket/data.bin", "hf://buckets/other-bucket/data.bin")
|
| # Copy a folder into another bucket (nests: backup/models/...)
| >>> copy_files("hf://buckets/my-bucket/models", "hf://buckets/other-bucket/backup/")
|
| # Copy folder contents (trailing /): files go directly into backup/
| >>> copy_files("hf://buckets/my-bucket/models/", "hf://buckets/other-bucket/backup/")
|
| # Copy a file from a model repo to a bucket
| >>> copy_files("hf://username/my-model/model.safetensors", "hf://buckets/my-bucket/")
|
| # Copy an entire dataset to a bucket
| >>> copy_files("hf://datasets/username/my-dataset/", "hf://buckets/my-bucket/datasets/")
|
| # Copy files between repositories
| >>> copy_files("hf://username/source-model/", "hf://username/dest-model/")
|
| # Copy a file from one repo to another
| >>> copy_files("hf://username/source-model/config.json", "hf://username/dest-model/config.json")
| ```
|
| create_branch(self, repo_id: 'str', *, branch: 'str', revision: 'str | None' = None, token: 'bool | str | None' = None, repo_type: 'str | None' = None, exist_ok: 'bool' = False) -> 'None'
| Create a new branch for a repo on the Hub, starting from the specified revision (defaults to `main`).
| To find a revision suiting your needs, you can use [`list_repo_refs`] or [`list_repo_commits`].
|
| Args:
| repo_id (`str`):
| The repository in which the branch will be created.
| Example: `"user/my-cool-model"`.
|
| branch (`str`):
| The name of the branch to create.
|
| revision (`str`, *optional*):
| The git revision to create the branch from. It can be a branch name or
| the OID/SHA of a commit, as a hexadecimal string. Defaults to the head
| of the `"main"` branch.
|
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if creating a branch on a dataset or
| space, `None` or `"model"` if tagging a model. Default is `None`.
|
| exist_ok (`bool`, *optional*, defaults to `False`):
| If `True`, do not raise an error if branch already exists.
|
| Raises:
| [`~utils.RepositoryNotFoundError`]:
| If repository is not found (error 404): wrong repo_id/repo_type, private
| but not authenticated or repo does not exist.
| [`~utils.BadRequestError`]:
| If invalid reference for a branch. Ex: `refs/pr/5` or 'refs/foo/bar'.
| [`~utils.HfHubHTTPError`]:
| If the branch already exists on the repo (error 409) and `exist_ok` is
| set to `False`.
|
| create_bucket(self, bucket_id: 'str', *, private: 'bool | None' = None, resource_group_id: 'str | None' = None, region: 'REPO_REGIONS | None' = None, exist_ok: 'bool' = False, token: 'bool | str | None' = None) -> 'BucketUrl'
| Create a bucket on the Hub.
|
| Args:
| bucket_id (`str`):
| A namespace (user or an organization) and a bucket name separated by a `/`.
| If no namespace is provided, the bucket will be created in the current user's namespace.
| private (`bool`, *optional*):
| Whether to make the bucket private. If `None` (default), the bucket will be public unless the
| organization's default is private.
| resource_group_id (`str`, *optional*):
| Resource group in which to create the bucket. Resource groups are only available for Enterprise Hub
| organizations and allow to define which members of the organization can access the resource. The ID
| of a resource group can be found in the URL of the resource's page on the Hub
| (e.g. `"66670e5163145ca562cb1988"`). To learn more about resource groups, see
| https://huggingface.co/docs/hub/en/security-resource-groups.
| region (`Literal["us", "eu"]`, *optional*):
| Cloud region in which to create the bucket. Can be one of `"us"` or `"eu"`. If not specified, the bucket will be
| created in the default region. Requires Team plan or above.
| exist_ok (`bool`, *optional*, defaults to `False`):
| If `True`, do not raise an error if the bucket already exists.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`BucketUrl`]: URL to the newly created bucket containing
| attributes like `endpoint`, `namespace`, and `bucket_id`.
|
| Example:
| ```python
| >>> from huggingface_hub import create_bucket
|
| >>> url = create_bucket(bucket_id="my-bucket")
| >>> url.bucket_id
| 'user/my-bucket'
| >>> url.url
| 'https://huggingface.co/buckets/user/my-bucket'
| >>> url.uri.to_uri()
| 'hf://buckets/user/my-bucket'
|
| >>> create_bucket(bucket_id="my-bucket", private=True, exist_ok=True)
| BucketUrl(...)
|
| >>> create_bucket(bucket_id="my-bucket", region="us")
| BucketUrl(...)
| ```
|
| create_collection(self, title: 'str', *, namespace: 'str | None' = None, description: 'str | None' = None, private: 'bool' = False, resource_group_id: 'str | None' = None, exists_ok: 'bool' = False, token: 'bool | str | None' = None) -> 'Collection'
| Create a new Collection on the Hub.
|
| Args:
| title (`str`):
| Title of the collection to create. Example: `"Recent models"`.
| namespace (`str`, *optional*):
| Namespace of the collection to create (username or org). Will default to the owner name.
| description (`str`, *optional*):
| Description of the collection to create. The maximum size for a description is 150 characters.
| private (`bool`, *optional*):
| Whether the collection should be private or not. Defaults to `False` (i.e. public collection).
| resource_group_id (`str`, *optional*):
| Assign the collection to a resource group of the owning organization. Only valid for
| organization-owned collections. The resource group ID is a 24-character hexadecimal string.
| exists_ok (`bool`, *optional*):
| If `True`, do not raise an error if collection already exists.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns: [`Collection`]
|
| Example:
|
| ```py
| >>> from huggingface_hub import create_collection
| >>> collection = create_collection(
| ... title="ICCV 2023",
| ... description="Portfolio of models, papers and demos I presented at ICCV 2023",
| ... )
| >>> collection.slug
| "username/iccv-2023-64f9a55bb3115b4f513ec026"
| ```
|
| create_commit(self, repo_id: 'str', operations: 'Iterable[CommitOperation]', *, commit_message: 'str', commit_description: 'str | None' = None, token: 'str | bool | None' = None, repo_type: 'str | None' = None, revision: 'str | None' = None, create_pr: 'bool | None' = None, num_threads: 'int' = 5, parent_commit: 'str | None' = None, run_as_future: 'bool' = False, _hot_reload: 'bool | None' = None) -> 'CommitInfo | Future[CommitInfo]'
| Creates a commit in the given repo, deleting & uploading files as needed.
|
| > [!WARNING]
| > The input list of `CommitOperation` will be mutated during the commit process. Do not reuse the same objects
| > for multiple commits.
|
| > [!WARNING]
| > `create_commit` assumes that the repo already exists on the Hub. If you get a
| > Client error 404, please make sure you are authenticated, that your token has the required permissions,
| > and that `repo_id` and `repo_type` are set correctly. If repo does not exist,
| > create it first using [`~hf_api.create_repo`].
|
| > [!WARNING]
| > `create_commit` is limited to 25k LFS files and a 1GB payload for regular files.
|
| Args:
| repo_id (`str`):
| The repository in which the commit will be created, for example:
| `"username/custom_transformers"`
|
| operations (`Iterable` of [`~hf_api.CommitOperation`]):
| An iterable of operations to include in the commit, either:
|
| - [`~hf_api.CommitOperationAdd`] to upload a file
| - [`~hf_api.CommitOperationDelete`] to delete a file
| - [`~hf_api.CommitOperationCopy`] to copy a file
|
| Operation objects will be mutated to include information relative to the upload. Do not reuse the
| same objects for multiple commits.
|
| commit_message (`str`):
| The summary (first line) of the commit that will be created.
|
| commit_description (`str`, *optional*):
| The description of the commit that will be created
|
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if uploading to a dataset or
| space, `None` or `"model"` if uploading to a model. Default is
| `None`.
|
| revision (`str`, *optional*):
| The git revision to commit from. Defaults to the head of the `"main"` branch.
|
| create_pr (`boolean`, *optional*):
| Whether or not to create a Pull Request with that commit. Defaults to `False`.
| If `revision` is not set, PR is opened against the `"main"` branch. If
| `revision` is set and is a branch, PR is opened against this branch. If
| `revision` is set and is not a branch name (example: a commit oid), an
| `RevisionNotFoundError` is returned by the server.
|
| num_threads (`int`, *optional*):
| Number of concurrent threads for uploading files. Defaults to 5.
| Setting it to 2 means at most 2 files will be uploaded concurrently.
|
| parent_commit (`str`, *optional*):
| The OID / SHA of the parent commit, as a hexadecimal string.
| Shorthands (7 first characters) are also supported. If specified and `create_pr` is `False`,
| the commit will fail if `revision` does not point to `parent_commit`. If specified and `create_pr`
| is `True`, the pull request will be created from `parent_commit`. Specifying `parent_commit`
| ensures the repo has not changed before committing the changes, and can be especially useful
| if the repo is updated / committed to concurrently.
| run_as_future (`bool`, *optional*):
| Whether or not to run this method in the background. Background jobs are run sequentially without
| blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects)
| object. Defaults to `False`.
|
| Returns:
| [`CommitInfo`] or `Future`:
| Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit
| url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will
| contain the result when executed.
|
| Raises:
| [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| If commit message is empty.
| [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| If parent commit is not a valid commit OID.
| [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| If a README.md file with an invalid metadata section is committed. In this case, the commit will fail
| early, before trying to upload any file.
| [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| If `create_pr` is `True` and revision is neither `None` nor `"main"`.
| [`~utils.RepositoryNotFoundError`]:
| If repository is not found (error 404): wrong repo_id/repo_type, private
| but not authenticated or repo does not exist.
|
| create_discussion(self, repo_id: 'str', title: 'str', *, token: 'bool | str | None' = None, description: 'str | None' = None, repo_type: 'str | None' = None, pull_request: 'bool' = False) -> 'DiscussionWithDetails'
| Creates a Discussion or Pull Request.
|
| Pull Requests created programmatically will be in `"draft"` status.
|
| Creating a Pull Request with changes can also be done at once with [`HfApi.create_commit`].
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated
| by a `/`.
| title (`str`):
| The title of the discussion. It can be up to 200 characters long,
| and must be at least 3 characters long. Leading and trailing whitespaces
| will be stripped.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| description (`str`, *optional*):
| An optional description for the Pull Request.
| Defaults to `"Discussion opened with the huggingface_hub Python library"`
| pull_request (`bool`, *optional*):
| Whether to create a Pull Request or discussion. If `True`, creates a Pull Request.
| If `False`, creates a discussion. Defaults to `False`.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if uploading to a dataset or
| space, `None` or `"model"` if uploading to a model. Default is
| `None`.
|
| Returns: [`DiscussionWithDetails`]
|
| > [!TIP]
| > Raises the following errors:
| >
| > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
| > if the HuggingFace API returned an error
| > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| > if some parameter value is invalid
| > - [`~utils.RepositoryNotFoundError`]
| > If the repository to download from cannot be found. This may be because it doesn't exist,
| > or because it is set to `private` and you do not have access.
|
| create_inference_endpoint(self, name: 'str', *, repository: 'str', framework: 'str', accelerator: 'str', instance_size: 'str', instance_type: 'str', region: 'str', vendor: 'str', account_id: 'str | None' = None, min_replica: 'int' = 1, max_replica: 'int' = 1, scaling_metric: 'InferenceEndpointScalingMetric | None' = None, scaling_threshold: 'float | None' = None, scale_to_zero_timeout: 'int | None' = None, revision: 'str | None' = None, task: 'str | None' = None, custom_image: 'dict | None' = None, container_command: 'list[str] | None' = None, container_args: 'list[str] | None' = None, env: 'dict[str, str] | None' = None, secrets: 'dict[str, str] | None' = None, type: 'InferenceEndpointType | str' = <InferenceEndpointType.AUTHENTICATED: 'authenticated'>, domain: 'str | None' = None, path: 'str | None' = None, cache_http_responses: 'bool | None' = None, tags: 'list[str] | None' = None, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'InferenceEndpoint'
| Create a new Inference Endpoint.
|
| Args:
| name (`str`):
| The unique name for the new Inference Endpoint.
| repository (`str`):
| The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`).
| framework (`str`):
| The machine learning framework used for the model (e.g. `"custom"`).
| accelerator (`str`):
| The hardware accelerator to be used for inference (e.g. `"cpu"`).
| instance_size (`str`):
| The size or type of the instance to be used for hosting the model (e.g. `"x4"`).
| instance_type (`str`):
| The cloud instance type where the Inference Endpoint will be deployed (e.g. `"intel-icl"`).
| region (`str`):
| The cloud region in which the Inference Endpoint will be created (e.g. `"us-east-1"`).
| vendor (`str`):
| The cloud provider or vendor where the Inference Endpoint will be hosted (e.g. `"aws"`).
| account_id (`str`, *optional*):
| The account ID used to link a VPC to a private Inference Endpoint (if applicable).
| min_replica (`int`, *optional*):
| The minimum number of replicas (instances) to keep running for the Inference Endpoint. To enable
| scaling to zero, set this value to 0 and adjust `scale_to_zero_timeout` accordingly. Defaults to 1.
| max_replica (`int`, *optional*):
| The maximum number of replicas (instances) to scale to for the Inference Endpoint. Defaults to 1.
| scaling_metric (`str` or [`InferenceEndpointScalingMetric `], *optional*):
| The metric reference for scaling. Either "pendingRequests" or "hardwareUsage" when provided. Defaults to
| None (meaning: let the HF Endpoints service specify the metric).
| scaling_threshold (`float`, *optional*):
| The scaling metric threshold used to trigger a scale up. Ignored when scaling metric is not provided.
| Defaults to None (meaning: let the HF Endpoints service specify the threshold).
| scale_to_zero_timeout (`int`, *optional*):
| The duration in minutes before an inactive endpoint is scaled to zero, or no scaling to zero if
| set to None and `min_replica` is not 0. Defaults to None.
| revision (`str`, *optional*):
| The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`).
| task (`str`, *optional*):
| The task on which to deploy the model (e.g. `"text-classification"`).
| custom_image (`dict`, *optional*):
| A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an
| Inference Endpoint running on the `text-generation-inference` (TGI) framework or a custom container
| (see examples).
| container_command (`list[str]`, *optional*):
| Override the container entrypoint command (maps to `model.command` in the API payload). Typically
| used together with `custom_image`.
| container_args (`list[str]`, *optional*):
| Arguments appended to the container entrypoint (maps to `model.args` in the API payload). Typically
| used together with `custom_image` to pass runtime flags to the container.
| env (`dict[str, str]`, *optional*):
| Non-secret environment variables to inject in the container environment.
| secrets (`dict[str, str]`, *optional*):
| Secret values to inject in the container environment.
| type ([`InferenceEndpointType]`, *optional*):
| The type of the Inference Endpoint, which can be `"authenticated"` (default), `"public"` or
| `"private"`. `"protected"` is deprecated in favor of `"authenticated"` and will be removed in a
| future release.
| domain (`str`, *optional*):
| The custom domain for the Inference Endpoint deployment, if setup the inference endpoint will be available at this domain (e.g. `"my-new-domain.cool-website.woof"`).
| path (`str`, *optional*):
| The custom path to the deployed model, should start with a `/` (e.g. `"/models/google-bert/bert-base-uncased"`).
| cache_http_responses (`bool`, *optional*):
| Whether to cache HTTP responses from the Inference Endpoint. Defaults to `False`.
| tags (`list[str]`, *optional*):
| A list of tags to associate with the Inference Endpoint.
| namespace (`str`, *optional*):
| The namespace where the Inference Endpoint will be created. Defaults to the current user's namespace.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`InferenceEndpoint`]: information about the updated Inference Endpoint.
|
| Example:
| ```python
| >>> from huggingface_hub import HfApi
| >>> api = HfApi()
| >>> endpoint = api.create_inference_endpoint(
| ... "my-endpoint-name",
| ... repository="gpt2",
| ... framework="pytorch",
| ... task="text-generation",
| ... accelerator="cpu",
| ... vendor="aws",
| ... region="us-east-1",
| ... type="authenticated",
| ... instance_size="x2",
| ... instance_type="intel-icl",
| ... )
| >>> endpoint
| InferenceEndpoint(name='my-endpoint-name', status="pending",...)
|
| # Run inference on the endpoint
| >>> endpoint.client.text_generation(...)
| "..."
| ```
|
| ```python
| # Start an Inference Endpoint running Zephyr-7b-beta on TGI
| >>> from huggingface_hub import HfApi
| >>> api = HfApi()
| >>> endpoint = api.create_inference_endpoint(
| ... "aws-zephyr-7b-beta-0486",
| ... repository="HuggingFaceH4/zephyr-7b-beta",
| ... framework="pytorch",
| ... task="text-generation",
| ... accelerator="gpu",
| ... vendor="aws",
| ... region="us-east-1",
| ... type="authenticated",
| ... instance_size="x1",
| ... instance_type="nvidia-a10g",
| ... env={
| ... "MAX_BATCH_PREFILL_TOKENS": "2048",
| ... "MAX_INPUT_LENGTH": "1024",
| ... "MAX_TOTAL_TOKENS": "1512",
| ... "MODEL_ID": "/repository"
| ... },
| ... custom_image={
| ... "healthRoute": "/health",
| ... "url": "ghcr.io/huggingface/text-generation-inference:1.1.0",
| ... },
| ... secrets={"MY_SECRET_KEY": "secret_value"},
| ... tags=["dev", "text-generation"],
| ... )
| ```
|
| ```python
| # Start an Inference Endpoint running ProsusAI/finbert while scaling to zero in 15 minutes
| >>> from huggingface_hub import HfApi
| >>> api = HfApi()
| >>> endpoint = api.create_inference_endpoint(
| ... "finbert-classifier",
| ... repository="ProsusAI/finbert",
| ... framework="pytorch",
| ... task="text-classification",
| ... min_replica=0,
| ... scale_to_zero_timeout=15,
| ... accelerator="cpu",
| ... vendor="aws",
| ... region="us-east-1",
| ... type="authenticated",
| ... instance_size="x2",
| ... instance_type="intel-icl",
| ... )
| >>> endpoint.wait(timeout=300)
| # Run inference on the endpoint
| >>> endpoint.client.text_generation(...)
| TextClassificationOutputElement(label='positive', score=0.8983615040779114)
| ```
|
| create_inference_endpoint_from_catalog(self, repo_id: 'str', *, name: 'str | None' = None, accelerator: "Literal['cpu', 'gpu', 'neuron'] | str | None" = None, token: 'bool | str | None' = None, namespace: 'str | None' = None) -> 'InferenceEndpoint'
| Create a new Inference Endpoint from a model in the Hugging Face Inference Catalog.
|
| The goal of the Inference Catalog is to provide a curated list of models that are optimized for inference
| and for which default configurations have been tested. See https://endpoints.huggingface.co/catalog for a list
| of available models in the catalog.
|
| Args:
| repo_id (`str`):
| The ID of the model in the catalog to deploy as an Inference Endpoint.
| name (`str`, *optional*):
| The unique name for the new Inference Endpoint. If not provided, a random name will be generated.
| accelerator (`str`, *optional*):
| The hardware accelerator to be used for inference. Possible values include `"cpu"`, `"gpu"`, and
| `"neuron"`. If not provided, the server will use a default appropriate for the model.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| namespace (`str`, *optional*):
| The namespace where the Inference Endpoint will be created. Defaults to the current user's namespace.
|
| Returns:
| [`InferenceEndpoint`]: information about the new Inference Endpoint.
|
| > [!WARNING]
| > `create_inference_endpoint_from_catalog` is experimental. Its API is subject to change in the future. Please provide feedback
| > if you have any suggestions or requests.
|
| create_pull_request(self, repo_id: 'str', title: 'str', *, token: 'bool | str | None' = None, description: 'str | None' = None, repo_type: 'str | None' = None) -> 'DiscussionWithDetails'
| Creates a Pull Request . Pull Requests created programmatically will be in `"draft"` status.
|
| Creating a Pull Request with changes can also be done at once with [`HfApi.create_commit`];
|
| This is a wrapper around [`HfApi.create_discussion`].
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated
| by a `/`.
| title (`str`):
| The title of the discussion. It can be up to 200 characters long,
| and must be at least 3 characters long. Leading and trailing whitespaces
| will be stripped.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| description (`str`, *optional*):
| An optional description for the Pull Request.
| Defaults to `"Discussion opened with the huggingface_hub Python library"`
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if uploading to a dataset or
| space, `None` or `"model"` if uploading to a model. Default is
| `None`.
|
| Returns: [`DiscussionWithDetails`]
|
| > [!TIP]
| > Raises the following errors:
| >
| > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
| > if the HuggingFace API returned an error
| > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| > if some parameter value is invalid
| > - [`~utils.RepositoryNotFoundError`]
| > If the repository to download from cannot be found. This may be because it doesn't exist,
| > or because it is set to `private` and you do not have access.
|
| create_repo(self, repo_id: 'str', *, token: 'str | bool | None' = None, private: 'bool | None' = None, visibility: 'RepoVisibility_T | None' = None, repo_type: 'str | None' = None, exist_ok: 'bool' = False, resource_group_id: 'str | None' = None, region: 'REPO_REGIONS | None' = None, space_sdk: 'str | None' = None, space_hardware: 'SpaceHardware | None' = None, space_storage: 'SpaceStorage | None' = None, space_sleep_time: 'int | None' = None, space_secrets: 'list[dict[str, str]] | None' = None, space_variables: 'list[dict[str, str]] | None' = None, space_volumes: 'list[Volume] | None' = None, space_template: 'str | None' = None) -> 'RepoUrl'
| Create an empty repo on the HuggingFace Hub.
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated
| by a `/`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| private (`bool`, *optional*):
| Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists. Cannot be passed together with `visibility`.
| visibility (`Literal["public", "private", "protected"]`, *optional*):
| Visibility of the repo. Can be `"public"` or `"private"`, or `"protected"` for Spaces. If `None`
| (default), the repo will be public unless the organization's default is private. This value is ignored
| if the repo already exists.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if uploading to a dataset or
| space, `None` or `"model"` if uploading to a model. Default is
| `None`.
| exist_ok (`bool`, *optional*, defaults to `False`):
| If `True`, do not raise an error if repo already exists.
| resource_group_id (`str`, *optional*):
| Resource group in which to create the repo. Resource groups is only available for Enterprise Hub organizations and
| allow to define which members of the organization can access the resource. The ID of a resource group
| can be found in the URL of the resource's page on the Hub (e.g. `"66670e5163145ca562cb1988"`).
| To learn more about resource groups, see https://huggingface.co/docs/hub/en/security-resource-groups.
| region (`Literal["us", "eu"]`, *optional*):
| Cloud region in which to create the repo. Can be one of `"us"` or `"eu"`. If not specified, the repo will be
| created in the default region. Requires Team plan or above.
| space_sdk (`str`, *optional*):
| Choice of SDK to use if repo_type is "space". Can be "streamlit", "gradio", "docker", or "static".
| space_hardware (`SpaceHardware` or `str`, *optional*):
| Choice of Hardware if repo_type is "space". See [`SpaceHardware`] for a complete list.
| space_storage (`SpaceStorage` or `str`, *optional*):
| <Deprecated, use `set_space_volumes` instead> Choice of persistent storage tier. Example: `"small"`. See [`SpaceStorage`] for a complete list.
| space_sleep_time (`int`, *optional*):
| Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
| your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure
| the sleep time (value is fixed to 48 hours of inactivity).
| See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
| space_secrets (`list[dict[str, str]]`, *optional*):
| A list of secret keys to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
| For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
| space_variables (`list[dict[str, str]]`, *optional*):
| A list of public environment variables to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
| For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables.
| space_volumes (`list[Volume]`, *optional*):
| A list of [`Volume`] objects to mount in the Space at creation time. Each volume has a `type`
| (`"bucket"`, `"model"`, `"dataset"`, or `"space"`), a `source` (repo or bucket ID), a `mount_path`
| (path inside the container), and optional `revision`, `read_only`, and `path` fields.
| Only applicable if repo_type is "space".
| space_template (`str`, *optional*):
| Seed the new Space from an official template. Can be either the template repo id
| (e.g. `"SpacesExamples/jupyterlab"`) or its short name (e.g. `"JupyterLab"`). Use
| [`HfApi.list_space_templates`] to list available templates. Only applicable if repo_type is
| "space". If the template is recommended to be private and visibility is not explicitly set, the Space
| is created as private.
|
| Returns:
| [`RepoUrl`]: URL to the newly created repo. Value is a subclass of `str` containing
| attributes like `endpoint`, `repo_type` and `repo_id`.
|
| create_scheduled_job(self, *, image: 'str', command: 'list[str]', schedule: 'str', suspend: 'bool | None' = None, concurrency: 'bool | None' = None, env: 'dict[str, Any] | None' = None, secrets: 'dict[str, Any] | None' = None, flavor: 'JobHardware | str | None' = None, timeout: 'int | float | str | None' = None, name: 'str | None' = None, labels: 'dict[str, str] | None' = None, volumes: 'list[Volume] | None' = None, expose: 'list[int] | None' = None, resource_group_id: 'str | None' = None, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'ScheduledJobInfo'
| Create scheduled compute Jobs on Hugging Face infrastructure.
|
| Args:
| image (`str`):
| The Docker image to use.
| Examples: `"ubuntu"`, `"python:3.12"`, `"pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"`.
| Example with an image from a Space: `"hf.co/spaces/lhoestq/duckdb"`.
|
| command (`list[str]`):
| The command to run. Example: `["echo", "hello"]`.
|
| schedule (`str`):
| One of "@annually", "@yearly", "@monthly", "@weekly", "@daily", "@hourly", or a
| CRON schedule expression (e.g., '0 9 * * 1' for 9 AM every Monday).
|
| suspend (`bool`, *optional*):
| If True, the scheduled Job is suspended (paused). Defaults to False.
|
| concurrency (`bool`, *optional*):
| If True, multiple instances of this Job can run concurrently. Defaults to False.
|
| env (`dict[str, Any]`, *optional*):
| Defines the environment variables for the Job.
|
| secrets (`dict[str, Any]`, *optional*):
| Defines the secret environment variables for the Job.
|
| flavor (`str`, *optional*):
| Flavor for the hardware. See [`JobHardware`] for possible values.
| Defaults to `"cpu-basic"`.
|
| timeout (`Union[int, float, str]`, *optional*):
| Max duration for the Job: int with s (seconds, default), m (minutes), h (hours) or d (days).
| Example: `300` or `"5m"` for 5 minutes.
|
| name (`str`, *optional*):
| A name for the scheduled Job. Stored as the `name` label. Cannot be passed together with a `name`
| key in `labels`. Names do not have to be unique. Defaults to a name derived from image and command (with a short hash suffix).
|
| labels (`dict[str, str]`, *optional*):
| Labels to attach to the job (key-value pairs).
|
| volumes (`list[Volume]`, *optional*):
| Hugging Face Buckets or Repos to mount as volumes in the job container.
| Each volume is a [`Volume`] with `type` (`"bucket"`, `"model"`, `"dataset"`, or `"space"`),
| `source` (e.g. `"username/my-bucket"`), and `mount_path` (e.g. `"/data"`).
|
| expose (`list[int]`, *optional*):
| Container ports to expose through the jobs proxy. Each listed port is reachable
| on the public jobs domain (e.g. `https://<job_id>--8000.hf.jobs`). Access always
| requires an HF token with read access to the job's namespace.
|
| resource_group_id (`str`, *optional*):
| The ID of the resource group to create the scheduled Job in. Used to control access to resources
| within an organization and for cost attribution/spending-limit features. If not provided, the
| scheduled Job is created outside of any resource group.
|
| namespace (`str`, *optional*):
| The namespace where the Job will be created. Defaults to the current user's namespace.
|
| token `(Union[bool, str, None]`, *optional*):
| A valid user access token. If not provided, the locally saved token will be used, which is the
| recommended authentication method. Set to `False` to disable authentication.
| Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
|
| Example:
| Create your first scheduled Job:
|
| ```python
| >>> from huggingface_hub import create_scheduled_job
| >>> create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"], schedule="@hourly")
| ```
|
| Use a CRON schedule expression:
|
| ```python
| >>> from huggingface_hub import create_scheduled_job
| >>> create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('this runs every 5min')"], schedule="*/5 * * * *")
| ```
|
| Create a scheduled GPU Job:
|
| ```python
| >>> from huggingface_hub import create_scheduled_job
| >>> image = "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"
| >>> command = ["python", "-c", "import torch; print(f"This code ran with the following GPU: {torch.cuda.get_device_name()}")"]
| >>> create_scheduled_job(image, command, flavor="a10g-small", schedule="@hourly")
| ```
|
| create_scheduled_uv_job(self, script: 'str', *, script_args: 'list[str] | None' = None, schedule: 'str', suspend: 'bool | None' = None, concurrency: 'bool | None' = None, dependencies: 'list[str] | None' = None, python: 'str | None' = None, image: 'str | None' = None, env: 'dict[str, Any] | None' = None, secrets: 'dict[str, Any] | None' = None, flavor: 'JobHardware | str | None' = None, timeout: 'int | float | str | None' = None, name: 'str | None' = None, labels: 'dict[str, str] | None' = None, volumes: 'list[Volume] | None' = None, expose: 'list[int] | None' = None, resource_group_id: 'str | None' = None, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'ScheduledJobInfo'
| Run a UV script Job on Hugging Face infrastructure.
|
| Args:
| script (`str`):
| Path or URL of the UV script, or a command.
|
| script_args (`list[str]`, *optional*)
| Arguments to pass to the script, or a command.
|
| schedule (`str`):
| One of "@annually", "@yearly", "@monthly", "@weekly", "@daily", "@hourly", or a
| CRON schedule expression (e.g., '0 9 * * 1' for 9 AM every Monday).
|
| suspend (`bool`, *optional*):
| If True, the scheduled Job is suspended (paused). Defaults to False.
|
| concurrency (`bool`, *optional*):
| If True, multiple instances of this Job can run concurrently. Defaults to False.
|
| dependencies (`list[str]`, *optional*)
| Dependencies to use to run the UV script.
|
| python (`str`, *optional*)
| Use a specific Python version. Default is 3.12.
|
| image (`str`, *optional*, defaults to "ghcr.io/astral-sh/uv:python3.12-bookworm"):
| Use a custom Docker image with `uv` installed.
|
| env (`dict[str, Any]`, *optional*):
| Defines the environment variables for the Job.
|
| secrets (`dict[str, Any]`, *optional*):
| Defines the secret environment variables for the Job.
|
| flavor (`str`, *optional*):
| Flavor for the hardware. See [`JobHardware`] for possible values.
| Defaults to `"cpu-basic"`.
|
| timeout (`Union[int, float, str]`, *optional*):
| Max duration for the Job: int with s (seconds, default), m (minutes), h (hours) or d (days).
| Example: `300` or `"5m"` for 5 minutes.
|
| name (`str`, *optional*):
| A name for the scheduled Job. Stored as the `name` label. Cannot be passed together with a `name`
| key in `labels`. Names do not have to be unique. Defaults to a name derived from script and its arguments (with a short hash suffix).
|
| labels (`dict[str, str]`, *optional*):
| Labels to attach to the job (key-value pairs).
|
| volumes (`list[Volume]`, *optional*):
| Hugging Face Buckets or Repos to mount as volumes in the job container.
| Each volume is a [`Volume`] with `type` (`"bucket"`, `"model"`, `"dataset"`, or `"space"`),
| `source` (e.g. `"username/my-bucket"`), and `mount_path` (e.g. `"/data"`).
|
| expose (`list[int]`, *optional*):
| Container ports to expose through the jobs proxy. Each listed port is reachable
| on the public jobs domain (e.g. `https://<job_id>--8000.hf.jobs`). Access always
| requires an HF token with read access to the job's namespace.
|
| resource_group_id (`str`, *optional*):
| The ID of the resource group to create the scheduled Job in. Used to control access to resources
| within an organization and for cost attribution/spending-limit features. If not provided, the
| scheduled Job is created outside of any resource group.
|
| namespace (`str`, *optional*):
| The namespace where the Job will be created. Defaults to the current user's namespace.
|
| token `(Union[bool, str, None]`, *optional*):
| A valid user access token. If not provided, the locally saved token will be used, which is the
| recommended authentication method. Set to `False` to disable authentication.
| Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
|
| Example:
|
| Schedule a script from a URL:
|
| ```python
| >>> from huggingface_hub import create_scheduled_uv_job
| >>> script = "https://raw.githubusercontent.com/huggingface/trl/refs/heads/main/trl/scripts/sft.py"
| >>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
| >>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small", schedule="@weekly")
| ```
|
| Schedule a local script:
|
| ```python
| >>> from huggingface_hub import create_scheduled_uv_job
| >>> script = "my_sft.py"
| >>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
| >>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small", schedule="@weekly")
| ```
|
| Schedule a command:
|
| ```python
| >>> from huggingface_hub import create_scheduled_uv_job
| >>> script = "lighteval"
| >>> script_args= ["endpoint", "inference-providers", "model_name=openai/gpt-oss-20b,provider=auto", "lighteval|gsm8k|0|0"]
| >>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["lighteval"], flavor="a10g-small", schedule="@weekly")
| ```
|
| create_tag(self, repo_id: 'str', *, tag: 'str', tag_message: 'str | None' = None, revision: 'str | None' = None, token: 'bool | str | None' = None, repo_type: 'str | None' = None, exist_ok: 'bool' = False) -> 'None'
| Tag a given commit of a repo on the Hub.
|
| Args:
| repo_id (`str`):
| The repository in which a commit will be tagged.
| Example: `"user/my-cool-model"`.
|
| tag (`str`):
| The name of the tag to create.
|
| tag_message (`str`, *optional*):
| The description of the tag to create.
|
| revision (`str`, *optional*):
| The git revision to tag. It can be a branch name or the OID/SHA of a
| commit, as a hexadecimal string. Shorthands (7 first characters) are
| also supported. Defaults to the head of the `"main"` branch.
|
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if tagging a dataset or
| space, `None` or `"model"` if tagging a model. Default is
| `None`.
|
| exist_ok (`bool`, *optional*, defaults to `False`):
| If `True`, do not raise an error if tag already exists.
|
| Raises:
| [`~utils.RepositoryNotFoundError`]:
| If repository is not found (error 404): wrong repo_id/repo_type, private
| but not authenticated or repo does not exist.
| [`~utils.RevisionNotFoundError`]:
| If revision is not found (error 404) on the repo.
| [`~utils.HfHubHTTPError`]:
| If the branch already exists on the repo (error 409) and `exist_ok` is
| set to `False`.
|
| create_webhook(self, *, url: 'str | None' = None, job_id: 'str | None' = None, watched: 'list[dict | WebhookWatchedItem]', domains: 'list[constants.WEBHOOK_DOMAIN_T] | None' = None, secret: 'str | None' = None, token: 'bool | str | None' = None) -> 'WebhookInfo'
| Create a new webhook.
|
| The webhook can either send a payload to a URL, or trigger a Job to run on Hugging Face infrastructure.
| This function should be called with one of `url` or `job_id`, but not both.
|
| Args:
| url (`str`):
| URL to send the payload to.
| job_id (`str`):
| ID of the source Job to trigger with the webhook payload in the environment variable WEBHOOK_PAYLOAD.
| Additional environment variables are available for convenience: WEBHOOK_REPO_ID, WEBHOOK_REPO_TYPE and WEBHOOK_SECRET.
| watched (`list[WebhookWatchedItem]`):
| List of [`WebhookWatchedItem`] to be watched by the webhook. It can be users, orgs, models, datasets or spaces.
| Watched items can also be provided as plain dictionaries.
| domains (`list[Literal["repo", "discussion"]]`, optional):
| List of domains to watch. It can be "repo", "discussion" or both.
| secret (`str`, optional):
| A secret to sign the payload with.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved token, which is the recommended
| method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`WebhookInfo`]:
| Info about the newly created webhook.
|
| Example:
|
| Create a webhook that sends a payload to a URL
| ```python
| >>> from huggingface_hub import create_webhook
| >>> payload = create_webhook(
| ... watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}],
| ... url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
| ... domains=["repo", "discussion"],
| ... secret="my-secret",
| ... )
| >>> print(payload)
| WebhookInfo(
| id="654bbbc16f2ec14d77f109cc",
| url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
| job=None,
| watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
| domains=["repo", "discussion"],
| secret="my-secret",
| disabled=False,
| )
| ```
|
| Run a Job and then create a webhook that triggers this Job
| ```python
| >>> from huggingface_hub import create_webhook, run_job
| >>> job = run_job(
| ... image="ubuntu",
| ... command=["bash", "-c", r"echo An event occurred in $WEBHOOK_REPO_ID: $WEBHOOK_PAYLOAD"],
| ... )
| >>> payload = create_webhook(
| ... watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}],
| ... job_id=job.id,
| ... domains=["repo", "discussion"],
| ... secret="my-secret",
| ... )
| >>> print(payload)
| WebhookInfo(
| id="654bbbc16f2ec14d77f109cc",
| url=None,
| job=JobSpec(
| docker_image='ubuntu',
| space_id=None,
| command=['bash', '-c', 'echo An event occurred in $WEBHOOK_REPO_ID: $WEBHOOK_PAYLOAD'],
| arguments=[],
| environment={},
| secrets=[],
| flavor='cpu-basic',
| timeout=None,
| tags=None,
| arch=None
| ),
| watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
| domains=["repo", "discussion"],
| secret="my-secret",
| disabled=False,
| )
| ```
|
| dataset_info(self, repo_id: 'str', *, revision: 'str | None' = None, timeout: 'float | None' = None, files_metadata: 'bool' = False, expand: 'list[ExpandDatasetProperty_T] | None' = None, token: 'bool | str | None' = None) -> 'DatasetInfo'
| Get info on one specific dataset on huggingface.co.
|
| Dataset can be private if you pass an acceptable token.
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated
| by a `/`.
| revision (`str`, *optional*):
| The revision of the dataset repository from which to get the
| information.
| timeout (`float`, *optional*):
| Whether to set a timeout for the request to the Hub.
| files_metadata (`bool`, *optional*):
| Whether or not to retrieve metadata for files in the repository
| (size, LFS metadata, etc). Defaults to `False`.
| expand (`list[ExpandDatasetProperty_T]`, *optional*):
| List properties to return in the response. When used, only the properties in the list will be returned.
| This parameter cannot be used if `files_metadata` is passed.
| Possible values are `"author"`, `"cardData"`, `"citation"`, `"createdAt"`, `"disabled"`, `"description"`, `"downloads"`, `"downloadsAllTime"`, `"gated"`, `"lastModified"`, `"likes"`, `"mainSize"`, `"paperswithcode_id"`, `"private"`, `"siblings"`, `"sha"`, `"tags"`, `"trendingScore"`, `"usedStorage"`, and `"resourceGroup"`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`hf_api.DatasetInfo`]: The dataset repository information.
|
| > [!TIP]
| > Raises the following errors:
| >
| > - [`~utils.RepositoryNotFoundError`]
| > If the repository to download from cannot be found. This may be because it doesn't exist,
| > or because it is set to `private` and you do not have access.
| > - [`~utils.RevisionNotFoundError`]
| > If the revision to download from cannot be found.
|
| delete_branch(self, repo_id: 'str', *, branch: 'str', token: 'bool | str | None' = None, repo_type: 'str | None' = None) -> 'None'
| Delete a branch from a repo on the Hub.
|
| Args:
| repo_id (`str`):
| The repository in which a branch will be deleted.
| Example: `"user/my-cool-model"`.
|
| branch (`str`):
| The name of the branch to delete.
|
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if creating a branch on a dataset or
| space, `None` or `"model"` if tagging a model. Default is `None`.
|
| Raises:
| [`~utils.RepositoryNotFoundError`]:
| If repository is not found (error 404): wrong repo_id/repo_type, private
| but not authenticated or repo does not exist.
| [`~utils.HfHubHTTPError`]:
| If trying to delete a protected branch. Ex: `main` cannot be deleted.
| [`~utils.HfHubHTTPError`]:
| If trying to delete a branch that does not exist.
|
| delete_bucket(self, bucket_id: 'str', *, missing_ok: 'bool' = False, token: 'bool | str | None' = None) -> 'None'
| Delete a bucket from the Hub.
|
| Args:
| bucket_id (`str`):
| The ID of the bucket (e.g. `"username/my-bucket"`).
| missing_ok (`bool`, *optional*, defaults to `False`):
| If `True`, do not raise an error if the bucket does not exist.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Raises:
| [`~errors.BucketNotFoundError`]: If the bucket cannot be found and `missing_ok` is set to `False` (default).
|
| Example:
| ```python
| >>> from huggingface_hub import delete_bucket
| >>> delete_bucket(bucket_id="Wauplin/first-bucket")
| >>> delete_bucket(bucket_id="Wauplin/first-bucket", missing_ok=True)
| ```
|
| delete_collection(self, collection_slug: 'str', *, missing_ok: 'bool' = False, token: 'bool | str | None' = None) -> 'None'
| Delete a collection on the Hub.
|
| Args:
| collection_slug (`str`):
| Slug of the collection to delete. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
| missing_ok (`bool`, *optional*):
| If `True`, do not raise an error if the collection doesn't exist.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Example:
|
| ```py
| >>> from huggingface_hub import delete_collection
| >>> collection = delete_collection("username/useless-collection-64f9a55bb3115b4f513ec026", missing_ok=True)
| ```
|
| > [!WARNING]
| > This is a non-revertible action. A deleted collection cannot be restored.
|
| delete_collection_item(self, collection_slug: 'str', item_object_id: 'str', *, missing_ok: 'bool' = False, token: 'bool | str | None' = None) -> 'None'
| Delete an item from a collection.
|
| Args:
| collection_slug (`str`):
| Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
| item_object_id (`str`):
| ID of the item in the collection. This is not the id of the item on the Hub (repo_id or paper id).
| It must be retrieved from a [`CollectionItem`] object. Example: `collection.items[0].item_object_id`.
| missing_ok (`bool`, *optional*):
| If `True`, do not raise an error if the item doesn't exist.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Example:
|
| ```py
| >>> from huggingface_hub import get_collection, delete_collection_item
|
| # Get collection first
| >>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")
|
| # Delete item based on its ID
| >>> delete_collection_item(
| ... collection_slug="TheBloke/recent-models-64f9a55bb3115b4f513ec026",
| ... item_object_id=collection.items[-1].item_object_id,
| ... )
| ```
|
| delete_file(self, path_in_repo: 'str', repo_id: 'str', *, token: 'str | bool | None' = None, repo_type: 'str | None' = None, revision: 'str | None' = None, commit_message: 'str | None' = None, commit_description: 'str | None' = None, create_pr: 'bool | None' = None, parent_commit: 'str | None' = None) -> 'CommitInfo'
| Deletes a file in the given repo.
|
| Args:
| path_in_repo (`str`):
| Relative filepath in the repo, for example:
| `"checkpoints/1fec34a/weights.bin"`
| repo_id (`str`):
| The repository from which the file will be deleted, for example:
| `"username/custom_transformers"`
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if the file is in a dataset or
| space, `None` or `"model"` if in a model. Default is `None`.
| revision (`str`, *optional*):
| The git revision to commit from. Defaults to the head of the `"main"` branch.
| commit_message (`str`, *optional*):
| The summary / title / first line of the generated commit. Defaults to
| `f"Delete {path_in_repo} with huggingface_hub"`.
| commit_description (`str` *optional*)
| The description of the generated commit
| create_pr (`boolean`, *optional*):
| Whether or not to create a Pull Request with that commit. Defaults to `False`.
| If `revision` is not set, PR is opened against the `"main"` branch. If
| `revision` is set and is a branch, PR is opened against this branch. If
| `revision` is set and is not a branch name (example: a commit oid), an
| `RevisionNotFoundError` is returned by the server.
| parent_commit (`str`, *optional*):
| The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
| If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
| If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
| Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
| especially useful if the repo is updated / committed to concurrently.
|
|
| > [!TIP]
| > Raises the following errors:
| >
| > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
| > if the HuggingFace API returned an error
| > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| > if some parameter value is invalid
| > - [`~utils.RepositoryNotFoundError`]
| > If the repository to download from cannot be found. This may be because it doesn't exist,
| > or because it is set to `private` and you do not have access.
| > - [`~utils.RevisionNotFoundError`]
| > If the revision to download from cannot be found.
| > - [`~utils.EntryNotFoundError`]
| > If the file to download cannot be found.
|
| delete_files(self, repo_id: 'str', delete_patterns: 'list[str]', *, token: 'bool | str | None' = None, repo_type: 'str | None' = None, revision: 'str | None' = None, commit_message: 'str | None' = None, commit_description: 'str | None' = None, create_pr: 'bool | None' = None, parent_commit: 'str | None' = None) -> 'CommitInfo'
| Delete files from a repository on the Hub.
|
| If a folder path is provided, the entire folder is deleted as well as
| all files it contained.
|
| Args:
| repo_id (`str`):
| The repository from which the folder will be deleted, for example:
| `"username/custom_transformers"`
| delete_patterns (`list[str]`):
| List of files or folders to delete. Each string can either be
| a file path, a folder path, or a wildcard pattern. Patterns are Standard
| Wildcards (globbing patterns) as documented [here](https://tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm).
| The pattern matching is based on [`fnmatch`](https://docs.python.org/3/library/fnmatch.html).
| Note that `fnmatch` matches `*` across path boundaries, unlike traditional Unix shell globbing.
| E.g. `["file.txt", "folder/", "data/*.parquet"]`
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| to the stored token.
| repo_type (`str`, *optional*):
| Type of the repo to delete files from. Can be `"model"`,
| `"dataset"` or `"space"`. Defaults to `"model"`.
| revision (`str`, *optional*):
| The git revision to commit from. Defaults to the head of the `"main"` branch.
| commit_message (`str`, *optional*):
| The summary (first line) of the generated commit. Defaults to
| `f"Delete files using huggingface_hub"`.
| commit_description (`str` *optional*)
| The description of the generated commit.
| create_pr (`boolean`, *optional*):
| Whether or not to create a Pull Request with that commit. Defaults to `False`.
| If `revision` is not set, PR is opened against the `"main"` branch. If
| `revision` is set and is a branch, PR is opened against this branch. If
| `revision` is set and is not a branch name (example: a commit oid), an
| `RevisionNotFoundError` is returned by the server.
| parent_commit (`str`, *optional*):
| The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
| If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
| If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
| Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
| especially useful if the repo is updated / committed to concurrently.
|
| delete_folder(self, path_in_repo: 'str', repo_id: 'str', *, token: 'bool | str | None' = None, repo_type: 'str | None' = None, revision: 'str | None' = None, commit_message: 'str | None' = None, commit_description: 'str | None' = None, create_pr: 'bool | None' = None, parent_commit: 'str | None' = None) -> 'CommitInfo'
| Deletes a folder in the given repo.
|
| Simple wrapper around [`create_commit`] method.
|
| Args:
| path_in_repo (`str`):
| Relative folder path in the repo, for example: `"checkpoints/1fec34a"`.
| repo_id (`str`):
| The repository from which the folder will be deleted, for example:
| `"username/custom_transformers"`
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| to the stored token.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if the folder is in a dataset or
| space, `None` or `"model"` if in a model. Default is `None`.
| revision (`str`, *optional*):
| The git revision to commit from. Defaults to the head of the `"main"` branch.
| commit_message (`str`, *optional*):
| The summary / title / first line of the generated commit. Defaults to
| `f"Delete folder {path_in_repo} with huggingface_hub"`.
| commit_description (`str` *optional*)
| The description of the generated commit.
| create_pr (`boolean`, *optional*):
| Whether or not to create a Pull Request with that commit. Defaults to `False`.
| If `revision` is not set, PR is opened against the `"main"` branch. If
| `revision` is set and is a branch, PR is opened against this branch. If
| `revision` is set and is not a branch name (example: a commit oid), an
| `RevisionNotFoundError` is returned by the server.
| parent_commit (`str`, *optional*):
| The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
| If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
| If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
| Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
| especially useful if the repo is updated / committed to concurrently.
|
| delete_inference_endpoint(self, name: 'str', *, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'None'
| Delete an Inference Endpoint.
|
| This operation is not reversible. If you don't want to be charged for an Inference Endpoint, it is preferable
| to pause it with [`pause_inference_endpoint`] or scale it to zero with [`scale_to_zero_inference_endpoint`].
|
| For convenience, you can also delete an Inference Endpoint using [`InferenceEndpoint.delete`].
|
| Args:
| name (`str`):
| The name of the Inference Endpoint to delete.
| namespace (`str`, *optional*):
| The namespace in which the Inference Endpoint is located. Defaults to the current user.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| delete_repo(self, repo_id: 'str', *, token: 'str | bool | None' = None, repo_type: 'str | None' = None, missing_ok: 'bool' = False) -> 'None'
| Delete a repo from the HuggingFace Hub. CAUTION: this is irreversible.
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated
| by a `/`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if uploading to a dataset or
| space, `None` or `"model"` if uploading to a model.
| missing_ok (`bool`, *optional*, defaults to `False`):
| If `True`, do not raise an error if repo does not exist.
|
| Raises:
| [`~utils.RepositoryNotFoundError`]
| If the repository to delete from cannot be found and `missing_ok` is set to False (default).
|
| delete_scheduled_job(self, *, scheduled_job_id: 'str', namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'None'
| Delete a scheduled compute Job on Hugging Face infrastructure.
|
| Args:
| scheduled_job_id (`str`):
| ID of the scheduled Job.
|
| namespace (`str`, *optional*):
| The namespace where the scheduled Job is. Defaults to the current user's namespace.
|
| token `(Union[bool, str, None]`, *optional*):
| A valid user access token. If not provided, the locally saved token will be used, which is the
| recommended authentication method. Set to `False` to disable authentication.
| Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
|
| delete_space_secret(self, repo_id: 'str', key: 'str', *, token: 'bool | str | None' = None) -> 'None'
| Deletes a secret from a Space.
|
| Secrets allow to set secret keys or tokens to a Space without hardcoding them.
| For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
|
| Args:
| repo_id (`str`):
| ID of the repo to update. Example: `"bigcode/in-the-stack"`.
| key (`str`):
| Secret key. Example: `"GITHUB_API_KEY"`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| delete_space_storage(self, repo_id: 'str', *, token: 'bool | str | None' = None) -> 'SpaceRuntime'
| Delete persistent storage for a Space.
|
| > [!WARNING]
| > `delete_space_storage` is deprecated and will be removed in version 2.0. Use [`delete_space_volumes`] instead.
|
| Args:
| repo_id (`str`):
| ID of the Space to update. Example: `"open-llm-leaderboard/open_llm_leaderboard"`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| Returns:
| [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
| Raises:
| [`BadRequestError`]
| If space has no persistent storage.
|
| delete_space_variable(self, repo_id: 'str', key: 'str', *, token: 'bool | str | None' = None) -> 'dict[str, SpaceVariable]'
| Deletes a variable from a Space.
|
| Variables allow to set environment variables to a Space without hardcoding them.
| For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables
|
| Args:
| repo_id (`str`):
| ID of the repo to update. Example: `"bigcode/in-the-stack"`.
| key (`str`):
| Variable key. Example: `"MODEL_REPO_ID"`
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| delete_space_volumes(self, repo_id: 'str', *, token: 'bool | str | None' = None) -> 'None'
| Remove all volumes from a Space.
|
| Args:
| repo_id (`str`):
| ID of the Space to update. Example: `"username/my-space"`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Raises:
| [`BadRequestError`]:
| If the Space has no volumes attached.
|
| Example:
| ```python
| >>> from huggingface_hub import HfApi
| >>> api = HfApi()
| >>> api.delete_space_volumes("username/my-space")
| ```
|
| delete_tag(self, repo_id: 'str', *, tag: 'str', token: 'bool | str | None' = None, repo_type: 'str | None' = None) -> 'None'
| Delete a tag from a repo on the Hub.
|
| Args:
| repo_id (`str`):
| The repository in which a tag will be deleted.
| Example: `"user/my-cool-model"`.
|
| tag (`str`):
| The name of the tag to delete.
|
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if tagging a dataset or space, `None` or
| `"model"` if tagging a model. Default is `None`.
|
| Raises:
| [`~utils.RepositoryNotFoundError`]:
| If repository is not found (error 404): wrong repo_id/repo_type, private
| but not authenticated or repo does not exist.
| [`~utils.RevisionNotFoundError`]:
| If tag is not found.
|
| delete_webhook(self, webhook_id: 'str', *, token: 'bool | str | None' = None) -> 'None'
| Delete a webhook.
|
| Args:
| webhook_id (`str`):
| The unique identifier of the webhook to delete.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved token, which is the recommended
| method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `None`
|
| Example:
| ```python
| >>> from huggingface_hub import delete_webhook
| >>> delete_webhook("654bbbc16f2ec14d77f109cc")
| ```
|
| disable_space_dev_mode(self, repo_id: 'str', *, token: 'bool | str | None' = None) -> 'SpaceRuntime'
| Disable dev mode on a Space.
|
| Spaces Dev Mode eases the debugging of your application and makes iterating on Spaces faster by allowing you
| to restart your application without stopping the Space container itself. This feature is available as part of
| a PRO or Team & Enterprise plan. See https://huggingface.co/docs/hub/spaces-dev-mode for more details.
|
| Args:
| repo_id (`str`):
| ID of the Space to disable dev mode. Example: `"Salesforce/BLIP2"`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`SpaceRuntime`]: Runtime information about your Space.
|
| Raises:
| [`~utils.RepositoryNotFoundError`]:
| If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you
| are not authenticated.
| [`~utils.HfHubHTTPError`]:
| 403 Forbidden: only the owner of a Space can set dev mode. If you want to handle a Space that you don't
| own, either ask the owner by opening a Discussion or duplicate the Space.
| [`~utils.BadRequestError`]:
| If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide
| a static Space, you can set it to private.
|
| disable_webhook(self, webhook_id: 'str', *, token: 'bool | str | None' = None) -> 'WebhookInfo'
| Disable a webhook (makes it "disabled").
|
| Args:
| webhook_id (`str`):
| The unique identifier of the webhook to disable.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved token, which is the recommended
| method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`WebhookInfo`]:
| Info about the disabled webhook.
|
| Example:
| ```python
| >>> from huggingface_hub import disable_webhook
| >>> disabled_webhook = disable_webhook("654bbbc16f2ec14d77f109cc")
| >>> disabled_webhook
| WebhookInfo(
| id="654bbbc16f2ec14d77f109cc",
| url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
| jon=None,
| watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
| domains=["repo", "discussion"],
| secret="my-secret",
| disabled=True,
| )
| ```
|
| download_bucket_files(self, bucket_id: 'str', files: 'list[tuple[str | BucketFile, str | Path]]', *, raise_on_missing_files: 'bool' = False, token: 'str | bool | None' = None) -> 'None'
| Download files from a bucket.
|
| Files input is a list of `(remote file, local file)` tuples where `remote file` is either the path of the file
| in the bucket or a [`BucketFile`] object, and `local file` is the destination path on the local filesystem.
| When passing a [`BucketFile`] object (obtained from [`list_bucket_tree`]), the method will skip the metadata
| fetching step and directly download the files.
|
| Args:
| bucket_id (`str`):
| The ID of the bucket (e.g. `"username/my-bucket"`).
| files (`list[tuple[Union[str, BucketFile], Union[str, Path]]]`):
| Files to download as a list of tuple (source, destination). See description above for format details.
| raise_on_missing_files (`bool`, *optional*):
| If `True`, raise an [`EntryNotFoundError`] when a requested file does not exist in the bucket. If
| `False` (default), missing files are skipped with a warning.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Example:
| ```python
| >>> from huggingface_hub import download_bucket_files
|
| >>> download_bucket_files(
| ... bucket_id="username/my-bucket",
| ... files=[
| ... ("models/model.safetensors", "./local/model.safetensors"),
| ... ("config.json", "./local/config.json"),
| ... ],
| ... )
| ```
|
| ```python
| >>> from huggingface_hub import download_bucket_files
|
| >>> parquet_files = [file for file in list_bucket_tree(bucket_id="username/my-bucket") if file.path.endswith(".parquet")]
| >>> download_bucket_files(
| ... bucket_id="username/my-bucket",
| ... files=[(file, f"./local/{file.path}") for file in parquet_files],
| ... )
| ```
|
| duplicate_repo(self, from_id: 'str', to_id: 'str | None' = None, *, repo_type: 'str | None' = None, private: 'bool | None' = None, visibility: 'RepoVisibility_T | None' = None, token: 'bool | str | None' = None, exist_ok: 'bool' = False, space_hardware: 'SpaceHardware | None' = None, space_storage: 'SpaceStorage | None' = None, space_sleep_time: 'int | None' = None, space_secrets: 'list[dict[str, str]] | None' = None, space_variables: 'list[dict[str, str]] | None' = None, space_volumes: 'list[Volume] | None' = None) -> 'RepoUrl'
| Duplicate a repo on the Hub (model, dataset, or Space).
|
| This performs a server-side copy that preserves full git history and LFS objects
| without requiring a local download/upload round-trip.
|
| Args:
| from_id (`str`):
| ID of the repo to duplicate. Example: `"openai/gdpval"`.
| to_id (`str`, *optional*):
| ID of the new repo. Example: `"myorg/my-gdpval"`. If not provided, the new
| repo will have the same name as the original repo, but in your account.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if duplicating a dataset or Space,
| `None` or `"model"` if duplicating a model. Default is `None`.
| private (`bool`, *optional*):
| Whether the new repo should be private or not. Defaults to the same
| privacy as the original repo. Cannot be passed together with `visibility`.
| visibility (`Literal["public", "private", "protected"]`, *optional*):
| Visibility of the new repo. Can be `"public"` or `"private"`, or `"protected"` for Spaces. Defaults
| to the same visibility as the original repo.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| exist_ok (`bool`, *optional*, defaults to `False`):
| If `True`, do not raise an error if repo already exists.
| space_hardware (`SpaceHardware` or `str`, *optional*):
| Choice of Hardware if repo_type is "space". Example: `"t4-medium"`. See
| [`SpaceHardware`] for a complete list.
| space_storage (`SpaceStorage` or `str`, *optional*):
| <Deprecated, use `set_space_volumes` instead> Choice of persistent storage tier if repo_type is "space". Example:
| `"small"`. See [`SpaceStorage`] for a complete list.
| space_sleep_time (`int`, *optional*):
| Number of seconds of inactivity to wait before a Space is put to sleep.
| Set to `-1` if you don't want your Space to sleep (default behavior for
| upgraded hardware). For free hardware, you can't configure the sleep time
| (value is fixed to 48 hours of inactivity). Only applicable if repo_type is "space".
| See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
| space_secrets (`list[dict[str, str]]`, *optional*):
| A list of secret keys to set in your Space. Each item is in the form
| `{"key": ..., "value": ..., "description": ...}` where description is optional.
| Only applicable if repo_type is "space".
| For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
| space_variables (`list[dict[str, str]]`, *optional*):
| A list of public environment variables to set in your Space. Each item is in
| the form `{"key": ..., "value": ..., "description": ...}` where description
| is optional. Only applicable if repo_type is "space".
| For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables.
| space_volumes (`list[Volume]`, *optional*):
| A list of [`Volume`] objects to mount in the Space at duplication time. Each volume has a `type`
| (`"bucket"`, `"model"`, `"dataset"`, or `"space"`), a `source` (repo or bucket ID), a `mount_path`
| (path inside the container), and optional `revision`, `read_only`, and `path` fields.
| Only applicable if repo_type is "space".
|
| Returns:
| [`RepoUrl`]: URL to the newly created repo. Value is a subclass of `str` containing
| attributes like `endpoint`, `repo_type` and `repo_id`.
|
| Raises:
| [`~utils.RepositoryNotFoundError`]:
| If one of `from_id` or `to_id` cannot be found. This may be because it doesn't exist,
| or because it is set to `private` and you do not have access.
| [`HfHubHTTPError`]:
| If the HuggingFace API returned an error
|
| Example:
| ```python
| >>> from huggingface_hub import duplicate_repo
|
| # Duplicate a model to your account
| >>> duplicate_repo("google/gemma-7b")
| RepoUrl('https://huggingface.co/nateraw/gemma-7b',...)
|
| # Duplicate a dataset with a custom name
| >>> duplicate_repo("openai/gdpval", to_id="myorg/my-gdpval", repo_type="dataset")
| RepoUrl('https://huggingface.co/datasets/myorg/my-gdpval',...)
|
| # Duplicate a Space with custom hardware
| >>> duplicate_repo("multimodalart/dreambooth-training", repo_type="space", space_hardware="t4-medium")
| RepoUrl('https://huggingface.co/spaces/nateraw/dreambooth-training',...)
| ```
|
| duplicate_space(self, from_id: 'str', to_id: 'str | None' = None, *, private: 'bool | None' = None, visibility: 'RepoVisibility_T | None' = None, token: 'bool | str | None' = None, exist_ok: 'bool' = False, hardware: 'SpaceHardware | None' = None, storage: 'SpaceStorage | None' = None, sleep_time: 'int | None' = None, secrets: 'list[dict[str, str]] | None' = None, variables: 'list[dict[str, str]] | None' = None) -> 'RepoUrl'
| Duplicate a Space.
|
| Programmatically duplicate a Space. The new Space will be created in your account and will be in the same state
| as the original Space (running or paused). You can duplicate a Space no matter the current state of a Space.
|
| Args:
| from_id (`str`):
| ID of the Space to duplicate. Example: `"pharma/CLIP-Interrogator"`.
| to_id (`str`, *optional*):
| ID of the new Space. Example: `"dog/CLIP-Interrogator"`. If not provided, the new Space will have the same
| name as the original Space, but in your account.
| private (`bool`, *optional*):
| Whether the new Space should be private or not. Defaults to the same privacy as the original Space. Cannot be passed together with `visibility`.
| visibility (`Literal["public", "private", "protected"]`, *optional*):
| Visibility of the new Space. Can be `"public"`, `"private"`, or `"protected"`. Defaults to the same
| visibility as the original Space.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| exist_ok (`bool`, *optional*, defaults to `False`):
| If `True`, do not raise an error if repo already exists.
| hardware (`SpaceHardware` or `str`, *optional*):
| Choice of Hardware. Example: `"t4-medium"`. See [`SpaceHardware`] for a complete list.
| storage (`SpaceStorage` or `str`, *optional*):
| Choice of persistent storage tier. Example: `"small"`. See [`SpaceStorage`] for a complete list.
| sleep_time (`int`, *optional*):
| Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
| your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure
| the sleep time (value is fixed to 48 hours of inactivity).
| See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
| secrets (`list[dict[str, str]]`, *optional*):
| A list of secret keys to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
| For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
| variables (`list[dict[str, str]]`, *optional*):
| A list of public environment variables to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
| For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables.
|
| Returns:
| [`RepoUrl`]: URL to the newly created repo. Value is a subclass of `str` containing
| attributes like `endpoint`, `repo_type` and `repo_id`.
|
| Raises:
| [`~utils.RepositoryNotFoundError`]:
| If one of `from_id` or `to_id` cannot be found. This may be because it doesn't exist,
| or because it is set to `private` and you do not have access.
| [`HfHubHTTPError`]:
| If the HuggingFace API returned an error
|
| Example:
| ```python
| >>> from huggingface_hub import duplicate_space
|
| # Duplicate a Space to your account
| >>> duplicate_space("multimodalart/dreambooth-training")
| RepoUrl('https://huggingface.co/spaces/nateraw/dreambooth-training',...)
|
| # Can set custom destination id and visibility flag.
| >>> duplicate_space("multimodalart/dreambooth-training", to_id="my-dreambooth", visibility="private")
| RepoUrl('https://huggingface.co/spaces/nateraw/my-dreambooth',...)
| ```
|
| > [!WARNING]
| > `duplicate_space` is deprecated and will be removed in version 2.0. Use [`~HfApi.duplicate_repo`] instead.
|
| edit_discussion_comment(self, repo_id: 'str', discussion_num: 'int', comment_id: 'str', new_content: 'str', *, token: 'bool | str | None' = None, repo_type: 'str | None' = None) -> 'DiscussionComment'
| Edits a comment on a Discussion / Pull Request.
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated
| by a `/`.
| discussion_num (`int`):
| The number of the Discussion or Pull Request . Must be a strictly positive integer.
| comment_id (`str`):
| The ID of the comment to edit.
| new_content (`str`):
| The new content of the comment. Comments support markdown formatting.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if uploading to a dataset or
| space, `None` or `"model"` if uploading to a model. Default is
| `None`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`DiscussionComment`]: the edited comment
|
| > [!TIP]
| > Raises the following errors:
| >
| > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
| > if the HuggingFace API returned an error
| > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| > if some parameter value is invalid
| > - [`~utils.RepositoryNotFoundError`]
| > If the repository to download from cannot be found. This may be because it doesn't exist,
| > or because it is set to `private` and you do not have access.
|
| enable_space_dev_mode(self, repo_id: 'str', *, token: 'bool | str | None' = None) -> 'SpaceRuntime'
| Enable dev mode on a Space.
|
| Spaces Dev Mode eases the debugging of your application and makes iterating on Spaces faster by allowing you
| to restart your application without stopping the Space container itself. This feature is available as part of
| a PRO or Team & Enterprise plan. See https://huggingface.co/docs/hub/spaces-dev-mode for more details.
|
| Args:
| repo_id (`str`):
| ID of the Space to enable dev mode. Example: `"Salesforce/BLIP2"`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`SpaceRuntime`]: Runtime information about your Space.
|
| Raises:
| [`~utils.RepositoryNotFoundError`]:
| If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you
| are not authenticated.
| [`~utils.HfHubHTTPError`]:
| 403 Forbidden: only the owner of a Space can set dev mode. If you want to handle a Space that you don't
| own, either ask the owner by opening a Discussion or duplicate the Space.
| [`~utils.BadRequestError`]:
| If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide
| a static Space, you can set it to private.
|
| enable_webhook(self, webhook_id: 'str', *, token: 'bool | str | None' = None) -> 'WebhookInfo'
| Enable a webhook (makes it "active").
|
| Args:
| webhook_id (`str`):
| The unique identifier of the webhook to enable.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved token, which is the recommended
| method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`WebhookInfo`]:
| Info about the enabled webhook.
|
| Example:
| ```python
| >>> from huggingface_hub import enable_webhook
| >>> enabled_webhook = enable_webhook("654bbbc16f2ec14d77f109cc")
| >>> enabled_webhook
| WebhookInfo(
| id="654bbbc16f2ec14d77f109cc",
| job=None,
| url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
| watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
| domains=["repo", "discussion"],
| secret="my-secret",
| disabled=False,
| )
| ```
|
| fetch_job_logs(self, *, job_id: 'str', namespace: 'str | None' = None, follow: 'bool' = False, tail: 'int | None' = None, token: 'bool | str | None' = None) -> 'Iterable[str]'
| Fetch all the logs from a compute Job on Hugging Face infrastructure.
|
| Args:
| job_id (`str`):
| ID of the Job.
|
| namespace (`str`, *optional*):
| The namespace where the Job is running. Defaults to the current user's namespace.
|
| follow (`bool`, *optional*):
| If `True`, stream logs in real-time until the job completes (blocking).
| If `False` (default), fetch only the currently available logs and return immediately (non-blocking).
|
| tail (`int`, *optional*):
| Maximum number of lines to return from the logs. When combined with `follow=True`,
| starts from the last N lines and continues streaming new logs. When `follow=False`,
| returns only the last N lines from currently available logs.
|
| token `(Union[bool, str, None]`, *optional*):
| A valid user access token. If not provided, the locally saved token will be used, which is the
| recommended authentication method. Set to `False` to disable authentication.
| Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
|
| Example:
|
| ```python
| >>> from huggingface_hub import fetch_job_logs, run_job
| >>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"])
| >>> for log in fetch_job_logs(job_id=job.id):
| ... print(log)
| Hello from HF compute!
|
| >>> # Non-blocking: fetch only currently available logs
| >>> for log in fetch_job_logs(job_id=job.id, follow=False):
| ... print(log)
|
| >>> # Stream logs starting from the last 100 lines
| >>> for log in fetch_job_logs(job_id=job.id, follow=True, tail=100):
| ... print(log)
| ```
|
| fetch_job_metrics(self, *, job_id: 'str', namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'Iterable[dict[str, Any]]'
| Fetch all the live metrics from a compute Job on Hugging Face infrastructure.
|
| Args:
| job_id (`str`):
| ID of the Job.
|
| namespace (`str`, *optional*):
| The namespace where the Job is running. Defaults to the current user's namespace.
|
| token `(Union[bool, str, None]`, *optional*):
| A valid user access token. If not provided, the locally saved token will be used, which is the
| recommended authentication method. Set to `False` to disable authentication.
| Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
|
| Example:
|
| ```python
| >>> from huggingface_hub import fetch_job_metrics, run_job
| >>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"], flavor="a10g-small")
| >>> for metrics in fetch_job_metrics(job_id=job.id):
| ... print(metrics)
| {
| "cpu_usage_pct": 0,
| "cpu_millicores": 3500,
| "memory_used_bytes": 1306624,
| "memory_total_bytes": 15032385536,
| "rx_bps": 0,
| "tx_bps": 0,
| "gpus": {
| "882fa930": {
| "utilization": 0,
| "memory_used_bytes": 0,
| "memory_total_bytes": 22836000000
| }
| },
| "replica": "57vr7"
| }
| ```
|
| fetch_space_logs(self, repo_id: 'str', *, build: 'bool' = False, follow: 'bool' = False, token: 'bool | str | None' = None) -> 'Iterable[str]'
| Fetch the run or build logs of a Space on the Hub.
|
| Useful for debugging a Space that is failing to build or crashing at runtime,
| especially from a script or agentic workflow where reading logs in a browser
| is not an option.
|
| Args:
| repo_id (`str`):
| ID of the Space. Example: `"bigcode/in-the-stack"`.
| build (`bool`, *optional*, defaults to `False`):
| If `True`, fetch the container build logs (useful when a Space is stuck
| in `BUILD_ERROR`). If `False` (default), fetch the run logs, i.e. the
| stdout/stderr of the running application.
| follow (`bool`, *optional*, defaults to `False`):
| If `True`, stream logs in real-time (blocking) until the server closes
| the stream or `KeyboardInterrupt` is raised. If `False` (default), fetch
| only the currently buffered logs and return immediately (non-blocking,
| like `docker logs`).
| token (`bool` or `str`, *optional*):
| A valid user access token. Defaults to the locally saved token, which is
| the recommended authentication method. Set to `False` to disable
| authentication. See
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
|
| Returns:
| `Iterable[str]`: A generator yielding log lines as they become available.
|
| Example:
|
| ```python
| >>> from huggingface_hub import fetch_space_logs
| >>> # Non-blocking: print currently available run logs and exit.
| >>> for line in fetch_space_logs("username/my-space"):
| ... print(line, end="")
|
| >>> # Debug a build failure:
| >>> for line in fetch_space_logs("username/my-space", build=True):
| ... print(line, end="")
|
| >>> # Stream run logs until the server closes the stream.
| >>> for line in fetch_space_logs("username/my-space", follow=True):
| ... print(line, end="")
| ```
|
| file_exists(self, repo_id: 'str', filename: 'str', *, repo_type: 'str | None' = None, revision: 'str | None' = None, token: 'str | bool | None' = None) -> 'bool'
| Checks if a file exists in a repository on the Hugging Face Hub.
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated
| by a `/`.
| filename (`str`):
| The name of the file to check, for example:
| `"config.json"`
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
| `None` or `"model"` if getting repository info from a model. Default is `None`.
| revision (`str`, *optional*):
| The revision of the repository from which to get the information. Defaults to `"main"` branch.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| True if the file exists, False otherwise.
|
| Examples:
| ```py
| >>> from huggingface_hub import file_exists
| >>> file_exists("bigcode/starcoder", "config.json")
| True
| >>> file_exists("bigcode/starcoder", "not-a-file")
| False
| >>> file_exists("bigcode/not-a-repo", "config.json")
| False
| ```
|
| get_bucket_file_metadata(self, bucket_id: 'str', remote_path: 'str', *, token: 'str | bool | None' = None) -> 'BucketFileMetadata'
| Fetch metadata of a file in a bucket.
|
| Args:
| bucket_id (`str`):
| The ID of the bucket (e.g. `"username/my-bucket"`).
| remote_path (`str`):
| The path of the file in the bucket.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`BucketFileMetadata`]: The file metadata containing size and xet information.
|
| Example:
| ```python
| >>> from huggingface_hub import get_bucket_file_metadata
| >>> metadata = get_bucket_file_metadata(
| ... bucket_id="username/my-bucket",
| ... remote_path="models/model.safetensors",
| ... )
| >>> metadata.size
| 42000
| ```
|
| get_bucket_paths_info(self, bucket_id: 'str', paths: 'Iterable[str]', *, token: 'str | bool | None' = None) -> 'Iterable[BucketFile]'
| Get information about a bucket's paths.
|
| Calls are made in batches of 1000 paths. Results are yielded as they are received.
|
| Args:
| bucket_id (`str`):
| The ID of the bucket (e.g. `"username/my-bucket"`).
| paths (`Iterable[str]`):
| The paths to get information about. If a path does not exist, it is ignored without raising an exception.
| Only file paths are supported.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `Iterable[BucketFile]`:
| The information about the paths, as an iterable of [`BucketFile`] objects.
|
| Example:
| ```py
| >>> from huggingface_hub import get_bucket_paths_info
| >>> paths_info = get_bucket_paths_info("username/my-bucket", ["file.txt", "checkpoints/model.safetensors"])
| >>> for info in paths_info:
| ... print(info)
| BucketFile(type='file', path='file.txt', size=2379, xet_hash='96e637d9665bd35477b1908a23f2e254edfba0618dbd2d62f90a6baee7d139cf', mtime=datetime.datetime(2024, 9, 25, 15, 31, 2, 346000, tzinfo=datetime.timezone.utc))
| BucketFile(type='file', path='checkpoints/model.safetensors', size=2408828, xet_hash='3ed0e9fefe788ddd61d1e26eba67057e9740a064b009256fbafadf6bb95785ca', mtime=datetime.datetime(2024, 9, 25, 15, 31, 2, 346000, tzinfo=datetime.timezone.utc))
| ```
|
| get_collection(self, collection_slug: 'str', *, token: 'bool | str | None' = None) -> 'Collection'
| Gets information about a Collection on the Hub.
|
| Args:
| collection_slug (`str`):
| Slug of the collection of the Hub. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns: [`Collection`]
|
| Example:
|
| ```py
| >>> from huggingface_hub import get_collection
| >>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")
| >>> collection.title
| 'Recent models'
| >>> len(collection.items)
| 37
| >>> collection.items[0]
| CollectionItem(
| item_object_id='651446103cd773a050bf64c2',
| item_id='TheBloke/U-Amethyst-20B-AWQ',
| item_type='model',
| position=88,
| note=None
| )
| ```
|
| get_dataset_leaderboard(self, repo_id: 'str', *, base_model_only: 'bool | None' = None, token: 'bool | str | None' = None, timeout: 'float | None' = None) -> 'list[DatasetLeaderboardEntry]'
| Get the leaderboard for a dataset on the Hub.
|
| The leaderboard ranks models based on their evaluation scores on the given benchmark
| dataset. Not all datasets have leaderboards — only benchmark datasets with evaluation
| results submitted to them. This gives a dataset-centric view of scores; for a model-centric
| view, use [`model_info`] with `expand=["evalResults"]`.
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated
| by a `/`. For example: `"allenai/olmOCR-bench"`.
| base_model_only (`bool` or `None`, *optional*):
| By default, the leaderboard only includes models that have no declared `base_model` relation
| (i.e. canonical/root repos), matching the Hub's default leaderboard view. Fine-tuned or derivative
| repos that declare a parent model are excluded. Pass `base_model_only=False` to disable this filter and
| include every submitted result, regardless of whether the model declares a base model relation.
| token (`bool` or `str`, *optional*):
| A valid user access token. Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| timeout (`float`, *optional*):
| Whether to set a timeout for the request to the Hub.
|
| Returns:
| `list[DatasetLeaderboardEntry]`: A list of [`DatasetLeaderboardEntry`] objects representing
| the leaderboard entries, sorted by rank.
|
| > [!TIP]
| > Raises the following errors:
| >
| > - [`~utils.RepositoryNotFoundError`]
| > If the repository cannot be found. This may be because it doesn't exist,
| > or because it is set to `private` and you do not have access.
| > - [`~utils.HfHubHTTPError`]
| > If the dataset does not have a leaderboard.
|
| Example:
| ```python
| >>> from huggingface_hub import HfApi
| >>> api = HfApi()
| >>> leaderboard = api.get_dataset_leaderboard("allenai/olmOCR-bench")
| >>> leaderboard[0].model_id
| 'datalab-to/chandra-ocr-2'
| >>> leaderboard[0].rank
| 1
|
| # Include fine-tuned / derivative models too
| >>> full_leaderboard = api.get_dataset_leaderboard("allenai/olmOCR-bench", base_model_only=False)
| ```
|
| get_dataset_tags(self) -> 'dict'
| List all valid dataset tags as a nested namespace object.
|
| get_discussion_details(self, repo_id: 'str', discussion_num: 'int', *, repo_type: 'str | None' = None, token: 'bool | str | None' = None) -> 'DiscussionWithDetails'
| Fetches a Discussion's / Pull Request 's details from the Hub.
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated
| by a `/`.
| discussion_num (`int`):
| The number of the Discussion or Pull Request . Must be a strictly positive integer.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if uploading to a dataset or
| space, `None` or `"model"` if uploading to a model. Default is
| `None`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns: [`DiscussionWithDetails`]
|
| > [!TIP]
| > Raises the following errors:
| >
| > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
| > if the HuggingFace API returned an error
| > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| > if some parameter value is invalid
| > - [`~utils.RepositoryNotFoundError`]
| > If the repository to download from cannot be found. This may be because it doesn't exist,
| > or because it is set to `private` and you do not have access.
|
| get_full_repo_name(self, model_id: 'str', *, organization: 'str | None' = None, token: 'bool | str | None' = None)
| Returns the repository name for a given model ID and optional
| organization.
|
| Args:
| model_id (`str`):
| The name of the model.
| organization (`str`, *optional*):
| If passed, the repository name will be in the organization
| namespace instead of the user namespace.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `str`: The repository name in the user's namespace
| ({username}/{model_id}) if no organization is passed, and under the
| organization namespace ({organization}/{model_id}) otherwise.
|
| get_hf_file_metadata(self, *, url: 'str', token: 'bool | str | None' = None, timeout: 'float | None' = 10) -> 'HfFileMetadata'
| Fetch metadata of a file versioned on the Hub for a given url.
|
| Args:
| url (`str`):
| File url, for example returned by [`hf_hub_url`].
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| timeout (`float`, *optional*, defaults to 10):
| How many seconds to wait for the server to send metadata before giving up.
|
| Returns:
| A [`HfFileMetadata`] object containing metadata such as location, etag, size and commit_hash.
|
| get_inference_endpoint(self, name: 'str', *, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'InferenceEndpoint'
| Get information about an Inference Endpoint.
|
| Args:
| name (`str`):
| The name of the Inference Endpoint to retrieve information about.
| namespace (`str`, *optional*):
| The namespace in which the Inference Endpoint is located. Defaults to the current user.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`InferenceEndpoint`]: information about the requested Inference Endpoint.
|
| Example:
| ```python
| >>> from huggingface_hub import HfApi
| >>> api = HfApi()
| >>> endpoint = api.get_inference_endpoint("my-text-to-image")
| >>> endpoint
| InferenceEndpoint(name='my-text-to-image', ...)
|
| # Get status
| >>> endpoint.status
| 'running'
| >>> endpoint.url
| 'https://my-text-to-image.region.vendor.endpoints.huggingface.cloud'
|
| # Run inference
| >>> endpoint.client.text_to_image(...)
| ```
|
| get_model_tags(self) -> 'dict'
| List all valid model tags as a nested namespace object
|
| get_organization_overview(self, organization: 'str', token: 'bool | str | None' = None) -> 'Organization'
| Get an overview of an organization on the Hub.
|
| Args:
| organization (`str`):
| Name of the organization to get an overview of.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved token, which is the recommended method
| for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `Organization`: An [`Organization`] object with the organization's overview.
|
| Raises:
| [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
| HTTP 404 If the organization does not exist on the Hub.
|
| get_paths_info(self, repo_id: 'str', paths: 'list[str] | str', *, expand: 'bool' = False, revision: 'str | None' = None, repo_type: 'str | None' = None, token: 'str | bool | None' = None) -> 'list[RepoFile | RepoFolder]'
| Get information about a repo's paths.
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated by a `/`.
| paths (`Union[list[str], str]`, *optional*):
| The paths to get information about. If a path do not exist, it is ignored without raising
| an exception.
| expand (`bool`, *optional*, defaults to `False`):
| Whether to fetch more information about the paths (e.g. last commit and files' security scan results). This
| operation is more expensive for the server so only 50 results are returned per page (instead of 1000).
| As pagination is implemented in `huggingface_hub`, this is transparent for you except for the time it
| takes to get the results.
| revision (`str`, *optional*):
| The revision of the repository from which to get the information. Defaults to `"main"` branch.
| repo_type (`str`, *optional*):
| The type of the repository from which to get the information (`"model"`, `"dataset"` or `"space"`.
| Defaults to `"model"`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `list[Union[RepoFile, RepoFolder]]`:
| The information about the paths, as a list of [`RepoFile`] and [`RepoFolder`] objects.
|
| Raises:
| [`~utils.RepositoryNotFoundError`]:
| If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
| does not exist.
| [`~utils.RevisionNotFoundError`]:
| If revision is not found (error 404) on the repo.
|
| Example:
| ```py
| >>> from huggingface_hub import get_paths_info
| >>> paths_info = get_paths_info("allenai/c4", ["README.md", "en"], repo_type="dataset")
| >>> paths_info
| [
| RepoFile(path='README.md', size=2379, blob_id='f84cb4c97182890fc1dbdeaf1a6a468fd27b4fff', lfs=None, last_commit=None, security=None),
| RepoFolder(path='en', tree_id='dc943c4c40f53d02b31ced1defa7e5f438d5862e', last_commit=None)
| ]
| ```
|
| get_repo_discussions(self, repo_id: 'str', *, author: 'str | None' = None, discussion_type: 'constants.DiscussionTypeFilter | None' = None, discussion_status: 'constants.DiscussionStatusFilter | None' = None, repo_type: 'str | None' = None, token: 'bool | str | None' = None) -> 'Iterator[Discussion]'
| Fetches Discussions and Pull Requests for the given repo.
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated
| by a `/`.
| author (`str`, *optional*):
| Pass a value to filter by discussion author. `None` means no filter.
| Default is `None`.
| discussion_type (`str`, *optional*):
| Set to `"pull_request"` to fetch only pull requests, `"discussion"`
| to fetch only discussions. Set to `"all"` or `None` to fetch both.
| Default is `None`.
| discussion_status (`str`, *optional*):
| Set to `"open"` (respectively `"closed"`) to fetch only open
| (respectively closed) discussions. Set to `"all"` or `None`
| to fetch both.
| Default is `None`.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if fetching from a dataset or
| space, `None` or `"model"` if fetching from a model. Default is
| `None`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `Iterator[Discussion]`: An iterator of [`Discussion`] objects.
|
| Example:
| Collecting all discussions of a repo in a list:
|
| ```python
| >>> from huggingface_hub import get_repo_discussions
| >>> discussions_list = list(get_repo_discussions(repo_id="bert-base-uncased"))
| ```
|
| Iterating over discussions of a repo:
|
| ```python
| >>> from huggingface_hub import get_repo_discussions
| >>> for discussion in get_repo_discussions(repo_id="bert-base-uncased"):
| ... print(discussion.num, discussion.title)
| ```
|
| get_safetensors_metadata(self, repo_id: 'str', *, repo_type: 'str | None' = None, revision: 'str | None' = None, token: 'bool | str | None' = None, timeout: 'float | None' = 10) -> 'SafetensorsRepoMetadata'
| Parse metadata for a safetensors repo on the Hub.
|
| We first check if the repo has a single safetensors file or a sharded safetensors repo. If it's a single
| safetensors file, we parse the metadata from this file. If it's a sharded safetensors repo, we parse the
| metadata from the index file and then parse the metadata from each shard.
|
| To parse metadata from a single safetensors file, use [`parse_safetensors_file_metadata`].
|
| For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.
|
| Args:
| repo_id (`str`):
| A user or an organization name and a repo name separated by a `/`.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if the file is in a dataset or space, `None` or `"model"` if in a
| model. Default is `None`.
| revision (`str`, *optional*):
| The git revision to fetch the file from. Can be a branch name, a tag, or a commit hash. Defaults to the
| head of the `"main"` branch.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| timeout (`float`, *optional*, defaults to 10):
| How many seconds to wait for the server to send data before giving up, passed to each request that
| fetches a safetensors file header. Set to `None` to disable the timeout (not recommended, as a stalled
| connection can hang the call indefinitely).
|
| Returns:
| [`SafetensorsRepoMetadata`]: information related to safetensors repo.
|
| Raises:
| [`NotASafetensorsRepoError`]
| If the repo is not a safetensors repo i.e. doesn't have either a
| `model.safetensors` or a `model.safetensors.index.json` file.
| [`SafetensorsParsingError`]
| If a safetensors file header couldn't be parsed correctly.
|
| Example:
| ```py
| # Parse repo with single weights file
| >>> metadata = get_safetensors_metadata("bigscience/bloomz-560m")
| >>> metadata
| SafetensorsRepoMetadata(
| metadata=None,
| sharded=False,
| weight_map={'h.0.input_layernorm.bias': 'model.safetensors', ...},
| files_metadata={'model.safetensors': SafetensorsFileMetadata(...)}
| )
| >>> metadata.files_metadata["model.safetensors"].metadata
| {'format': 'pt'}
|
| # Parse repo with sharded model
| >>> metadata = get_safetensors_metadata("bigscience/bloom")
| Parse safetensors files: 100%|██████████████████████████████████████████| 72/72 [00:12<00:00, 5.78it/s]
| >>> metadata
| SafetensorsRepoMetadata(metadata={'total_size': 352494542848}, sharded=True, weight_map={...}, files_metadata={...})
| >>> len(metadata.files_metadata)
| 72 # All safetensors files have been fetched
|
| # Parse repo with sharded model
| >>> get_safetensors_metadata("runwayml/stable-diffusion-v1-5")
| NotASafetensorsRepoError: 'runwayml/stable-diffusion-v1-5' is not a safetensors repo. Couldn't find 'model.safetensors.index.json' or 'model.safetensors' files.
| ```
|
| get_space_runtime(self, repo_id: 'str', *, token: 'bool | str | None' = None) -> 'SpaceRuntime'
| Gets runtime information about a Space.
|
| Args:
| repo_id (`str`):
| ID of the repo to update. Example: `"bigcode/in-the-stack"`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| Returns:
| [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
|
| get_space_secrets(self, repo_id: 'str', *, token: 'bool | str | None' = None) -> 'dict[str, SpaceSecret]'
| Gets all secrets from a Space.
|
| Secret values are write-only and cannot be read back. Only the key, description, and last update time
| are returned.
|
| Secrets allow to set secret keys or tokens to a Space without hardcoding them.
| For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
|
| Args:
| repo_id (`str`):
| ID of the repo to query. Example: `"bigcode/in-the-stack"`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `dict[str, SpaceSecret]`: Dictionary of [`SpaceSecret`] objects keyed by secret name.
|
| Example:
| ```python
| >>> from huggingface_hub import HfApi
| >>> api = HfApi()
| >>> api.get_space_secrets("username/my-space")
| {'HF_TOKEN': SpaceSecret(key='HF_TOKEN', description='...', updated_at=datetime.datetime(...))}
| ```
|
| get_space_variables(self, repo_id: 'str', *, token: 'bool | str | None' = None) -> 'dict[str, SpaceVariable]'
| Gets all variables from a Space.
|
| Variables allow to set environment variables to a Space without hardcoding them.
| For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables
|
| Args:
| repo_id (`str`):
| ID of the repo to query. Example: `"bigcode/in-the-stack"`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| get_user_overview(self, username: 'str', token: 'bool | str | None' = None) -> 'User'
| Get an overview of a user on the Hub.
|
| Args:
| username (`str`):
| Username of the user to get an overview of.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `User`: A [`User`] object with the user's overview.
|
| Raises:
| [`HfHubHTTPError`]:
| HTTP 404 If the user does not exist on the Hub.
|
| get_webhook(self, webhook_id: 'str', *, token: 'bool | str | None' = None) -> 'WebhookInfo'
| Get a webhook by its id.
|
| Args:
| webhook_id (`str`):
| The unique identifier of the webhook to get.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved token, which is the recommended
| method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`WebhookInfo`]:
| Info about the webhook.
|
| Example:
| ```python
| >>> from huggingface_hub import get_webhook
| >>> webhook = get_webhook("654bbbc16f2ec14d77f109cc")
| >>> print(webhook)
| WebhookInfo(
| id="654bbbc16f2ec14d77f109cc",
| job=None,
| watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
| url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
| secret="my-secret",
| domains=["repo", "discussion"],
| disabled=False,
| )
| ```
|
| grant_access(self, repo_id: 'str', user: 'str', *, repo_type: 'str | None' = None, token: 'bool | str | None' = None) -> 'None'
| Grant access to a user for a given gated repo.
|
| Granting access don't require for the user to send an access request by themselves. The user is automatically
| added to the accepted list meaning they can download the files You can revoke the granted access at any time
| using [`cancel_access_request`] or [`reject_access_request`].
|
| For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
|
| Args:
| repo_id (`str`):
| The id of the repo to grant access to.
| user (`str`):
| The username of the user to grant access.
| repo_type (`str`, *optional*):
| The type of the repo to grant access to. Must be one of `model`, `dataset` or `space`.
| Defaults to `model`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Raises:
| [`HfHubHTTPError`]:
| HTTP 400 if the repo is not gated.
| [`HfHubHTTPError`]:
| HTTP 400 if the user already has access to the repo.
| [`HfHubHTTPError`]:
| HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
| or `admin` role in the organization the repo belongs to or if you passed a `read` token.
| [`HfHubHTTPError`]:
| HTTP 404 if the user does not exist on the Hub.
|
| hf_hub_download(self, repo_id: 'str', filename: 'str', *, subfolder: 'str | None' = None, repo_type: 'str | None' = None, revision: 'str | None' = None, cache_dir: 'str | Path | None' = None, local_dir: 'str | Path | None' = None, force_download: 'bool' = False, etag_timeout: 'float' = 10, token: 'bool | str | None' = None, local_files_only: 'bool' = False, tqdm_class: 'type[base_tqdm] | None' = None, dry_run: 'bool' = False) -> 'str | DryRunFileInfo'
| Download a given file if it's not already present in the local cache.
|
| The new cache file layout looks like this:
| - The cache directory contains one subfolder per repo_id (namespaced by repo type)
| - inside each repo folder:
| - refs is a list of the latest known revision => commit_hash pairs
| - blobs contains the actual file blobs (identified by their git-sha or sha256, depending on
| whether they're LFS files or not)
| - snapshots contains one subfolder per commit, each "commit" contains the subset of the files
| that have been resolved at that particular commit. Each filename is a symlink to the blob
| at that particular commit.
|
| ```
| [ 96] .
| └── [ 160] models--julien-c--EsperBERTo-small
| ├── [ 160] blobs
| │ ├── [321M] 403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
| │ ├── [ 398] 7cb18dc9bafbfcf74629a4b760af1b160957a83e
| │ └── [1.4K] d7edf6bd2a681fb0175f7735299831ee1b22b812
| ├── [ 96] refs
| │ └── [ 40] main
| └── [ 128] snapshots
| ├── [ 128] 2439f60ef33a0d46d85da5001d52aeda5b00ce9f
| │ ├── [ 52] README.md -> ../../blobs/d7edf6bd2a681fb0175f7735299831ee1b22b812
| │ └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
| └── [ 128] bbc77c8132af1cc5cf678da3f1ddf2de43606d48
| ├── [ 52] README.md -> ../../blobs/7cb18dc9bafbfcf74629a4b760af1b160957a83e
| └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
| ```
|
| If `local_dir` is provided, the file structure from the repo will be replicated in this location. When using this
| option, the `cache_dir` will not be used and a `.cache/huggingface/` folder will be created at the root of `local_dir`
| to store some metadata related to the downloaded files. While this mechanism is not as robust as the main
| cache-system, it's optimized for regularly pulling the latest version of a repository.
|
| Args:
| repo_id (`str`):
| A user or an organization name and a repo name separated by a `/`.
| filename (`str`):
| The name of the file in the repo.
| subfolder (`str`, *optional*):
| An optional value corresponding to a folder inside the repository.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if downloading from a dataset or space,
| `None` or `"model"` if downloading from a model. Default is `None`.
| revision (`str`, *optional*):
| An optional Git revision id which can be a branch name, a tag, or a
| commit hash.
| cache_dir (`str`, `Path`, *optional*):
| Path to the folder where cached files are stored.
| local_dir (`str` or `Path`, *optional*):
| If provided, the downloaded file will be placed under this directory.
| force_download (`bool`, *optional*, defaults to `False`):
| Whether the file should be downloaded even if it already exists in
| the local cache.
| etag_timeout (`float`, *optional*, defaults to `10`):
| When fetching ETag, how many seconds to wait for the server to send
| data before giving up which is passed to `httpx.request`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| 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.
| tqdm_class (`tqdm`, *optional*):
| If provided, overwrites the default behavior for the progress bar. Passed
| argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior.
| Defaults to the custom HF progress bar that can be disabled by setting
| `HF_HUB_DISABLE_PROGRESS_BARS` environment variable.
| dry_run (`bool`, *optional*, defaults to `False`):
| If `True`, perform a dry run without actually downloading the file. Returns a
| [`DryRunFileInfo`] object containing information about what would be downloaded.
|
| Returns:
| `str` or [`DryRunFileInfo`]:
| - If `dry_run=False`: Local path of file or if networking is off, last version of file cached on disk.
| - If `dry_run=True`: A [`DryRunFileInfo`] object containing download information.
|
| Raises:
| [`~utils.RepositoryNotFoundError`]
| If the repository to download from cannot be found. This may be because it doesn't exist,
| or because it is set to `private` and you do not have access.
| [`~utils.RevisionNotFoundError`]
| If the revision to download from cannot be found.
| [`~utils.RemoteEntryNotFoundError`]
| If the file to download cannot be found.
| [`~utils.LocalEntryNotFoundError`]
| If network is disabled or unavailable and file is not found in cache.
| [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
| If `token=True` but the token cannot be found.
| [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError)
| If ETag cannot be determined.
| [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| If some parameter value is invalid.
|
| hide_discussion_comment(self, repo_id: 'str', discussion_num: 'int', comment_id: 'str', *, token: 'bool | str | None' = None, repo_type: 'str | None' = None) -> 'DiscussionComment'
| Hides a comment on a Discussion / Pull Request.
|
| > [!WARNING]
| > Hidden comments' content cannot be retrieved anymore. Hiding a comment is irreversible.
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated
| by a `/`.
| discussion_num (`int`):
| The number of the Discussion or Pull Request . Must be a strictly positive integer.
| comment_id (`str`):
| The ID of the comment to edit.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if uploading to a dataset or
| space, `None` or `"model"` if uploading to a model. Default is
| `None`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`DiscussionComment`]: the hidden comment
|
| > [!TIP]
| > Raises the following errors:
| >
| > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
| > if the HuggingFace API returned an error
| > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| > if some parameter value is invalid
| > - [`~utils.RepositoryNotFoundError`]
| > If the repository to download from cannot be found. This may be because it doesn't exist,
| > or because it is set to `private` and you do not have access.
|
| inspect_job(self, *, job_id: 'str', namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'JobInfo'
| Inspect a compute Job on Hugging Face infrastructure.
|
| Args:
| job_id (`str`):
| ID of the Job.
|
| namespace (`str`, *optional*):
| The namespace where the Job is running. Defaults to the current user's namespace.
|
| token `(Union[bool, str, None]`, *optional*):
| A valid user access token. If not provided, the locally saved token will be used, which is the
| recommended authentication method. Set to `False` to disable authentication.
| Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
|
| Example:
|
| ```python
| >>> from huggingface_hub import inspect_job, run_job
| >>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"])
| >>> inspect_job(job.id)
| JobInfo(
| id='68780d00bbe36d38803f645f',
| created_at=datetime.datetime(2025, 7, 16, 20, 35, 12, 808000, tzinfo=datetime.timezone.utc),
| docker_image='python:3.12',
| space_id=None,
| command=['python', '-c', "print('Hello from HF compute!')"],
| arguments=[],
| environment={},
| secrets={},
| flavor='cpu-basic',
| status=JobStatus(stage='RUNNING', message=None)
| )
| ```
|
| inspect_scheduled_job(self, *, scheduled_job_id: 'str', namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'ScheduledJobInfo'
| Inspect a scheduled compute Job on Hugging Face infrastructure.
|
| Args:
| scheduled_job_id (`str`):
| ID of the scheduled Job.
|
| namespace (`str`, *optional*):
| The namespace where the scheduled Job is. Defaults to the current user's namespace.
|
| token `(Union[bool, str, None]`, *optional*):
| A valid user access token. If not provided, the locally saved token will be used, which is the
| recommended authentication method. Set to `False` to disable authentication.
| Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
|
| Example:
|
| ```python
| >>> from huggingface_hub import inspect_job, create_scheduled_job
| >>> scheduled_job = create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"], schedule="@hourly")
| >>> inspect_scheduled_job(scheduled_job.id)
| ```
|
| kernel_info(self, repo_id: 'str', *, revision: 'str | None' = None, timeout: 'float | None' = None, token: 'bool | str | None' = None) -> 'KernelInfo'
| Get info on one specific kernel on huggingface.co.
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated by a `/`.
| revision (`str`, *optional*):
| The revision of the kernel repository from which to get the
| information.
| timeout (`float`, *optional*):
| Whether to set a timeout for the request to the Hub.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`~hf_api.ModelInfo`]: The kernel repository information.
|
| list_accepted_access_requests(self, repo_id: 'str', *, repo_type: 'str | None' = None, token: 'bool | str | None' = None) -> 'Iterable[AccessRequest]'
| Get accepted access requests for a given gated repo.
|
| An accepted request means the user has requested access to the repo and the request has been accepted. The user
| can download any file of the repo. If the approval mode is automatic, this list should contains by default all
| requests. Accepted requests can be cancelled or rejected at any time using [`cancel_access_request`] and
| [`reject_access_request`]. A cancelled request will go back to the pending list while a rejected request will
| go to the rejected list. In both cases, the user will lose access to the repo.
|
| For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
|
| Args:
| repo_id (`str`):
| The id of the repo to get access requests for.
| repo_type (`str`, *optional*):
| The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`.
| Defaults to `model`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `Iterable[AccessRequest]`: An iterable of [`AccessRequest`] objects. Each time contains a `username`, `email`,
| `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will
| be populated with user's answers.
|
| Raises:
| [`HfHubHTTPError`]:
| HTTP 400 if the repo is not gated.
| [`HfHubHTTPError`]:
| HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
| or `admin` role in the organization the repo belongs to or if you passed a `read` token.
|
| Example:
| ```py
| >>> from huggingface_hub import list_accepted_access_requests
|
| >>> requests = list(list_accepted_access_requests("meta-llama/Llama-2-7b"))
| >>> len(requests)
| 411
| >>> requests[0]
| [
| AccessRequest(
| username='clem',
| fullname='Clem 🤗',
| email='***',
| timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
| status='accepted',
| fields=None,
| ),
| ...
| ]
| ```
|
| list_bucket_tree(self, bucket_id: 'str', prefix: 'str | None' = None, *, recursive: 'bool | None' = None, token: 'str | bool | None' = None) -> 'Iterable[BucketFile | BucketFolder]'
| List files in a bucket.
|
| Args:
| bucket_id (`str`):
| The ID of the bucket (e.g. `"username/my-bucket"`).
| prefix (`str`, *optional*):
| Filter results to files whose path starts with this prefix.
| recursive (`bool`, *optional*):
| If `True`, list files recursively. If `False` (default), list files and directories only at root.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `Iterable[Union[BucketFile, BucketFolder]]`: An iterable of [`BucketFile`] and [`BucketFolder`] objects
| containing file and directory information (path, etc.).
|
| Example:
| ```python
| >>> from huggingface_hub import list_bucket_tree
| >>> for file_info in list_bucket_tree(bucket_id="username/my-bucket"):
| ... print(file_info.path)
|
| >>> # Filter by prefix
| >>> for file_info in list_bucket_tree(bucket_id="username/my-bucket", prefix="models/"):
| ... print(file_info.path)
| ```
|
| list_buckets(self, namespace: 'str | None' = None, *, search: 'str | None' = None, token: 'bool | str | None' = None) -> 'Iterable[BucketInfo]'
| List buckets on the Hub under a certain namespace.
|
| Args:
| namespace (`str`, *optional*):
| List buckets under this namespace (user or organization). Defaults to listing user's buckets.
| search (`str`, *optional*):
| A search string to filter bucket names.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `Iterable[BucketInfo]`: An iterable of [`BucketInfo`] objects.
|
| Example:
| ```python
| >>> from huggingface_hub import list_buckets
| >>> for bucket in list_buckets(): # lists buckets in the user's namespace
| ... print(bucket)
|
| >>> for bucket in list_buckets(namespace="huggingface"): # lists buckets in the "huggingface" organization
| ... print(bucket)
|
| >>> for bucket in list_buckets(search="my-prefix"): # filter buckets by name
| ... print(bucket)
| ```
|
| list_collections(self, *, owner: 'list[str] | str | None' = None, item: 'list[str] | str | None' = None, sort: 'CollectionSort_T | None' = None, limit: 'int | None' = None, token: 'bool | str | None' = None) -> 'Iterable[Collection]'
| List collections on the Huggingface Hub, given some filters.
|
| > [!WARNING]
| > When listing collections, the item list per collection is truncated to 4 items maximum. To retrieve all items
| > from a collection, you must use [`get_collection`].
|
| Args:
| owner (`list[str]` or `str`, *optional*):
| Filter by owner's username.
| item (`list[str]` or `str`, *optional*):
| Filter collections containing a particular items. Example: `"models/teknium/OpenHermes-2.5-Mistral-7B"`, `"datasets/squad"` or `"papers/2311.12983"`.
| sort (`Literal["lastModified", "trending", "upvotes"]`, *optional*):
| Sort collections by last modified, trending or upvotes.
| limit (`int`, *optional*):
| Maximum number of collections to be returned.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `Iterable[Collection]`: an iterable of [`Collection`] objects.
|
| list_daily_papers(self, *, date: 'str | None' = None, token: 'bool | str | None' = None, week: 'str | None' = None, month: 'str | None' = None, submitter: 'str | None' = None, sort: 'DailyPapersSort_T | None' = None, p: 'int | None' = None, limit: 'int | None' = None) -> 'Iterable[PaperInfo]'
| List the daily papers published on a given date on the Hugging Face Hub.
|
| Args:
| date (`str`, *optional*):
| Date in ISO format (YYYY-MM-DD) for which to fetch daily papers.
| Defaults to most recent ones.
| token (Union[bool, str, None], *optional*):
| A valid user access token (string). Defaults to the locally saved
| token. To disable authentication, pass `False`.
| week (`str`, *optional*):
| Week in ISO format (YYYY-Www) for which to fetch daily papers. Example, `2025-W09`.
| month (`str`, *optional*):
| Month in ISO format (YYYY-MM) for which to fetch daily papers. Example, `2025-02`.
| submitter (`str`, *optional*):
| Username of the submitter to filter daily papers.
| sort (`Literal["publishedAt", "trending"]`, *optional*):
| Sort order for the daily papers. Can be either by `publishedAt` or by `trending`.
| Defaults to `"publishedAt"`
| p (`int`, *optional*):
| Page number for pagination. Defaults to 0.
| limit (`int`, *optional*):
| Limit of papers to fetch. Defaults to 50.
|
| Returns:
| `Iterable[PaperInfo]`: an iterable of [`huggingface_hub.hf_api.PaperInfo`] objects.
|
| Example:
|
| ```python
| >>> from huggingface_hub import HfApi
|
| >>> api = HfApi()
| >>> list(api.list_daily_papers(date="2025-10-29"))
| ```
|
| list_dataset_parquet_files(self, repo_id: 'str', *, config: 'str | None' = None, token: 'bool | str | None' = None) -> 'list[DatasetParquetEntry]'
| List parquet files available for a dataset on the Hub.
|
| All datasets hosted on the Hub are auto-converted to Parquet by the
| [Dataset Viewer](https://huggingface.co/docs/dataset-viewer/parquet).
| This method returns the list of parquet files with their URLs, configs,
| splits and sizes.
|
| Args:
| repo_id (`str`):
| The dataset repository ID (e.g. `"username/dataset-name"`).
| config (`str`, *optional*):
| Filter by a specific config/subset name. When provided, only
| parquet files for that config are returned.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `list[DatasetParquetEntry]`: a list of [`DatasetParquetEntry`] objects
| containing config, split, url and size for each parquet file.
|
| Example:
| ```python
| >>> from huggingface_hub import list_dataset_parquet_files
| >>> list_dataset_parquet_files("lhoestq/demo1")
| >>> entries[0]
| DatasetParquetEntry(config='default', split='train', url='https://huggingface.co/...', size=5038)
| ```
|
| list_datasets(self, *, filter: 'str | Iterable[str] | None' = None, author: 'str | None' = None, benchmark: "Literal[True] | Literal['official'] | str | None" = None, dataset_name: 'str | None' = None, gated: 'bool | None' = None, language_creators: 'str | list[str] | None' = None, language: 'str | list[str] | None' = None, multilinguality: 'str | list[str] | None' = None, size_categories: 'str | list[str] | None' = None, task_categories: 'str | list[str] | None' = None, task_ids: 'str | list[str] | None' = None, search: 'str | None' = None, sort: 'DatasetSort_T | None' = None, limit: 'int | None' = None, expand: 'list[ExpandDatasetProperty_T] | None' = None, full: 'bool | None' = None, token: 'bool | str | None' = None) -> 'Iterable[DatasetInfo]'
| List datasets hosted on the Huggingface Hub, given some filters.
|
| Args:
| filter (`str` or `Iterable[str]`, *optional*):
| A string or list of string to filter datasets on the hub.
| author (`str`, *optional*):
| A string which identify the author of the returned datasets.
| benchmark (`True`, `"official"`, `str`, *optional*):
| Filter datasets by benchmark. Can be `True` or `"official"` to return official benchmark datasets.
| For future-compatibility, can also be a string representing the benchmark name (currently only "official" is supported).
| dataset_name (`str`, *optional*):
| A string or list of strings that can be used to identify datasets on
| the Hub by its name, such as `SQAC` or `wikineural`
| gated (`bool`, *optional*):
| A boolean to filter datasets on the Hub that are gated or not. By default, all datasets are returned.
| If `gated=True` is passed, only gated datasets are returned.
| If `gated=False` is passed, only non-gated datasets are returned.
| language_creators (`str` or `List`, *optional*):
| A string or list of strings that can be used to identify datasets on
| the Hub with how the data was curated, such as `crowdsourced` or
| `machine_generated`.
| language (`str` or `List`, *optional*):
| A string or list of strings representing a two-character language to
| filter datasets by on the Hub.
| multilinguality (`str` or `List`, *optional*):
| A string or list of strings representing a filter for datasets that
| contain multiple languages.
| size_categories (`str` or `List`, *optional*):
| A string or list of strings that can be used to identify datasets on
| the Hub by the size of the dataset such as `100K<n<1M` or
| `1M<n<10M`.
| tags (`str` or `List`, *optional*):
| Deprecated. Pass tags in `filter` to filter datasets by tags.
| task_categories (`str` or `List`, *optional*):
| A string or list of strings that can be used to identify datasets on
| the Hub by the designed task, such as `audio_classification` or
| `named_entity_recognition`.
| task_ids (`str` or `List`, *optional*):
| A string or list of strings that can be used to identify datasets on
| the Hub by the specific task such as `speech_emotion_recognition` or
| `paraphrase`.
| search (`str`, *optional*):
| A string that will be contained in the returned datasets.
| sort (`DatasetSort_T`, *optional*):
| The key with which to sort the resulting datasets. Possible values are "created_at", "downloads",
| "last_modified", "likes" and "trending_score".
| limit (`int`, *optional*):
| The limit on the number of datasets fetched. Leaving this option
| to `None` fetches all datasets.
| expand (`list[ExpandDatasetProperty_T]`, *optional*):
| List properties to return in the response. When used, only the properties in the list will be returned.
| This parameter cannot be used if `full` is passed.
| Possible values are `"author"`, `"cardData"`, `"citation"`, `"createdAt"`, `"disabled"`, `"description"`, `"downloads"`, `"downloadsAllTime"`, `"gated"`, `"lastModified"`, `"likes"`, `"mainSize"`, `"paperswithcode_id"`, `"private"`, `"siblings"`, `"sha"`, `"tags"`, `"trendingScore"`, `"usedStorage"`, and `"resourceGroup"`.
| full (`bool`, *optional*):
| Whether to fetch all dataset data, including the `last_modified`,
| the `card_data` and the files. Can contain useful information such as the
| PapersWithCode ID.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `Iterable[DatasetInfo]`: an iterable of [`huggingface_hub.hf_api.DatasetInfo`] objects.
|
| Example usage with the `filter` argument:
|
| ```python
| >>> from huggingface_hub import HfApi
|
| >>> api = HfApi()
|
| # List all datasets
| >>> api.list_datasets()
|
|
| # List only the text classification datasets
| >>> api.list_datasets(filter="task_categories:text-classification")
|
|
| # List only the datasets in russian for language modeling
| >>> api.list_datasets(
| ... filter=("language:ru", "task_ids:language-modeling")
| ... )
|
| # List FiftyOne datasets (identified by the tag "fiftyone" in dataset card)
| >>> api.list_datasets(tags="fiftyone")
| ```
|
| Example usage with the `search` argument:
|
| ```python
| >>> from huggingface_hub import HfApi
|
| >>> api = HfApi()
|
| # List all datasets with "text" in their name
| >>> api.list_datasets(search="text")
|
| # List all datasets with "text" in their name made by google
| >>> api.list_datasets(search="text", author="google")
| ```
|
| list_inference_catalog(self, *, token: 'bool | str | None' = None) -> 'list[str]'
| List models available in the Hugging Face Inference Catalog.
|
| The goal of the Inference Catalog is to provide a curated list of models that are optimized for inference
| and for which default configurations have been tested. See https://endpoints.huggingface.co/catalog for a list
| of available models in the catalog.
|
| Use [`create_inference_endpoint_from_catalog`] to deploy a model from the catalog.
|
| Args:
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
|
| Returns:
| List[`str`]: A list of model IDs available in the catalog.
| > [!WARNING]
| > `list_inference_catalog` is experimental. Its API is subject to change in the future. Please provide feedback
| > if you have any suggestions or requests.
|
| list_inference_endpoints(self, namespace: 'str | None' = None, *, token: 'bool | str | None' = None) -> 'list[InferenceEndpoint]'
| Lists all inference endpoints for the given namespace.
|
| Args:
| namespace (`str`, *optional*):
| The namespace to list endpoints for. Defaults to the current user. Set to `"*"` to list all endpoints
| from all namespaces (i.e. personal namespace and all orgs the user belongs to).
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| list[`InferenceEndpoint`]: A list of all inference endpoints for the given namespace.
|
| Example:
| ```python
| >>> from huggingface_hub import HfApi
| >>> api = HfApi()
| >>> api.list_inference_endpoints()
| [InferenceEndpoint(name='my-endpoint', ...), ...]
| ```
|
| list_jobs(self, *, status: 'list[JobStage | str] | JobStage | str | None' = None, labels: 'dict[str, str] | None' = None, timeout: 'int | None' = None, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'Iterable[JobInfo]'
| List compute Jobs on Hugging Face infrastructure.
|
| Args:
| status (`JobStage`, `str` or `list`, *optional*):
| Only return Jobs with the given status(es), e.g. `"RUNNING"` or `[JobStage.RUNNING, JobStage.SCHEDULING]`.
| See [`JobStage`] for possible values.
|
| labels (`dict[str, str]`, *optional*):
| Only return Jobs that have all the given `key=value` labels, e.g. `{"env": "prod", "team": "ml"}`.
|
| timeout (`float`, *optional*):
| Whether to set a timeout for the request to the Hub.
|
| namespace (`str`, *optional*):
| The namespace from where it lists the jobs. Defaults to the current user's namespace.
|
| token `(Union[bool, str, None]`, *optional*):
| A valid user access token. If not provided, the locally saved token will be used, which is the
| recommended authentication method. Set to `False` to disable authentication.
| Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
|
| Returns:
| `Iterable[JobInfo]`: an iterable of [`JobInfo`] objects.
|
| list_jobs_hardware(self, token: 'bool | str | None' = None) -> 'list[JobHardwareInfo]'
| List available hardware options for Jobs on Hugging Face infrastructure.
|
| Returns:
| `list[JobHardwareInfo]`: A list of available hardware configurations.
|
| Example:
|
| ```python
| >>> from huggingface_hub import HfApi
| >>> api = HfApi()
| >>> hardware_list = api.list_jobs_hardware()
| >>> hardware_list[0]
| JobHardwareInfo(name='cpu-basic', pretty_name='CPU Basic', cpu='2 vCPU', ram='16 GB', ephemeral_storage='20 GB', accelerator=None, unit_cost_micro_usd=167, unit_cost_usd=0.000167, unit_label='minute')
| >>> hardware_list[0].name
| 'cpu-basic'
|
| # Filter GPU options
| >>> gpu_hardware = [hw for hw in hardware_list if hw.accelerator is not None]
| >>> gpu_hardware[0].accelerator.model
| 'T4'
| ```
|
| list_lfs_files(self, repo_id: 'str', *, repo_type: 'str | None' = None, token: 'bool | str | None' = None) -> 'Iterable[LFSFileInfo]'
| List all LFS files in a repo on the Hub.
|
| This is primarily useful to count how much storage a repo is using and to eventually clean up large files
| with [`permanently_delete_lfs_files`]. Note that this would be a permanent action that will affect all commits
| referencing this deleted files and that cannot be undone.
|
| Args:
| repo_id (`str`):
| The repository for which you are listing LFS files.
| repo_type (`str`, *optional*):
| Type of repository. Set to `"dataset"` or `"space"` if listing from a dataset or space, `None` or
| `"model"` if listing from a model. Default is `None`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `Iterable[LFSFileInfo]`: An iterator of [`LFSFileInfo`] objects.
|
| Example:
| ```py
| >>> from huggingface_hub import HfApi
| >>> api = HfApi()
| >>> lfs_files = api.list_lfs_files("username/my-cool-repo")
|
| # Filter files files to delete based on a combination of `filename`, `pushed_at`, `ref` or `size`.
| # e.g. select only LFS files in the "checkpoints" folder
| >>> lfs_files_to_delete = (lfs_file for lfs_file in lfs_files if lfs_file.filename.startswith("checkpoints/"))
|
| # Permanently delete LFS files
| >>> api.permanently_delete_lfs_files("username/my-cool-repo", lfs_files_to_delete)
| ```
|
| list_liked_repos(self, user: 'str | None' = None, *, token: 'bool | str | None' = None) -> 'UserLikes'
| List all public repos liked by a user on huggingface.co.
|
| This list is public so token is optional. If `user` is not passed, it defaults to
| the logged in user.
|
| See also [`unlike`].
|
| Args:
| user (`str`, *optional*):
| Name of the user for which you want to fetch the likes.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`UserLikes`]: object containing the user name and 3 lists of repo ids (1 for
| models, 1 for datasets and 1 for Spaces).
|
| Raises:
| [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| If `user` is not passed and no token found (either from argument or from machine).
|
| Example:
| ```python
| >>> from huggingface_hub import list_liked_repos
|
| >>> likes = list_liked_repos("julien-c")
|
| >>> likes.user
| "julien-c"
|
| >>> likes.models
| ["osanseviero/streamlit_1.15", "Xhaheen/ChatGPT_HF", ...]
| ```
|
| list_models(self, *, filter: 'str | Iterable[str] | None' = None, author: 'str | None' = None, apps: 'str | list[str] | None' = None, gated: 'bool | None' = None, inference: "Literal['warm'] | None" = None, inference_provider: "Literal['all'] | PROVIDER_T | list[PROVIDER_T] | None" = None, model_name: 'str | None' = None, trained_dataset: 'str | list[str] | None' = None, search: 'str | None' = None, pipeline_tag: 'str | None' = None, num_parameters: 'str | None' = None, emissions_thresholds: 'tuple[float, float] | None' = None, sort: 'ModelSort_T | None' = None, limit: 'int | None' = None, expand: 'list[ExpandModelProperty_T] | None' = None, full: 'bool | None' = None, cardData: 'bool' = False, fetch_config: 'bool' = False, token: 'bool | str | None' = None) -> 'Iterable[ModelInfo]'
| List models hosted on the Huggingface Hub, given some filters.
|
| Args:
| filter (`str` or `Iterable[str]`, *optional*):
| A string or list of string to filter models on the Hub.
| Models can be filtered by library, language, task, tags, and more.
| author (`str`, *optional*):
| A string which identify the author (user or organization) of the
| returned models.
| apps (`str` or `List`, *optional*):
| A string or list of strings to filter models on the Hub that
| support the specified apps. Example values include `"ollama"` or `["ollama", "vllm"]`.
| gated (`bool`, *optional*):
| A boolean to filter models on the Hub that are gated or not. By default, all models are returned.
| If `gated=True` is passed, only gated models are returned.
| If `gated=False` is passed, only non-gated models are returned.
| inference (`Literal["warm"]`, *optional*):
| If "warm", filter models on the Hub currently served by at least one provider.
| inference_provider (`Literal["all"]` or `str`, *optional*):
| A string to filter models on the Hub that are served by a specific provider.
| Pass `"all"` to get all models served by at least one provider.
| trained_dataset (`str` or `List`, *optional*):
| A string tag or a list of string tags of the trained dataset for a
| model on the Hub.
| search (`str`, *optional*):
| A string that will be contained in the returned model ids.
| pipeline_tag (`str`, *optional*):
| A string pipeline tag to filter models on the Hub by, such as `summarization`.
| num_parameters (`str`, *optional*):
| Filter models by parameter count. Accepts the same range syntax as the Hub UI and API, for example
| `"min:6B,max:128B"`, `"min:6B"` or `"max:128B"`.
| emissions_thresholds (`Tuple`, *optional*):
| A tuple of two ints or floats representing a minimum and maximum
| carbon footprint to filter the resulting models with in grams.
| sort (`ModelSort_T`, *optional*):
| The key with which to sort the resulting models. Possible values are "created_at", "downloads",
| "last_modified", "likes" and "trending_score".
| limit (`int`, *optional*):
| The limit on the number of models fetched. Leaving this option
| to `None` fetches all models.
| expand (`list[ExpandModelProperty_T]`, *optional*):
| List properties to return in the response. When used, only the properties in the list will be returned.
| This parameter cannot be used if `full`, `cardData` or `fetch_config` are passed.
| Possible values are `"author"`, `"cardData"`, `"config"`, `"createdAt"`, `"disabled"`, `"downloads"`, `"downloadsAllTime"`, `"evalResults"`, `"gated"`, `"gguf"`, `"inference"`, `"inferenceProviderMapping"`, `"lastModified"`, `"library_name"`, `"likes"`, `"mask_token"`, `"model-index"`, `"pipeline_tag"`, `"private"`, `"safetensors"`, `"sha"`, `"siblings"`, `"spaces"`, `"tags"`, `"transformersInfo"`, `"trendingScore"`, `"widgetData"`, and `"resourceGroup"`.
| full (`bool`, *optional*):
| Whether to fetch all model data, including the `last_modified`,
| the `sha`, the files and the `tags`. This is set to `True` by
| default when using a filter.
| cardData (`bool`, *optional*):
| Whether to grab the metadata for the model as well. Can contain
| useful information such as carbon emissions, metrics, and
| datasets trained on.
| fetch_config (`bool`, *optional*):
| Whether to fetch the model configs as well. This is not included
| in `full` due to its size.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| model_name (`str`, *optional*):
| (deprecated). Use `search` instead.
|
| Returns:
| `Iterable[ModelInfo]`: an iterable of [`huggingface_hub.hf_api.ModelInfo`] objects.
|
| Example:
|
| ```python
| >>> from huggingface_hub import HfApi
|
| >>> api = HfApi()
|
| # List all models
| >>> api.list_models()
|
| # List text classification models
| >>> api.list_models(filter="text-classification")
|
| # List models from the KerasHub library
| >>> api.list_models(filter="keras-hub")
|
| # List models served by Cohere
| >>> api.list_models(inference_provider="cohere")
|
| # List models with "bert" in their name
| >>> api.list_models(search="bert")
|
| # List models with "bert" in their name and pushed by google
| >>> api.list_models(search="bert", author="google")
|
| # List models with 6B to 128B parameters
| >>> api.list_models(num_parameters="min:6B,max:128B", sort="likes")
| ```
|
| list_organization_followers(self, organization: 'str', token: 'bool | str | None' = None) -> 'Iterable[User]'
| List followers of an organization on the Hub.
|
| Args:
| organization (`str`):
| Name of the organization to get the followers of.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `Iterable[User]`: A list of [`User`] objects with the followers of the organization.
|
| Raises:
| [`HfHubHTTPError`]:
| HTTP 404 If the organization does not exist on the Hub.
|
| list_organization_members(self, organization: 'str', token: 'bool | str | None' = None) -> 'Iterable[User]'
| List of members of an organization on the Hub.
|
| Args:
| organization (`str`):
| Name of the organization to get the members of.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `Iterable[User]`: A list of [`User`] objects with the members of the organization.
|
| Raises:
| [`HfHubHTTPError`]:
| HTTP 404 If the organization does not exist on the Hub.
|
| list_papers(self, *, query: 'str | None' = None, limit: 'int | None' = None, token: 'bool | str | None' = None) -> 'Iterable[PaperInfo]'
| List daily papers on the Hugging Face Hub given a search query.
|
| Args:
| query (`str`, *optional*):
| A search query string to find papers.
| If provided, returns papers that match the query.
| limit (`int`, *optional*):
| The maximum number of papers to return.
| token (Union[bool, str, None], *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `Iterable[PaperInfo]`: an iterable of [`huggingface_hub.hf_api.PaperInfo`] objects.
|
| Example:
|
| ```python
| >>> from huggingface_hub import HfApi
|
| >>> api = HfApi()
|
| # List all papers with "attention" in their title
| >>> api.list_papers(query="attention")
| ```
|
| list_pending_access_requests(self, repo_id: 'str', *, repo_type: 'str | None' = None, token: 'bool | str | None' = None) -> 'Iterable[AccessRequest]'
| Get pending access requests for a given gated repo.
|
| A pending request means the user has requested access to the repo but the request has not been processed yet.
| If the approval mode is automatic, this list should be empty. Pending requests can be accepted or rejected
| using [`accept_access_request`] and [`reject_access_request`].
|
| For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
|
| Args:
| repo_id (`str`):
| The id of the repo to get access requests for.
| repo_type (`str`, *optional*):
| The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`.
| Defaults to `model`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `Iterable[AccessRequest]`: An iterable of [`AccessRequest`] objects. Each time contains a `username`, `email`,
| `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will
| be populated with user's answers.
|
| Raises:
| [`HfHubHTTPError`]:
| HTTP 400 if the repo is not gated.
| [`HfHubHTTPError`]:
| HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
| or `admin` role in the organization the repo belongs to or if you passed a `read` token.
|
| Example:
| ```py
| >>> from huggingface_hub import list_pending_access_requests, accept_access_request
|
| # List pending requests
| >>> requests = list(list_pending_access_requests("meta-llama/Llama-2-7b"))
| >>> len(requests)
| 411
| >>> requests[0]
| [
| AccessRequest(
| username='clem',
| fullname='Clem 🤗',
| email='***',
| timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
| status='pending',
| fields=None,
| ),
| ...
| ]
|
| # Accept Clem's request
| >>> accept_access_request("meta-llama/Llama-2-7b", "clem")
| ```
|
| list_rejected_access_requests(self, repo_id: 'str', *, repo_type: 'str | None' = None, token: 'bool | str | None' = None) -> 'Iterable[AccessRequest]'
| Get rejected access requests for a given gated repo.
|
| A rejected request means the user has requested access to the repo and the request has been explicitly rejected
| by a repo owner (either you or another user from your organization). The user cannot download any file of the
| repo. Rejected requests can be accepted or cancelled at any time using [`accept_access_request`] and
| [`cancel_access_request`]. A cancelled request will go back to the pending list while an accepted request will
| go to the accepted list.
|
| For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
|
| Args:
| repo_id (`str`):
| The id of the repo to get access requests for.
| repo_type (`str`, *optional*):
| The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`.
| Defaults to `model`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `Iterable[AccessRequest]`: An iterable of [`AccessRequest`] objects. Each time contains a `username`, `email`,
| `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will
| be populated with user's answers.
|
| Raises:
| [`HfHubHTTPError`]:
| HTTP 400 if the repo is not gated.
| [`HfHubHTTPError`]:
| HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
| or `admin` role in the organization the repo belongs to or if you passed a `read` token.
|
| Example:
| ```py
| >>> from huggingface_hub import list_rejected_access_requests
|
| >>> requests = list(list_rejected_access_requests("meta-llama/Llama-2-7b"))
| >>> len(requests)
| 411
| >>> requests[0]
| [
| AccessRequest(
| username='clem',
| fullname='Clem 🤗',
| email='***',
| timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
| status='rejected',
| fields=None,
| ),
| ...
| ]
| ```
|
| list_repo_commits(self, repo_id: 'str', *, repo_type: 'str | None' = None, token: 'bool | str | None' = None, revision: 'str | None' = None, formatted: 'bool' = False) -> 'list[GitCommitInfo]'
| Get the list of commits of a given revision for a repo on the Hub.
|
| Commits are sorted by date (last commit first).
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated by a `/`.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if listing commits from a dataset or a Space, `None` or `"model"` if
| listing from a model. Default is `None`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| revision (`str`, *optional*):
| The git revision to commit from. Defaults to the head of the `"main"` branch.
| formatted (`bool`):
| Whether to return the HTML-formatted title and description of the commits. Defaults to False.
|
| Example:
| ```py
| >>> from huggingface_hub import HfApi
| >>> api = HfApi()
|
| # Commits are sorted by date (last commit first)
| >>> initial_commit = api.list_repo_commits("gpt2")[-1]
|
| # Initial commit is always a system commit containing the `.gitattributes` file.
| >>> initial_commit
| GitCommitInfo(
| commit_id='9b865efde13a30c13e0a33e536cf3e4a5a9d71d8',
| authors=['system'],
| created_at=datetime.datetime(2019, 2, 18, 10, 36, 15, tzinfo=datetime.timezone.utc),
| title='initial commit',
| message='',
| formatted_title=None,
| formatted_message=None
| )
|
| # Create an empty branch by deriving from initial commit
| >>> api.create_branch("gpt2", "new_empty_branch", revision=initial_commit.commit_id)
| ```
|
| Returns:
| list[[`GitCommitInfo`]]: list of objects containing information about the commits for a repo on the Hub.
|
| Raises:
| [`~utils.RepositoryNotFoundError`]:
| If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
| does not exist.
| [`~utils.RevisionNotFoundError`]:
| If revision is not found (error 404) on the repo.
|
| list_repo_files(self, repo_id: 'str', *, revision: 'str | None' = None, repo_type: 'str | None' = None, token: 'str | bool | None' = None) -> 'list[str]'
| Get the list of files in a given repo.
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated by a `/`.
| revision (`str`, *optional*):
| The revision of the repository from which to get the information.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if uploading to a dataset or space, `None` or `"model"` if uploading to
| a model. Default is `None`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `list[str]`: the list of files in a given repository.
|
| list_repo_likers(self, repo_id: 'str', *, repo_type: 'str | None' = None, token: 'bool | str | None' = None) -> 'Iterable[User]'
| List all users who liked a given repo on the hugging Face Hub.
|
| See also [`list_liked_repos`].
|
| Args:
| repo_id (`str`):
| The repository to retrieve . Example: `"user/my-cool-model"`.
|
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if uploading to a dataset or
| space, `None` or `"model"` if uploading to a model. Default is
| `None`.
|
| Returns:
| `Iterable[User]`: an iterable of [`huggingface_hub.hf_api.User`] objects.
|
| list_repo_refs(self, repo_id: 'str', *, repo_type: 'str | None' = None, include_pull_requests: 'bool' = False, token: 'str | bool | None' = None) -> 'GitRefs'
| Get the list of refs of a given repo (both tags and branches).
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated
| by a `/`.
| repo_type (`str`, *optional*):
| Set to `"dataset"`, `"space"` or `"kernel"` if listing refs from a dataset, a Space or a Kernel,
| `None` or `"model"` if listing from a model. Default is `None`.
| include_pull_requests (`bool`, *optional*):
| Whether to include refs from pull requests in the list. Defaults to `False`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Example:
| ```py
| >>> from huggingface_hub import HfApi
| >>> api = HfApi()
| >>> api.list_repo_refs("gpt2")
| GitRefs(branches=[GitRefInfo(name='main', ref='refs/heads/main', target_commit='e7da7f221d5bf496a48136c0cd264e630fe9fcc8')], converts=[], tags=[])
|
| >>> api.list_repo_refs("bigcode/the-stack", repo_type='dataset')
| GitRefs(
| branches=[
| GitRefInfo(name='main', ref='refs/heads/main', target_commit='18edc1591d9ce72aa82f56c4431b3c969b210ae3'),
| GitRefInfo(name='v1.1.a1', ref='refs/heads/v1.1.a1', target_commit='f9826b862d1567f3822d3d25649b0d6d22ace714')
| ],
| converts=[],
| tags=[
| GitRefInfo(name='v1.0', ref='refs/tags/v1.0', target_commit='c37a8cd1e382064d8aced5e05543c5f7753834da')
| ]
| )
| ```
|
| Returns:
| [`GitRefs`]: object containing all information about branches and tags for a
| repo on the Hub.
|
| list_repo_tree(self, repo_id: 'str', path_in_repo: 'str | None' = None, *, recursive: 'bool' = False, expand: 'bool' = False, revision: 'str | None' = None, repo_type: 'str | None' = None, token: 'str | bool | None' = None) -> 'Iterable[RepoFile | RepoFolder]'
| List a repo tree's files and folders and get information about them.
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated by a `/`.
| path_in_repo (`str`, *optional*):
| Relative path of the tree (folder) in the repo, for example:
| `"checkpoints/1fec34a/results"`. Will default to the root tree (folder) of the repository.
| recursive (`bool`, *optional*, defaults to `False`):
| Whether to list tree's files and folders recursively.
| expand (`bool`, *optional*, defaults to `False`):
| Whether to fetch more information about the tree's files and folders (e.g. last commit and files' security scan results). This
| operation is more expensive for the server so only 50 results are returned per page (instead of 1000).
| As pagination is implemented in `huggingface_hub`, this is transparent for you except for the time it
| takes to get the results.
| revision (`str`, *optional*):
| The revision of the repository from which to get the tree. Defaults to `"main"` branch.
| repo_type (`str`, *optional*):
| The type of the repository from which to get the tree (`"model"`, `"dataset"`, `"space"` or `"kernel"`).
| Defaults to `"model"`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `Iterable[Union[RepoFile, RepoFolder]]`:
| The information about the tree's files and folders, as an iterable of [`RepoFile`] and [`RepoFolder`] objects. The order of the files and folders is
| not guaranteed.
|
| Raises:
| [`~utils.RepositoryNotFoundError`]:
| If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
| does not exist.
| [`~utils.RevisionNotFoundError`]:
| If revision is not found (error 404) on the repo.
| [`~utils.RemoteEntryNotFoundError`]:
| If the tree (folder) does not exist (error 404) on the repo.
|
| Examples:
|
| Get information about a repo's tree.
| ```py
| >>> from huggingface_hub import list_repo_tree
| >>> repo_tree = list_repo_tree("lysandre/arxiv-nlp")
| >>> repo_tree
| <generator object HfApi.list_repo_tree at 0x7fa4088e1ac0>
| >>> list(repo_tree)
| [
| RepoFile(path='.gitattributes', size=391, blob_id='ae8c63daedbd4206d7d40126955d4e6ab1c80f8f', lfs=None, last_commit=None, security=None),
| RepoFile(path='README.md', size=391, blob_id='43bd404b159de6fba7c2f4d3264347668d43af25', lfs=None, last_commit=None, security=None),
| RepoFile(path='config.json', size=554, blob_id='2f9618c3a19b9a61add74f70bfb121335aeef666', lfs=None, last_commit=None, security=None),
| RepoFile(
| path='flax_model.msgpack', size=497764107, blob_id='8095a62ccb4d806da7666fcda07467e2d150218e',
| lfs={'size': 497764107, 'sha256': 'd88b0d6a6ff9c3f8151f9d3228f57092aaea997f09af009eefd7373a77b5abb9', 'pointer_size': 134}, last_commit=None, security=None
| ),
| RepoFile(path='merges.txt', size=456318, blob_id='226b0752cac7789c48f0cb3ec53eda48b7be36cc', lfs=None, last_commit=None, security=None),
| RepoFile(
| path='pytorch_model.bin', size=548123560, blob_id='64eaa9c526867e404b68f2c5d66fd78e27026523',
| lfs={'size': 548123560, 'sha256': '9be78edb5b928eba33aa88f431551348f7466ba9f5ef3daf1d552398722a5436', 'pointer_size': 134}, last_commit=None, security=None
| ),
| RepoFile(path='vocab.json', size=898669, blob_id='b00361fece0387ca34b4b8b8539ed830d644dbeb', lfs=None, last_commit=None, security=None)]
| ]
| ```
|
| Get even more information about a repo's tree (last commit and files' security scan results)
| ```py
| >>> from huggingface_hub import list_repo_tree
| >>> repo_tree = list_repo_tree("prompthero/openjourney-v4", expand=True)
| >>> list(repo_tree)
| [
| RepoFolder(
| path='feature_extractor',
| tree_id='aa536c4ea18073388b5b0bc791057a7296a00398',
| last_commit={
| 'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190',
| 'title': 'Upload diffusers weights (#48)',
| 'date': datetime.datetime(2023, 3, 21, 9, 5, 27, tzinfo=datetime.timezone.utc)
| }
| ),
| RepoFolder(
| path='safety_checker',
| tree_id='65aef9d787e5557373fdf714d6c34d4fcdd70440',
| last_commit={
| 'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190',
| 'title': 'Upload diffusers weights (#48)',
| 'date': datetime.datetime(2023, 3, 21, 9, 5, 27, tzinfo=datetime.timezone.utc)
| }
| ),
| RepoFile(
| path='model_index.json',
| size=582,
| blob_id='d3d7c1e8c3e78eeb1640b8e2041ee256e24c9ee1',
| lfs=None,
| last_commit={
| 'oid': 'b195ed2d503f3eb29637050a886d77bd81d35f0e',
| 'title': 'Fix deprecation warning by changing `CLIPFeatureExtractor` to `CLIPImageProcessor`. (#54)',
| 'date': datetime.datetime(2023, 5, 15, 21, 41, 59, tzinfo=datetime.timezone.utc)
| },
| security={
| 'safe': True,
| 'av_scan': {'virusFound': False, 'virusNames': None},
| 'pickle_import_scan': None
| }
| )
| ...
| ]
| ```
|
| list_scheduled_jobs(self, *, timeout: 'int | None' = None, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'list[ScheduledJobInfo]'
| List scheduled compute Jobs on Hugging Face infrastructure.
|
| Args:
| timeout (`float`, *optional*):
| Whether to set a timeout for the request to the Hub.
|
| namespace (`str`, *optional*):
| The namespace from where it lists the jobs. Defaults to the current user's namespace.
|
| token `(Union[bool, str, None]`, *optional*):
| A valid user access token. If not provided, the locally saved token will be used, which is the
| recommended authentication method. Set to `False` to disable authentication.
| Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
|
| list_space_templates(self, *, token: 'str | bool | None' = None) -> 'list[SpaceTemplate]'
| List the official Space templates available on the Hub.
|
| The `repo_id` of a returned template (or its short `name`) can be passed as `space_template`
| to [`HfApi.create_repo`] to seed a new Space from that template.
|
| Args:
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `list[SpaceTemplate]`: The list of available Space templates.
|
| Example:
| ```py
| >>> from huggingface_hub import list_space_templates
| >>> templates = list_space_templates()
| >>> templates[0]
| SpaceTemplate(name='Streamlit', repo_id='streamlit/streamlit-template-space', sdk='docker', preferred_private=False)
| ```
|
| list_spaces(self, *, filter: 'str | Iterable[str] | None' = None, author: 'str | None' = None, search: 'str | None' = None, datasets: 'str | Iterable[str] | None' = None, models: 'str | Iterable[str] | None' = None, linked: 'bool' = False, sort: 'SpaceSort_T | None' = None, limit: 'int | None' = None, expand: 'list[ExpandSpaceProperty_T] | None' = None, full: 'bool | None' = None, token: 'bool | str | None' = None) -> 'Iterable[SpaceInfo]'
| List spaces hosted on the Huggingface Hub, given some filters.
|
| Args:
| filter (`str` or `Iterable`, *optional*):
| A string tag or list of tags that can be used to identify Spaces on the Hub.
| author (`str`, *optional*):
| A string which identify the author of the returned Spaces.
| search (`str`, *optional*):
| A string that will be contained in the returned Spaces.
| datasets (`str` or `Iterable`, *optional*):
| Whether to return Spaces that make use of a dataset.
| The name of a specific dataset can be passed as a string.
| models (`str` or `Iterable`, *optional*):
| Whether to return Spaces that make use of a model.
| The name of a specific model can be passed as a string.
| linked (`bool`, *optional*):
| Whether to return Spaces that make use of either a model or a dataset.
| sort (`SpaceSort_T`, *optional*):
| The key with which to sort the resulting spaces. Possible values are "created_at", "last_modified",
| "likes" and "trending_score".
| limit (`int`, *optional*):
| The limit on the number of Spaces fetched. Leaving this option
| to `None` fetches all Spaces.
| expand (`list[ExpandSpaceProperty_T]`, *optional*):
| List properties to return in the response. When used, only the properties in the list will be returned.
| This parameter cannot be used if `full` is passed.
| Possible values are `"author"`, `"cardData"`, `"datasets"`, `"disabled"`, `"lastModified"`, `"createdAt"`, `"likes"`, `"models"`, `"private"`, `"runtime"`, `"sdk"`, `"siblings"`, `"sha"`, `"subdomain"`, `"tags"`, `"trendingScore"`, `"usedStorage"`, and `"resourceGroup"`.
| full (`bool`, *optional*):
| Whether to fetch all Spaces data, including the `last_modified`, `siblings`
| and `card_data` fields.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `Iterable[SpaceInfo]`: an iterable of [`huggingface_hub.hf_api.SpaceInfo`] objects.
|
| list_spaces_hardware(self, token: 'bool | str | None' = None) -> 'list[JobHardwareInfo]'
| List available hardware options for Spaces.
|
| Returns:
| `list[JobHardwareInfo]`: A list of available hardware configurations.
|
| Example:
|
| ```python
| >>> from huggingface_hub import list_spaces_hardware
| >>> hardware_list = list_spaces_hardware()
| >>> hardware_list[0]
| JobHardwareInfo(name='cpu-basic', pretty_name='CPU Basic', cpu='2 vCPU', ram='16 GB', ...)
| >>> hardware_list[0].name
| 'cpu-basic'
| ```
|
| list_user_followers(self, username: 'str', token: 'bool | str | None' = None) -> 'Iterable[User]'
| Get the list of followers of a user on the Hub.
|
| Args:
| username (`str`):
| Username of the user to get the followers of.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `Iterable[User]`: A list of [`User`] objects with the followers of the user.
|
| Raises:
| [`HfHubHTTPError`]:
| HTTP 404 If the user does not exist on the Hub.
|
| list_user_following(self, username: 'str', token: 'bool | str | None' = None) -> 'Iterable[User]'
| Get the list of users followed by a user on the Hub.
|
| Args:
| username (`str`):
| Username of the user to get the users followed by.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `Iterable[User]`: A list of [`User`] objects with the users followed by the user.
|
| Raises:
| [`HfHubHTTPError`]:
| HTTP 404 If the user does not exist on the Hub.
|
| list_user_repos(self, namespace: 'str | None' = None, *, token: 'bool | str | None' = None) -> 'Iterable[RepoStorageInfo]'
| List all repositories (models, datasets, spaces, buckets) for a user or organization with storage info.
|
| Uses the `/api/settings/repositories` endpoint for the authenticated user or
| `/api/organizations/{namespace}/settings/repositories` for an organization.
|
| Args:
| namespace (`str`, *optional*):
| Organization name. If not provided, lists repos for the authenticated user.
| token (`bool` or `str`, *optional*):
| A valid user access token. Defaults to the locally saved token.
|
| Returns:
| `Iterable[RepoStorageInfo]`: An iterable of [`RepoStorageInfo`] objects.
|
| Example:
| ```python
| >>> from huggingface_hub import list_user_repos
|
| >>> repos = list(list_user_repos())
| >>> repos[0]
| RepoStorageInfo(id='username/my-model', type='model', ...)
|
| >>> # List repos from an organization
| >>> repos = list(list_user_repos(namespace="my-org"))
| ```
|
| list_webhooks(self, *, token: 'bool | str | None' = None) -> 'list[WebhookInfo]'
| List all configured webhooks.
|
| Args:
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved token, which is the recommended
| method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `list[WebhookInfo]`:
| List of webhook info objects.
|
| Example:
| ```python
| >>> from huggingface_hub import list_webhooks
| >>> webhooks = list_webhooks()
| >>> len(webhooks)
| 2
| >>> webhooks[0]
| WebhookInfo(
| id="654bbbc16f2ec14d77f109cc",
| watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
| url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
| secret="my-secret",
| domains=["repo", "discussion"],
| disabled=False,
| )
| ```
|
| merge_pull_request(self, repo_id: 'str', discussion_num: 'int', *, token: 'bool | str | None' = None, comment: 'str | None' = None, repo_type: 'str | None' = None)
| Merges a Pull Request.
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated
| by a `/`.
| discussion_num (`int`):
| The number of the Discussion or Pull Request . Must be a strictly positive integer.
| comment (`str`, *optional*):
| An optional comment to post with the status change.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if uploading to a dataset or
| space, `None` or `"model"` if uploading to a model. Default is
| `None`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`DiscussionStatusChange`]: the status change event
|
| > [!TIP]
| > Raises the following errors:
| >
| > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
| > if the HuggingFace API returned an error
| > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| > if some parameter value is invalid
| > - [`~utils.RepositoryNotFoundError`]
| > If the repository to download from cannot be found. This may be because it doesn't exist,
| > or because it is set to `private` and you do not have access.
|
| model_info(self, repo_id: 'str', *, revision: 'str | None' = None, timeout: 'float | None' = None, securityStatus: 'bool | None' = None, files_metadata: 'bool' = False, expand: 'list[ExpandModelProperty_T] | None' = None, token: 'bool | str | None' = None) -> 'ModelInfo'
| Get info on one specific model on huggingface.co
|
| Model can be private if you pass an acceptable token or are logged in.
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated
| by a `/`.
| revision (`str`, *optional*):
| The revision of the model repository from which to get the
| information.
| timeout (`float`, *optional*):
| Whether to set a timeout for the request to the Hub.
| securityStatus (`bool`, *optional*):
| Whether to retrieve the security status from the model
| repository as well. The security status will be returned in the `security_repo_status` field.
| files_metadata (`bool`, *optional*):
| Whether or not to retrieve metadata for files in the repository
| (size, LFS metadata, etc). Defaults to `False`.
| expand (`list[ExpandModelProperty_T]`, *optional*):
| List properties to return in the response. When used, only the properties in the list will be returned.
| This parameter cannot be used if `securityStatus` or `files_metadata` are passed.
| Possible values are `"author"`, `"baseModels"`, `"cardData"`, `"childrenModelCount"`, `"config"`, `"createdAt"`, `"disabled"`, `"downloads"`, `"downloadsAllTime"`, `"evalResults"`, `"gated"`, `"gguf"`, `"inference"`, `"inferenceProviderMapping"`, `"lastModified"`, `"library_name"`, `"likes"`, `"mask_token"`, `"model-index"`, `"pipeline_tag"`, `"private"`, `"safetensors"`, `"sha"`, `"siblings"`, `"spaces"`, `"tags"`, `"transformersInfo"`, `"trendingScore"`, `"widgetData"`, `"usedStorage"`, and `"resourceGroup"`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`huggingface_hub.hf_api.ModelInfo`]: The model repository information.
|
| > [!TIP]
| > Raises the following errors:
| >
| > - [`~utils.RepositoryNotFoundError`]
| > If the repository to download from cannot be found. This may be because it doesn't exist,
| > or because it is set to `private` and you do not have access.
| > - [`~utils.RevisionNotFoundError`]
| > If the revision to download from cannot be found.
|
| move_bucket(self, from_id: 'str', to_id: 'str', *, token: 'bool | str | None' = None) -> 'None'
| Move a bucket from "namespace1/repo_name1" to "namespace2/repo_name2"
|
| Note there are certain limitations. For more information about moving
| repositories, please see
| https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo.
|
| Args:
| from_id (`str`):
| A namespace (user or an organization) and a bucket name separated
| by a `/`. Original bucket identifier (e.g. `"username/my-bucket"`).
| to_id (`str`):
| A namespace (user or an organization) and a bucket name separated
| by a `/`. Final bucket identifier (e.g. `"username/new-bucket-name"`
| or `"organization/my-bucket"`).
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Raises:
| [`~errors.BucketNotFoundError`]:
| If the source bucket cannot be found. This may be because it doesn't exist,
| or because it is set to `private` and you do not have access.
|
| Example:
| ```python
| >>> from huggingface_hub import move_bucket
|
| >>> # Rename a bucket within the same namespace
| >>> move_bucket(from_id="username/old-name", to_id="username/new-name")
|
| >>> # Transfer a bucket to an organization
| >>> move_bucket(from_id="username/my-bucket", to_id="my-org/my-bucket")
| ```
|
| move_repo(self, from_id: 'str', to_id: 'str', *, repo_type: 'str | None' = None, token: 'str | bool | None' = None)
| Moving a repository from namespace1/repo_name1 to namespace2/repo_name2
|
| Note there are certain limitations. For more information about moving
| repositories, please see
| https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo.
|
| Args:
| from_id (`str`):
| A namespace (user or an organization) and a repo name separated
| by a `/`. Original repository identifier.
| to_id (`str`):
| A namespace (user or an organization) and a repo name separated
| by a `/`. Final repository identifier.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if uploading to a dataset or
| space, `None` or `"model"` if uploading to a model. Default is
| `None`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| > [!TIP]
| > Raises the following errors:
| >
| > - [`~utils.RepositoryNotFoundError`]
| > If the repository to download from cannot be found. This may be because it doesn't exist,
| > or because it is set to `private` and you do not have access.
|
| paper_info(self, id: 'str') -> 'PaperInfo'
| Get information for a paper on the Hub.
|
| Args:
| id (`str`, **optional**):
| ArXiv id of the paper.
|
| Returns:
| `PaperInfo`: A `PaperInfo` object.
|
| Raises:
| [`HfHubHTTPError`]:
| HTTP 404 If the paper does not exist on the Hub.
|
| parse_safetensors_file_metadata(self, repo_id: 'str', filename: 'str', *, repo_type: 'str | None' = None, revision: 'str | None' = None, token: 'bool | str | None' = None, timeout: 'float | None' = 10) -> 'SafetensorsFileMetadata'
| Parse metadata from a safetensors file on the Hub.
|
| To parse metadata from all safetensors files in a repo at once, use [`get_safetensors_metadata`].
|
| For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.
|
| Args:
| repo_id (`str`):
| A user or an organization name and a repo name separated by a `/`.
| filename (`str`):
| The name of the file in the repo.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if the file is in a dataset or space, `None` or `"model"` if in a
| model. Default is `None`.
| revision (`str`, *optional*):
| The git revision to fetch the file from. Can be a branch name, a tag, or a commit hash. Defaults to the
| head of the `"main"` branch.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| timeout (`float`, *optional*, defaults to 10):
| How many seconds to wait for the server to send data before giving up. Set to `None` to disable the
| timeout (not recommended, as a stalled connection can hang the call indefinitely).
|
| Returns:
| [`SafetensorsFileMetadata`]: information related to a safetensors file.
|
| Raises:
| [`NotASafetensorsRepoError`]:
| If the repo is not a safetensors repo i.e. doesn't have either a
| `model.safetensors` or a `model.safetensors.index.json` file.
| [`SafetensorsParsingError`]:
| If a safetensors file header couldn't be parsed correctly.
|
| pause_inference_endpoint(self, name: 'str', *, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'InferenceEndpoint'
| Pause an Inference Endpoint.
|
| A paused Inference Endpoint will not be charged. It can be resumed at any time using [`resume_inference_endpoint`].
| This is different than scaling the Inference Endpoint to zero with [`scale_to_zero_inference_endpoint`], which
| would be automatically restarted when a request is made to it.
|
| For convenience, you can also pause an Inference Endpoint using [`pause_inference_endpoint`].
|
| Args:
| name (`str`):
| The name of the Inference Endpoint to pause.
| namespace (`str`, *optional*):
| The namespace in which the Inference Endpoint is located. Defaults to the current user.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`InferenceEndpoint`]: information about the paused Inference Endpoint.
|
| pause_space(self, repo_id: 'str', *, token: 'bool | str | None' = None) -> 'SpaceRuntime'
| Pause your Space.
|
| A paused Space stops executing until manually restarted by its owner. This is different from the sleeping
| state in which free Spaces go after 48h of inactivity. Paused time is not billed to your account, no matter the
| hardware you've selected. To restart your Space, use [`restart_space`] and go to your Space settings page.
|
| For more details, please visit [the docs](https://huggingface.co/docs/hub/spaces-gpus#pause).
|
| Args:
| repo_id (`str`):
| ID of the Space to pause. Example: `"Salesforce/BLIP2"`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`SpaceRuntime`]: Runtime information about your Space including `stage=PAUSED` and requested hardware.
|
| Raises:
| [`~utils.RepositoryNotFoundError`]:
| If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you
| are not authenticated.
| [`~utils.HfHubHTTPError`]:
| 403 Forbidden: only the owner of a Space can pause it. If you want to manage a Space that you don't
| own, either ask the owner by opening a Discussion or duplicate the Space.
| [`~utils.BadRequestError`]:
| If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide
| a static Space, you can set it to private.
|
| permanently_delete_lfs_files(self, repo_id: 'str', lfs_files: 'Iterable[LFSFileInfo]', *, rewrite_history: 'bool' = True, repo_type: 'str | None' = None, token: 'bool | str | None' = None) -> 'None'
| Permanently delete LFS files from a repo on the Hub.
|
| > [!WARNING]
| > This is a permanent action that will affect all commits referencing the deleted files and might corrupt your
| > repository. This is a non-revertible operation. Use it only if you know what you are doing.
|
| Args:
| repo_id (`str`):
| The repository for which you are listing LFS files.
| lfs_files (`Iterable[LFSFileInfo]`):
| An iterable of [`LFSFileInfo`] items to permanently delete from the repo. Use [`list_lfs_files`] to list
| all LFS files from a repo.
| rewrite_history (`bool`, *optional*, default to `True`):
| Whether to rewrite repository history to remove file pointers referencing the deleted LFS files (recommended).
| repo_type (`str`, *optional*):
| Type of repository. Set to `"dataset"` or `"space"` if listing from a dataset or space, `None` or
| `"model"` if listing from a model. Default is `None`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Example:
| ```py
| >>> from huggingface_hub import HfApi
| >>> api = HfApi()
| >>> lfs_files = api.list_lfs_files("username/my-cool-repo")
|
| # Filter files files to delete based on a combination of `filename`, `pushed_at`, `ref` or `size`.
| # e.g. select only LFS files in the "checkpoints" folder
| >>> lfs_files_to_delete = (lfs_file for lfs_file in lfs_files if lfs_file.filename.startswith("checkpoints/"))
|
| # Permanently delete LFS files
| >>> api.permanently_delete_lfs_files("username/my-cool-repo", lfs_files_to_delete)
| ```
|
| preupload_lfs_files(self, repo_id: 'str', additions: 'Iterable[CommitOperationAdd]', *, token: 'str | bool | None' = None, repo_type: 'str | None' = None, revision: 'str | None' = None, create_pr: 'bool | None' = None, num_threads: 'int' = 5, free_memory: 'bool' = True, gitignore_content: 'str | None' = None)
| Pre-upload LFS files to S3 in preparation on a future commit.
|
| This method is useful if you are generating the files to upload on-the-fly and you don't want to store them
| in memory before uploading them all at once.
|
| > [!WARNING]
| > This is a power-user method. You shouldn't need to call it directly to make a normal commit.
| > Use [`create_commit`] directly instead.
|
| > [!WARNING]
| > Commit operations will be mutated during the process. In particular, the attached `path_or_fileobj` will be
| > removed after the upload to save memory (and replaced by an empty `bytes` object). Do not reuse the same
| > objects except to pass them to [`create_commit`]. If you don't want to remove the attached content from the
| > commit operation object, pass `free_memory=False`.
|
| Args:
| repo_id (`str`):
| The repository in which you will commit the files, for example: `"username/custom_transformers"`.
|
| additions (`Iterable` of [`CommitOperationAdd`]):
| The list of files to upload. Warning: the objects in this list will be mutated to include information
| relative to the upload. Do not reuse the same objects for multiple commits.
|
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| repo_type (`str`, *optional*):
| The type of repository to upload to (e.g. `"model"` -default-, `"dataset"` or `"space"`).
|
| revision (`str`, *optional*):
| The git revision to commit from. Defaults to the head of the `"main"` branch.
|
| create_pr (`boolean`, *optional*):
| Whether or not you plan to create a Pull Request with that commit. Defaults to `False`.
|
| num_threads (`int`, *optional*):
| Number of concurrent threads for uploading files. Defaults to 5.
| Setting it to 2 means at most 2 files will be uploaded concurrently.
|
| free_memory (`bool`, *optional*, defaults to `True`):
| If `True`, the `path_or_fileobj` attribute of each `CommitOperationAdd` is replaced by an empty
| `bytes` object after upload to save memory. Set to `False` if you need to reuse the operation
| objects outside of a subsequent [`create_commit`] call.
|
| gitignore_content (`str`, *optional*):
| The content of the `.gitignore` file to know which files should be ignored. The order of priority
| is to first check if `gitignore_content` is passed, then check if the `.gitignore` file is present
| in the list of files to commit and finally default to the `.gitignore` file already hosted on the Hub
| (if any).
|
| Example:
| ```py
| >>> from huggingface_hub import CommitOperationAdd, preupload_lfs_files, create_commit, create_repo
|
| >>> repo_id = create_repo("test_preupload").repo_id
|
| # Generate and preupload LFS files one by one
| >>> operations = [] # List of all `CommitOperationAdd` objects that will be generated
| >>> for i in range(5):
| ... content = ... # generate binary content
| ... addition = CommitOperationAdd(path_in_repo=f"shard_{i}_of_5.bin", path_or_fileobj=content)
| ... preupload_lfs_files(repo_id, additions=[addition]) # upload + free memory
| ... operations.append(addition)
|
| # Create commit
| >>> create_commit(repo_id, operations=operations, commit_message="Commit all shards")
| ```
|
| read_paper(self, id: 'str') -> 'str'
| Get the markdown content of a paper page on the Hub.
|
| Args:
| id (`str`):
| ArXiv id of the paper.
|
| Returns:
| `str`: The paper page content as markdown.
|
| Raises:
| [`HfHubHTTPError`]:
| HTTP 404 If the paper does not exist on the Hub.
|
| reject_access_request(self, repo_id: 'str', user: 'str', *, repo_type: 'str | None' = None, rejection_reason: 'str | None', token: 'bool | str | None' = None) -> 'None'
| Reject an access request from a user for a given gated repo.
|
| A rejected request will go to the rejected list. The user cannot download any file of the repo. Rejected
| requests can be accepted or cancelled at any time using [`accept_access_request`] and [`cancel_access_request`].
| A cancelled request will go back to the pending list while an accepted request will go to the accepted list.
|
| For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
|
| Args:
| repo_id (`str`):
| The id of the repo to reject access request for.
| user (`str`):
| The username of the user which access request should be rejected.
| repo_type (`str`, *optional*):
| The type of the repo to reject access request for. Must be one of `model`, `dataset` or `space`.
| Defaults to `model`.
| rejection_reason (`str`, *optional*):
| Optional rejection reason that will be visible to the user (max 200 characters).
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Raises:
| [`HfHubHTTPError`]:
| HTTP 400 if the repo is not gated.
| [`HfHubHTTPError`]:
| HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
| or `admin` role in the organization the repo belongs to or if you passed a `read` token.
| [`HfHubHTTPError`]:
| HTTP 404 if the user does not exist on the Hub.
| [`HfHubHTTPError`]:
| HTTP 404 if the user access request cannot be found.
| [`HfHubHTTPError`]:
| HTTP 404 if the user access request is already in the rejected list.
|
| rename_discussion(self, repo_id: 'str', discussion_num: 'int', new_title: 'str', *, token: 'bool | str | None' = None, repo_type: 'str | None' = None) -> 'DiscussionTitleChange'
| Renames a Discussion.
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated
| by a `/`.
| discussion_num (`int`):
| The number of the Discussion or Pull Request . Must be a strictly positive integer.
| new_title (`str`):
| The new title for the discussion
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if uploading to a dataset or
| space, `None` or `"model"` if uploading to a model. Default is
| `None`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`DiscussionTitleChange`]: the title change event
|
|
| Examples:
| ```python
| >>> new_title = "New title, fixing a typo"
| >>> HfApi().rename_discussion(
| ... repo_id="username/repo_name",
| ... discussion_num=34
| ... new_title=new_title
| ... )
| # DiscussionTitleChange(id='deadbeef0000000', type='title-change', ...)
|
| ```
|
| > [!TIP]
| > Raises the following errors:
| >
| > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
| > if the HuggingFace API returned an error
| > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| > if some parameter value is invalid
| > - [`~utils.RepositoryNotFoundError`]
| > If the repository to download from cannot be found. This may be because it doesn't exist,
| > or because it is set to `private` and you do not have access.
|
| repo_exists(self, repo_id: 'str', *, repo_type: 'str | None' = None, token: 'str | bool | None' = None) -> 'bool'
| Checks if a repository exists on the Hugging Face Hub.
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated
| by a `/`.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
| `None` or `"model"` if getting repository info from a model. Default is `None`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| True if the repository exists, False otherwise.
|
| Examples:
| ```py
| >>> from huggingface_hub import repo_exists
| >>> repo_exists("google/gemma-7b")
| True
| >>> repo_exists("google/not-a-repo")
| False
| ```
|
| repo_info(self, repo_id: 'str', *, revision: 'str | None' = None, repo_type: 'str | None' = None, timeout: 'float | None' = None, files_metadata: 'bool' = False, expand: 'ExpandModelProperty_T | ExpandDatasetProperty_T | ExpandSpaceProperty_T | None' = None, token: 'bool | str | None' = None) -> 'ModelInfo | DatasetInfo | SpaceInfo | KernelInfo'
| Get the info object for a given repo of a given type.
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated
| by a `/`.
| revision (`str`, *optional*):
| The revision of the repository from which to get the
| information.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
| `None` or `"model"` if getting repository info from a model. Default is `None`.
| timeout (`float`, *optional*):
| Whether to set a timeout for the request to the Hub.
| expand (`ExpandModelProperty_T` or `ExpandDatasetProperty_T` or `ExpandSpaceProperty_T`, *optional*):
| List properties to return in the response. When used, only the properties in the list will be returned.
| This parameter cannot be used if `files_metadata` is passed.
| For an exhaustive list of available properties, check out [`model_info`], [`dataset_info`] or [`space_info`].
| files_metadata (`bool`, *optional*):
| Whether or not to retrieve metadata for files in the repository
| (size, LFS metadata, etc). Defaults to `False`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `Union[SpaceInfo, DatasetInfo, ModelInfo]`: The repository information, as a
| [`huggingface_hub.hf_api.DatasetInfo`], [`huggingface_hub.hf_api.ModelInfo`]
| or [`huggingface_hub.hf_api.SpaceInfo`] object.
|
| > [!TIP]
| > Raises the following errors:
| >
| > - [`~utils.RepositoryNotFoundError`]
| > If the repository to download from cannot be found. This may be because it doesn't exist,
| > or because it is set to `private` and you do not have access.
| > - [`~utils.RevisionNotFoundError`]
| > If the revision to download from cannot be found.
|
| request_space_hardware(self, repo_id: 'str', hardware: 'SpaceHardware', *, token: 'bool | str | None' = None, sleep_time: 'int | None' = None) -> 'SpaceRuntime'
| Request new hardware for a Space.
|
| Args:
| repo_id (`str`):
| ID of the repo to update. Example: `"bigcode/in-the-stack"`.
| hardware (`str` or [`SpaceHardware`]):
| Hardware on which to run the Space. Example: `"t4-medium"`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| sleep_time (`int`, *optional*):
| Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
| your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure
| the sleep time (value is fixed to 48 hours of inactivity).
| See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
| Returns:
| [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
|
| > [!TIP]
| > It is also possible to request hardware directly when creating the Space repo! See [`create_repo`] for details.
|
| request_space_storage(self, repo_id: 'str', storage: 'SpaceStorage', *, token: 'bool | str | None' = None) -> 'SpaceRuntime'
| Request persistent storage for a Space.
|
| > [!WARNING]
| > `request_space_storage` is deprecated and will be removed in version 2.0. Use [`set_space_volumes`] instead.
|
| Args:
| repo_id (`str`):
| ID of the Space to update. Example: `"open-llm-leaderboard/open_llm_leaderboard"`.
| storage (`str` or [`SpaceStorage`]):
| Storage tier. Either 'small', 'medium', or 'large'.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| Returns:
| [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
|
| resolve_revision(self, repo_id: 'str', *, repo_type: 'str | None' = None, revision: 'str | None' = None, cache_dir: 'str | Path | None' = None, local_files_only: 'bool' = False, token: 'bool | str | None' = None) -> 'ResolvedRevision'
| Resolve a revision (branch, tag, PR ref) to a commit hash.
|
| This is meant for libraries that download and load several components of a repo separately (config,
| weights, tokenizer, ...). Resolving the revision once and passing the returned [`ResolvedRevision`] around
| guarantees that every subsequent call targets the exact same commit, even if the repo is updated in the
| meantime. It also saves HTTP calls, as downloads made with a commit hash can be served from the local
| cache without contacting the Hub.
|
| The `revision` -> `commit hash` mapping is cached on disk (in the `refs/` folder of the cache), on a
| best-effort basis. If the Hub cannot be reached later on (offline mode, connection error, timeout, Hub
| downtime, ...), the cached value is used as a fallback.
|
| > [!TIP]
| > If you only need to download a full repo snapshot, a single [`snapshot_download`] call is enough and
| > already does the right thing. `resolve_revision` is only useful when downloading files separately.
|
| Args:
| repo_id (`str`):
| A user or an organization name and a repo name separated by a `/`.
| repo_type (`str`, *optional*):
| Set to `"dataset"`, `"space"` or `"kernel"` if the repo is a dataset, space or kernel repo,
| `None` or `"model"` if it is a model. Default is `None`.
| revision (`str`, *optional*):
| The revision to resolve. Can be a branch name, a tag, a PR ref or a commit hash. Defaults to the
| default branch. If a [`ResolvedRevision`] is passed, it is returned as is.
| cache_dir (`str`, `Path`, *optional*):
| Path to the folder where cached files are stored. Defaults to the value of `HF_HUB_CACHE`.
| local_files_only (`bool`, *optional*, defaults to `False`):
| If `True`, resolve the revision from the local cache only, without contacting the Hub.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved token, which is the recommended
| method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`ResolvedRevision`]: A `str` subclass holding both the requested revision and the commit hash it resolves to.
|
| Raises:
| [`~errors.RevisionResolutionError`]
| If the revision cannot be resolved: the Hub could not be reached and nothing is cached locally.
| [`~errors.RevisionNotFoundError`]
| If the revision does not exist on the Hub.
| [`~errors.RepositoryNotFoundError`]
| If the repository cannot be found. This may be because it doesn't exist, or because it is set to
| `private` and you do not have access.
|
| Example:
| ```py
| >>> from huggingface_hub import hf_hub_download, resolve_revision
| >>> revision = resolve_revision("openai-community/gpt2")
| >>> revision
| ResolvedRevision(initial=None, resolved='607a30d783dfa663caf39e06633721c8d4cfcd7e')
|
| # Pass it around: every download is pinned to the same commit
| >>> config = hf_hub_download("openai-community/gpt2", "config.json", revision=revision)
| >>> weights = hf_hub_download("openai-community/gpt2", "model.safetensors", revision=revision)
| ```
|
| restart_space(self, repo_id: 'str', *, token: 'bool | str | None' = None, factory_reboot: 'bool' = False) -> 'SpaceRuntime'
| Restart your Space.
|
| This is the only way to programmatically restart a Space if you've put it on Pause (see [`pause_space`]). You
| must be the owner of the Space to restart it. If you are using an upgraded hardware, your account will be
| billed as soon as the Space is restarted. You can trigger a restart no matter the current state of a Space.
|
| For more details, please visit [the docs](https://huggingface.co/docs/hub/spaces-gpus#pause).
|
| Args:
| repo_id (`str`):
| ID of the Space to restart. Example: `"Salesforce/BLIP2"`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| factory_reboot (`bool`, *optional*):
| If `True`, the Space will be rebuilt from scratch without caching any requirements.
|
| Returns:
| [`SpaceRuntime`]: Runtime information about your Space.
|
| Raises:
| [`~utils.RepositoryNotFoundError`]:
| If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you
| are not authenticated.
| [`~utils.HfHubHTTPError`]:
| 403 Forbidden: only the owner of a Space can restart it. If you want to restart a Space that you don't
| own, either ask the owner by opening a Discussion or duplicate the Space.
| [`~utils.BadRequestError`]:
| If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide
| a static Space, you can set it to private.
|
| resume_inference_endpoint(self, name: 'str', *, namespace: 'str | None' = None, running_ok: 'bool' = True, token: 'bool | str | None' = None) -> 'InferenceEndpoint'
| Resume an Inference Endpoint.
|
| For convenience, you can also resume an Inference Endpoint using [`InferenceEndpoint.resume`].
|
| Args:
| name (`str`):
| The name of the Inference Endpoint to resume.
| namespace (`str`, *optional*):
| The namespace in which the Inference Endpoint is located. Defaults to the current user.
| running_ok (`bool`, *optional*):
| If `True`, the method will not raise an error if the Inference Endpoint is already running. Defaults to
| `True`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`InferenceEndpoint`]: information about the resumed Inference Endpoint.
|
| resume_scheduled_job(self, *, scheduled_job_id: 'str', namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'None'
| Resume (unpause) a scheduled compute Job on Hugging Face infrastructure.
|
| Args:
| scheduled_job_id (`str`):
| ID of the scheduled Job.
|
| namespace (`str`, *optional*):
| The namespace where the scheduled Job is. Defaults to the current user's namespace.
|
| token `(Union[bool, str, None]`, *optional*):
| A valid user access token. If not provided, the locally saved token will be used, which is the
| recommended authentication method. Set to `False` to disable authentication.
| Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
|
| revision_exists(self, repo_id: 'str', revision: 'str', *, repo_type: 'str | None' = None, token: 'str | bool | None' = None) -> 'bool'
| Checks if a specific revision exists on a repo on the Hugging Face Hub.
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated
| by a `/`.
| revision (`str`):
| The revision of the repository to check.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
| `None` or `"model"` if getting repository info from a model. Default is `None`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| True if the repository and the revision exists, False otherwise.
|
| Examples:
| ```py
| >>> from huggingface_hub import revision_exists
| >>> revision_exists("google/gemma-7b", "float16")
| True
| >>> revision_exists("google/gemma-7b", "not-a-revision")
| False
| ```
|
| run_as_future(self, fn: 'Callable[..., R]', *args, **kwargs) -> 'Future[R]'
| Run a method in the background and return a Future instance.
|
| The main goal is to run methods without blocking the main thread (e.g. to push data during a training).
| Background jobs are queued to preserve order but are not ran in parallel. If you need to speed-up your scripts
| by parallelizing lots of call to the API, you must setup and use your own [ThreadPoolExecutor](https://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor).
|
| Note: Most-used methods like [`upload_file`], [`upload_folder`] and [`create_commit`] have a `run_as_future: bool`
| argument to directly call them in the background. This is equivalent to calling `api.run_as_future(...)` on them
| but less verbose.
|
| Args:
| fn (`Callable`):
| The method to run in the background.
| *args, **kwargs:
| Arguments with which the method will be called.
|
| Return:
| `Future`: a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects) instance to
| get the result of the task.
|
| Example:
| ```py
| >>> from huggingface_hub import HfApi
| >>> api = HfApi()
| >>> future = api.run_as_future(api.whoami) # instant
| >>> future.done()
| False
| >>> future.result() # wait until complete and return result
| (...)
| >>> future.done()
| True
| ```
|
| run_job(self, *, image: 'str', command: 'list[str]', env: 'dict[str, Any] | None' = None, secrets: 'dict[str, Any] | None' = None, flavor: 'JobHardware | str | None' = None, timeout: 'int | float | str | None' = None, name: 'str | None' = None, labels: 'dict[str, str] | None' = None, volumes: 'list[Volume] | None' = None, expose: 'list[int] | None' = None, ssh: 'bool' = False, resource_group_id: 'str | None' = None, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'JobInfo'
| Run compute Jobs on Hugging Face infrastructure.
|
| Args:
| image (`str`):
| The Docker image to use.
| Examples: `"ubuntu"`, `"python:3.12"`, `"pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"`.
| Example with an image from a Space: `"hf.co/spaces/lhoestq/duckdb"`.
|
| command (`list[str]`):
| The command to run. Example: `["echo", "hello"]`.
|
| env (`dict[str, Any]`, *optional*):
| Defines the environment variables for the Job.
|
| secrets (`dict[str, Any]`, *optional*):
| Defines the secret environment variables for the Job.
|
| flavor (`str`, *optional*):
| Flavor for the hardware. See [`JobHardware`] for possible values.
| Defaults to `"cpu-basic"`.
|
| timeout (`Union[int, float, str]`, *optional*):
| Max duration for the Job: int with s (seconds, default), m (minutes), h (hours) or d (days).
| Example: `300` or `"5m"` for 5 minutes.
|
| name (`str`, *optional*):
| A name for the Job. Stored as the `name` label. Cannot be passed together with a `name` key in
| `labels`. Names do not have to be unique. Defaults to a name derived from image and command (with a short hash suffix).
|
| labels (`dict[str, str]`, *optional*):
| Labels to attach to the job (key-value pairs).
|
| volumes (`list[Volume]`, *optional*):
| Hugging Face Buckets or Repos to mount as volumes in the job container.
| Each volume is a [`Volume`] with `type` (`"bucket"`, `"model"`, `"dataset"`, or `"space"`),
| `source` (e.g. `"username/my-bucket"`), and `mount_path` (e.g. `"/data"`).
|
| expose (`list[int]`, *optional*):
| Container ports to expose through the jobs proxy. Each listed port is reachable
| on the public jobs domain (e.g. `https://<job_id>--8000.hf.jobs`). Access always
| requires an HF token with read access to the job's namespace.
|
| ssh (`bool`, *optional*):
| If True, the job's container is reachable over SSH at the URL given by `job.status.ssh_url`
| (e.g. `ssh <job_id>@ssh.hf.jobs`, or `hf jobs ssh <job_id>` from the CLI). Connecting requires
| write access to the job's namespace and an SSH public key registered on the Hub
| (https://huggingface.co/settings/keys). Defaults to False.
|
| resource_group_id (`str`, *optional*):
| The ID of the resource group to create the Job in. Used to control access to resources within an
| organization and for cost attribution/spending-limit features. If not provided, the Job is created
| outside of any resource group.
|
| namespace (`str`, *optional*):
| The namespace where the Job will be created. Defaults to the current user's namespace.
|
| token `(Union[bool, str, None]`, *optional*):
| A valid user access token. If not provided, the locally saved token will be used, which is the
| recommended authentication method. Set to `False` to disable authentication.
| Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
|
| Example:
| Run your first Job:
|
| ```python
| >>> from huggingface_hub import run_job
| >>> run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"])
| ```
|
| Run a GPU Job:
|
| ```python
| >>> from huggingface_hub import run_job
| >>> image = "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"
| >>> command = ["python", "-c", "import torch; print(f"This code ran with the following GPU: {torch.cuda.get_device_name()}")"]
| >>> run_job(image=image, command=command, flavor="a10g-small")
| ```
|
| Run a Job with volumes:
|
| ```python
| >>> from huggingface_hub import Volume, run_job
| >>> dataset_volume = Volume(type="dataset", source="HuggingFaceFW/fineweb", mount_path="/data")
| >>> output_bucket_volume = Volume(type="bucket", source="username/my-bucket", mount_path="/output")
| >>> image = "duckdb/duckdb"
| >>> command = ["duckdb", "-c", "COPY (SELECT * FROM '/data/**/*.parquet' LIMIT 5) TO '/output/first-rows.parquet'"]
| >>> run_job(image=image, command=command, volumes=[dataset_volume, output_bucket_volume])
| ```
|
| run_uv_job(self, script: 'str', *, script_args: 'list[str] | None' = None, dependencies: 'list[str] | None' = None, python: 'str | None' = None, image: 'str | None' = None, env: 'dict[str, Any] | None' = None, secrets: 'dict[str, Any] | None' = None, flavor: 'JobHardware | str | None' = None, timeout: 'int | float | str | None' = None, name: 'str | None' = None, labels: 'dict[str, str] | None' = None, volumes: 'list[Volume] | None' = None, expose: 'list[int] | None' = None, ssh: 'bool' = False, resource_group_id: 'str | None' = None, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'JobInfo'
| Run a UV script Job on Hugging Face infrastructure.
|
| Args:
| script (`str`):
| Path or URL of the UV script, or a command.
|
| script_args (`list[str]`, *optional*)
| Arguments to pass to the script or command.
|
| dependencies (`list[str]`, *optional*)
| Dependencies to use to run the UV script.
|
| python (`str`, *optional*)
| Use a specific Python version. Default is 3.12.
|
| image (`str`, *optional*, defaults to "ghcr.io/astral-sh/uv:python3.12-bookworm"):
| Use a custom Docker image with `uv` installed.
|
| env (`dict[str, Any]`, *optional*):
| Defines the environment variables for the Job.
|
| secrets (`dict[str, Any]`, *optional*):
| Defines the secret environment variables for the Job.
|
| flavor (`str`, *optional*):
| Flavor for the hardware. See [`JobHardware`] for possible values.
| Defaults to `"cpu-basic"`.
|
| timeout (`Union[int, float, str]`, *optional*):
| Max duration for the Job: int with s (seconds, default), m (minutes), h (hours) or d (days).
| Example: `300` or `"5m"` for 5 minutes.
|
| name (`str`, *optional*):
| A name for the Job. Stored as the `name` label. Cannot be passed together with a `name` key in
| `labels`. Names do not have to be unique. Defaults to a name derived from script and its arguments (with a short hash suffix).
|
| labels (`dict[str, str]`, *optional*):
| Labels to attach to the job (key-value pairs).
|
| volumes (`list[Volume]`, *optional*):
| Hugging Face Buckets or Repos to mount as volumes in the job container.
| Each volume is a [`Volume`] with `type` (`"bucket"`, `"model"`, `"dataset"`, or `"space"`),
| `source` (e.g. `"username/my-bucket"`), and `mount_path` (e.g. `"/data"`).
|
| expose (`list[int]`, *optional*):
| Container ports to expose through the jobs proxy. Each listed port is reachable
| on the public jobs domain (e.g. `https://<job_id>--8000.hf.jobs`). Access always
| requires an HF token with read access to the job's namespace.
|
| ssh (`bool`, *optional*):
| If True, the job's container is reachable over SSH at the URL given by `job.status.ssh_url`
| (e.g. `ssh <job_id>@ssh.hf.jobs`, or `hf jobs ssh <job_id>` from the CLI). Connecting requires
| write access to the job's namespace and an SSH public key registered on the Hub
| (https://huggingface.co/settings/keys). Defaults to False.
|
| resource_group_id (`str`, *optional*):
| The ID of the resource group to create the Job in. Used to control access to resources within an
| organization and for cost attribution/spending-limit features. If not provided, the Job is created
| outside of any resource group.
|
| namespace (`str`, *optional*):
| The namespace where the Job will be created. Defaults to the current user's namespace.
|
| token `(Union[bool, str, None]`, *optional*):
| A valid user access token. If not provided, the locally saved token will be used, which is the
| recommended authentication method. Set to `False` to disable authentication.
| Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
|
| Example:
|
| Run a script from a URL:
|
| ```python
| >>> from huggingface_hub import run_uv_job
| >>> script = "https://raw.githubusercontent.com/huggingface/trl/refs/heads/main/trl/scripts/sft.py"
| >>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
| >>> run_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small")
| ```
|
| Run a local script:
|
| ```python
| >>> from huggingface_hub import run_uv_job
| >>> script = "my_sft.py"
| >>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
| >>> run_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small")
| ```
|
| Run a command:
|
| ```python
| >>> from huggingface_hub import run_uv_job
| >>> script = "lighteval"
| >>> script_args= ["endpoint", "inference-providers", "model_name=openai/gpt-oss-20b,provider=auto", "lighteval|gsm8k|0|0"]
| >>> run_uv_job(script, script_args=script_args, dependencies=["lighteval"], flavor="a10g-small")
| ```
|
| Mount volumes, e.g. to save model checkpoints during training:
|
| ```python
| >>> from huggingface_hub import Volume, run_uv_job
| >>> script = "my_sft.py"
| >>> script_args = ["--output_dir", "/training-outputs/training-v3-final", ...]
| >>> checkpoints_bucket = Volume(type="bucket", source="username/my-bucket", mount_path="/training-outputs")
| >>> run_uv_job(script, script_args=script_args, volumes=[checkpoints_bucket])
| ```
|
| scale_to_zero_inference_endpoint(self, name: 'str', *, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'InferenceEndpoint'
| Scale Inference Endpoint to zero.
|
| An Inference Endpoint scaled to zero will not be charged. It will be resume on the next request to it, with a
| cold start delay. This is different than pausing the Inference Endpoint with [`pause_inference_endpoint`], which
| would require a manual resume with [`resume_inference_endpoint`].
|
| For convenience, you can also scale an Inference Endpoint to zero using [`InferenceEndpoint.scale_to_zero`].
|
| Args:
| name (`str`):
| The name of the Inference Endpoint to scale to zero.
| namespace (`str`, *optional*):
| The namespace in which the Inference Endpoint is located. Defaults to the current user.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`InferenceEndpoint`]: information about the scaled-to-zero Inference Endpoint.
|
| search_spaces(self, query: 'str', *, filter: 'str | Iterable[str] | None' = None, sdk: 'str | list[str] | None' = None, include_non_running: 'bool' = False, token: 'bool | str | None' = None) -> 'Iterable[SpaceSearchResult]'
| Search Spaces on the Hub using semantic search.
|
| This endpoint uses semantic search (embedding-based) for multi-word queries
| and full-text search for single-word queries.
|
| Args:
| query (`str`):
| The search query string.
| filter (`str` or `Iterable[str]`, *optional*):
| A string tag or list of tags to filter by.
| sdk (`str` or `list[str]`, *optional*):
| Filter by SDK (e.g. `"gradio"`, `"docker"`, `"static"`).
| include_non_running (`bool`, *optional*):
| Whether to include non-running Spaces in results. Defaults to `False`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| `Iterable[SpaceSearchResult]`: an iterable of [`SpaceSearchResult`] objects.
|
| Example:
| ```python
| >>> from huggingface_hub import HfApi
| >>> api = HfApi()
| >>> results = list(api.search_spaces("generate image"))
| >>> results[0].id
| 'mrfakename/Z-Image-Turbo'
| >>> results[0].ai_category
| 'Image Generation'
| ```
|
| set_space_sleep_time(self, repo_id: 'str', sleep_time: 'int', *, token: 'bool | str | None' = None) -> 'SpaceRuntime'
| Set a custom sleep time for a Space running on upgraded hardware..
|
| Your Space will go to sleep after X seconds of inactivity. You are not billed when your Space is in "sleep"
| mode. If a new visitor lands on your Space, it will "wake it up". Only upgraded hardware can have a
| configurable sleep time. To know more about the sleep stage, please refer to
| https://huggingface.co/docs/hub/spaces-gpus#sleep-time.
|
| Args:
| repo_id (`str`):
| ID of the repo to update. Example: `"bigcode/in-the-stack"`.
| sleep_time (`int`, *optional*):
| Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
| your Space to pause (default behavior for upgraded hardware). For free hardware, you can't configure
| the sleep time (value is fixed to 48 hours of inactivity).
| See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| Returns:
| [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
|
| > [!TIP]
| > It is also possible to set a custom sleep time when requesting hardware with [`request_space_hardware`].
|
| set_space_volumes(self, repo_id: 'str', volumes: 'list[Volume]', *, token: 'bool | str | None' = None) -> 'None'
| Set volumes for a Space.
|
| Sets (or replaces) the list of volumes mounted in the Space. Each volume gives the Space's container access
| to a Hub resource (model, dataset, or storage bucket).
|
| Args:
| repo_id (`str`):
| ID of the Space to update. Example: `"username/my-space"`.
| volumes (`list[Volume]`):
| List of [`Volume`] objects to mount. Each volume has a `type` (`"bucket"`, `"model"`, `"dataset"`, or
| `"space"`), a `source` (repo or bucket ID), a `mount_path` (path inside the container), and optional
| `revision`, `read_only`, and `path` fields.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Raises:
| [`BadRequestError`]:
| If the Space is a static Space (volumes are not supported on static Spaces).
|
| Example:
| ```python
| >>> from huggingface_hub import HfApi, Volume
| >>> api = HfApi()
| >>> api.set_space_volumes(
| ... "username/my-space",
| ... volumes=[
| ... Volume(type="model", source="username/my-model", mount_path="/models", read_only=True),
| ... Volume(type="bucket", source="username/my-bucket", mount_path="/data"),
| ... ],
| ... )
| ```
|
| snapshot_download(self, repo_id: 'str', *, repo_type: 'str | None' = None, revision: 'str | None' = None, cache_dir: 'str | Path | None' = None, local_dir: 'str | Path | None' = None, etag_timeout: 'float' = 10, force_download: 'bool' = False, token: 'bool | str | None' = None, local_files_only: 'bool' = False, allow_patterns: 'list[str] | str | None' = None, ignore_patterns: 'list[str] | str | None' = None, max_workers: 'int' = 8, tqdm_class: 'type[base_tqdm] | None' = None, dry_run: 'bool' = False) -> 'str | list[DryRunFileInfo]'
| Download repo files.
|
| Download a whole snapshot of a repo's files at the specified revision. This is useful when you want all files from
| a repo, because you don't know which ones you will need a priori. All files are nested inside a folder in order
| to keep their actual filename relative to that folder. You can also filter which files to download using
| `allow_patterns` and `ignore_patterns`.
|
| If `local_dir` is provided, the file structure from the repo will be replicated in this location. When using this
| option, the `cache_dir` will not be used and a `.cache/huggingface/` folder will be created at the root of `local_dir`
| to store some metadata related to the downloaded files.While this mechanism is not as robust as the main
| cache-system, it's optimized for regularly pulling the latest version of a repository.
|
| An alternative would be to clone the repo but this requires git and git-lfs to be installed and properly
| configured. It is also not possible to filter which files to download when cloning a repository using git.
|
| Args:
| repo_id (`str`):
| A user or an organization name and a repo name separated by a `/`.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if downloading from a dataset or space,
| `None` or `"model"` if downloading from a model. Default is `None`.
| revision (`str`, *optional*):
| An optional Git revision id which can be a branch name, a tag, or a
| commit hash.
| cache_dir (`str`, `Path`, *optional*):
| Path to the folder where cached files are stored.
| local_dir (`str` or `Path`, *optional*):
| If provided, the downloaded files will be placed under this directory.
| etag_timeout (`float`, *optional*, defaults to `10`):
| When fetching ETag, how many seconds to wait for the server to send
| data before giving up which is passed to `httpx.request`.
| force_download (`bool`, *optional*, defaults to `False`):
| Whether the file should be downloaded even if it already exists in the local cache.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| 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.
| allow_patterns (`list[str]` or `str`, *optional*):
| If provided, only files matching at least one pattern are downloaded.
| ignore_patterns (`list[str]` or `str`, *optional*):
| If provided, files matching any of the patterns are not downloaded.
| max_workers (`int`, *optional*):
| Number of concurrent threads to download files (1 thread = 1 file download).
| Defaults to 8.
| tqdm_class (`tqdm`, *optional*):
| If provided, overwrites the default behavior for the progress bar. Passed
| argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior.
| Note that the `tqdm_class` is not passed to each individual download.
| Defaults to the custom HF progress bar that can be disabled by setting
| `HF_HUB_DISABLE_PROGRESS_BARS` environment variable.
| dry_run (`bool`, *optional*, defaults to `False`):
| If `True`, perform a dry run without actually downloading the files. Returns a list of
| [`DryRunFileInfo`] objects containing information about what would be downloaded.
|
| Returns:
| `str` or list of [`DryRunFileInfo`]:
| - If `dry_run=False`: Folder path of the repo snapshot.
| - If `dry_run=True`: A list of [`DryRunFileInfo`] objects containing download information.
|
| Raises:
| [`~utils.RepositoryNotFoundError`]
| If the repository to download from cannot be found. This may be because it doesn't exist,
| or because it is set to `private` and you do not have access.
| [`~utils.RevisionNotFoundError`]
| If the revision to download from cannot be found.
| [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
| If `token=True` and the token cannot be found.
| [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) if
| ETag cannot be determined.
| [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| if some parameter value is invalid.
|
| space_info(self, repo_id: 'str', *, revision: 'str | None' = None, timeout: 'float | None' = None, files_metadata: 'bool' = False, expand: 'list[ExpandSpaceProperty_T] | None' = None, token: 'bool | str | None' = None) -> 'SpaceInfo'
| Get info on one specific Space on huggingface.co.
|
| Space can be private if you pass an acceptable token.
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated
| by a `/`.
| revision (`str`, *optional*):
| The revision of the space repository from which to get the
| information.
| timeout (`float`, *optional*):
| Whether to set a timeout for the request to the Hub.
| files_metadata (`bool`, *optional*):
| Whether or not to retrieve metadata for files in the repository
| (size, LFS metadata, etc). Defaults to `False`.
| expand (`list[ExpandSpaceProperty_T]`, *optional*):
| List properties to return in the response. When used, only the properties in the list will be returned.
| This parameter cannot be used if `full` is passed.
| Possible values are `"author"`, `"cardData"`, `"createdAt"`, `"datasets"`, `"disabled"`, `"lastModified"`, `"likes"`, `"models"`, `"private"`, `"runtime"`, `"sdk"`, `"siblings"`, `"sha"`, `"subdomain"`, `"tags"`, `"trendingScore"`, `"usedStorage"`, and `"resourceGroup"`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`~hf_api.SpaceInfo`]: The space repository information.
|
| > [!TIP]
| > Raises the following errors:
| >
| > - [`~utils.RepositoryNotFoundError`]
| > If the repository to download from cannot be found. This may be because it doesn't exist,
| > or because it is set to `private` and you do not have access.
| > - [`~utils.RevisionNotFoundError`]
| > If the revision to download from cannot be found.
|
| super_squash_history(self, repo_id: 'str', *, branch: 'str | None' = None, commit_message: 'str | None' = None, repo_type: 'str | None' = None, token: 'str | bool | None' = None) -> 'None'
| Squash commit history on a branch for a repo on the Hub.
|
| Squashing the repo history is useful when you know you'll make hundreds of commits and you don't want to
| clutter the history. Squashing commits can only be performed from the head of a branch.
|
| > [!WARNING]
| > Once squashed, the commit history cannot be retrieved. This is a non-revertible operation.
|
| > [!WARNING]
| > Once the history of a branch has been squashed, it is not possible to merge it back into another branch since
| > their history will have diverged.
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated by a `/`.
| branch (`str`, *optional*):
| The branch to squash. Defaults to the head of the `"main"` branch.
| commit_message (`str`, *optional*):
| The commit message to use for the squashed commit.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if listing commits from a dataset or a Space, `None` or `"model"` if
| listing from a model. Default is `None`.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Raises:
| [`~utils.RepositoryNotFoundError`]:
| If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
| does not exist.
| [`~utils.RevisionNotFoundError`]:
| If the branch to squash cannot be found.
| [`~utils.BadRequestError`]:
| If invalid reference for a branch. You cannot squash history on tags.
|
| Example:
| ```py
| >>> from huggingface_hub import HfApi
| >>> api = HfApi()
|
| # Create repo
| >>> repo_id = api.create_repo("test-squash").repo_id
|
| # Make a lot of commits.
| >>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"content")
| >>> api.upload_file(repo_id=repo_id, path_in_repo="lfs.bin", path_or_fileobj=b"content")
| >>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"another_content")
|
| # Squash history
| >>> api.super_squash_history(repo_id=repo_id)
| ```
|
| suspend_scheduled_job(self, *, scheduled_job_id: 'str', namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'None'
| Suspend (pause) a scheduled compute Job on Hugging Face infrastructure.
|
| Args:
| scheduled_job_id (`str`):
| ID of the scheduled Job.
|
| namespace (`str`, *optional*):
| The namespace where the scheduled Job is. Defaults to the current user's namespace.
|
| token `(Union[bool, str, None]`, *optional*):
| A valid user access token. If not provided, the locally saved token will be used, which is the
| recommended authentication method. Set to `False` to disable authentication.
| Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
|
| sync_bucket(self, source: 'str | None' = None, dest: 'str | None' = None, *, delete: 'bool' = False, ignore_times: 'bool' = False, ignore_sizes: 'bool' = False, existing: 'bool' = False, ignore_existing: 'bool' = False, include: 'list[str] | None' = None, exclude: 'list[str] | None' = None, filter_from: 'str | None' = None, plan: 'str | None' = None, apply: 'str | None' = None, dry_run: 'bool' = False, verbose: 'bool' = False, quiet: 'bool' = False, token: 'bool | str | None' = None) -> 'SyncPlan'
| Sync files between a local directory and a bucket.
|
| This is equivalent to the ``hf buckets sync`` CLI command. One of ``source`` or ``dest`` must be a bucket path
| (``hf://buckets/...``) and the other must be a local directory path.
|
| Args:
| source (`str`, *optional*):
| Source path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``.
| Required unless using ``apply``.
| dest (`str`, *optional*):
| Destination path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``.
| Required unless using ``apply``.
| delete (`bool`, *optional*, defaults to `False`):
| Delete destination files not present in source.
| ignore_times (`bool`, *optional*, defaults to `False`):
| Skip files only based on size, ignoring modification times.
| ignore_sizes (`bool`, *optional*, defaults to `False`):
| Skip files only based on modification times, ignoring sizes.
| existing (`bool`, *optional*, defaults to `False`):
| Skip creating new files on receiver (only update existing files).
| ignore_existing (`bool`, *optional*, defaults to `False`):
| Skip updating files that exist on receiver (only create new files).
| include (`list[str]`, *optional*):
| Include files matching patterns (fnmatch-style).
| exclude (`list[str]`, *optional*):
| Exclude files matching patterns (fnmatch-style).
| filter_from (`str`, *optional*):
| Path to a filter file with include/exclude rules.
| plan (`str`, *optional*):
| Save sync plan to this JSONL file instead of executing.
| apply (`str`, *optional*):
| Apply a previously saved plan file. When set, ``source`` and ``dest`` are not needed.
| dry_run (`bool`, *optional*, defaults to `False`):
| Print sync plan to stdout as JSONL without executing.
| verbose (`bool`, *optional*, defaults to `False`):
| Show detailed per-file operations.
| quiet (`bool`, *optional*, defaults to `False`):
| Suppress all output and progress bars.
| token (Union[bool, str, None], optional):
| A valid user access token. If not provided, the locally saved token will be used.
|
| Returns:
| [`SyncPlan`]: The computed (or loaded) sync plan.
|
| Example:
| ```python
| >>> from huggingface_hub import HfApi
| >>> api = HfApi()
|
| # Upload local directory to bucket
| >>> api.sync_bucket("./data", "hf://buckets/username/my-bucket")
|
| # Download bucket to local directory
| >>> api.sync_bucket("hf://buckets/username/my-bucket", "./data")
|
| # Sync with delete and filtering
| >>> api.sync_bucket(
| ... "./data",
| ... "hf://buckets/username/my-bucket",
| ... delete=True,
| ... include=["*.safetensors"],
| ... )
|
| # Dry run: preview what would be synced
| >>> plan = api.sync_bucket("./data", "hf://buckets/username/my-bucket", dry_run=True)
| >>> plan.summary()
| {'uploads': 3, 'downloads': 0, 'deletes': 0, 'skips': 1, 'total_size': 4096}
|
| # Save plan for review, then apply
| >>> api.sync_bucket("./data", "hf://buckets/username/my-bucket", plan="sync-plan.jsonl")
| >>> api.sync_bucket(apply="sync-plan.jsonl")
| ```
|
| sync_job_volume(self, source: 'str | Path', mount_path: 'str', *, remote_name: 'str | None' = None, read_only: 'bool' = True, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'Volume'
| Sync a local directory to a bucket and return a [`Volume`] ready to mount in a Job.
|
| Files are uploaded to a subfolder of the `{namespace}/jobs-artifacts` bucket (auto-created as
| private; a warning is emitted if it already exists and is public) using the same sync logic
| as [`sync_bucket`]: re-syncing the same directory only
| uploads new or modified files. By default the subfolder name is derived from the directory
| path and the machine's hostname, so repeated calls from the same directory reuse the same
| remote folder. Pass `remote_name` to use a fixed name instead.
|
| Note that the data is *copied* to the bucket, not mounted live: changes made locally after
| the sync are not visible to the Job (re-run `sync_job_volume` to update), and the volume is
| mounted read-only by default. To retrieve data written by a Job to a read-write volume, sync
| the bucket folder back with [`sync_bucket`]. If the source directory is empty (e.g. an output
| directory), a placeholder `.keep` file is uploaded so the volume can still be mounted.
|
| Args:
| source (`str` or `Path`):
| Path to a local directory to sync.
| mount_path (`str`):
| Mount path inside the Job container, e.g. `"/inputs"`. Must start with `/`.
| remote_name (`str`, *optional*):
| Name of the bucket subfolder to sync to. Defaults to a `{dirname}-{hash}` name derived
| from the source path and the machine's hostname.
| read_only (`bool`, *optional*, defaults to `True`):
| Mount the volume read-only in the Job. Pass `False` to let the Job write back to the
| bucket folder (e.g. to retrieve outputs with [`sync_bucket`] afterwards).
| namespace (`str`, *optional*):
| The namespace owning the `jobs-artifacts` bucket. Defaults to the current user's
| namespace. Use the same namespace as the Job that will mount the volume.
| token (`Union[bool, str, None]`, *optional*):
| A valid user access token. If not provided, the locally saved token will be used, which is the
| recommended authentication method. Set to `False` to disable authentication.
| Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
|
| Returns:
| [`Volume`]: A bucket volume scoped to the synced subfolder, to pass in the `volumes` list
| of [`run_job`], [`run_uv_job`], [`create_scheduled_job`] or [`create_scheduled_uv_job`].
|
| Example:
| ```python
| >>> from huggingface_hub import run_uv_job, sync_job_volume
|
| # Upload ./training-data once, then run multiple jobs against it
| >>> volume = sync_job_volume("./training-data", "/data")
| >>> run_uv_job("train.py", script_args=["--learning-rate", "0.01"], volumes=[volume])
| >>> run_uv_job("train.py", script_args=["--learning-rate", "0.05"], volumes=[volume])
|
| # Read-write volume to retrieve outputs after the job completes
| >>> volume = sync_job_volume("./outputs", "/outputs", read_only=False)
| >>> job = run_uv_job("process.py", volumes=[volume])
| ```
|
| trigger_scheduled_job(self, *, scheduled_job_id: 'str', namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'JobInfo'
| Trigger a scheduled Job to run immediately.
|
| This triggers one immediate run of the scheduled job's spec. It does **not** modify the schedule
| and does **not** affect the next scheduled run. If an instance is already running and the scheduled
| job does not allow concurrent runs, the request is rejected (HTTP 409).
|
| Args:
| scheduled_job_id (`str`):
| ID of the scheduled Job.
|
| namespace (`str`, *optional*):
| The namespace where the scheduled Job is. Defaults to the current user's namespace.
|
| token `(Union[bool, str, None]`, *optional*):
| A valid user access token. If not provided, the locally saved token will be used, which is the
| recommended authentication method. Set to `False` to disable authentication.
| Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
|
| Returns:
| [`JobInfo`]: Info about the triggered run.
|
| Raises:
| [`~utils.HfHubHTTPError`]:
| HTTP 409 if another instance is already running and `concurrency` is disabled on the scheduled job.
|
| unlike(self, repo_id: 'str', *, token: 'bool | str | None' = None, repo_type: 'str | None' = None) -> 'None'
| Unlike a given repo on the Hub (e.g. remove from favorite list).
|
| To prevent spam usage, it is not possible to `like` a repository from a script.
|
| See also [`list_liked_repos`].
|
| Args:
| repo_id (`str`):
| The repository to unlike. Example: `"user/my-cool-model"`.
|
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if unliking a dataset or space, `None` or
| `"model"` if unliking a model. Default is `None`.
|
| Raises:
| [`~utils.RepositoryNotFoundError`]:
| If repository is not found (error 404): wrong repo_id/repo_type, private
| but not authenticated or repo does not exist.
|
| Example:
| ```python
| >>> from huggingface_hub import list_liked_repos, unlike
| >>> "gpt2" in list_liked_repos().models # we assume you have already liked gpt2
| True
| >>> unlike("gpt2")
| >>> "gpt2" in list_liked_repos().models
| False
| ```
|
| update_collection_item(self, collection_slug: 'str', item_object_id: 'str', *, note: 'str | None' = None, position: 'int | None' = None, token: 'bool | str | None' = None) -> 'None'
| Update an item in a collection.
|
| Args:
| collection_slug (`str`):
| Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
| item_object_id (`str`):
| ID of the item in the collection. This is not the id of the item on the Hub (repo_id or paper id).
| It must be retrieved from a [`CollectionItem`] object. Example: `collection.items[0].item_object_id`.
| note (`str`, *optional*):
| A note to attach to the item in the collection. The maximum size for a note is 500 characters.
| position (`int`, *optional*):
| New position of the item in the collection.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Example:
|
| ```py
| >>> from huggingface_hub import get_collection, update_collection_item
|
| # Get collection first
| >>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")
|
| # Update item based on its ID (add note + update position)
| >>> update_collection_item(
| ... collection_slug="TheBloke/recent-models-64f9a55bb3115b4f513ec026",
| ... item_object_id=collection.items[-1].item_object_id,
| ... note="Newly updated model!"
| ... position=0,
| ... )
| ```
|
| update_collection_metadata(self, collection_slug: 'str', *, title: 'str | None' = None, description: 'str | None' = None, position: 'int | None' = None, private: 'bool | None' = None, theme: 'str | None' = None, token: 'bool | str | None' = None) -> 'Collection'
| Update metadata of a collection on the Hub.
|
| All arguments are optional. Only provided metadata will be updated.
|
| Args:
| collection_slug (`str`):
| Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
| title (`str`):
| Title of the collection to update.
| description (`str`, *optional*):
| Description of the collection to update. The maximum size for a description is 150 characters.
| position (`int`, *optional*):
| New position of the collection in the list of collections of the user.
| private (`bool`, *optional*):
| Whether the collection should be private or not.
| theme (`str`, *optional*):
| Theme of the collection on the Hub.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns: [`Collection`]
|
| Example:
|
| ```py
| >>> from huggingface_hub import update_collection_metadata
| >>> collection = update_collection_metadata(
| ... collection_slug="username/iccv-2023-64f9a55bb3115b4f513ec026",
| ... title="ICCV Oct. 2023"
| ... description="Portfolio of models, datasets, papers and demos I presented at ICCV Oct. 2023",
| ... private=False,
| ... theme="pink",
| ... )
| >>> collection.slug
| "username/iccv-oct-2023-64f9a55bb3115b4f513ec026"
| # ^collection slug got updated but not the trailing ID
| ```
|
| update_collection_resource_group(self, collection_slug: 'str', resource_group_id: 'str | None', *, token: 'bool | str | None' = None) -> 'None'
| Assign a collection to a resource group, or remove it from any resource group.
|
| Only valid for organization-owned collections.
|
| Args:
| collection_slug (`str`):
| Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
| resource_group_id (`str` or `None`):
| The resource group to assign the collection to, as a 24-character hexadecimal string. If `None`,
| the collection is removed from any resource group.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Example:
|
| ```py
| >>> from huggingface_hub import update_collection_resource_group
| >>> update_collection_resource_group(
| ... collection_slug="my-org/iccv-2023-64f9a55bb3115b4f513ec026",
| ... resource_group_id="66980ecfc1e12a49c8f0e42d",
| ... )
| ```
|
| update_inference_endpoint(self, name: 'str', *, accelerator: 'str | None' = None, instance_size: 'str | None' = None, instance_type: 'str | None' = None, min_replica: 'int | None' = None, max_replica: 'int | None' = None, scale_to_zero_timeout: 'int | None' = None, scaling_metric: 'InferenceEndpointScalingMetric | None' = None, scaling_threshold: 'float | None' = None, repository: 'str | None' = None, framework: 'str | None' = None, revision: 'str | None' = None, task: 'str | None' = None, custom_image: 'dict | None' = None, env: 'dict[str, str] | None' = None, secrets: 'dict[str, str] | None' = None, domain: 'str | None' = None, path: 'str | None' = None, cache_http_responses: 'bool | None' = None, tags: 'list[str] | None' = None, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'InferenceEndpoint'
| Update an Inference Endpoint.
|
| This method allows the update of either the compute configuration, the deployed model, the route, or any combination.
| All arguments are optional but at least one must be provided.
|
| For convenience, you can also update an Inference Endpoint using [`InferenceEndpoint.update`].
|
| Args:
| name (`str`):
| The name of the Inference Endpoint to update.
|
| accelerator (`str`, *optional*):
| The hardware accelerator to be used for inference (e.g. `"cpu"`).
| instance_size (`str`, *optional*):
| The size or type of the instance to be used for hosting the model (e.g. `"x4"`).
| instance_type (`str`, *optional*):
| The cloud instance type where the Inference Endpoint will be deployed (e.g. `"intel-icl"`).
| min_replica (`int`, *optional*):
| The minimum number of replicas (instances) to keep running for the Inference Endpoint.
| max_replica (`int`, *optional*):
| The maximum number of replicas (instances) to scale to for the Inference Endpoint.
| scale_to_zero_timeout (`int`, *optional*):
| The duration in minutes before an inactive endpoint is scaled to zero.
| scaling_metric (`str` or [`InferenceEndpointScalingMetric `], *optional*):
| The metric reference for scaling. Either "pendingRequests" or "hardwareUsage" when provided.
| Defaults to None.
| scaling_threshold (`float`, *optional*):
| The scaling metric threshold used to trigger a scale up. Ignored when scaling metric is not provided.
| Defaults to None.
| repository (`str`, *optional*):
| The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`).
| framework (`str`, *optional*):
| The machine learning framework used for the model (e.g. `"custom"`).
| revision (`str`, *optional*):
| The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`).
| task (`str`, *optional*):
| The task on which to deploy the model (e.g. `"text-classification"`).
| custom_image (`dict`, *optional*):
| A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an
| Inference Endpoint running on the `text-generation-inference` (TGI) framework (see examples).
| env (`dict[str, str]`, *optional*):
| Non-secret environment variables to inject in the container environment
| secrets (`dict[str, str]`, *optional*):
| Secret values to inject in the container environment.
|
| domain (`str`, *optional*):
| The custom domain for the Inference Endpoint deployment, if setup the inference endpoint will be available at this domain (e.g. `"my-new-domain.cool-website.woof"`).
| path (`str`, *optional*):
| The custom path to the deployed model, should start with a `/` (e.g. `"/models/google-bert/bert-base-uncased"`).
|
| cache_http_responses (`bool`, *optional*):
| Whether to cache HTTP responses from the Inference Endpoint.
| tags (`list[str]`, *optional*):
| A list of tags to associate with the Inference Endpoint.
|
| namespace (`str`, *optional*):
| The namespace where the Inference Endpoint will be updated. Defaults to the current user's namespace.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`InferenceEndpoint`]: information about the updated Inference Endpoint.
|
| update_job_labels(self, *, job_id: 'str', labels: 'dict[str, str]', namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'JobInfo'
| Update labels of an existing Job.
|
| Replaces all existing user-provided labels with the new labels.
|
| Args:
| job_id (`str`):
| ID of the Job.
|
| labels (`dict[str, str]`):
| New labels to set on the job. Replaces all existing labels.
| Both keys and values must be max 100 characters and contain only
| alphanumeric characters, dots, dashes, and underscores.
|
| namespace (`str`, *optional*):
| The namespace where the Job is running. Defaults to the current user's namespace.
|
| token `(Union[bool, str, None]`, *optional*):
| A valid user access token. If not provided, the locally saved token will be used, which is the
| recommended authentication method. Set to `False` to disable authentication.
| Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
|
| Returns:
| [`JobInfo`]: The updated Job info.
|
| update_repo_settings(self, repo_id: 'str', *, gated: "Literal['auto', 'manual', False] | None" = None, private: 'bool | None' = None, visibility: 'RepoVisibility_T | None' = None, token: 'str | bool | None' = None, repo_type: 'str | None' = None) -> 'None'
| Update the settings of a repository, including gated access and visibility.
|
| To give more control over how repos are used, the Hub allows repo authors to enable
| access requests for their repos, and also to change the visibility of the repo.
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated by a /.
| gated (`Literal["auto", "manual", False]`, *optional*):
| The gated status for the repository. If set to `None` (default), the `gated` setting of the repository won't be updated.
| * "auto": The repository is gated, and access requests are automatically approved or denied based on predefined criteria.
| * "manual": The repository is gated, and access requests require manual approval.
| * False : The repository is not gated, and anyone can access it.
| private (`bool`, *optional*):
| Whether the repository should be private. Cannot be passed together with `visibility`.
| visibility (`Literal["public", "private", "protected"]`, *optional*):
| Visibility of the repository. Can be `"public"` or `"private"`, or `"protected"` for Spaces.
| token (`Union[str, bool, None]`, *optional*):
| A valid user access token (string). Defaults to the locally saved token,
| which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass False.
| repo_type (`str`, *optional*):
| The type of the repository to update settings from (`"model"`, `"dataset"` or `"space"`).
| Defaults to `"model"`.
| Raises:
| [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| If gated is not one of "auto", "manual", or False.
| [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| If repo_type is not one of the values in constants.REPO_TYPES.
| [`~utils.HfHubHTTPError`]:
| If the request to the Hugging Face Hub API fails.
| [`~utils.RepositoryNotFoundError`]
| If the repository to download from cannot be found. This may be because it doesn't exist,
| or because it is set to `private` and you do not have access.
|
| update_scheduled_job_labels(self, *, scheduled_job_id: 'str', labels: 'dict[str, str]', namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'ScheduledJobInfo'
| Update labels of an existing scheduled Job.
|
| Replaces all existing user-provided labels with the new labels.
|
| Args:
| scheduled_job_id (`str`):
| ID of the scheduled Job.
|
| labels (`dict[str, str]`):
| New labels to set on the scheduled job. Replaces all existing labels.
| Both keys and values must be max 100 characters and contain only
| alphanumeric characters, dots, dashes, and underscores.
|
| namespace (`str`, *optional*):
| The namespace where the scheduled Job is. Defaults to the current user's namespace.
|
| token `(Union[bool, str, None]`, *optional*):
| A valid user access token. If not provided, the locally saved token will be used, which is the
| recommended authentication method. Set to `False` to disable authentication.
| Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
|
| Returns:
| [`ScheduledJobInfo`]: The updated scheduled Job info.
|
| update_webhook(self, webhook_id: 'str', *, url: 'str | None' = None, watched: 'list[dict | WebhookWatchedItem] | None' = None, domains: 'list[constants.WEBHOOK_DOMAIN_T] | None' = None, secret: 'str | None' = None, token: 'bool | str | None' = None) -> 'WebhookInfo'
| Update an existing webhook.
|
| Args:
| webhook_id (`str`):
| The unique identifier of the webhook to be updated.
| url (`str`, optional):
| The URL to which the payload will be sent.
| watched (`list[WebhookWatchedItem]`, optional):
| List of items to watch. It can be users, orgs, models, datasets, or spaces.
| Refer to [`WebhookWatchedItem`] for more details. Watched items can also be provided as plain dictionaries.
| domains (`list[Literal["repo", "discussion"]]`, optional):
| The domains to watch. This can include "repo", "discussion", or both.
| secret (`str`, optional):
| A secret to sign the payload with, providing an additional layer of security.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved token, which is the recommended
| method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`WebhookInfo`]:
| Info about the updated webhook.
|
| Example:
| ```python
| >>> from huggingface_hub import update_webhook
| >>> updated_payload = update_webhook(
| ... webhook_id="654bbbc16f2ec14d77f109cc",
| ... url="https://new.webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
| ... watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}],
| ... domains=["repo"],
| ... secret="my-secret",
| ... )
| >>> print(updated_payload)
| WebhookInfo(
| id="654bbbc16f2ec14d77f109cc",
| job=None,
| url="https://new.webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
| watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
| domains=["repo"],
| secret="my-secret",
| disabled=False,
| ```
|
| upload_file(self, *, path_or_fileobj: 'str | Path | bytes | BinaryIO', path_in_repo: 'str', repo_id: 'str', token: 'str | bool | None' = None, repo_type: 'str | None' = None, revision: 'str | None' = None, commit_message: 'str | None' = None, commit_description: 'str | None' = None, create_pr: 'bool | None' = None, parent_commit: 'str | None' = None, run_as_future: 'bool' = False, _hot_reload: 'bool | None' = None) -> 'CommitInfo | Future[CommitInfo]'
| Upload a local file (up to 50 GB) to the given repo. The upload is done
| through a HTTP post request, and doesn't require git or git-lfs to be
| installed.
|
| Args:
| path_or_fileobj (`str`, `Path`, `bytes`, or `IO`):
| Path to a file on the local machine or binary data stream /
| fileobj / buffer.
| path_in_repo (`str`):
| Relative filepath in the repo, for example:
| `"checkpoints/1fec34a/weights.bin"`
| repo_id (`str`):
| The repository to which the file will be uploaded, for example:
| `"username/custom_transformers"`
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if uploading to a dataset or
| space, `None` or `"model"` if uploading to a model. Default is
| `None`.
| revision (`str`, *optional*):
| The git revision to commit from. Defaults to the head of the `"main"` branch.
| commit_message (`str`, *optional*):
| The summary / title / first line of the generated commit
| commit_description (`str` *optional*)
| The description of the generated commit
| create_pr (`boolean`, *optional*):
| Whether or not to create a Pull Request with that commit. Defaults to `False`.
| If `revision` is not set, PR is opened against the `"main"` branch. If
| `revision` is set and is a branch, PR is opened against this branch. If
| `revision` is set and is not a branch name (example: a commit oid), an
| `RevisionNotFoundError` is returned by the server.
| parent_commit (`str`, *optional*):
| The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
| If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
| If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
| Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
| especially useful if the repo is updated / committed to concurrently.
| run_as_future (`bool`, *optional*):
| Whether or not to run this method in the background. Background jobs are run sequentially without
| blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects)
| object. Defaults to `False`.
|
|
| Returns:
| [`CommitInfo`] or `Future`:
| Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit
| url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will
| contain the result when executed.
| > [!TIP]
| > Raises the following errors:
| >
| > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
| > if the HuggingFace API returned an error
| > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| > if some parameter value is invalid
| > - [`~utils.RepositoryNotFoundError`]
| > If the repository to download from cannot be found. This may be because it doesn't exist,
| > or because it is set to `private` and you do not have access.
| > - [`~utils.RevisionNotFoundError`]
| > If the revision to download from cannot be found.
|
| > [!WARNING]
| > `upload_file` assumes that the repo already exists on the Hub. If you get a
| > Client error 404, please make sure you are authenticated, that your token has the required permissions,
| > and that `repo_id` and `repo_type` are set correctly. If repo does not exist,
| > create it first using [`~hf_api.create_repo`].
|
| Example:
|
| ```python
| >>> from huggingface_hub import upload_file
|
| >>> with open("./local/filepath", "rb") as fobj:
| ... upload_file(
| ... path_or_fileobj=fileobj,
| ... path_in_repo="remote/file/path.h5",
| ... repo_id="username/my-dataset",
| ... repo_type="dataset",
| ... token="my_token",
| ... )
|
| >>> upload_file(
| ... path_or_fileobj=".\\local\\file\\path",
| ... path_in_repo="remote/file/path.h5",
| ... repo_id="username/my-model",
| ... token="my_token",
| ... )
|
| >>> upload_file(
| ... path_or_fileobj=".\\local\\file\\path",
| ... path_in_repo="remote/file/path.h5",
| ... repo_id="username/my-model",
| ... token="my_token",
| ... create_pr=True,
| ... )
| ```
|
| upload_folder(self, *, repo_id: 'str', folder_path: 'str | Path', path_in_repo: 'str | None' = None, commit_message: 'str | None' = None, commit_description: 'str | None' = None, token: 'str | bool | None' = None, repo_type: 'str | None' = None, revision: 'str | None' = None, create_pr: 'bool | None' = None, parent_commit: 'str | None' = None, allow_patterns: 'list[str] | str | None' = None, ignore_patterns: 'list[str] | str | None' = None, delete_patterns: 'list[str] | str | None' = None, run_as_future: 'bool' = False) -> 'CommitInfo | Future[CommitInfo]'
| Upload a local folder to the given repo. The upload is done through a HTTP requests, and doesn't require git or
| git-lfs to be installed.
|
| The structure of the folder will be preserved. Files with the same name already present in the repository will
| be overwritten. Others will be left untouched.
|
| Use the `allow_patterns` and `ignore_patterns` arguments to specify which files to upload. These parameters
| accept either a single pattern or a list of patterns. Patterns are Standard Wildcards (globbing patterns) as
| documented [here](https://tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm). If both `allow_patterns` and
| `ignore_patterns` are provided, both constraints apply. By default, all files from the folder are uploaded.
|
| Use the `delete_patterns` argument to specify remote files you want to delete. Input type is the same as for
| `allow_patterns` (see above). If `path_in_repo` is also provided, the patterns are matched against paths
| relative to this folder. For example, `upload_folder(..., path_in_repo="experiment", delete_patterns="logs/*")`
| will delete any remote file under `./experiment/logs/`. Note that the `.gitattributes` file will not be deleted
| even if it matches the patterns.
|
| Any `.git/` folder present in any subdirectory will be ignored. However, please be aware that the `.gitignore`
| file is not taken into account.
|
| When `hf_xet` is installed (the default), files are uploaded through a streamed pipeline: uploads start while
| the folder is still being checked against the Hub, files are hashed while being chunked for upload (single
| read pass), and large folders are automatically committed in several batches to stay below server limits
| (follow-up commits get a ` (part N)` suffix on the commit message). If the upload is interrupted, re-running
| the same call resumes it: already-committed files are skipped and already-uploaded data is deduplicated. When
| `hf_xet` is not installed, falls back to a single commit created with [`create_commit`].
|
| Args:
| repo_id (`str`):
| The repository to which the file will be uploaded, for example:
| `"username/custom_transformers"`
| folder_path (`str` or `Path`):
| Path to the folder to upload on the local file system
| path_in_repo (`str`, *optional*):
| Relative path of the directory in the repo, for example:
| `"checkpoints/1fec34a/results"`. Will default to the root folder of the repository.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| repo_type (`str`, *optional*):
| Set to `"dataset"` or `"space"` if uploading to a dataset or
| space, `None` or `"model"` if uploading to a model. Default is
| `None`.
| revision (`str`, *optional*):
| The git revision to commit from. Defaults to the head of the `"main"` branch.
| commit_message (`str`, *optional*):
| The summary / title / first line of the generated commit. Defaults to:
| `f"Upload {path_in_repo} with huggingface_hub"`
| commit_description (`str` *optional*):
| The description of the generated commit
| create_pr (`boolean`, *optional*):
| Whether or not to create a Pull Request with that commit. Defaults to `False`. The PR is always
| opened against the default branch: setting both `create_pr=True` and `revision` raises a
| `ValueError`. Note that each call with `create_pr=True` opens a new pull request: to resume an
| interrupted upload into the existing PR, re-run with `revision="refs/pr/N"` instead.
| parent_commit (`str`, *optional*):
| The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
| If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
| Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
| especially useful if the repo is updated / committed to concurrently. If the upload is split into
| several commits (large folders), `parent_commit` only applies to the first one.
| allow_patterns (`list[str]` or `str`, *optional*):
| If provided, only files matching at least one pattern are uploaded.
| ignore_patterns (`list[str]` or `str`, *optional*):
| If provided, files matching any of the patterns are not uploaded.
| delete_patterns (`list[str]` or `str`, *optional*):
| If provided, remote files matching any of the patterns will be deleted from the repo while committing
| new files. This is useful if you don't know which files have already been uploaded.
| Note: to avoid discrepancies the `.gitattributes` file is not deleted even if it matches the pattern.
| run_as_future (`bool`, *optional*):
| Whether or not to run this method in the background. Background jobs are run sequentially without
| blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects)
| object. Defaults to `False`.
|
| Returns:
| [`CommitInfo`] or `Future`:
| Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit
| url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will
| contain the result when executed.
|
| > [!TIP]
| > Raises the following errors:
| >
| > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
| > if the HuggingFace API returned an error
| > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| > if some parameter value is invalid
|
| > [!WARNING]
| > `upload_folder` assumes that the repo already exists on the Hub. If you get a Client error 404, please make
| > sure you are authenticated, that your token has the required permissions, and that `repo_id` and `repo_type`
| > are set correctly. If repo does not exist, create it first using [`~hf_api.create_repo`].
|
| Example:
|
| ```python
| # Upload checkpoints folder except the log files
| >>> upload_folder(
| ... folder_path="local/checkpoints",
| ... path_in_repo="remote/experiment/checkpoints",
| ... repo_id="username/my-dataset",
| ... repo_type="datasets",
| ... token="my_token",
| ... ignore_patterns="**/logs/*.txt",
| ... )
|
| # Upload checkpoints folder including logs while deleting existing logs from the repo
| # Useful if you don't know exactly which log files have already being pushed
| >>> upload_folder(
| ... folder_path="local/checkpoints",
| ... path_in_repo="remote/experiment/checkpoints",
| ... repo_id="username/my-dataset",
| ... repo_type="datasets",
| ... token="my_token",
| ... delete_patterns="**/logs/*.txt",
| ... )
|
| # Upload checkpoints folder while creating a PR
| >>> upload_folder(
| ... folder_path="local/checkpoints",
| ... path_in_repo="remote/experiment/checkpoints",
| ... repo_id="username/my-dataset",
| ... repo_type="datasets",
| ... token="my_token",
| ... create_pr=True,
| ... )
| ```
|
| upload_large_folder(self, repo_id: 'str', folder_path: 'str | Path', *, repo_type: 'str', revision: 'str | None' = None, private: 'bool | None' = None, allow_patterns: 'list[str] | str | None' = None, ignore_patterns: 'list[str] | str | None' = None, num_workers: 'int | None' = None, print_report: 'bool' = True, print_report_every: 'int' = 60) -> 'None'
| Upload a large folder to the Hub in the most resilient way possible.
|
| > [!WARNING]
| > `upload_large_folder` is deprecated and will be removed in a future release. [`upload_folder`] is now multi-commits
| > by default and resilient to interruptions so it is the recommended way to upload large folders.
|
| Several workers are started to upload files in an optimized way. Before being committed to a repo, files must be
| hashed and be pre-uploaded if they are LFS files. Workers will perform these tasks for each file in the folder.
| At each step, some metadata information about the upload process is saved in the folder under `.cache/.huggingface/`
| to be able to resume the process if interrupted. The whole process might result in several commits.
|
| Args:
| repo_id (`str`):
| The repository to which the file will be uploaded.
| E.g. `"HuggingFaceTB/smollm-corpus"`.
| folder_path (`str` or `Path`):
| Path to the folder to upload on the local file system.
| repo_type (`str`):
| Type of the repository. Must be one of `"model"`, `"dataset"` or `"space"`.
| Unlike in all other `HfApi` methods, `repo_type` is explicitly required here. This is to avoid
| any mistake when uploading a large folder to the Hub, and therefore prevent from having to re-upload
| everything.
| revision (`str`, `optional`):
| The branch to commit to. If not provided, the `main` branch will be used.
| private (`bool`, `optional`):
| Whether the repository should be private.
| If `None` (default), the repo will be public unless the organization's default is private.
| allow_patterns (`list[str]` or `str`, *optional*):
| If provided, only files matching at least one pattern are uploaded.
| ignore_patterns (`list[str]` or `str`, *optional*):
| If provided, files matching any of the patterns are not uploaded.
| num_workers (`int`, *optional*):
| Number of workers to start. Defaults to half of CPU cores (minimum 1).
| A higher number of workers may speed up the process if your machine allows it. However, on machines with a
| slower connection, it is recommended to keep the number of workers low to ensure better resumability.
| Indeed, partially uploaded files will have to be completely re-uploaded if the process is interrupted.
| print_report (`bool`, *optional*):
| Whether to print a report of the upload progress. Defaults to True.
| Report is printed to `sys.stdout` every X seconds (60 by defaults) and overwrites the previous report.
| print_report_every (`int`, *optional*):
| Frequency at which the report is printed. Defaults to 60 seconds.
|
| > [!TIP]
| > A few things to keep in mind:
| > - Repository limits still apply: https://huggingface.co/docs/hub/repositories-recommendations
| > - Do not start several processes in parallel.
| > - You can interrupt and resume the process at any time.
| > - Do not upload the same folder to several repositories. If you need to do so, you must delete the local `.cache/.huggingface/` folder first.
|
| > [!WARNING]
| > While being much more robust to upload large folders, `upload_large_folder` is more limited than [`upload_folder`] feature-wise. In practice:
| > - you cannot set a custom `path_in_repo`. If you want to upload to a subfolder, you need to set the proper structure locally.
| > - you cannot set a custom `commit_message` and `commit_description` since multiple commits are created.
| > - you cannot delete from the repo while uploading. Please make a separate commit first.
| > - you cannot create a PR directly. Please create a PR first (from the UI or using [`create_pull_request`]) and then commit to it by passing `revision`.
|
| **Technical details:**
|
| `upload_large_folder` process is as follow:
| 1. (Check parameters and setup.)
| 2. Create repo if missing.
| 3. List local files to upload.
| 4. Run validation checks and display warnings if repository limits might be exceeded:
| - Warns if the total number of files exceeds 100k (recommended limit).
| - Warns if any folder contains more than 10k files (recommended limit).
| - Warns about files larger than 20GB (recommended) or 50GB (hard limit).
| 5. Start workers. Workers can perform the following tasks:
| - Hash a file.
| - Get upload mode (regular or LFS) for a list of files.
| - Pre-upload an LFS file.
| - Commit a bunch of files.
| Once a worker finishes a task, it will move on to the next task based on the priority list (see below) until
| all files are uploaded and committed.
| 6. While workers are up, regularly print a report to sys.stdout.
|
| Order of priority:
| 1. Commit if more than 5 minutes since last commit attempt (and at least 1 file).
| 2. Commit if at least 150 files are ready to commit.
| 3. Get upload mode if at least 10 files have been hashed.
| 4. Pre-upload LFS file if at least 1 file and no worker is pre-uploading.
| 5. Hash file if at least 1 file and no worker is hashing.
| 6. Get upload mode if at least 1 file and no worker is getting upload mode.
| 7. Pre-upload LFS file if at least 1 file.
| 8. Hash file if at least 1 file to hash.
| 9. Get upload mode if at least 1 file to get upload mode.
| 10. Commit if at least 1 file to commit and at least 1 min since last commit attempt.
| 11. Commit if at least 1 file to commit and all other queues are empty.
|
| Special rules:
| - Only one worker can commit at a time.
| - If no tasks are available, the worker waits for 10 seconds before checking again.
|
| verify_repo_checksums(self, repo_id: 'str', *, repo_type: 'str | None' = None, revision: 'str | None' = None, local_dir: 'str | Path | None' = None, cache_dir: 'str | Path | None' = None, token: 'str | bool | None' = None) -> 'FolderVerification'
| Verify local files for a repo against Hub checksums.
|
| Args:
| repo_id (`str`):
| A namespace (user or an organization) and a repo name separated by a `/`.
| repo_type (`str`, *optional*):
| The type of the repository from which to get the tree (`"model"`, `"dataset"` or `"space"`.
| Defaults to `"model"`.
| revision (`str`, *optional*):
| The revision of the repository from which to get the tree. Defaults to `"main"` branch.
| local_dir (`str` or `Path`, *optional*):
| The local directory to verify.
| cache_dir (`str` or `Path`, *optional*):
| The cache directory to verify.
| token (Union[bool, str, None], optional):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
|
| Returns:
| [`FolderVerification`]: a structured result containing the verification details.
|
| Raises:
| [`~utils.RepositoryNotFoundError`]:
| If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
| does not exist.
| [`~utils.RevisionNotFoundError`]:
| If revision is not found (error 404) on the repo.
|
| wait_for_job(self, job_id: 'str | list[str]', *, timeout: 'float | None' = None, poll_interval: 'float' = 1.0, stages: 'list[JobStage] | None' = None, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'JobInfo | list[JobInfo]'
| Wait until one or more compute Jobs on Hugging Face infrastructure reach a given stage.
|
| Each Job status is polled (with [`inspect_job`]) every `poll_interval` seconds until its stage is one
| of `stages` (terminal stages by default: `"COMPLETED"`, `"CANCELED"`, `"ERROR"` or `"DELETED"`). The
| final [`JobInfo`] is returned in all cases: a failed or canceled Job does **not** raise an exception —
| check `job.status.stage` to act on the outcome.
|
| Terminal stages always stop the wait, even when not listed in `stages`. This avoids waiting forever for
| a stage the Job will never reach (e.g. waiting for `"RUNNING"` on a Job that fails during scheduling).
|
| Args:
| job_id (`str` or `list[str]`):
| ID of the Job, or a list of Job IDs to wait for. If a list is passed, a list of [`JobInfo`]
| is returned (in the same order).
|
| timeout (`float`, *optional*):
| The maximum time to wait for the Job(s) to finish, in seconds. If `None`, will wait
| indefinitely.
|
| poll_interval (`float`, *optional*):
| The time to wait between each status check, in seconds. Defaults to 1s.
|
| stages (`list[JobStage]`, *optional*):
| The stages to wait for. Defaults to the terminal stages (`"COMPLETED"`, `"CANCELED"`,
| `"ERROR"`, `"DELETED"`). Pass e.g. `[JobStage.RUNNING]` to wait for the Job to start running.
| Terminal stages always stop the wait regardless of this value.
|
| namespace (`str`, *optional*):
| The namespace where the Job(s) are running. Defaults to the current user's namespace.
|
| token `(Union[bool, str, None]`, *optional*):
| A valid user access token. If not provided, the locally saved token will be used, which is the
| recommended authentication method. Set to `False` to disable authentication.
| Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
|
| Returns:
| [`JobInfo`] or `list[JobInfo]`: the final Job info(s).
|
| Raises:
| `TimeoutError`:
| If at least one Job has not reached one of the target stages after `timeout` seconds.
|
| Example:
|
| ```python
| >>> from huggingface_hub import run_job, wait_for_job
| >>> job = run_job(image="python:3.12", command=["python", "-c", "print('Hello from HF compute!')"])
| >>> wait_for_job(job_id=job.id).status.stage
| 'COMPLETED'
| ```
|
| wait_for_space(self, repo_id: 'str', *, timeout: 'float | None' = None, poll_interval: 'float' = 1.0, token: 'bool | str | None' = None) -> 'SpaceRuntime'
| Wait until a Space reaches a terminal stage (not building/starting).
|
| Polls [`get_space_runtime`] every `poll_interval` seconds until the Space's stage
| is no longer intermediate (`BUILDING`, `RUNNING_BUILDING`, `APP_STARTING`,
| `RUNNING_APP_STARTING`). Returns the final [`SpaceRuntime`] in all cases — check
| `runtime.stage` to act on the outcome (e.g. `RUNNING` vs `BUILD_ERROR`).
|
| Args:
| repo_id (`str`):
| ID of the Space to wait for. Example: `"username/my-space"`.
| timeout (`float`, *optional*):
| Maximum time to wait in seconds. If `None`, waits indefinitely.
| poll_interval (`float`, *optional*):
| Seconds between status checks. Defaults to 1s.
| token (`bool` or `str`, *optional*):
| A valid user access token. Defaults to the locally saved token, which is the
| recommended authentication method. Set to `False` to disable authentication.
| See https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
|
| Returns:
| [`SpaceRuntime`]: The final runtime information once the Space reaches a terminal stage.
|
| Raises:
| `TimeoutError`:
| If the Space has not reached a terminal stage after `timeout` seconds.
|
| Example:
|
| ```python
| >>> from huggingface_hub import restart_space, wait_for_space
| >>> restart_space("username/my-space")
| >>> runtime = wait_for_space("username/my-space")
| >>> runtime.stage
| 'RUNNING'
| ```
|
| whoami(self, token: 'bool | str | None' = None, *, cache: 'bool' = False) -> 'dict'
| Call HF API to know "whoami".
|
| If passing `cache=True`, the result will be cached for subsequent calls for the duration of the Python process. This is useful if you plan to call
| `whoami` multiple times as this endpoint is heavily rate-limited for security reasons.
|
| Args:
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| cache (`bool`, *optional*):
| Whether to cache the result of the `whoami` call for subsequent calls.
| If an error occurs during the first call, it won't be cached.
| Defaults to `False`.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
huggingface-hub.HfFileMetadata
Python Library Documentation: class HfFileMetadata in module huggingface_hub.file_download
class HfFileMetadata(builtins.object)
| HfFileMetadata(commit_hash: str | None, etag: str | None, location: str, size: int | None, xet_file_data: huggingface_hub.utils._xet.XetFileData | None) -> None
|
| Data structure containing information about a file versioned on the Hub.
|
| Returned by [`get_hf_file_metadata`] based on a URL.
|
| Args:
| commit_hash (`str`, *optional*):
| The commit_hash related to the file.
| etag (`str`, *optional*):
| Etag of the file on the server.
| location (`str`):
| Location where to download the file. Can be a Hub url or not (CDN).
| size (`size`):
| Size of the file. In case of an LFS file, contains the size of the actual
| LFS file, not the pointer.
| xet_file_data (`XetFileData`, *optional*):
| Xet information for the file. This is only set if the file is stored using Xet storage.
|
| Methods defined here:
|
| __delattr__(self, name)
| Implement delattr(self, name).
|
| __eq__(self, other)
| Return self==value.
|
| __hash__(self)
| Return hash(self).
|
| __init__(self, commit_hash: str | None, etag: str | None, location: str, size: int | None, xet_file_data: huggingface_hub.utils._xet.XetFileData | None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| __setattr__(self, name, value)
| Implement setattr(self, name, value).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'commit_hash': str | None, 'etag': str | None, 'loc...
|
| __dataclass_fields__ = {'commit_hash': Field(name='commit_hash',type=s...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __match_args__ = ('commit_hash', 'etag', 'location', 'size', 'xet_file...
huggingface-hub.HfFileSystem
Python Library Documentation: class HfFileSystem in module huggingface_hub.hf_file_system
class HfFileSystem(fsspec.spec.AbstractFileSystem)
| HfFileSystem(*args, **kwargs)
|
| Access a remote Hugging Face Hub repository as if were a local file system.
|
| > [!WARNING]
| > [`HfFileSystem`] provides fsspec compatibility, which is useful for libraries that require it (e.g., reading
| > Hugging Face datasets directly with `pandas`). However, it introduces additional overhead due to this compatibility
| > layer. For better performance and reliability, it's recommended to use `HfApi` methods when possible.
|
| The file system supports paths for the `hf://` protocol, which follows those URL schemes:
|
| * Models, Datasets and Spaces repositories:
|
| ```
| hf://<repo-id>[@<revision>]/<path/in/repo>
| hf://datasets/<repo-id>[@<revision>]/<path/in/repo>
| hf://spaces/<repo-id>[@<revision>]/<path/in/repo>
| ```
|
| * Buckets (generic storage):
|
| ```
| hf://buckets/<bucket-id>/<path/in/bucket>
| ```
|
| Note: when using the [`HfFileSystem`] directly, passing the `hf://` protocol prefix is optional in paths.
|
| Args:
| endpoint (`str`, *optional*):
| Endpoint of the Hub. Defaults to <https://huggingface.co>.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| block_size (`int`, *optional*):
| Block size for reading and writing files.
| expand_info (`bool`, *optional*):
| Whether to expand the information of the files.
| **storage_options (`dict`, *optional*):
| Additional options for the filesystem. See [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.__init__).
|
| Usage:
|
| ```python
| >>> from huggingface_hub import hffs
|
| >>> # List files
| >>> hffs.glob("my-username/my-model/*.bin")
| ['my-username/my-model/pytorch_model.bin']
| >>> hffs.ls("datasets/my-username/my-dataset", detail=False)
| ['datasets/my-username/my-dataset/.gitattributes', 'datasets/my-username/my-dataset/README.md', 'datasets/my-username/my-dataset/data.json']
|
| >>> # Read/write files
| >>> with hffs.open("my-username/my-model/pytorch_model.bin") as f:
| ... data = f.read()
| >>> with hffs.open("my-username/my-model/pytorch_model.bin", "wb") as f:
| ... f.write(data)
| ```
|
| Specify a token for authentication:
| ```python
| >>> from huggingface_hub import HfFileSystem
| >>> hffs = HfFileSystem(token=token)
| ```
|
| Method resolution order:
| HfFileSystem
| fsspec.spec.AbstractFileSystem
| builtins.object
|
| Methods defined here:
|
| __init__(self, *args, endpoint: str | None = None, token: bool | str | None = None, block_size: int | None = None, expand_info: bool | None = None, **storage_options)
| Create and configure file-system instance
|
| Instances may be cachable, so if similar enough arguments are seen
| a new instance is not required. The token attribute exists to allow
| implementations to cache instances if they wish.
|
| A reasonable default should be provided if there are no arguments.
|
| Subclasses should call this method.
|
| Parameters
| ----------
| use_listings_cache, listings_expiry_time, max_paths:
| passed to ``DirCache``, if the implementation supports
| directory listing caching. Pass use_listings_cache=False
| to disable such caching.
| skip_instance_cache: bool
| If this is a cachable implementation, pass True here to force
| creating a new instance even if a matching instance exists, and prevent
| storing this instance.
| asynchronous: bool
| loop: asyncio-compatible IOLoop or None
|
| __reduce__(self)
| Helper for pickle.
|
| cp_file(self, path1: str, path2: str, revision: str | None = None, **kwargs) -> None
| Copy a file within or between repositories.
|
| > [!WARNING]
| > Note: When possible, use `HfApi.upload_file()` for better performance.
|
| Args:
| path1 (`str`):
| Source path to copy from.
| path2 (`str`):
| Destination path to copy to.
| revision (`str`, *optional*):
| The git revision to copy from.
|
| exists(self, path, **kwargs)
| Check if a file exists.
|
| For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.exists).
|
| > [!WARNING]
| > Note: When possible, use `HfApi.file_exists()` for better performance.
|
| Args:
| path (`str`):
| Path to check.
|
| Returns:
| `bool`: True if file exists, False otherwise.
|
| find(self, path: str, maxdepth: int | None = None, withdirs: bool = False, detail: bool = False, refresh: bool = False, revision: str | None = None, **kwargs) -> list[str] | dict[str, dict[str, typing.Any]]
| List all files below path.
|
| For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.find).
|
| Args:
| path (`str`):
| Root path to list files from.
| maxdepth (`int`, *optional*):
| Maximum depth to descend into subdirectories.
| withdirs (`bool`, *optional*):
| Include directory paths in the output. Defaults to False.
| detail (`bool`, *optional*):
| If True, returns a dict mapping paths to file information. Defaults to False.
| refresh (`bool`, *optional*):
| If True, bypass the cache and fetch the latest data. Defaults to False.
| revision (`str`, *optional*):
| The git revision to list from.
|
| Returns:
| `Union[list[str], dict[str, dict[str, Any]]]`: List of paths or dict of file information.
|
| get_file(self, rpath, lpath, callback=<fsspec.callbacks.NoOpCallback object at 0x000001F176839970>, outfile=None, **kwargs) -> None
| Copy single remote file to local.
|
| > [!WARNING]
| > Note: When possible, use `HfApi.hf_hub_download()` or `HfApi.download_bucket_files` for better performance.
|
| Args:
| rpath (`str`):
| Remote path to download from.
| lpath (`str`):
| Local path to download to.
| callback (`Callback`, *optional*):
| Optional callback to track download progress. Defaults to no callback.
| outfile (`IO`, *optional*):
| Optional file-like object to write to. If provided, `lpath` is ignored.
|
| glob(self, path: str, maxdepth: int | None = None, **kwargs) -> list[str]
| Find files by glob-matching.
|
| For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.glob).
|
| Args:
| path (`str`):
| Path pattern to match.
| maxdepth (`int`, *optional*):
| Maximum depth to descend into directories. By default, no limit.
|
| Returns:
| `list[str]`: List of paths matching the pattern.
|
| info(self, path: str, refresh: bool = False, revision: str | None = None, **kwargs) -> dict[str, typing.Any]
| Get information about a file or directory.
|
| For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.info).
|
| > [!WARNING]
| > Note: When possible, use `HfApi.get_paths_info()` or `HfApi.repo_info()` for better performance
| > (or `HfApi.get_bucket_paths_info()` or `HfApi.bucket_info()` for buckets)
|
| Args:
| path (`str`):
| Path to get info for.
| refresh (`bool`, *optional*):
| If True, bypass the cache and fetch the latest data. Defaults to False.
| revision (`str`, *optional*):
| The git revision to get info from.
|
| Returns:
| `dict[str, Any]`: Dictionary containing file information (type, size, commit info, etc.).
|
| invalidate_cache(self, path: str | None = None) -> None
| Clear the cache for a given path.
|
| For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.invalidate_cache).
|
| Args:
| path (`str`, *optional*):
| Path to clear from cache. If not provided, clear the entire cache.
|
| isdir(self, path)
| Check if a path is a directory.
|
| For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.isdir).
|
| Args:
| path (`str`):
| Path to check.
|
| Returns:
| `bool`: True if path is a directory, False otherwise.
|
| isfile(self, path)
| Check if a path is a file.
|
| For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.isfile).
|
| Args:
| path (`str`):
| Path to check.
|
| Returns:
| `bool`: True if path is a file, False otherwise.
|
| ls(self, path: str, detail: bool = True, refresh: bool = False, revision: str | None = None, **kwargs) -> list[str | dict[str, typing.Any]]
| List the contents of a directory.
|
| For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.ls).
|
| > [!WARNING]
| > Note: When possible, use `HfApi.list_repo_tree()` for better performance.
|
| Args:
| path (`str`):
| Path to the directory.
| detail (`bool`, *optional*):
| If True, returns a list of dictionaries containing file information. If False,
| returns a list of file paths. Defaults to True.
| refresh (`bool`, *optional*):
| If True, bypass the cache and fetch the latest data. Defaults to False.
| revision (`str`, *optional*):
| The git revision to list from.
|
| Returns:
| `list[Union[str, dict[str, Any]]]`: List of file paths (if detail=False) or list of file information
| dictionaries (if detail=True).
|
| modified(self, path: str, **kwargs) -> datetime.datetime
| Get the last modified time of a file.
|
| For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.modified).
|
| Args:
| path (`str`):
| Path to the file.
|
| Returns:
| `datetime`: Last modified time of the file.
|
| resolve_path(self, path: str, revision: str | None = None) -> huggingface_hub.hf_file_system.HfFileSystemResolvedRepositoryPath | huggingface_hub.hf_file_system.HfFileSystemResolvedBucketPath
| Resolve a Hugging Face file system path into its components.
|
| Args:
| path (`str`):
| Path to resolve.
| revision (`str`, *optional*):
| The revision of the repo to resolve. Defaults to the revision specified in the path.
|
| Returns:
| [`HfFileSystemResolvedPath`]: Resolved path information containing `repo_type`, `repo_id`, `revision` and `path_in_repo`.
|
| Raises:
| `ValueError`:
| If path contains conflicting revision information.
| `NotImplementedError`:
| If trying to list repositories.
|
| rm(self, path: str, recursive: bool = False, maxdepth: int | None = None, revision: str | None = None, **kwargs) -> None
| Delete files from a repository.
|
| For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.rm).
|
| > [!WARNING]
| > Note: When possible, use `HfApi.delete_file()` for better performance.
|
| Args:
| path (`str`):
| Path to delete.
| recursive (`bool`, *optional*):
| If True, delete directory and all its contents. Defaults to False.
| maxdepth (`int`, *optional*):
| Maximum number of subdirectories to visit when deleting recursively.
| revision (`str`, *optional*):
| The git revision to delete from.
|
| start_transaction(self)
| Begin write transaction for deferring files, non-context version
|
| url(self, path: str) -> str
| Get the HTTP URL of the given path.
|
| Args:
| path (`str`):
| Path to get URL for.
|
| Returns:
| `str`: HTTP URL to access the file or directory on the Hub.
|
| walk(self, path: str, *args, **kwargs) -> collections.abc.Iterator[tuple[str, list[str], list[str]]]
| Return all files below the given path.
|
| For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.walk).
|
| Args:
| path (`str`):
| Root path to list files from.
|
| Returns:
| `Iterator[tuple[str, list[str], list[str]]]`: An iterator of (path, list of directory names, list of file names) tuples.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| transaction
| A context within which files are committed together upon exit
|
| Requires the file class to implement `.commit()` and `.discard()`
| for the normal and exception cases.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| protocol = 'hf'
|
| root_marker = ''
|
| ----------------------------------------------------------------------
| Methods inherited from fsspec.spec.AbstractFileSystem:
|
| __dask_tokenize__(self)
|
| __eq__(self, other)
| Return self==value.
|
| __hash__(self)
| Return hash(self).
|
| cat(self, path, recursive=False, on_error='raise', **kwargs)
| Fetch (potentially multiple) paths' contents
|
| Parameters
| ----------
| recursive: bool
| If True, assume the path(s) are directories, and get all the
| contained files
| on_error : "raise", "omit", "return"
| If raise, an underlying exception will be raised (converted to KeyError
| if the type is in self.missing_exceptions); if omit, keys with exception
| will simply not be included in the output; if "return", all keys are
| included in the output, but the value will be bytes or an exception
| instance.
| kwargs: passed to cat_file
|
| Returns
| -------
| dict of {path: contents} if there are multiple paths
| or the path has been otherwise expanded
|
| cat_file(self, path, start=None, end=None, **kwargs)
| Get the content of a file
|
| Parameters
| ----------
| path: URL of file on this filesystems
| start, end: int
| Bytes limits of the read. If negative, backwards from end,
| like usual python slices. Either can be None for start or
| end of file, respectively
| kwargs: passed to ``open()``.
|
| cat_ranges(self, paths, starts, ends, max_gap=None, on_error='return', **kwargs)
| Get the contents of byte ranges from one or more files
|
| Parameters
| ----------
| paths: list
| A list of of filepaths on this filesystems
| starts, ends: int or list
| Bytes limits of the read. If using a single int, the same value will be
| used to read all the specified files.
|
| checksum(self, path)
| Unique value for current version of file
|
| If the checksum is the same from one moment to another, the contents
| are guaranteed to be the same. If the checksum changes, the contents
| *might* have changed.
|
| This should normally be overridden; default will probably capture
| creation/modification timestamp (which would be good) or maybe
| access timestamp (which would be bad)
|
| copy(self, path1, path2, recursive=False, maxdepth=None, on_error=None, **kwargs)
| Copy within two locations in the filesystem
|
| on_error : "raise", "ignore"
| If raise, any not-found exceptions will be raised; if ignore any
| not-found exceptions will cause the path to be skipped; defaults to
| raise unless recursive is true, where the default is ignore
|
| cp(self, path1, path2, **kwargs)
| Alias of `AbstractFileSystem.copy`.
|
| created(self, path)
| Return the created timestamp of a file as a datetime.datetime
|
| delete(self, path, recursive=False, maxdepth=None)
| Alias of `AbstractFileSystem.rm`.
|
| disk_usage(self, path, total=True, maxdepth=None, **kwargs)
| Alias of `AbstractFileSystem.du`.
|
| download(self, rpath, lpath, recursive=False, **kwargs)
| Alias of `AbstractFileSystem.get`.
|
| du(self, path, total=True, maxdepth=None, withdirs=False, **kwargs)
| Space used by files and optionally directories within a path
|
| Directory size does not include the size of its contents.
|
| Parameters
| ----------
| path: str
| total: bool
| Whether to sum all the file sizes
| maxdepth: int or None
| Maximum number of directory levels to descend, None for unlimited.
| withdirs: bool
| Whether to include directory paths in the output.
| kwargs: passed to ``find``
|
| Returns
| -------
| Dict of {path: size} if total=False, or int otherwise, where numbers
| refer to bytes used.
|
| end_transaction(self)
| Finish write transaction, non-context version
|
| expand_path(self, path, recursive=False, maxdepth=None, assume_literal=False, **kwargs)
| Turn one or more globs or directories into a list of all matching paths
| to files or directories.
|
| kwargs are passed to ``glob`` or ``find``, which may in turn call ``ls``
|
| get(self, rpath, lpath, recursive=False, callback=<fsspec.callbacks.NoOpCallback object at 0x000001F176839970>, maxdepth=None, **kwargs)
| Copy file(s) to local.
|
| Copies a specific file or tree of files (if recursive=True). If lpath
| ends with a "/", it will be assumed to be a directory, and target files
| will go within. Can submit a list of paths, which may be glob-patterns
| and will be expanded.
|
| Calls get_file for each source.
|
| get_mapper(self, root='', check=False, create=False, missing_exceptions=None)
| Create key/value store based on this file-system
|
| Makes a MutableMapping interface to the FS at the given root path.
| See ``fsspec.mapping.FSMap`` for further details.
|
| head(self, path, size=1024)
| Get the first ``size`` bytes from file
|
| lexists(self, path, **kwargs)
| If there is a file at the given path (including
| broken links)
|
| listdir(self, path, detail=True, **kwargs)
| Alias of `AbstractFileSystem.ls`.
|
| makedir(self, path, create_parents=True, **kwargs)
| Alias of `AbstractFileSystem.mkdir`.
|
| makedirs(self, path, exist_ok=False)
| Recursively make directories
|
| Creates directory at path and any intervening required directories.
| Raises exception if, for instance, the path already exists but is a
| file.
|
| Parameters
| ----------
| path: str
| leaf directory name
| exist_ok: bool (False)
| If False, will error if the target already exists
|
| mkdir(self, path, create_parents=True, **kwargs)
| Create directory entry at path
|
| For systems that don't have true directories, may create an for
| this instance only and not touch the real filesystem
|
| Parameters
| ----------
| path: str
| location
| create_parents: bool
| if True, this is equivalent to ``makedirs``
| kwargs:
| may be permissions, etc.
|
| mkdirs(self, path, exist_ok=False)
| Alias of `AbstractFileSystem.makedirs`.
|
| move(self, path1, path2, **kwargs)
| Alias of `AbstractFileSystem.mv`.
|
| mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs)
| Move file(s) from one location to another
|
| open(self, path, mode='rb', block_size=None, cache_options=None, compression=None, **kwargs)
| Return a file-like object from the filesystem
|
| The resultant instance must function correctly in a context ``with``
| block.
|
| Parameters
| ----------
| path: str
| Target file
| mode: str like 'rb', 'w'
| See builtin ``open()``
| Mode "x" (exclusive write) may be implemented by the backend. Even if
| it is, whether it is checked up front or on commit, and whether it is
| atomic is implementation-dependent.
| block_size: int
| Some indication of buffering - this is a value in bytes
| cache_options : dict, optional
| Extra arguments to pass through to the cache.
| compression: string or None
| If given, open file using compression codec. Can either be a compression
| name (a key in ``fsspec.compression.compr``) or "infer" to guess the
| compression from the filename suffix.
| encoding, errors, newline: passed on to TextIOWrapper for text mode
|
| pipe(self, path, value=None, **kwargs)
| Put value into path
|
| (counterpart to ``cat``)
|
| Parameters
| ----------
| path: string or dict(str, bytes)
| If a string, a single remote location to put ``value`` bytes; if a dict,
| a mapping of {path: bytesvalue}.
| value: bytes, optional
| If using a single path, these are the bytes to put there. Ignored if
| ``path`` is a dict
|
| pipe_file(self, path, value, mode='overwrite', **kwargs)
| Set the bytes of given file
|
| put(self, lpath, rpath, recursive=False, callback=<fsspec.callbacks.NoOpCallback object at 0x000001F176839970>, maxdepth=None, **kwargs)
| Copy file(s) from local.
|
| Copies a specific file or tree of files (if recursive=True). If rpath
| ends with a "/", it will be assumed to be a directory, and target files
| will go within.
|
| Calls put_file for each source.
|
| put_file(self, lpath, rpath, callback=<fsspec.callbacks.NoOpCallback object at 0x000001F176839970>, mode='overwrite', **kwargs)
| Copy single file to remote
|
| read_block(self, fn, offset, length, delimiter=None)
| Read a block of bytes from
|
| Starting at ``offset`` of the file, read ``length`` bytes. If
| ``delimiter`` is set then we ensure that the read starts and stops at
| delimiter boundaries that follow the locations ``offset`` and ``offset
| + length``. If ``offset`` is zero then we start at zero. The
| bytestring returned WILL include the end delimiter string.
|
| If offset+length is beyond the eof, reads to eof.
|
| Parameters
| ----------
| fn: string
| Path to filename
| offset: int
| Byte offset to start read
| length: int
| Number of bytes to read. If None, read to end.
| delimiter: bytes (optional)
| Ensure reading starts and stops at delimiter bytestring
|
| Examples
| --------
| >>> fs.read_block('data/file.csv', 0, 13) # doctest: +SKIP
| b'Alice, 100\nBo'
| >>> fs.read_block('data/file.csv', 0, 13, delimiter=b'\n') # doctest: +SKIP
| b'Alice, 100\nBob, 200\n'
|
| Use ``length=None`` to read to the end of the file.
| >>> fs.read_block('data/file.csv', 0, None, delimiter=b'\n') # doctest: +SKIP
| b'Alice, 100\nBob, 200\nCharlie, 300'
|
| See Also
| --------
| :func:`fsspec.utils.read_block`
|
| read_bytes(self, path, start=None, end=None, **kwargs)
| Alias of `AbstractFileSystem.cat_file`.
|
| read_text(self, path, encoding=None, errors=None, newline=None, **kwargs)
| Get the contents of the file as a string.
|
| Parameters
| ----------
| path: str
| URL of file on this filesystems
| encoding, errors, newline: same as `open`.
|
| rename(self, path1, path2, **kwargs)
| Alias of `AbstractFileSystem.mv`.
|
| rm_file(self, path)
| Delete a file
|
| rmdir(self, path)
| Remove a directory, if empty
|
| sign(self, path, expiration=100, **kwargs)
| Create a signed URL representing the given path
|
| Some implementations allow temporary URLs to be generated, as a
| way of delegating credentials.
|
| Parameters
| ----------
| path : str
| The path on the filesystem
| expiration : int
| Number of seconds to enable the URL for (if supported)
|
| Returns
| -------
| URL : str
| The signed URL
|
| Raises
| ------
| NotImplementedError : if method is not implemented for a filesystem
|
| size(self, path)
| Size in bytes of file
|
| sizes(self, paths)
| Size in bytes of each file in a list of paths
|
| stat(self, path, **kwargs)
| Alias of `AbstractFileSystem.info`.
|
| tail(self, path, size=1024)
| Get the last ``size`` bytes from file
|
| to_dict(self, *, include_password: 'bool' = True) -> 'dict[str, Any]'
| JSON-serializable dictionary representation of this filesystem instance.
|
| Parameters
| ----------
| include_password: bool, default True
| Whether to include the password (if any) in the output.
|
| Returns
| -------
| Dictionary with keys ``cls`` (the python location of this class),
| protocol (text name of this class's protocol, first one in case of
| multiple), ``args`` (positional args, usually empty), and all other
| keyword arguments as their own keys.
|
| Warnings
| --------
| Serialized filesystems may contain sensitive information which have been
| passed to the constructor, such as passwords and tokens. Make sure you
| store and send them in a secure environment!
|
| to_json(self, *, include_password: 'bool' = True) -> 'str'
| JSON representation of this filesystem instance.
|
| Parameters
| ----------
| include_password: bool, default True
| Whether to include the password (if any) in the output.
|
| Returns
| -------
| JSON string with keys ``cls`` (the python location of this class),
| protocol (text name of this class's protocol, first one in case of
| multiple), ``args`` (positional args, usually empty), and all other
| keyword arguments as their own keys.
|
| Warnings
| --------
| Serialized filesystems may contain sensitive information which have been
| passed to the constructor, such as passwords and tokens. Make sure you
| store and send them in a secure environment!
|
| touch(self, path, truncate=True, **kwargs)
| Create empty file, or update timestamp
|
| Parameters
| ----------
| path: str
| file location
| truncate: bool
| If True, always set file size to 0; if False, update timestamp and
| leave file unchanged, if backend allows this
|
| tree(self, path: 'str' = '/', recursion_limit: 'int' = 2, max_display: 'int' = 25, display_size: 'bool' = False, prefix: 'str' = '', is_last: 'bool' = True, first: 'bool' = True, indent_size: 'int' = 4) -> 'str'
| Return a tree-like structure of the filesystem starting from the given path as a string.
|
| Parameters
| ----------
| path: Root path to start traversal from
| recursion_limit: Maximum depth of directory traversal
| max_display: Maximum number of items to display per directory
| display_size: Whether to display file sizes
| prefix: Current line prefix for visual tree structure
| is_last: Whether current item is last in its level
| first: Whether this is the first call (displays root path)
| indent_size: Number of spaces by indent
|
| Returns
| -------
| str: A string representing the tree structure.
|
| Example
| -------
| >>> from fsspec import filesystem
|
| >>> fs = filesystem('ftp', host='test.rebex.net', user='demo', password='password')
| >>> tree = fs.tree(display_size=True, recursion_limit=3, indent_size=8, max_display=10)
| >>> print(tree)
|
| ukey(self, path)
| Hash of file properties, to tell if it has changed
|
| unstrip_protocol(self, name: 'str') -> 'str'
| Format FS-specific path to generic, including protocol
|
| upload(self, lpath, rpath, recursive=False, **kwargs)
| Alias of `AbstractFileSystem.put`.
|
| write_bytes(self, path, value, **kwargs)
| Alias of `AbstractFileSystem.pipe_file`.
|
| write_text(self, path, value, encoding=None, errors=None, newline=None, **kwargs)
| Write the text to the given file.
|
| An existing file will be overwritten.
|
| Parameters
| ----------
| path: str
| URL of file on this filesystems
| value: str
| Text to write.
| encoding, errors, newline: same as `open`.
|
| ----------------------------------------------------------------------
| Class methods inherited from fsspec.spec.AbstractFileSystem:
|
| clear_instance_cache()
| Clear the cache of filesystem instances.
|
| Notes
| -----
| Unless overridden by setting the ``cachable`` class attribute to False,
| the filesystem class stores a reference to newly created instances. This
| prevents Python's normal rules around garbage collection from working,
| since the instances refcount will not drop to zero until
| ``clear_instance_cache`` is called.
|
| current()
| Return the most recently instantiated FileSystem
|
| If no instance has been created, then create one with defaults
|
| ----------------------------------------------------------------------
| Static methods inherited from fsspec.spec.AbstractFileSystem:
|
| from_dict(dct: 'dict[str, Any]') -> 'AbstractFileSystem'
| Recreate a filesystem instance from dictionary representation.
|
| See ``.to_dict()`` for the expected structure of the input.
|
| Parameters
| ----------
| dct: Dict[str, Any]
|
| Returns
| -------
| file system instance, not necessarily of this particular class.
|
| Warnings
| --------
| This can import arbitrary modules (as determined by the ``cls`` key).
| Make sure you haven't installed any modules that may execute malicious code
| at import time.
|
| from_json(blob: 'str') -> 'AbstractFileSystem'
| Recreate a filesystem instance from JSON representation.
|
| See ``.to_json()`` for the expected structure of the input.
|
| Parameters
| ----------
| blob: str
|
| Returns
| -------
| file system instance, not necessarily of this particular class.
|
| Warnings
| --------
| This can import arbitrary modules (as determined by the ``cls`` key).
| Make sure you haven't installed any modules that may execute malicious code
| at import time.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from fsspec.spec.AbstractFileSystem:
|
| fsid
| Persistent filesystem id that can be used to compare filesystems
| across sessions.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from fsspec.spec.AbstractFileSystem:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from fsspec.spec.AbstractFileSystem:
|
| async_impl = False
|
| blocksize = 4194304
|
| cachable = True
|
| mirror_sync_methods = False
|
| sep = '/'
|
| transaction_type = <class 'fsspec.transaction.Transaction'>
| Filesystem transaction write context
|
| Gathers files for deferred commit or discard, so that several write
| operations can be finalized semi-atomically. This works by having this
| instance as the ``.transaction`` attribute of the given filesystem
huggingface-hub.HfFileSystemFile
Python Library Documentation: class HfFileSystemFile in module huggingface_hub.hf_file_system
class HfFileSystemFile(fsspec.spec.AbstractBufferedFile)
| HfFileSystemFile(fs: huggingface_hub.hf_file_system.HfFileSystem, path: str, revision: str | None = None, **kwargs)
|
| Method resolution order:
| HfFileSystemFile
| fsspec.spec.AbstractBufferedFile
| io.IOBase
| _io._IOBase
| builtins.object
|
| Methods defined here:
|
| __del__(self)
|
| __init__(self, fs: huggingface_hub.hf_file_system.HfFileSystem, path: str, revision: str | None = None, **kwargs)
| Template for files with buffered reading and writing
|
| Parameters
| ----------
| fs: instance of FileSystem
| path: str
| location in file-system
| mode: str
| Normal file modes. Currently only 'wb', 'ab' or 'rb'. Some file
| systems may be read-only, and some may not support append.
| block_size: int
| Buffer size for reading or writing, 'default' for class default
| autocommit: bool
| Whether to write to final destination; may only impact what
| happens when file is being closed.
| cache_type: {"readahead", "none", "mmap", "bytes"}, default "readahead"
| Caching policy in read mode. See the definitions in ``core``.
| cache_options : dict
| Additional options passed to the constructor for the cache specified
| by `cache_type`.
| size: int
| If given and in read mode, suppressed having to look up the file size
| kwargs:
| Gets stored as self.kwargs
|
| read(self, length=-1)
| Read remote file.
|
| If `length` is not provided or is -1, the entire file is downloaded and read. On POSIX systems the file is
| loaded in memory directly. Otherwise, the file is downloaded to a temporary file and read from there.
|
| url(self) -> str
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| ----------------------------------------------------------------------
| Methods inherited from fsspec.spec.AbstractBufferedFile:
|
| __enter__(self)
|
| __eq__(self, other)
| Files are equal if they have the same checksum, only in read mode
|
| __exit__(self, *args)
|
| __hash__(self)
| Return hash(self).
|
| __iter__(self)
| Implement iter(self).
|
| __next__(self)
| Implement next(self).
|
| __reduce__(self)
| Helper for pickle.
|
| __repr__ = __str__(self)
|
| __str__(self)
| Return str(self).
|
| close(self)
| Close file
|
| Finalizes writes, discards cache
|
| commit(self)
| Move from temp to final destination
|
| discard(self)
| Throw away temporary file
|
| flush(self, force=False)
| Write buffered data to backend store.
|
| Writes the current buffer, if it is larger than the block-size, or if
| the file is being closed.
|
| Parameters
| ----------
| force: bool
| When closing, write the last block even if it is smaller than
| blocks are allowed to be. Disallows further writing to this file.
|
| info(self)
| File information about this path
|
| readable(self)
| Whether opened for reading
|
| readinto(self, b)
| mirrors builtin file's readinto method
|
| https://docs.python.org/3/library/io.html#io.RawIOBase.readinto
|
| readinto1(self, b)
|
| readline(self)
| Read until and including the first occurrence of newline character
|
| Note that, because of character encoding, this is not necessarily a
| true line ending.
|
| readlines(self)
| Return all data, split by the newline character, including the newline character
|
| readuntil(self, char=b'\n', blocks=None)
| Return data between current position and first occurrence of char
|
| char is included in the output, except if the end of the tile is
| encountered first.
|
| Parameters
| ----------
| char: bytes
| Thing to find
| blocks: None or int
| How much to read in each go. Defaults to file blocksize - which may
| mean a new read on every call.
|
| seek(self, loc, whence=0)
| Set current file location
|
| Parameters
| ----------
| loc: int
| byte location
| whence: {0, 1, 2}
| from start of file, current location or end of file, resp.
|
| seekable(self)
| Whether is seekable (only in read mode)
|
| tell(self)
| Current file location
|
| writable(self)
| Whether opened for writing
|
| write(self, data)
| Write data to buffer.
|
| Buffer only sent on flush() or if buffer is greater than
| or equal to blocksize.
|
| Parameters
| ----------
| data: bytes
| Set of bytes to be written.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from fsspec.spec.AbstractBufferedFile:
|
| full_name
|
| ----------------------------------------------------------------------
| Data descriptors inherited from fsspec.spec.AbstractBufferedFile:
|
| closed
|
| details
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from fsspec.spec.AbstractBufferedFile:
|
| DEFAULT_BLOCK_SIZE = 5242880
|
| ----------------------------------------------------------------------
| Methods inherited from _io._IOBase:
|
| fileno(self, /)
| Return underlying file descriptor if one exists.
|
| Raise OSError if the IO object does not use a file descriptor.
|
| isatty(self, /)
| Return whether this is an 'interactive' stream.
|
| Return False if it can't be determined.
|
| truncate(self, size=None, /)
| Truncate file to size bytes.
|
| File pointer is left unchanged. Size defaults to the current IO position
| as reported by tell(). Return the new size.
|
| writelines(self, lines, /)
| Write a list of lines to stream.
|
| Line separators are not added, so it is usual for each of the
| lines provided to have a line separator at the end.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _io._IOBase:
|
| __dict__
huggingface-hub.HfFileSystemResolvedPath
Python Library Documentation: class HfFileSystemResolvedPath in module huggingface_hub.hf_file_system
class HfFileSystemResolvedPath(builtins.object)
| HfFileSystemResolvedPath(root: str, path: str) -> None
|
| Top level Data structure containing information about a resolved Hugging Face file system path.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, root: str, path: str) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| unresolve(self) -> str
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'path': <class 'str'>, 'root': <class 'str'>}
|
| __dataclass_fields__ = {'path': Field(name='path',type=<class 'str'>,d...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('root', 'path')
huggingface-hub.HfFileSystemStreamFile
Python Library Documentation: class HfFileSystemStreamFile in module huggingface_hub.hf_file_system
class HfFileSystemStreamFile(fsspec.spec.AbstractBufferedFile)
| HfFileSystemStreamFile(fs: huggingface_hub.hf_file_system.HfFileSystem, path: str, mode: str = 'rb', revision: str | None = None, block_size: int = 0, cache_type: str = 'none', **kwargs)
|
| Method resolution order:
| HfFileSystemStreamFile
| fsspec.spec.AbstractBufferedFile
| io.IOBase
| _io._IOBase
| builtins.object
|
| Methods defined here:
|
| __del__(self)
|
| __init__(self, fs: huggingface_hub.hf_file_system.HfFileSystem, path: str, mode: str = 'rb', revision: str | None = None, block_size: int = 0, cache_type: str = 'none', **kwargs)
| Template for files with buffered reading and writing
|
| Parameters
| ----------
| fs: instance of FileSystem
| path: str
| location in file-system
| mode: str
| Normal file modes. Currently only 'wb', 'ab' or 'rb'. Some file
| systems may be read-only, and some may not support append.
| block_size: int
| Buffer size for reading or writing, 'default' for class default
| autocommit: bool
| Whether to write to final destination; may only impact what
| happens when file is being closed.
| cache_type: {"readahead", "none", "mmap", "bytes"}, default "readahead"
| Caching policy in read mode. See the definitions in ``core``.
| cache_options : dict
| Additional options passed to the constructor for the cache specified
| by `cache_type`.
| size: int
| If given and in read mode, suppressed having to look up the file size
| kwargs:
| Gets stored as self.kwargs
|
| __reduce__(self)
| Helper for pickle.
|
| read(self, length: int = -1)
| Read the remote file.
|
| If the file is already open, we reuse the connection.
| Otherwise, open a new connection and read from it.
|
| If reading the stream fails, we retry with a new connection.
|
| seek(self, loc: int, whence: int = 0)
| Set current file location
|
| Parameters
| ----------
| loc: int
| byte location
| whence: {0, 1, 2}
| from start of file, current location or end of file, resp.
|
| url(self) -> str
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| ----------------------------------------------------------------------
| Methods inherited from fsspec.spec.AbstractBufferedFile:
|
| __enter__(self)
|
| __eq__(self, other)
| Files are equal if they have the same checksum, only in read mode
|
| __exit__(self, *args)
|
| __hash__(self)
| Return hash(self).
|
| __iter__(self)
| Implement iter(self).
|
| __next__(self)
| Implement next(self).
|
| __repr__ = __str__(self)
|
| __str__(self)
| Return str(self).
|
| close(self)
| Close file
|
| Finalizes writes, discards cache
|
| commit(self)
| Move from temp to final destination
|
| discard(self)
| Throw away temporary file
|
| flush(self, force=False)
| Write buffered data to backend store.
|
| Writes the current buffer, if it is larger than the block-size, or if
| the file is being closed.
|
| Parameters
| ----------
| force: bool
| When closing, write the last block even if it is smaller than
| blocks are allowed to be. Disallows further writing to this file.
|
| info(self)
| File information about this path
|
| readable(self)
| Whether opened for reading
|
| readinto(self, b)
| mirrors builtin file's readinto method
|
| https://docs.python.org/3/library/io.html#io.RawIOBase.readinto
|
| readinto1(self, b)
|
| readline(self)
| Read until and including the first occurrence of newline character
|
| Note that, because of character encoding, this is not necessarily a
| true line ending.
|
| readlines(self)
| Return all data, split by the newline character, including the newline character
|
| readuntil(self, char=b'\n', blocks=None)
| Return data between current position and first occurrence of char
|
| char is included in the output, except if the end of the tile is
| encountered first.
|
| Parameters
| ----------
| char: bytes
| Thing to find
| blocks: None or int
| How much to read in each go. Defaults to file blocksize - which may
| mean a new read on every call.
|
| seekable(self)
| Whether is seekable (only in read mode)
|
| tell(self)
| Current file location
|
| writable(self)
| Whether opened for writing
|
| write(self, data)
| Write data to buffer.
|
| Buffer only sent on flush() or if buffer is greater than
| or equal to blocksize.
|
| Parameters
| ----------
| data: bytes
| Set of bytes to be written.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from fsspec.spec.AbstractBufferedFile:
|
| full_name
|
| ----------------------------------------------------------------------
| Data descriptors inherited from fsspec.spec.AbstractBufferedFile:
|
| closed
|
| details
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from fsspec.spec.AbstractBufferedFile:
|
| DEFAULT_BLOCK_SIZE = 5242880
|
| ----------------------------------------------------------------------
| Methods inherited from _io._IOBase:
|
| fileno(self, /)
| Return underlying file descriptor if one exists.
|
| Raise OSError if the IO object does not use a file descriptor.
|
| isatty(self, /)
| Return whether this is an 'interactive' stream.
|
| Return False if it can't be determined.
|
| truncate(self, size=None, /)
| Truncate file to size bytes.
|
| File pointer is left unchanged. Size defaults to the current IO position
| as reported by tell(). Return the new size.
|
| writelines(self, lines, /)
| Write a list of lines to stream.
|
| Line separators are not added, so it is usual for each of the
| lines provided to have a line separator at the end.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _io._IOBase:
|
| __dict__
huggingface-hub.HfUri
Python Library Documentation: class HfUri in module huggingface_hub.utils._hf_uris
class HfUri(builtins.object)
| HfUri(type: Literal['model', 'dataset', 'space', 'kernel', 'bucket'], id: str, revision: str | None = None, path_in_repo: str = '', _raw: str | None = None) -> None
|
| Parsed representation of a Hugging Face Hub URI ('hf://...').
|
| Attributes:
| type (`str`):
| One of 'model', 'dataset', 'space', 'kernel' or 'bucket'.
| id (`str`):
| The repository id ('namespace/name', e.g. 'my-org/my-model') for repo URIs, or the bucket id ('namespace/name') for bucket URIs.
| revision (`str`, *optional*):
| The revision specified after '@' in the URI, URL-decoded. 'None' if no revision was specified, or for bucket URIs (which
| never carry a revision). Special refs like 'refs/pr/10' and 'refs/convert/parquet' are preserved as-is.
| path_in_repo (`str`):
| The path inside the repo or bucket. Empty string if the URI points at the root.
|
| Methods defined here:
|
| __delattr__(self, name)
| Implement delattr(self, name).
|
| __eq__(self, other)
| Return self==value.
|
| __hash__(self)
| Return hash(self).
|
| __init__(self, type: Literal['model', 'dataset', 'space', 'kernel', 'bucket'], id: str, revision: str | None = None, path_in_repo: str = '', _raw: str | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __post_init__(self) -> None
|
| __repr__(self)
| Return repr(self).
|
| __setattr__(self, name, value)
| Implement setattr(self, name, value).
|
| to_uri(self) -> str
| Render the URI as a canonical 'hf://' string.
|
| The type prefix is always written explicitly (e.g. 'hf://models/my-org/my-model').
|
| to_url(self, endpoint: str | None = None) -> str
| Render the URI as a Hugging Face **web URL** (the kind you open in a browser).
|
| This is the inverse of parsing a URL with [`parse_hf_uri`]. The returned URL points at:
|
| - the repository / bucket landing page when no path or revision is set;
| - the folder viewer ('/tree/<revision>') when only a revision is set;
| - the file viewer ('/blob/<revision>/<path>') for repository files (revision defaults to 'main');
| - the tree route ('/tree/<path>') for bucket files (buckets are not versioned).
|
| Args:
| endpoint (`str`, *optional*):
| Base endpoint to use. Defaults to 'constants.ENDPOINT' (i.e. 'https://huggingface.co').
|
| Returns:
| `str`: the web URL.
|
| Example:
| ```py
| >>> from huggingface_hub import parse_hf_uri
| >>> parse_hf_uri("hf://datasets/my-org/my-dataset@v1/train.csv").to_url()
| 'https://huggingface.co/datasets/my-org/my-dataset/blob/v1/train.csv'
| ```
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| is_bucket
| True if this URI points at a bucket.
|
| is_repo
| True if this URI points at a repository (model, dataset, space or kernel).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_raw': str | None, 'id': <class 'str'>, 'path_in_r...
|
| __dataclass_fields__ = {'_raw': Field(name='_raw',type=str | None,defa...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __match_args__ = ('type', 'id', 'revision', 'path_in_repo', '_raw')
|
| path_in_repo = ''
|
| revision = None
huggingface-hub.ImageClassificationInput
Python Library Documentation: class ImageClassificationInput in module huggingface_hub.inference._generated.types.image_classification
class ImageClassificationInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageClassificationInput(inputs: str, parameters: huggingface_hub.inference._generated.types.image_classification.ImageClassificationParameters | None = None) -> None
|
| Inputs for Image Classification inference
|
| Method resolution order:
| ImageClassificationInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: str, parameters: huggingface_hub.inference._generated.types.image_classification.ImageClassificationParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'str'>, 'parameters': huggingface_...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ImageClassificationOutputElement
Python Library Documentation: class ImageClassificationOutputElement in module huggingface_hub.inference._generated.types.image_classification
class ImageClassificationOutputElement(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageClassificationOutputElement(label: str, score: float) -> None
|
| Outputs of inference for the Image Classification task
|
| Method resolution order:
| ImageClassificationOutputElement
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, label: str, score: float) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'label': <class 'str'>, 'score': <class 'float'>}
|
| __dataclass_fields__ = {'label': Field(name='label',type=<class 'str'>...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('label', 'score')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ImageClassificationOutputTransform
Python Library Documentation: _LiteralGenericAlias in module typing
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
huggingface-hub.ImageClassificationParameters
Python Library Documentation: class ImageClassificationParameters in module huggingface_hub.inference._generated.types.image_classification
class ImageClassificationParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageClassificationParameters(function_to_apply: Optional[ForwardRef('ImageClassificationOutputTransform')] = None, top_k: int | None = None) -> None
|
| Additional inference parameters for Image Classification
|
| Method resolution order:
| ImageClassificationParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, function_to_apply: Optional[ForwardRef('ImageClassificationOutputTransform')] = None, top_k: int | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'function_to_apply': typing.Optional[ForwardRef('Im...
|
| __dataclass_fields__ = {'function_to_apply': Field(name='function_to_a...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('function_to_apply', 'top_k')
|
| function_to_apply = None
|
| top_k = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ImageSegmentationInput
Python Library Documentation: class ImageSegmentationInput in module huggingface_hub.inference._generated.types.image_segmentation
class ImageSegmentationInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageSegmentationInput(inputs: str, parameters: huggingface_hub.inference._generated.types.image_segmentation.ImageSegmentationParameters | None = None) -> None
|
| Inputs for Image Segmentation inference
|
| Method resolution order:
| ImageSegmentationInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: str, parameters: huggingface_hub.inference._generated.types.image_segmentation.ImageSegmentationParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'str'>, 'parameters': huggingface_...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ImageSegmentationOutputElement
Python Library Documentation: class ImageSegmentationOutputElement in module huggingface_hub.inference._generated.types.image_segmentation
class ImageSegmentationOutputElement(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageSegmentationOutputElement(label: str, mask: str, score: float | None = None) -> None
|
| Outputs of inference for the Image Segmentation task
| A predicted mask / segment
|
| Method resolution order:
| ImageSegmentationOutputElement
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, label: str, mask: str, score: float | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'label': <class 'str'>, 'mask': <class 'str'>, 'sco...
|
| __dataclass_fields__ = {'label': Field(name='label',type=<class 'str'>...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('label', 'mask', 'score')
|
| score = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ImageSegmentationParameters
Python Library Documentation: class ImageSegmentationParameters in module huggingface_hub.inference._generated.types.image_segmentation
class ImageSegmentationParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageSegmentationParameters(mask_threshold: float | None = None, overlap_mask_area_threshold: float | None = None, subtask: Optional[ForwardRef('ImageSegmentationSubtask')] = None, threshold: float | None = None) -> None
|
| Additional inference parameters for Image Segmentation
|
| Method resolution order:
| ImageSegmentationParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, mask_threshold: float | None = None, overlap_mask_area_threshold: float | None = None, subtask: Optional[ForwardRef('ImageSegmentationSubtask')] = None, threshold: float | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'mask_threshold': float | None, 'overlap_mask_area_...
|
| __dataclass_fields__ = {'mask_threshold': Field(name='mask_threshold',...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('mask_threshold', 'overlap_mask_area_threshold', 'su...
|
| mask_threshold = None
|
| overlap_mask_area_threshold = None
|
| subtask = None
|
| threshold = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ImageSegmentationSubtask
Python Library Documentation: _LiteralGenericAlias in module typing
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
huggingface-hub.ImageTextToImageInput
Python Library Documentation: class ImageTextToImageInput in module huggingface_hub.inference._generated.types.image_text_to_image
class ImageTextToImageInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageTextToImageInput(inputs: str | None = None, parameters: huggingface_hub.inference._generated.types.image_text_to_image.ImageTextToImageParameters | None = None) -> None
|
| Inputs for Image Text To Image inference. Either inputs (image) or prompt (in parameters)
| must be provided, or both.
|
| Method resolution order:
| ImageTextToImageInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: str | None = None, parameters: huggingface_hub.inference._generated.types.image_text_to_image.ImageTextToImageParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': str | None, 'parameters': huggingface_hub...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=str | None,...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| inputs = None
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ImageTextToImageOutput
Python Library Documentation: class ImageTextToImageOutput in module huggingface_hub.inference._generated.types.image_text_to_image
class ImageTextToImageOutput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageTextToImageOutput(image: Any) -> None
|
| Outputs of inference for the Image Text To Image task
|
| Method resolution order:
| ImageTextToImageOutput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, image: Any) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'image': typing.Any}
|
| __dataclass_fields__ = {'image': Field(name='image',type=typing.Any,de...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('image',)
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ImageTextToImageParameters
Python Library Documentation: class ImageTextToImageParameters in module huggingface_hub.inference._generated.types.image_text_to_image
class ImageTextToImageParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageTextToImageParameters(guidance_scale: float | None = None, negative_prompt: str | None = None, num_inference_steps: int | None = None, prompt: str | None = None, seed: int | None = None, target_size: huggingface_hub.inference._generated.types.image_text_to_image.ImageTextToImageTargetSize | None = None) -> None
|
| Additional inference parameters for Image Text To Image
|
| Method resolution order:
| ImageTextToImageParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, guidance_scale: float | None = None, negative_prompt: str | None = None, num_inference_steps: int | None = None, prompt: str | None = None, seed: int | None = None, target_size: huggingface_hub.inference._generated.types.image_text_to_image.ImageTextToImageTargetSize | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'guidance_scale': float | None, 'negative_prompt': ...
|
| __dataclass_fields__ = {'guidance_scale': Field(name='guidance_scale',...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('guidance_scale', 'negative_prompt', 'num_inference_...
|
| guidance_scale = None
|
| negative_prompt = None
|
| num_inference_steps = None
|
| prompt = None
|
| seed = None
|
| target_size = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ImageTextToImageTargetSize
Python Library Documentation: class ImageTextToImageTargetSize in module huggingface_hub.inference._generated.types.image_text_to_image
class ImageTextToImageTargetSize(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageTextToImageTargetSize(height: int, width: int) -> None
|
| The size in pixels of the output image. This parameter is only supported by some
| providers and for specific models. It will be ignored when unsupported.
|
| Method resolution order:
| ImageTextToImageTargetSize
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, height: int, width: int) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'height': <class 'int'>, 'width': <class 'int'>}
|
| __dataclass_fields__ = {'height': Field(name='height',type=<class 'int...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('height', 'width')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ImageTextToVideoInput
Python Library Documentation: class ImageTextToVideoInput in module huggingface_hub.inference._generated.types.image_text_to_video
class ImageTextToVideoInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageTextToVideoInput(inputs: str | None = None, parameters: huggingface_hub.inference._generated.types.image_text_to_video.ImageTextToVideoParameters | None = None) -> None
|
| Inputs for Image Text To Video inference. Either inputs (image) or prompt (in parameters)
| must be provided, or both.
|
| Method resolution order:
| ImageTextToVideoInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: str | None = None, parameters: huggingface_hub.inference._generated.types.image_text_to_video.ImageTextToVideoParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': str | None, 'parameters': huggingface_hub...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=str | None,...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| inputs = None
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ImageTextToVideoOutput
Python Library Documentation: class ImageTextToVideoOutput in module huggingface_hub.inference._generated.types.image_text_to_video
class ImageTextToVideoOutput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageTextToVideoOutput(video: Any) -> None
|
| Outputs of inference for the Image Text To Video task
|
| Method resolution order:
| ImageTextToVideoOutput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, video: Any) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'video': typing.Any}
|
| __dataclass_fields__ = {'video': Field(name='video',type=typing.Any,de...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('video',)
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ImageTextToVideoParameters
Python Library Documentation: class ImageTextToVideoParameters in module huggingface_hub.inference._generated.types.image_text_to_video
class ImageTextToVideoParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageTextToVideoParameters(guidance_scale: float | None = None, negative_prompt: str | None = None, num_frames: float | None = None, num_inference_steps: int | None = None, prompt: str | None = None, seed: int | None = None, target_size: huggingface_hub.inference._generated.types.image_text_to_video.ImageTextToVideoTargetSize | None = None) -> None
|
| Additional inference parameters for Image Text To Video
|
| Method resolution order:
| ImageTextToVideoParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, guidance_scale: float | None = None, negative_prompt: str | None = None, num_frames: float | None = None, num_inference_steps: int | None = None, prompt: str | None = None, seed: int | None = None, target_size: huggingface_hub.inference._generated.types.image_text_to_video.ImageTextToVideoTargetSize | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'guidance_scale': float | None, 'negative_prompt': ...
|
| __dataclass_fields__ = {'guidance_scale': Field(name='guidance_scale',...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('guidance_scale', 'negative_prompt', 'num_frames', '...
|
| guidance_scale = None
|
| negative_prompt = None
|
| num_frames = None
|
| num_inference_steps = None
|
| prompt = None
|
| seed = None
|
| target_size = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ImageTextToVideoTargetSize
Python Library Documentation: class ImageTextToVideoTargetSize in module huggingface_hub.inference._generated.types.image_text_to_video
class ImageTextToVideoTargetSize(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageTextToVideoTargetSize(height: int, width: int) -> None
|
| The size in pixel of the output video frames.
|
| Method resolution order:
| ImageTextToVideoTargetSize
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, height: int, width: int) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'height': <class 'int'>, 'width': <class 'int'>}
|
| __dataclass_fields__ = {'height': Field(name='height',type=<class 'int...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('height', 'width')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ImageToImageInput
Python Library Documentation: class ImageToImageInput in module huggingface_hub.inference._generated.types.image_to_image
class ImageToImageInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageToImageInput(inputs: str, parameters: huggingface_hub.inference._generated.types.image_to_image.ImageToImageParameters | None = None) -> None
|
| Inputs for Image To Image inference
|
| Method resolution order:
| ImageToImageInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: str, parameters: huggingface_hub.inference._generated.types.image_to_image.ImageToImageParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'str'>, 'parameters': huggingface_...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ImageToImageOutput
Python Library Documentation: class ImageToImageOutput in module huggingface_hub.inference._generated.types.image_to_image
class ImageToImageOutput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageToImageOutput(image: Any) -> None
|
| Outputs of inference for the Image To Image task
|
| Method resolution order:
| ImageToImageOutput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, image: Any) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'image': typing.Any}
|
| __dataclass_fields__ = {'image': Field(name='image',type=typing.Any,de...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('image',)
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ImageToImageParameters
Python Library Documentation: class ImageToImageParameters in module huggingface_hub.inference._generated.types.image_to_image
class ImageToImageParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageToImageParameters(guidance_scale: float | None = None, negative_prompt: str | None = None, num_inference_steps: int | None = None, prompt: str | None = None, target_size: huggingface_hub.inference._generated.types.image_to_image.ImageToImageTargetSize | None = None) -> None
|
| Additional inference parameters for Image To Image
|
| Method resolution order:
| ImageToImageParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, guidance_scale: float | None = None, negative_prompt: str | None = None, num_inference_steps: int | None = None, prompt: str | None = None, target_size: huggingface_hub.inference._generated.types.image_to_image.ImageToImageTargetSize | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'guidance_scale': float | None, 'negative_prompt': ...
|
| __dataclass_fields__ = {'guidance_scale': Field(name='guidance_scale',...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('guidance_scale', 'negative_prompt', 'num_inference_...
|
| guidance_scale = None
|
| negative_prompt = None
|
| num_inference_steps = None
|
| prompt = None
|
| target_size = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ImageToImageTargetSize
Python Library Documentation: class ImageToImageTargetSize in module huggingface_hub.inference._generated.types.image_to_image
class ImageToImageTargetSize(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageToImageTargetSize(height: int, width: int) -> None
|
| The size in pixels of the output image. This parameter is only supported by some
| providers and for specific models. It will be ignored when unsupported.
|
| Method resolution order:
| ImageToImageTargetSize
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, height: int, width: int) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'height': <class 'int'>, 'width': <class 'int'>}
|
| __dataclass_fields__ = {'height': Field(name='height',type=<class 'int...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('height', 'width')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ImageToTextEarlyStoppingEnum
Python Library Documentation: _LiteralGenericAlias in module typing
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
huggingface-hub.ImageToTextGenerationParameters
Python Library Documentation: class ImageToTextGenerationParameters in module huggingface_hub.inference._generated.types.image_to_text
class ImageToTextGenerationParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageToTextGenerationParameters(do_sample: bool | None = None, early_stopping: Union[bool, ForwardRef('ImageToTextEarlyStoppingEnum'), NoneType] = None, epsilon_cutoff: float | None = None, eta_cutoff: float | None = None, max_length: int | None = None, max_new_tokens: int | None = None, min_length: int | None = None, min_new_tokens: int | None = None, num_beam_groups: int | None = None, num_beams: int | None = None, penalty_alpha: float | None = None, temperature: float | None = None, top_k: int | None = None, top_p: float | None = None, typical_p: float | None = None, use_cache: bool | None = None) -> None
|
| Parametrization of the text generation process
|
| Method resolution order:
| ImageToTextGenerationParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, do_sample: bool | None = None, early_stopping: Union[bool, ForwardRef('ImageToTextEarlyStoppingEnum'), NoneType] = None, epsilon_cutoff: float | None = None, eta_cutoff: float | None = None, max_length: int | None = None, max_new_tokens: int | None = None, min_length: int | None = None, min_new_tokens: int | None = None, num_beam_groups: int | None = None, num_beams: int | None = None, penalty_alpha: float | None = None, temperature: float | None = None, top_k: int | None = None, top_p: float | None = None, typical_p: float | None = None, use_cache: bool | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'do_sample': bool | None, 'early_stopping': typing....
|
| __dataclass_fields__ = {'do_sample': Field(name='do_sample',type=bool ...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('do_sample', 'early_stopping', 'epsilon_cutoff', 'et...
|
| do_sample = None
|
| early_stopping = None
|
| epsilon_cutoff = None
|
| eta_cutoff = None
|
| max_length = None
|
| max_new_tokens = None
|
| min_length = None
|
| min_new_tokens = None
|
| num_beam_groups = None
|
| num_beams = None
|
| penalty_alpha = None
|
| temperature = None
|
| top_k = None
|
| top_p = None
|
| typical_p = None
|
| use_cache = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ImageToTextInput
Python Library Documentation: class ImageToTextInput in module huggingface_hub.inference._generated.types.image_to_text
class ImageToTextInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageToTextInput(inputs: Any, parameters: huggingface_hub.inference._generated.types.image_to_text.ImageToTextParameters | None = None) -> None
|
| Inputs for Image To Text inference
|
| Method resolution order:
| ImageToTextInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: Any, parameters: huggingface_hub.inference._generated.types.image_to_text.ImageToTextParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': typing.Any, 'parameters': huggingface_hub...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=typing.Any,...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ImageToTextOutput
Python Library Documentation: class ImageToTextOutput in module huggingface_hub.inference._generated.types.image_to_text
class ImageToTextOutput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageToTextOutput(generated_text: Any, image_to_text_output_generated_text: str | None = None) -> None
|
| Outputs of inference for the Image To Text task
|
| Method resolution order:
| ImageToTextOutput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, generated_text: Any, image_to_text_output_generated_text: str | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'generated_text': typing.Any, 'image_to_text_output...
|
| __dataclass_fields__ = {'generated_text': Field(name='generated_text',...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('generated_text', 'image_to_text_output_generated_te...
|
| image_to_text_output_generated_text = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ImageToTextParameters
Python Library Documentation: class ImageToTextParameters in module huggingface_hub.inference._generated.types.image_to_text
class ImageToTextParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageToTextParameters(generation_parameters: huggingface_hub.inference._generated.types.image_to_text.ImageToTextGenerationParameters | None = None, max_new_tokens: int | None = None) -> None
|
| Additional inference parameters for Image To Text
|
| Method resolution order:
| ImageToTextParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, generation_parameters: huggingface_hub.inference._generated.types.image_to_text.ImageToTextGenerationParameters | None = None, max_new_tokens: int | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'generation_parameters': huggingface_hub.inference....
|
| __dataclass_fields__ = {'generation_parameters': Field(name='generatio...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('generation_parameters', 'max_new_tokens')
|
| generation_parameters = None
|
| max_new_tokens = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ImageToVideoInput
Python Library Documentation: class ImageToVideoInput in module huggingface_hub.inference._generated.types.image_to_video
class ImageToVideoInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageToVideoInput(inputs: str, parameters: huggingface_hub.inference._generated.types.image_to_video.ImageToVideoParameters | None = None) -> None
|
| Inputs for Image To Video inference
|
| Method resolution order:
| ImageToVideoInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: str, parameters: huggingface_hub.inference._generated.types.image_to_video.ImageToVideoParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'str'>, 'parameters': huggingface_...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ImageToVideoOutput
Python Library Documentation: class ImageToVideoOutput in module huggingface_hub.inference._generated.types.image_to_video
class ImageToVideoOutput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageToVideoOutput(video: Any) -> None
|
| Outputs of inference for the Image To Video task
|
| Method resolution order:
| ImageToVideoOutput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, video: Any) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'video': typing.Any}
|
| __dataclass_fields__ = {'video': Field(name='video',type=typing.Any,de...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('video',)
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ImageToVideoParameters
Python Library Documentation: class ImageToVideoParameters in module huggingface_hub.inference._generated.types.image_to_video
class ImageToVideoParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageToVideoParameters(guidance_scale: float | None = None, negative_prompt: str | None = None, num_frames: float | None = None, num_inference_steps: int | None = None, prompt: str | None = None, seed: int | None = None, target_size: huggingface_hub.inference._generated.types.image_to_video.ImageToVideoTargetSize | None = None) -> None
|
| Additional inference parameters for Image To Video
|
| Method resolution order:
| ImageToVideoParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, guidance_scale: float | None = None, negative_prompt: str | None = None, num_frames: float | None = None, num_inference_steps: int | None = None, prompt: str | None = None, seed: int | None = None, target_size: huggingface_hub.inference._generated.types.image_to_video.ImageToVideoTargetSize | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'guidance_scale': float | None, 'negative_prompt': ...
|
| __dataclass_fields__ = {'guidance_scale': Field(name='guidance_scale',...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('guidance_scale', 'negative_prompt', 'num_frames', '...
|
| guidance_scale = None
|
| negative_prompt = None
|
| num_frames = None
|
| num_inference_steps = None
|
| prompt = None
|
| seed = None
|
| target_size = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ImageToVideoTargetSize
Python Library Documentation: class ImageToVideoTargetSize in module huggingface_hub.inference._generated.types.image_to_video
class ImageToVideoTargetSize(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ImageToVideoTargetSize(height: int, width: int) -> None
|
| The size in pixel of the output video frames.
|
| Method resolution order:
| ImageToVideoTargetSize
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, height: int, width: int) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'height': <class 'int'>, 'width': <class 'int'>}
|
| __dataclass_fields__ = {'height': Field(name='height',type=<class 'int...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('height', 'width')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.InferenceClient
Python Library Documentation: class InferenceClient in module huggingface_hub.inference._client
class InferenceClient(builtins.object)
| InferenceClient(model: str | None = None, *, provider: Union[Literal['cerebras', 'cohere', 'deepinfra', 'fal-ai', 'featherless-ai', 'fireworks-ai', 'groq', 'hf-inference', 'novita', 'nscale', 'openai', 'ovhcloud', 'publicai', 'replicate', 'scaleway', 'together', 'wavespeed', 'zai-org'], Literal['auto'], NoneType] = None, token: str | None = None, timeout: float | None = None, headers: dict[str, str] | None = None, cookies: dict[str, str] | None = None, bill_to: str | None = None, base_url: str | None = None, api_key: str | None = None) -> None
|
| Initialize a new Inference Client.
|
| [`InferenceClient`] aims to provide a unified experience to perform inference. The client can be used
| seamlessly with either the (free) Inference API, self-hosted Inference Endpoints, or third-party Inference Providers.
|
| Args:
| model (`str`, `optional`):
| The model to run inference with. Can be a model id hosted on the Hugging Face Hub, e.g. `meta-llama/Meta-Llama-3-8B-Instruct`
| or a URL to a deployed Inference Endpoint. Defaults to None, in which case a recommended model is
| automatically selected for the task.
| Note: for better compatibility with OpenAI's client, `model` has been aliased as `base_url`. Those 2
| arguments are mutually exclusive. If a URL is passed as `model` or `base_url` for chat completion, the `(/v1)/chat/completions` suffix path will be appended to the URL.
| provider (`str`, *optional*):
| Name of the provider to use for inference. Can be `"cerebras"`, `"cohere"`, `"deepinfra"`, `"fal-ai"`, `"featherless-ai"`, `"fireworks-ai"`, `"groq"`, `"hf-inference"`, `"novita"`, `"nscale"`, `"openai"`, `"ovhcloud"`, `"publicai"`, `"replicate"`, `"scaleway"`, `"together"`, `"wavespeed"` or `"zai-org"`.
| Defaults to "auto": automatic routing, which defaults to "fastest" provider; you can
| switch to "cheapest" or "preferred" provider order at https://hf.co/settings/inference-providers.
| If model is a URL or `base_url` is passed, then `provider` is not used.
| token (`str`, *optional*):
| Hugging Face token. Will default to the locally saved token if not provided.
| Note: for better compatibility with OpenAI's client, `token` has been aliased as `api_key`. Those 2
| arguments are mutually exclusive and have the exact same behavior.
| timeout (`float`, `optional`):
| The maximum number of seconds to wait for a response from the server. Defaults to None, meaning it will loop until the server is available.
| headers (`dict[str, str]`, `optional`):
| Additional headers to send to the server. By default only the authorization and user-agent headers are sent.
| Values in this dictionary will override the default values.
| bill_to (`str`, `optional`):
| The billing account to use for the requests. By default the requests are billed on the user's account.
| Requests can only be billed to an organization the user is a member of, and which has subscribed to Enterprise Hub.
| cookies (`dict[str, str]`, `optional`):
| Additional cookies to send to the server.
| base_url (`str`, `optional`):
| Base URL to run inference. This is a duplicated argument from `model` to make [`InferenceClient`]
| follow the same pattern as `openai.OpenAI` client. Cannot be used if `model` is set. Defaults to None.
| api_key (`str`, `optional`):
| Token to use for authentication. This is a duplicated argument from `token` to make [`InferenceClient`]
| follow the same pattern as `openai.OpenAI` client. Cannot be used if `token` is set. Defaults to None.
|
| Methods defined here:
|
| __enter__(self)
|
| __exit__(self, exc_type, exc_value, traceback)
|
| __init__(self, model: str | None = None, *, provider: Union[Literal['cerebras', 'cohere', 'deepinfra', 'fal-ai', 'featherless-ai', 'fireworks-ai', 'groq', 'hf-inference', 'novita', 'nscale', 'openai', 'ovhcloud', 'publicai', 'replicate', 'scaleway', 'together', 'wavespeed', 'zai-org'], Literal['auto'], NoneType] = None, token: str | None = None, timeout: float | None = None, headers: dict[str, str] | None = None, cookies: dict[str, str] | None = None, bill_to: str | None = None, base_url: str | None = None, api_key: str | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| audio_classification(self, audio: Union[bytes, BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], *, model: str | None = None, top_k: int | None = None, function_to_apply: Optional[ForwardRef('AudioClassificationOutputTransform')] = None) -> list[huggingface_hub.inference._generated.types.audio_classification.AudioClassificationOutputElement]
| Perform audio classification on the provided audio content.
|
| Args:
| audio (Union[str, Path, bytes, BinaryIO]):
| The audio content to classify. It can be raw audio bytes, a local audio file, or a URL pointing to an
| audio file.
| model (`str`, *optional*):
| The model to use for audio classification. Can be a model ID hosted on the Hugging Face Hub
| or a URL to a deployed Inference Endpoint. If not provided, the default recommended model for
| audio classification will be used.
| top_k (`int`, *optional*):
| When specified, limits the output to the top K most probable classes.
| function_to_apply (`"AudioClassificationOutputTransform"`, *optional*):
| The function to apply to the model outputs in order to retrieve the scores.
|
| Returns:
| `list[AudioClassificationOutputElement]`: List of [`AudioClassificationOutputElement`] items containing the predicted labels and their confidence.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
| >>> client.audio_classification("audio.flac")
| [
| AudioClassificationOutputElement(score=0.4976358711719513, label='hap'),
| AudioClassificationOutputElement(score=0.3677836060523987, label='neu'),
| ...
| ]
| ```
|
| audio_to_audio(self, audio: Union[bytes, BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], *, model: str | None = None) -> list[huggingface_hub.inference._generated.types.audio_to_audio.AudioToAudioOutputElement]
| Performs multiple tasks related to audio-to-audio depending on the model (eg: speech enhancement, source separation).
|
| Args:
| audio (Union[str, Path, bytes, BinaryIO]):
| The audio content for the model. It can be raw audio bytes, a local audio file, or a URL pointing to an
| audio file.
| model (`str`, *optional*):
| The model can be any model which takes an audio file and returns another audio file. Can be a model ID hosted on the Hugging Face Hub
| or a URL to a deployed Inference Endpoint. If not provided, the default recommended model for
| audio_to_audio will be used.
|
| Returns:
| `list[AudioToAudioOutputElement]`: A list of [`AudioToAudioOutputElement`] items containing audios label, content-type, and audio content in blob.
|
| Raises:
| `InferenceTimeoutError`:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
| >>> audio_output = client.audio_to_audio("audio.flac")
| >>> for i, item in enumerate(audio_output):
| >>> with open(f"output_{i}.flac", "wb") as f:
| f.write(item.blob)
| ```
|
| automatic_speech_recognition(self, audio: Union[bytes, BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], *, model: str | None = None, extra_body: dict | None = None) -> huggingface_hub.inference._generated.types.automatic_speech_recognition.AutomaticSpeechRecognitionOutput
| Perform automatic speech recognition (ASR or audio-to-text) on the given audio content.
|
| Args:
| audio (Union[str, Path, bytes, BinaryIO]):
| The content to transcribe. It can be raw audio bytes, local audio file, or a URL to an audio file.
| model (`str`, *optional*):
| The model to use for ASR. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. If not provided, the default recommended model for ASR will be used.
| extra_body (`dict`, *optional*):
| Additional provider-specific parameters to pass to the model. Refer to the provider's documentation
| for supported parameters.
| Returns:
| [`AutomaticSpeechRecognitionOutput`]: An item containing the transcribed text and optionally the timestamp chunks.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
| >>> client.automatic_speech_recognition("hello_world.flac").text
| "hello world"
| ```
|
| chat_completion(self, messages: list[dict | huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputMessage], *, model: str | None = None, stream: bool = False, frequency_penalty: float | None = None, logit_bias: list[float] | None = None, logprobs: bool | None = None, max_tokens: int | None = None, n: int | None = None, presence_penalty: float | None = None, response_format: Union[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputResponseFormatText, huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputResponseFormatJSONSchema, huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputResponseFormatJSONObject, NoneType] = None, seed: int | None = None, stop: list[str] | None = None, stream_options: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputStreamOptions | None = None, temperature: float | None = None, tool_choice: Union[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputToolChoiceClass, ForwardRef('ChatCompletionInputToolChoiceEnum'), NoneType] = None, tool_prompt: str | None = None, tools: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputTool] | None = None, top_logprobs: int | None = None, top_p: float | None = None, extra_body: dict | None = None) -> huggingface_hub.inference._generated.types.chat_completion.ChatCompletionOutput | collections.abc.Iterable[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutput]
| A method for completing conversations using a specified language model.
|
| > [!TIP]
| > The `client.chat_completion` method is aliased as `client.chat.completions.create` for compatibility with OpenAI's client.
| > Inputs and outputs are strictly the same and using either syntax will yield the same results.
| > Check out the [Inference guide](https://huggingface.co/docs/huggingface_hub/guides/inference#openai-compatibility)
| > for more details about OpenAI's compatibility.
|
| > [!TIP]
| > You can pass provider-specific parameters to the model by using the `extra_body` argument.
|
| Args:
| messages (List of [`ChatCompletionInputMessage`]):
| Conversation history consisting of roles and content pairs.
| model (`str`, *optional*):
| The model to use for chat-completion. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. If not provided, the default recommended model for chat-based text-generation will be used.
| See https://huggingface.co/tasks/text-generation for more details.
| If `model` is a model ID, it is passed to the server as the `model` parameter. If you want to define a
| custom URL while setting `model` in the request payload, you must set `base_url` when initializing [`InferenceClient`].
| frequency_penalty (`float`, *optional*):
| Penalizes new tokens based on their existing frequency
| in the text so far. Range: [-2.0, 2.0]. Defaults to 0.0.
| logit_bias (`list[float]`, *optional*):
| Adjusts the likelihood of specific tokens appearing in the generated output.
| logprobs (`bool`, *optional*):
| Whether to return log probabilities of the output tokens or not. If true, returns the log
| probabilities of each output token returned in the content of message.
| max_tokens (`int`, *optional*):
| Maximum number of tokens allowed in the response. Defaults to 100.
| n (`int`, *optional*):
| The number of completions to generate for each prompt.
| presence_penalty (`float`, *optional*):
| Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the
| text so far, increasing the model's likelihood to talk about new topics.
| response_format ([`ChatCompletionInputGrammarType`], *optional*):
| Grammar constraints. Can be either a JSONSchema or a regex.
| seed (Optional[`int`], *optional*):
| Seed for reproducible control flow. Defaults to None.
| stop (`list[str]`, *optional*):
| Up to four strings which trigger the end of the response.
| Defaults to None.
| stream (`bool`, *optional*):
| Enable realtime streaming of responses. Defaults to False.
| stream_options ([`ChatCompletionInputStreamOptions`], *optional*):
| Options for streaming completions.
| temperature (`float`, *optional*):
| Controls randomness of the generations. Lower values ensure
| less random completions. Range: [0, 2]. Defaults to 1.0.
| top_logprobs (`int`, *optional*):
| An integer between 0 and 5 specifying the number of most likely tokens to return at each token
| position, each with an associated log probability. logprobs must be set to true if this parameter is
| used.
| top_p (`float`, *optional*):
| Fraction of the most likely next words to sample from.
| Must be between 0 and 1. Defaults to 1.0.
| tool_choice ([`ChatCompletionInputToolChoiceClass`] or [`ChatCompletionInputToolChoiceEnum`], *optional*):
| The tool to use for the completion. Defaults to "auto".
| tool_prompt (`str`, *optional*):
| A prompt to be appended before the tools.
| tools (List of [`ChatCompletionInputTool`], *optional*):
| A list of tools the model may call. Currently, only functions are supported as a tool. Use this to
| provide a list of functions the model may generate JSON inputs for.
| extra_body (`dict`, *optional*):
| Additional provider-specific parameters to pass to the model. Refer to the provider's documentation
| for supported parameters.
| Returns:
| [`ChatCompletionOutput`] or Iterable of [`ChatCompletionStreamOutput`]:
| Generated text returned from the server:
| - if `stream=False`, the generated text is returned as a [`ChatCompletionOutput`] (default).
| - if `stream=True`, the generated text is returned token by token as a sequence of [`ChatCompletionStreamOutput`].
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
|
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> messages = [{"role": "user", "content": "What is the capital of France?"}]
| >>> client = InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
| >>> client.chat_completion(messages, max_tokens=100)
| ChatCompletionOutput(
| choices=[
| ChatCompletionOutputComplete(
| finish_reason='eos_token',
| index=0,
| message=ChatCompletionOutputMessage(
| role='assistant',
| content='The capital of France is Paris.',
| name=None,
| tool_calls=None
| ),
| logprobs=None
| )
| ],
| created=1719907176,
| id='',
| model='meta-llama/Meta-Llama-3-8B-Instruct',
| object='text_completion',
| system_fingerprint='2.0.4-sha-f426a33',
| usage=ChatCompletionOutputUsage(
| completion_tokens=8,
| prompt_tokens=17,
| total_tokens=25
| )
| )
| ```
|
| Example using streaming:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> messages = [{"role": "user", "content": "What is the capital of France?"}]
| >>> client = InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
| >>> for token in client.chat_completion(messages, max_tokens=10, stream=True):
| ... print(token)
| ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content='The', role='assistant'), index=0, finish_reason=None)], created=1710498504)
| ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content=' capital', role='assistant'), index=0, finish_reason=None)], created=1710498504)
| (...)
| ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content=' may', role='assistant'), index=0, finish_reason=None)], created=1710498504)
| ```
|
| Example using OpenAI's syntax:
| ```py
| # instead of `from openai import OpenAI`
| from huggingface_hub import InferenceClient
|
| # instead of `client = OpenAI(...)`
| client = InferenceClient(
| base_url=...,
| api_key=...,
| )
|
| output = client.chat.completions.create(
| model="meta-llama/Meta-Llama-3-8B-Instruct",
| messages=[
| {"role": "system", "content": "You are a helpful assistant."},
| {"role": "user", "content": "Count to 10"},
| ],
| stream=True,
| max_tokens=1024,
| )
|
| for chunk in output:
| print(chunk.choices[0].delta.content)
| ```
|
| Example using a third-party provider directly with extra (provider-specific) parameters. Usage will be billed on your Together AI account.
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient(
| ... provider="together", # Use Together AI provider
| ... api_key="<together_api_key>", # Pass your Together API key directly
| ... )
| >>> client.chat_completion(
| ... model="meta-llama/Meta-Llama-3-8B-Instruct",
| ... messages=[{"role": "user", "content": "What is the capital of France?"}],
| ... extra_body={"safety_model": "Meta-Llama/Llama-Guard-7b"},
| ... )
| ```
|
| Example using a third-party provider through Hugging Face Routing. Usage will be billed on your Hugging Face account.
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient(
| ... provider="novita", # Use Novita provider
| ... api_key="hf_...", # Pass your HF token
| ... )
| >>> client.chat_completion(
| ... model="meta-llama/Meta-Llama-3-8B-Instruct",
| ... messages=[{"role": "user", "content": "What is the capital of France?"}],
| ... )
| ```
|
| Example using Image + Text as input:
| ```py
| >>> from huggingface_hub import InferenceClient
|
| # provide a remote URL
| >>> image_url ="https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
| # or a base64-encoded image
| >>> image_path = "/path/to/image.jpeg"
| >>> with open(image_path, "rb") as f:
| ... base64_image = base64.b64encode(f.read()).decode("utf-8")
| >>> image_url = f"data:image/jpeg;base64,{base64_image}"
|
| >>> client = InferenceClient("meta-llama/Llama-3.2-11B-Vision-Instruct")
| >>> output = client.chat.completions.create(
| ... messages=[
| ... {
| ... "role": "user",
| ... "content": [
| ... {
| ... "type": "image_url",
| ... "image_url": {"url": image_url},
| ... },
| ... {
| ... "type": "text",
| ... "text": "Describe this image in one sentence.",
| ... },
| ... ],
| ... },
| ... ],
| ... )
| >>> output
| The image depicts the iconic Statue of Liberty situated in New York Harbor, New York, on a clear day.
| ```
|
| Example using tools:
| ```py
| >>> client = InferenceClient("meta-llama/Meta-Llama-3-70B-Instruct")
| >>> messages = [
| ... {
| ... "role": "system",
| ... "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.",
| ... },
| ... {
| ... "role": "user",
| ... "content": "What's the weather like the next 3 days in San Francisco, CA?",
| ... },
| ... ]
| >>> tools = [
| ... {
| ... "type": "function",
| ... "function": {
| ... "name": "get_current_weather",
| ... "description": "Get the current weather",
| ... "parameters": {
| ... "type": "object",
| ... "properties": {
| ... "location": {
| ... "type": "string",
| ... "description": "The city and state, e.g. San Francisco, CA",
| ... },
| ... "format": {
| ... "type": "string",
| ... "enum": ["celsius", "fahrenheit"],
| ... "description": "The temperature unit to use. Infer this from the users location.",
| ... },
| ... },
| ... "required": ["location", "format"],
| ... },
| ... },
| ... },
| ... {
| ... "type": "function",
| ... "function": {
| ... "name": "get_n_day_weather_forecast",
| ... "description": "Get an N-day weather forecast",
| ... "parameters": {
| ... "type": "object",
| ... "properties": {
| ... "location": {
| ... "type": "string",
| ... "description": "The city and state, e.g. San Francisco, CA",
| ... },
| ... "format": {
| ... "type": "string",
| ... "enum": ["celsius", "fahrenheit"],
| ... "description": "The temperature unit to use. Infer this from the users location.",
| ... },
| ... "num_days": {
| ... "type": "integer",
| ... "description": "The number of days to forecast",
| ... },
| ... },
| ... "required": ["location", "format", "num_days"],
| ... },
| ... },
| ... },
| ... ]
|
| >>> response = client.chat_completion(
| ... model="meta-llama/Meta-Llama-3-70B-Instruct",
| ... messages=messages,
| ... tools=tools,
| ... tool_choice="auto",
| ... max_tokens=500,
| ... )
| >>> response.choices[0].message.tool_calls[0].function
| ChatCompletionOutputFunctionDefinition(
| arguments={
| 'location': 'San Francisco, CA',
| 'format': 'fahrenheit',
| 'num_days': 3
| },
| name='get_n_day_weather_forecast',
| description=None
| )
| ```
|
| Example using response_format:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient("meta-llama/Meta-Llama-3-70B-Instruct")
| >>> messages = [
| ... {
| ... "role": "user",
| ... "content": "I saw a puppy a cat and a raccoon during my bike ride in the park. What did I see and when?",
| ... },
| ... ]
| >>> response_format = {
| ... "type": "json",
| ... "value": {
| ... "properties": {
| ... "location": {"type": "string"},
| ... "activity": {"type": "string"},
| ... "animals_seen": {"type": "integer", "minimum": 1, "maximum": 5},
| ... "animals": {"type": "array", "items": {"type": "string"}},
| ... },
| ... "required": ["location", "activity", "animals_seen", "animals"],
| ... },
| ... }
| >>> response = client.chat_completion(
| ... messages=messages,
| ... response_format=response_format,
| ... max_tokens=500,
| ... )
| >>> response.choices[0].message.content
| '{
|
| "activity": "bike ride",
| "animals": ["puppy", "cat", "raccoon"],
| "animals_seen": 3,
| "location": "park"}'
| ```
|
| close(self)
|
| document_question_answering(self, image: Union[bytes, BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], question: str, *, model: str | None = None, doc_stride: int | None = None, handle_impossible_answer: bool | None = None, lang: str | None = None, max_answer_len: int | None = None, max_question_len: int | None = None, max_seq_len: int | None = None, top_k: int | None = None, word_boxes: list[list[float] | str] | None = None) -> list[huggingface_hub.inference._generated.types.document_question_answering.DocumentQuestionAnsweringOutputElement]
| Answer questions on document images.
|
| Args:
| image (`Union[str, Path, bytes, BinaryIO]`):
| The input image for the context. It can be raw bytes, an image file, or a URL to an online image.
| question (`str`):
| Question to be answered.
| model (`str`, *optional*):
| The model to use for the document question answering task. Can be a model ID hosted on the Hugging Face Hub or a URL to
| a deployed Inference Endpoint. If not provided, the default recommended document question answering model will be used.
| Defaults to None.
| doc_stride (`int`, *optional*):
| If the words in the document are too long to fit with the question for the model, it will be split in
| several chunks with some overlap. This argument controls the size of that overlap.
| handle_impossible_answer (`bool`, *optional*):
| Whether to accept impossible as an answer
| lang (`str`, *optional*):
| Language to use while running OCR. Defaults to english.
| max_answer_len (`int`, *optional*):
| The maximum length of predicted answers (e.g., only answers with a shorter length are considered).
| max_question_len (`int`, *optional*):
| The maximum length of the question after tokenization. It will be truncated if needed.
| max_seq_len (`int`, *optional*):
| The maximum length of the total sentence (context + question) in tokens of each chunk passed to the
| model. The context will be split in several chunks (using doc_stride as overlap) if needed.
| top_k (`int`, *optional*):
| The number of answers to return (will be chosen by order of likelihood). Can return less than top_k
| answers if there are not enough options available within the context.
| word_boxes (`list[Union[list[float], str`, *optional*):
| A list of words and bounding boxes (normalized 0->1000). If provided, the inference will skip the OCR
| step and use the provided bounding boxes instead.
| Returns:
| `list[DocumentQuestionAnsweringOutputElement]`: a list of [`DocumentQuestionAnsweringOutputElement`] items containing the predicted label, associated probability, word ids, and page number.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
| >>> client.document_question_answering(image="https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png", question="What is the invoice number?")
| [DocumentQuestionAnsweringOutputElement(answer='us-001', end=16, score=0.9999666213989258, start=16)]
| ```
|
| feature_extraction(self, text: str | list[str], *, normalize: bool | None = None, prompt_name: str | None = None, truncate: bool | None = None, truncation_direction: Optional[Literal['left', 'right']] = None, dimensions: int | None = None, encoding_format: Optional[Literal['float', 'base64']] = None, model: str | None = None) -> 'np.ndarray'
| Generate embeddings for a given text or batch of texts.
|
| Args:
| text (`str` or `list[str]`):
| The text or list of texts to embed.
| model (`str`, *optional*):
| The model to use for the feature extraction task. Can be a model ID hosted on the Hugging Face Hub or a URL to
| a deployed Inference Endpoint. If not provided, the default recommended feature extraction model will be used.
| Defaults to None.
| normalize (`bool`, *optional*):
| Whether to normalize the embeddings or not.
| Only available on server powered by Text-Embedding-Inference.
| prompt_name (`str`, *optional*):
| The name of the prompt that should be used by for encoding. If not set, no prompt will be applied.
| Must be a key in the `Sentence Transformers` configuration `prompts` dictionary.
| For example if ``prompt_name`` is "query" and the ``prompts`` is {"query": "query: ",...},
| then the sentence "What is the capital of France?" will be encoded as "query: What is the capital of France?"
| because the prompt text will be prepended before any text to encode.
| truncate (`bool`, *optional*):
| Whether to truncate the embeddings or not.
| Only available on server powered by Text-Embedding-Inference.
| truncation_direction (`Literal["left", "right"]`, *optional*):
| Which side of the input should be truncated when `truncate=True` is passed.
| dimensions (`int`, *optional*):
| The number of dimensions the resulting output embeddings should have.
| Only available on OpenAI-compatible embedding endpoints.
| encoding_format (`Literal["float", "base64"]`, *optional*):
| The format of the output embeddings. Either "float" or "base64".
| Only available on OpenAI-compatible embedding endpoints.
|
| Returns:
| `np.ndarray`: The embedding representing the input text(s) as a float32 numpy array.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
| >>> client.feature_extraction("Hi, who are you?")
| array([[ 2.424802 , 2.93384 , 1.1750331 , ..., 1.240499, -0.13776633, -0.7889173 ],
| [-0.42943227, -0.6364878 , -1.693462 , ..., 0.41978157, -2.4336355 , 0.6162071 ],
| ...,
| [ 0.28552425, -0.928395 , -1.2077185 , ..., 0.76810825, -2.1069427 , 0.6236161 ]], dtype=float32)
| ```
|
| fill_mask(self, text: str, *, model: str | None = None, targets: list[str] | None = None, top_k: int | None = None) -> list[huggingface_hub.inference._generated.types.fill_mask.FillMaskOutputElement]
| Fill in a hole with a missing word (token to be precise).
|
| Args:
| text (`str`):
| a string to be filled from, must contain the [MASK] token (check model card for exact name of the mask).
| model (`str`, *optional*):
| The model to use for the fill mask task. Can be a model ID hosted on the Hugging Face Hub or a URL to
| a deployed Inference Endpoint. If not provided, the default recommended fill mask model will be used.
| targets (`list[str`, *optional*):
| When passed, the model will limit the scores to the passed targets instead of looking up in the whole
| vocabulary. If the provided targets are not in the model vocab, they will be tokenized and the first
| resulting token will be used (with a warning, and that might be slower).
| top_k (`int`, *optional*):
| When passed, overrides the number of predictions to return.
| Returns:
| `list[FillMaskOutputElement]`: a list of [`FillMaskOutputElement`] items containing the predicted label, associated
| probability, token reference, and completed text.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
| >>> client.fill_mask("The goal of life is <mask>.")
| [
| FillMaskOutputElement(score=0.06897063553333282, token=11098, token_str=' happiness', sequence='The goal of life is happiness.'),
| FillMaskOutputElement(score=0.06554922461509705, token=45075, token_str=' immortality', sequence='The goal of life is immortality.')
| ]
| ```
|
| get_endpoint_info(self, *, model: str | None = None) -> dict[str, typing.Any]
| Get information about the deployed endpoint.
|
| This endpoint is only available on endpoints powered by Text-Generation-Inference (TGI) or Text-Embedding-Inference (TEI).
| Endpoints powered by `transformers` return an empty payload.
|
| Args:
| model (`str`, *optional*):
| The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
|
| Returns:
| `dict[str, Any]`: Information about the endpoint.
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient("meta-llama/Meta-Llama-3-70B-Instruct")
| >>> client.get_endpoint_info()
| {
| 'model_id': 'meta-llama/Meta-Llama-3-70B-Instruct',
| 'model_sha': None,
| 'model_dtype': 'torch.float16',
| 'model_device_type': 'cuda',
| 'model_pipeline_tag': None,
| 'max_concurrent_requests': 128,
| 'max_best_of': 2,
| 'max_stop_sequences': 4,
| 'max_input_length': 8191,
| 'max_total_tokens': 8192,
| 'waiting_served_ratio': 0.3,
| 'max_batch_total_tokens': 1259392,
| 'max_waiting_tokens': 20,
| 'max_batch_size': None,
| 'validation_workers': 32,
| 'max_client_batch_size': 4,
| 'version': '2.0.2',
| 'sha': 'dccab72549635c7eb5ddb17f43f0b7cdff07c214',
| 'docker_label': 'sha-dccab72'
| }
| ```
|
| health_check(self, model: str | None = None) -> bool
| Check the health of the deployed endpoint.
|
| Health check is only available with Inference Endpoints powered by Text-Generation-Inference (TGI) or Text-Embedding-Inference (TEI).
|
| Args:
| model (`str`, *optional*):
| URL of the Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
|
| Returns:
| `bool`: True if everything is working fine.
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient("https://jzgu0buei5.us-east-1.aws.endpoints.huggingface.cloud")
| >>> client.health_check()
| True
| ```
|
| image_classification(self, image: Union[bytes, BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], *, model: str | None = None, function_to_apply: Optional[ForwardRef('ImageClassificationOutputTransform')] = None, top_k: int | None = None) -> list[huggingface_hub.inference._generated.types.image_classification.ImageClassificationOutputElement]
| Perform image classification on the given image using the specified model.
|
| Args:
| image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`):
| The image to classify. It can be raw bytes, an image file, a URL to an online image, or a PIL Image.
| model (`str`, *optional*):
| The model to use for image classification. Can be a model ID hosted on the Hugging Face Hub or a URL to a
| deployed Inference Endpoint. If not provided, the default recommended model for image classification will be used.
| function_to_apply (`"ImageClassificationOutputTransform"`, *optional*):
| The function to apply to the model outputs in order to retrieve the scores.
| top_k (`int`, *optional*):
| When specified, limits the output to the top K most probable classes.
| Returns:
| `list[ImageClassificationOutputElement]`: a list of [`ImageClassificationOutputElement`] items containing the predicted label and associated probability.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
| >>> client.image_classification("https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg")
| [ImageClassificationOutputElement(label='Blenheim spaniel', score=0.9779096841812134), ...]
| ```
|
| image_segmentation(self, image: Union[bytes, BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], *, model: str | None = None, mask_threshold: float | None = None, overlap_mask_area_threshold: float | None = None, subtask: Optional[ForwardRef('ImageSegmentationSubtask')] = None, threshold: float | None = None) -> list[huggingface_hub.inference._generated.types.image_segmentation.ImageSegmentationOutputElement]
| Perform image segmentation on the given image using the specified model.
|
| > [!WARNING]
| > You must have `PIL` installed if you want to work with images (`pip install Pillow`).
|
| Args:
| image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`):
| The image to segment. It can be raw bytes, an image file, a URL to an online image, or a PIL Image.
| model (`str`, *optional*):
| The model to use for image segmentation. Can be a model ID hosted on the Hugging Face Hub or a URL to a
| deployed Inference Endpoint. If not provided, the default recommended model for image segmentation will be used.
| mask_threshold (`float`, *optional*):
| Threshold to use when turning the predicted masks into binary values.
| overlap_mask_area_threshold (`float`, *optional*):
| Mask overlap threshold to eliminate small, disconnected segments.
| subtask (`"ImageSegmentationSubtask"`, *optional*):
| Segmentation task to be performed, depending on model capabilities.
| threshold (`float`, *optional*):
| Probability threshold to filter out predicted masks.
| Returns:
| `list[ImageSegmentationOutputElement]`: A list of [`ImageSegmentationOutputElement`] items containing the segmented masks and associated attributes.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
| >>> client.image_segmentation("cat.jpg")
| [ImageSegmentationOutputElement(score=0.989008, label='LABEL_184', mask=<PIL.PngImagePlugin.PngImageFile image mode=L size=400x300 at 0x7FDD2B129CC0>), ...]
| ```
|
| image_to_image(self, image: Union[bytes, BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], prompt: str | None = None, *, negative_prompt: str | None = None, num_inference_steps: int | None = None, guidance_scale: float | None = None, model: str | None = None, target_size: huggingface_hub.inference._generated.types.image_to_image.ImageToImageTargetSize | None = None, **kwargs) -> 'Image'
| Perform image-to-image translation using a specified model.
|
| > [!WARNING]
| > You must have `PIL` installed if you want to work with images (`pip install Pillow`).
|
| Args:
| image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`):
| The input image for translation. It can be raw bytes, an image file, a URL to an online image, or a PIL Image.
| prompt (`str`, *optional*):
| The text prompt to guide the image generation.
| negative_prompt (`str`, *optional*):
| One prompt to guide what NOT to include in image generation.
| num_inference_steps (`int`, *optional*):
| For diffusion models. The number of denoising steps. More denoising steps usually lead to a higher
| quality image at the expense of slower inference.
| guidance_scale (`float`, *optional*):
| For diffusion models. A higher guidance scale value encourages the model to generate images closely
| linked to the text prompt at the expense of lower image quality.
| model (`str`, *optional*):
| The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
| target_size (`ImageToImageTargetSize`, *optional*):
| The size in pixels of the output image. This parameter is only supported by some providers and for
| specific models. It will be ignored when unsupported.
|
| Returns:
| `Image`: The translated image.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
| >>> image = client.image_to_image("cat.jpg", prompt="turn the cat into a tiger")
| >>> image.save("tiger.jpg")
| ```
|
| image_to_text(self, image: Union[bytes, BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], *, model: str | None = None) -> huggingface_hub.inference._generated.types.image_to_text.ImageToTextOutput
| Takes an input image and return text.
|
| Models can have very different outputs depending on your use case (image captioning, optical character recognition
| (OCR), Pix2Struct, etc.). Please have a look to the model card to learn more about a model's specificities.
|
| Args:
| image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`):
| The input image to caption. It can be raw bytes, an image file, a URL to an online image, or a PIL Image.
| model (`str`, *optional*):
| The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
|
| Returns:
| [`ImageToTextOutput`]: The generated text.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
| >>> client.image_to_text("cat.jpg")
| 'a cat standing in a grassy field '
| >>> client.image_to_text("https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg")
| 'a dog laying on the grass next to a flower pot '
| ```
|
| image_to_video(self, image: Union[bytes, BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], *, model: str | None = None, prompt: str | None = None, negative_prompt: str | None = None, num_frames: float | None = None, num_inference_steps: int | None = None, guidance_scale: float | None = None, seed: int | None = None, target_size: huggingface_hub.inference._generated.types.image_to_video.ImageToVideoTargetSize | None = None, **kwargs) -> bytes
| Generate a video from an input image.
|
| Args:
| image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`):
| The input image to generate a video from. It can be raw bytes, an image file, a URL to an online image, or a PIL Image.
| model (`str`, *optional*):
| The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
| prompt (`str`, *optional*):
| The text prompt to guide the video generation.
| negative_prompt (`str`, *optional*):
| One prompt to guide what NOT to include in video generation.
| num_frames (`float`, *optional*):
| The num_frames parameter determines how many video frames are generated.
| num_inference_steps (`int`, *optional*):
| For diffusion models. The number of denoising steps. More denoising steps usually lead to a higher
| quality image at the expense of slower inference.
| guidance_scale (`float`, *optional*):
| For diffusion models. A higher guidance scale value encourages the model to generate videos closely
| linked to the text prompt at the expense of lower image quality.
| seed (`int`, *optional*):
| The seed to use for the video generation.
| target_size (`ImageToVideoTargetSize`, *optional*):
| The size in pixel of the output video frames.
| num_inference_steps (`int`, *optional*):
| The number of denoising steps. More denoising steps usually lead to a higher quality video at the
| expense of slower inference.
| seed (`int`, *optional*):
| Seed for the random number generator.
|
| Returns:
| `bytes`: The generated video.
|
| Examples:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
| >>> video = client.image_to_video("cat.jpg", model="Wan-AI/Wan2.2-I2V-A14B", prompt="turn the cat into a tiger")
| >>> with open("tiger.mp4", "wb") as f:
| ... f.write(video)
| ```
|
| object_detection(self, image: Union[bytes, BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], *, model: str | None = None, threshold: float | None = None) -> list[huggingface_hub.inference._generated.types.object_detection.ObjectDetectionOutputElement]
| Perform object detection on the given image using the specified model.
|
| > [!WARNING]
| > You must have `PIL` installed if you want to work with images (`pip install Pillow`).
|
| Args:
| image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`):
| The image to detect objects on. It can be raw bytes, an image file, a URL to an online image, or a PIL Image.
| model (`str`, *optional*):
| The model to use for object detection. Can be a model ID hosted on the Hugging Face Hub or a URL to a
| deployed Inference Endpoint. If not provided, the default recommended model for object detection (DETR) will be used.
| threshold (`float`, *optional*):
| The probability necessary to make a prediction.
| Returns:
| `list[ObjectDetectionOutputElement]`: A list of [`ObjectDetectionOutputElement`] items containing the bounding boxes and associated attributes.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
| `ValueError`:
| If the request output is not a List.
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
| >>> client.object_detection("people.jpg")
| [ObjectDetectionOutputElement(score=0.9486683011054993, label='person', box=ObjectDetectionBoundingBox(xmin=59, ymin=39, xmax=420, ymax=510)), ...]
| ```
|
| question_answering(self, question: str, context: str, *, model: str | None = None, align_to_words: bool | None = None, doc_stride: int | None = None, handle_impossible_answer: bool | None = None, max_answer_len: int | None = None, max_question_len: int | None = None, max_seq_len: int | None = None, top_k: int | None = None) -> huggingface_hub.inference._generated.types.question_answering.QuestionAnsweringOutputElement | list[huggingface_hub.inference._generated.types.question_answering.QuestionAnsweringOutputElement]
| Retrieve the answer to a question from a given text.
|
| Args:
| question (`str`):
| Question to be answered.
| context (`str`):
| The context of the question.
| model (`str`):
| The model to use for the question answering task. Can be a model ID hosted on the Hugging Face Hub or a URL to
| a deployed Inference Endpoint.
| align_to_words (`bool`, *optional*):
| Attempts to align the answer to real words. Improves quality on space separated languages. Might hurt
| on non-space-separated languages (like Japanese or Chinese)
| doc_stride (`int`, *optional*):
| If the context is too long to fit with the question for the model, it will be split in several chunks
| with some overlap. This argument controls the size of that overlap.
| handle_impossible_answer (`bool`, *optional*):
| Whether to accept impossible as an answer.
| max_answer_len (`int`, *optional*):
| The maximum length of predicted answers (e.g., only answers with a shorter length are considered).
| max_question_len (`int`, *optional*):
| The maximum length of the question after tokenization. It will be truncated if needed.
| max_seq_len (`int`, *optional*):
| The maximum length of the total sentence (context + question) in tokens of each chunk passed to the
| model. The context will be split in several chunks (using docStride as overlap) if needed.
| top_k (`int`, *optional*):
| The number of answers to return (will be chosen by order of likelihood). Note that we return less than
| topk answers if there are not enough options available within the context.
|
| Returns:
| Union[`QuestionAnsweringOutputElement`, list[`QuestionAnsweringOutputElement`]]:
| When top_k is 1 or not provided, it returns a single `QuestionAnsweringOutputElement`.
| When top_k is greater than 1, it returns a list of `QuestionAnsweringOutputElement`.
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
| >>> client.question_answering(question="What's my name?", context="My name is Clara and I live in Berkeley.")
| QuestionAnsweringOutputElement(answer='Clara', end=16, score=0.9326565265655518, start=11)
| ```
|
| sentence_similarity(self, sentence: str, other_sentences: list[str], *, model: str | None = None) -> list[float]
| Compute the semantic similarity between a sentence and a list of other sentences by comparing their embeddings.
|
| Args:
| sentence (`str`):
| The main sentence to compare to others.
| other_sentences (`list[str]`):
| The list of sentences to compare to.
| model (`str`, *optional*):
| The model to use for the sentence similarity task. Can be a model ID hosted on the Hugging Face Hub or a URL to
| a deployed Inference Endpoint. If not provided, the default recommended sentence similarity model will be used.
| Defaults to None.
|
| Returns:
| `list[float]`: The embedding representing the input text.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
| >>> client.sentence_similarity(
| ... "Machine learning is so easy.",
| ... other_sentences=[
| ... "Deep learning is so straightforward.",
| ... "This is so difficult, like rocket science.",
| ... "I can't believe how much I struggled with this.",
| ... ],
| ... )
| [0.7785726189613342, 0.45876261591911316, 0.2906220555305481]
| ```
|
| summarization(self, text: str, *, model: str | None = None, clean_up_tokenization_spaces: bool | None = None, generate_parameters: dict[str, typing.Any] | None = None, truncation: Optional[ForwardRef('SummarizationTruncationStrategy')] = None) -> huggingface_hub.inference._generated.types.summarization.SummarizationOutput
| Generate a summary of a given text using a specified model.
|
| Args:
| text (`str`):
| The input text to summarize.
| model (`str`, *optional*):
| The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. If not provided, the default recommended model for summarization will be used.
| clean_up_tokenization_spaces (`bool`, *optional*):
| Whether to clean up the potential extra spaces in the text output.
| generate_parameters (`dict[str, Any]`, *optional*):
| Additional parametrization of the text generation algorithm.
| truncation (`"SummarizationTruncationStrategy"`, *optional*):
| The truncation strategy to use.
| Returns:
| [`SummarizationOutput`]: The generated summary text.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
| >>> client.summarization("The Eiffel tower...")
| SummarizationOutput(generated_text="The Eiffel tower is one of the most famous landmarks in the world....")
| ```
|
| table_question_answering(self, table: dict[str, typing.Any], query: str, *, model: str | None = None, padding: Optional[ForwardRef('Padding')] = None, sequential: bool | None = None, truncation: bool | None = None) -> huggingface_hub.inference._generated.types.table_question_answering.TableQuestionAnsweringOutputElement
| Retrieve the answer to a question from information given in a table.
|
| Args:
| table (`str`):
| A table of data represented as a dict of lists where entries are headers and the lists are all the
| values, all lists must have the same size.
| query (`str`):
| The query in plain text that you want to ask the table.
| model (`str`):
| The model to use for the table-question-answering task. Can be a model ID hosted on the Hugging Face
| Hub or a URL to a deployed Inference Endpoint.
| padding (`"Padding"`, *optional*):
| Activates and controls padding.
| sequential (`bool`, *optional*):
| Whether to do inference sequentially or as a batch. Batching is faster, but models like SQA require the
| inference to be done sequentially to extract relations within sequences, given their conversational
| nature.
| truncation (`bool`, *optional*):
| Activates and controls truncation.
|
| Returns:
| [`TableQuestionAnsweringOutputElement`]: a table question answering output containing the answer, coordinates, cells and the aggregator used.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
| >>> query = "How many stars does the transformers repository have?"
| >>> table = {"Repository": ["Transformers", "Datasets", "Tokenizers"], "Stars": ["36542", "4512", "3934"]}
| >>> client.table_question_answering(table, query, model="google/tapas-base-finetuned-wtq")
| TableQuestionAnsweringOutputElement(answer='36542', coordinates=[[0, 1]], cells=['36542'], aggregator='AVERAGE')
| ```
|
| tabular_classification(self, table: dict[str, typing.Any], *, model: str | None = None) -> list[str]
| Classifying a target category (a group) based on a set of attributes.
|
| Args:
| table (`dict[str, Any]`):
| Set of attributes to classify.
| model (`str`, *optional*):
| The model to use for the tabular classification task. Can be a model ID hosted on the Hugging Face Hub or a URL to
| a deployed Inference Endpoint. If not provided, the default recommended tabular classification model will be used.
| Defaults to None.
|
| Returns:
| `List`: a list of labels, one per row in the initial table.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
| >>> table = {
| ... "fixed_acidity": ["7.4", "7.8", "10.3"],
| ... "volatile_acidity": ["0.7", "0.88", "0.32"],
| ... "citric_acid": ["0", "0", "0.45"],
| ... "residual_sugar": ["1.9", "2.6", "6.4"],
| ... "chlorides": ["0.076", "0.098", "0.073"],
| ... "free_sulfur_dioxide": ["11", "25", "5"],
| ... "total_sulfur_dioxide": ["34", "67", "13"],
| ... "density": ["0.9978", "0.9968", "0.9976"],
| ... "pH": ["3.51", "3.2", "3.23"],
| ... "sulphates": ["0.56", "0.68", "0.82"],
| ... "alcohol": ["9.4", "9.8", "12.6"],
| ... }
| >>> client.tabular_classification(table=table, model="julien-c/wine-quality")
| ["5", "5", "5"]
| ```
|
| tabular_regression(self, table: dict[str, typing.Any], *, model: str | None = None) -> list[float]
| Predicting a numerical target value given a set of attributes/features in a table.
|
| Args:
| table (`dict[str, Any]`):
| Set of attributes stored in a table. The attributes used to predict the target can be both numerical and categorical.
| model (`str`, *optional*):
| The model to use for the tabular regression task. Can be a model ID hosted on the Hugging Face Hub or a URL to
| a deployed Inference Endpoint. If not provided, the default recommended tabular regression model will be used.
| Defaults to None.
|
| Returns:
| `List`: a list of predicted numerical target values.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
| >>> table = {
| ... "Height": ["11.52", "12.48", "12.3778"],
| ... "Length1": ["23.2", "24", "23.9"],
| ... "Length2": ["25.4", "26.3", "26.5"],
| ... "Length3": ["30", "31.2", "31.1"],
| ... "Species": ["Bream", "Bream", "Bream"],
| ... "Width": ["4.02", "4.3056", "4.6961"],
| ... }
| >>> client.tabular_regression(table, model="scikit-learn/Fish-Weight")
| [110, 120, 130]
| ```
|
| text_classification(self, text: str, *, model: str | None = None, top_k: int | None = None, function_to_apply: Optional[ForwardRef('TextClassificationOutputTransform')] = None) -> list[huggingface_hub.inference._generated.types.text_classification.TextClassificationOutputElement]
| Perform text classification (e.g. sentiment-analysis) on the given text.
|
| Args:
| text (`str`):
| A string to be classified.
| model (`str`, *optional*):
| The model to use for the text classification task. Can be a model ID hosted on the Hugging Face Hub or a URL to
| a deployed Inference Endpoint. If not provided, the default recommended text classification model will be used.
| Defaults to None.
| top_k (`int`, *optional*):
| When specified, limits the output to the top K most probable classes.
| function_to_apply (`"TextClassificationOutputTransform"`, *optional*):
| The function to apply to the model outputs in order to retrieve the scores.
|
| Returns:
| `list[TextClassificationOutputElement]`: a list of [`TextClassificationOutputElement`] items containing the predicted label and associated probability.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
| >>> client.text_classification("I like you")
| [
| TextClassificationOutputElement(label='POSITIVE', score=0.9998695850372314),
| TextClassificationOutputElement(label='NEGATIVE', score=0.0001304351753788069),
| ]
| ```
|
| text_generation(self, prompt: str, *, details: bool | None = None, stream: bool | None = None, model: str | None = None, adapter_id: str | None = None, best_of: int | None = None, decoder_input_details: bool | None = None, do_sample: bool | None = None, frequency_penalty: float | None = None, grammar: huggingface_hub.inference._generated.types.text_generation.TextGenerationInputGrammarType | None = None, max_new_tokens: int | None = None, repetition_penalty: float | None = None, return_full_text: bool | None = None, seed: int | None = None, stop: list[str] | None = None, stop_sequences: list[str] | None = None, temperature: float | None = None, top_k: int | None = None, top_n_tokens: int | None = None, top_p: float | None = None, truncate: int | None = None, typical_p: float | None = None, watermark: bool | None = None) -> str | huggingface_hub.inference._generated.types.text_generation.TextGenerationOutput | collections.abc.Iterable[str] | collections.abc.Iterable[huggingface_hub.inference._generated.types.text_generation.TextGenerationStreamOutput]
| Given a prompt, generate the following text.
|
| > [!TIP]
| > If you want to generate a response from chat messages, you should use the [`InferenceClient.chat_completion`] method.
| > It accepts a list of messages instead of a single text prompt and handles the chat templating for you.
|
| Args:
| prompt (`str`):
| Input text.
| details (`bool`, *optional*):
| By default, text_generation returns a string. Pass `details=True` if you want a detailed output (tokens,
| probabilities, seed, finish reason, etc.). Only available for models running on with the
| `text-generation-inference` backend.
| stream (`bool`, *optional*):
| By default, text_generation returns the full generated text. Pass `stream=True` if you want a stream of
| tokens to be returned. Only available for models running on with the `text-generation-inference`
| backend.
| model (`str`, *optional*):
| The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
| adapter_id (`str`, *optional*):
| Lora adapter id.
| best_of (`int`, *optional*):
| Generate best_of sequences and return the one if the highest token logprobs.
| decoder_input_details (`bool`, *optional*):
| Return the decoder input token logprobs and ids. You must set `details=True` as well for it to be taken
| into account. Defaults to `False`.
| do_sample (`bool`, *optional*):
| Activate logits sampling
| frequency_penalty (`float`, *optional*):
| Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in
| the text so far, decreasing the model's likelihood to repeat the same line verbatim.
| grammar ([`TextGenerationInputGrammarType`], *optional*):
| Grammar constraints. Can be either a JSONSchema or a regex.
| max_new_tokens (`int`, *optional*):
| Maximum number of generated tokens. Defaults to 100.
| repetition_penalty (`float`, *optional*):
| The parameter for repetition penalty. 1.0 means no penalty. See [this
| paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
| return_full_text (`bool`, *optional*):
| Whether to prepend the prompt to the generated text
| seed (`int`, *optional*):
| Random sampling seed
| stop (`list[str]`, *optional*):
| Stop generating tokens if a member of `stop` is generated.
| stop_sequences (`list[str]`, *optional*):
| Deprecated argument. Use `stop` instead.
| temperature (`float`, *optional*):
| The value used to module the logits distribution.
| top_n_tokens (`int`, *optional*):
| Return information about the `top_n_tokens` most likely tokens at each generation step, instead of
| just the sampled token.
| top_k (`int`, *optional`):
| The number of highest probability vocabulary tokens to keep for top-k-filtering.
| top_p (`float`, *optional`):
| If set to < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or
| higher are kept for generation.
| truncate (`int`, *optional`):
| Truncate inputs tokens to the given size.
| typical_p (`float`, *optional`):
| Typical Decoding mass
| See [Typical Decoding for Natural Language Generation](https://arxiv.org/abs/2202.00666) for more information
| watermark (`bool`, *optional*):
| Watermarking with [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226)
|
| Returns:
| `Union[str, TextGenerationOutput, Iterable[str], Iterable[TextGenerationStreamOutput]]`:
| Generated text returned from the server:
| - if `stream=False` and `details=False`, the generated text is returned as a `str` (default)
| - if `stream=True` and `details=False`, the generated text is returned token by token as a `Iterable[str]`
| - if `stream=False` and `details=True`, the generated text is returned with more details as a [`~huggingface_hub.TextGenerationOutput`]
| - if `details=True` and `stream=True`, the generated text is returned token by token as a iterable of [`~huggingface_hub.TextGenerationStreamOutput`]
|
| Raises:
| `ValidationError`:
| If input values are not valid. No HTTP call is made to the server.
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
|
| # Case 1: generate text
| >>> client.text_generation("The huggingface_hub library is ", max_new_tokens=12)
| '100% open source and built to be easy to use.'
|
| # Case 2: iterate over the generated tokens. Useful for large generation.
| >>> for token in client.text_generation("The huggingface_hub library is ", max_new_tokens=12, stream=True):
| ... print(token)
| 100
| %
| open
| source
| and
| built
| to
| be
| easy
| to
| use
| .
|
| # Case 3: get more details about the generation process.
| >>> client.text_generation("The huggingface_hub library is ", max_new_tokens=12, details=True)
| TextGenerationOutput(
| generated_text='100% open source and built to be easy to use.',
| details=TextGenerationDetails(
| finish_reason='length',
| generated_tokens=12,
| seed=None,
| prefill=[
| TextGenerationPrefillOutputToken(id=487, text='The', logprob=None),
| TextGenerationPrefillOutputToken(id=53789, text=' hugging', logprob=-13.171875),
| (...)
| TextGenerationPrefillOutputToken(id=204, text=' ', logprob=-7.0390625)
| ],
| tokens=[
| TokenElement(id=1425, text='100', logprob=-1.0175781, special=False),
| TokenElement(id=16, text='%', logprob=-0.0463562, special=False),
| (...)
| TokenElement(id=25, text='.', logprob=-0.5703125, special=False)
| ],
| best_of_sequences=None
| )
| )
|
| # Case 4: iterate over the generated tokens with more details.
| # Last object is more complete, containing the full generated text and the finish reason.
| >>> for details in client.text_generation("The huggingface_hub library is ", max_new_tokens=12, details=True, stream=True):
| ... print(details)
| ...
| TextGenerationStreamOutput(token=TokenElement(id=1425, text='100', logprob=-1.0175781, special=False), generated_text=None, details=None)
| TextGenerationStreamOutput(token=TokenElement(id=16, text='%', logprob=-0.0463562, special=False), generated_text=None, details=None)
| TextGenerationStreamOutput(token=TokenElement(id=1314, text=' open', logprob=-1.3359375, special=False), generated_text=None, details=None)
| TextGenerationStreamOutput(token=TokenElement(id=3178, text=' source', logprob=-0.28100586, special=False), generated_text=None, details=None)
| TextGenerationStreamOutput(token=TokenElement(id=273, text=' and', logprob=-0.5961914, special=False), generated_text=None, details=None)
| TextGenerationStreamOutput(token=TokenElement(id=3426, text=' built', logprob=-1.9423828, special=False), generated_text=None, details=None)
| TextGenerationStreamOutput(token=TokenElement(id=271, text=' to', logprob=-1.4121094, special=False), generated_text=None, details=None)
| TextGenerationStreamOutput(token=TokenElement(id=314, text=' be', logprob=-1.5224609, special=False), generated_text=None, details=None)
| TextGenerationStreamOutput(token=TokenElement(id=1833, text=' easy', logprob=-2.1132812, special=False), generated_text=None, details=None)
| TextGenerationStreamOutput(token=TokenElement(id=271, text=' to', logprob=-0.08520508, special=False), generated_text=None, details=None)
| TextGenerationStreamOutput(token=TokenElement(id=745, text=' use', logprob=-0.39453125, special=False), generated_text=None, details=None)
| TextGenerationStreamOutput(token=TokenElement(
| id=25,
| text='.',
| logprob=-0.5703125,
| special=False),
| generated_text='100% open source and built to be easy to use.',
| details=TextGenerationStreamOutputStreamDetails(finish_reason='length', generated_tokens=12, seed=None)
| )
|
| # Case 5: generate constrained output using grammar
| >>> response = client.text_generation(
| ... prompt="I saw a puppy a cat and a raccoon during my bike ride in the park",
| ... model="HuggingFaceH4/zephyr-orpo-141b-A35b-v0.1",
| ... max_new_tokens=100,
| ... repetition_penalty=1.3,
| ... grammar={
| ... "type": "json",
| ... "value": {
| ... "properties": {
| ... "location": {"type": "string"},
| ... "activity": {"type": "string"},
| ... "animals_seen": {"type": "integer", "minimum": 1, "maximum": 5},
| ... "animals": {"type": "array", "items": {"type": "string"}},
| ... },
| ... "required": ["location", "activity", "animals_seen", "animals"],
| ... },
| ... },
| ... )
| >>> json.loads(response)
| {
| "activity": "bike riding",
| "animals": ["puppy", "cat", "raccoon"],
| "animals_seen": 3,
| "location": "park"
| }
| ```
|
| text_to_image(self, prompt: str, *, negative_prompt: str | None = None, height: int | None = None, width: int | None = None, num_inference_steps: int | None = None, guidance_scale: float | None = None, model: str | None = None, scheduler: str | None = None, seed: int | None = None, extra_body: dict[str, typing.Any] | None = None) -> 'Image'
| Generate an image based on a given text using a specified model.
|
| > [!WARNING]
| > You must have `PIL` installed if you want to work with images (`pip install Pillow`).
|
| > [!TIP]
| > You can pass provider-specific parameters to the model by using the `extra_body` argument.
|
| Args:
| prompt (`str`):
| The prompt to generate an image from.
| negative_prompt (`str`, *optional*):
| One prompt to guide what NOT to include in image generation.
| height (`int`, *optional*):
| The height in pixels of the output image
| width (`int`, *optional*):
| The width in pixels of the output image
| num_inference_steps (`int`, *optional*):
| The number of denoising steps. More denoising steps usually lead to a higher quality image at the
| expense of slower inference.
| guidance_scale (`float`, *optional*):
| A higher guidance scale value encourages the model to generate images closely linked to the text
| prompt, but values too high may cause saturation and other artifacts.
| model (`str`, *optional*):
| The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. If not provided, the default recommended text-to-image model will be used.
| Defaults to None.
| scheduler (`str`, *optional*):
| Override the scheduler with a compatible one.
| seed (`int`, *optional*):
| Seed for the random number generator.
| extra_body (`dict[str, Any]`, *optional*):
| Additional provider-specific parameters to pass to the model. Refer to the provider's documentation
| for supported parameters.
|
| Returns:
| `Image`: The generated image.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
|
| >>> image = client.text_to_image("An astronaut riding a horse on the moon.")
| >>> image.save("astronaut.png")
|
| >>> image = client.text_to_image(
| ... "An astronaut riding a horse on the moon.",
| ... negative_prompt="low resolution, blurry",
| ... model="stabilityai/stable-diffusion-2-1",
| ... )
| >>> image.save("better_astronaut.png")
| ```
| Example using a third-party provider directly. Usage will be billed on your fal.ai account.
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient(
| ... provider="fal-ai", # Use fal.ai provider
| ... api_key="fal-ai-api-key", # Pass your fal.ai API key
| ... )
| >>> image = client.text_to_image(
| ... "A majestic lion in a fantasy forest",
| ... model="black-forest-labs/FLUX.1-schnell",
| ... )
| >>> image.save("lion.png")
| ```
|
| Example using a third-party provider through Hugging Face Routing. Usage will be billed on your Hugging Face account.
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient(
| ... provider="replicate", # Use replicate provider
| ... api_key="hf_...", # Pass your HF token
| ... )
| >>> image = client.text_to_image(
| ... "An astronaut riding a horse on the moon.",
| ... model="black-forest-labs/FLUX.1-dev",
| ... )
| >>> image.save("astronaut.png")
| ```
|
| Example using Replicate provider with extra parameters
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient(
| ... provider="replicate", # Use replicate provider
| ... api_key="hf_...", # Pass your HF token
| ... )
| >>> image = client.text_to_image(
| ... "An astronaut riding a horse on the moon.",
| ... model="black-forest-labs/FLUX.1-schnell",
| ... extra_body={"output_quality": 100},
| ... )
| >>> image.save("astronaut.png")
| ```
|
| text_to_speech(self, text: str, *, model: str | None = None, do_sample: bool | None = None, early_stopping: Union[bool, ForwardRef('TextToSpeechEarlyStoppingEnum'), NoneType] = None, epsilon_cutoff: float | None = None, eta_cutoff: float | None = None, max_length: int | None = None, max_new_tokens: int | None = None, min_length: int | None = None, min_new_tokens: int | None = None, num_beam_groups: int | None = None, num_beams: int | None = None, penalty_alpha: float | None = None, temperature: float | None = None, top_k: int | None = None, top_p: float | None = None, typical_p: float | None = None, use_cache: bool | None = None, extra_body: dict[str, typing.Any] | None = None) -> bytes
| Synthesize an audio of a voice pronouncing a given text.
|
| > [!TIP]
| > You can pass provider-specific parameters to the model by using the `extra_body` argument.
|
| Args:
| text (`str`):
| The text to synthesize.
| model (`str`, *optional*):
| The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. If not provided, the default recommended text-to-speech model will be used.
| Defaults to None.
| do_sample (`bool`, *optional*):
| Whether to use sampling instead of greedy decoding when generating new tokens.
| early_stopping (`Union[bool, "TextToSpeechEarlyStoppingEnum"]`, *optional*):
| Controls the stopping condition for beam-based methods.
| epsilon_cutoff (`float`, *optional*):
| If set to float strictly between 0 and 1, only tokens with a conditional probability greater than
| epsilon_cutoff will be sampled. In the paper, suggested values range from 3e-4 to 9e-4, depending on
| the size of the model. See [Truncation Sampling as Language Model
| Desmoothing](https://hf.co/papers/2210.15191) for more details.
| eta_cutoff (`float`, *optional*):
| Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to float strictly
| between 0 and 1, a token is only considered if it is greater than either eta_cutoff or sqrt(eta_cutoff)
| * exp(-entropy(softmax(next_token_logits))). The latter term is intuitively the expected next token
| probability, scaled by sqrt(eta_cutoff). In the paper, suggested values range from 3e-4 to 2e-3,
| depending on the size of the model. See [Truncation Sampling as Language Model
| Desmoothing](https://hf.co/papers/2210.15191) for more details.
| max_length (`int`, *optional*):
| The maximum length (in tokens) of the generated text, including the input.
| max_new_tokens (`int`, *optional*):
| The maximum number of tokens to generate. Takes precedence over max_length.
| min_length (`int`, *optional*):
| The minimum length (in tokens) of the generated text, including the input.
| min_new_tokens (`int`, *optional*):
| The minimum number of tokens to generate. Takes precedence over min_length.
| num_beam_groups (`int`, *optional*):
| Number of groups to divide num_beams into in order to ensure diversity among different groups of beams.
| See [this paper](https://hf.co/papers/1610.02424) for more details.
| num_beams (`int`, *optional*):
| Number of beams to use for beam search.
| penalty_alpha (`float`, *optional*):
| The value balances the model confidence and the degeneration penalty in contrastive search decoding.
| temperature (`float`, *optional*):
| The value used to modulate the next token probabilities.
| top_k (`int`, *optional*):
| The number of highest probability vocabulary tokens to keep for top-k-filtering.
| top_p (`float`, *optional*):
| If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to
| top_p or higher are kept for generation.
| typical_p (`float`, *optional*):
| Local typicality measures how similar the conditional probability of predicting a target token next is
| to the expected conditional probability of predicting a random token next, given the partial text
| already generated. If set to float < 1, the smallest set of the most locally typical tokens with
| probabilities that add up to typical_p or higher are kept for generation. See [this
| paper](https://hf.co/papers/2202.00666) for more details.
| use_cache (`bool`, *optional*):
| Whether the model should use the past last key/values attentions to speed up decoding
| extra_body (`dict[str, Any]`, *optional*):
| Additional provider-specific parameters to pass to the model. Refer to the provider's documentation
| for supported parameters.
| Returns:
| `bytes`: The generated audio.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| >>> from pathlib import Path
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
|
| >>> audio = client.text_to_speech("Hello world")
| >>> Path("hello_world.flac").write_bytes(audio)
| ```
|
| Example using a third-party provider directly. Usage will be billed on your Replicate account.
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient(
| ... provider="replicate",
| ... api_key="your-replicate-api-key", # Pass your Replicate API key directly
| ... )
| >>> audio = client.text_to_speech(
| ... text="Hello world",
| ... model="OuteAI/OuteTTS-0.3-500M",
| ... )
| >>> Path("hello_world.flac").write_bytes(audio)
| ```
|
| Example using a third-party provider through Hugging Face Routing. Usage will be billed on your Hugging Face account.
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient(
| ... provider="replicate",
| ... api_key="hf_...", # Pass your HF token
| ... )
| >>> audio =client.text_to_speech(
| ... text="Hello world",
| ... model="OuteAI/OuteTTS-0.3-500M",
| ... )
| >>> Path("hello_world.flac").write_bytes(audio)
| ```
| Example using Replicate provider with extra parameters
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient(
| ... provider="replicate", # Use replicate provider
| ... api_key="hf_...", # Pass your HF token
| ... )
| >>> audio = client.text_to_speech(
| ... "Hello, my name is Kororo, an awesome text-to-speech model.",
| ... model="hexgrad/Kokoro-82M",
| ... extra_body={"voice": "af_nicole"},
| ... )
| >>> Path("hello.flac").write_bytes(audio)
| ```
|
| Example music-gen using "YuE-s1-7B-anneal-en-cot" on fal.ai
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> lyrics = '''
| ... [verse]
| ... In the town where I was born
| ... Lived a man who sailed to sea
| ... And he told us of his life
| ... In the land of submarines
| ... So we sailed on to the sun
| ... 'Til we found a sea of green
| ... And we lived beneath the waves
| ... In our yellow submarine
|
| ... [chorus]
| ... We all live in a yellow submarine
| ... Yellow submarine, yellow submarine
| ... We all live in a yellow submarine
| ... Yellow submarine, yellow submarine
| ... '''
| >>> genres = "pavarotti-style tenor voice"
| >>> client = InferenceClient(
| ... provider="fal-ai",
| ... model="m-a-p/YuE-s1-7B-anneal-en-cot",
| ... api_key=...,
| ... )
| >>> audio = client.text_to_speech(lyrics, extra_body={"genres": genres})
| >>> with open("output.mp3", "wb") as f:
| ... f.write(audio)
| ```
|
| text_to_video(self, prompt: str, *, model: str | None = None, guidance_scale: float | None = None, negative_prompt: list[str] | None = None, num_frames: float | None = None, num_inference_steps: int | None = None, seed: int | None = None, extra_body: dict[str, typing.Any] | None = None) -> bytes
| Generate a video based on a given text.
|
| > [!TIP]
| > You can pass provider-specific parameters to the model by using the `extra_body` argument.
|
| Args:
| prompt (`str`):
| The prompt to generate a video from.
| model (`str`, *optional*):
| The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. If not provided, the default recommended text-to-video model will be used.
| Defaults to None.
| guidance_scale (`float`, *optional*):
| A higher guidance scale value encourages the model to generate videos closely linked to the text
| prompt, but values too high may cause saturation and other artifacts.
| negative_prompt (`list[str]`, *optional*):
| One or several prompt to guide what NOT to include in video generation.
| num_frames (`float`, *optional*):
| The num_frames parameter determines how many video frames are generated.
| num_inference_steps (`int`, *optional*):
| The number of denoising steps. More denoising steps usually lead to a higher quality video at the
| expense of slower inference.
| seed (`int`, *optional*):
| Seed for the random number generator.
| extra_body (`dict[str, Any]`, *optional*):
| Additional provider-specific parameters to pass to the model. Refer to the provider's documentation
| for supported parameters.
|
| Returns:
| `bytes`: The generated video.
|
| Example:
|
| Example using a third-party provider directly. Usage will be billed on your fal.ai account.
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient(
| ... provider="fal-ai", # Using fal.ai provider
| ... api_key="fal-ai-api-key", # Pass your fal.ai API key
| ... )
| >>> video = client.text_to_video(
| ... "A majestic lion running in a fantasy forest",
| ... model="tencent/HunyuanVideo",
| ... )
| >>> with open("lion.mp4", "wb") as file:
| ... file.write(video)
| ```
|
| Example using a third-party provider through Hugging Face Routing. Usage will be billed on your Hugging Face account.
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient(
| ... provider="replicate", # Using replicate provider
| ... api_key="hf_...", # Pass your HF token
| ... )
| >>> video = client.text_to_video(
| ... "A cat running in a park",
| ... model="genmo/mochi-1-preview",
| ... )
| >>> with open("cat.mp4", "wb") as file:
| ... file.write(video)
| ```
|
| token_classification(self, text: str, *, model: str | None = None, aggregation_strategy: Optional[ForwardRef('TokenClassificationAggregationStrategy')] = None, ignore_labels: list[str] | None = None, stride: int | None = None) -> list[huggingface_hub.inference._generated.types.token_classification.TokenClassificationOutputElement]
| Perform token classification on the given text.
| Usually used for sentence parsing, either grammatical, or Named Entity Recognition (NER) to understand keywords contained within text.
|
| Args:
| text (`str`):
| A string to be classified.
| model (`str`, *optional*):
| The model to use for the token classification task. Can be a model ID hosted on the Hugging Face Hub or a URL to
| a deployed Inference Endpoint. If not provided, the default recommended token classification model will be used.
| Defaults to None.
| aggregation_strategy (`"TokenClassificationAggregationStrategy"`, *optional*):
| The strategy used to fuse tokens based on model predictions
| ignore_labels (`list[str`, *optional*):
| A list of labels to ignore
| stride (`int`, *optional*):
| The number of overlapping tokens between chunks when splitting the input text.
|
| Returns:
| `list[TokenClassificationOutputElement]`: List of [`TokenClassificationOutputElement`] items containing the entity group, confidence score, word, start and end index.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
| >>> client.token_classification("My name is Sarah Jessica Parker but you can call me Jessica")
| [
| TokenClassificationOutputElement(
| entity_group='PER',
| score=0.9971321225166321,
| word='Sarah Jessica Parker',
| start=11,
| end=31,
| ),
| TokenClassificationOutputElement(
| entity_group='PER',
| score=0.9773476123809814,
| word='Jessica',
| start=52,
| end=59,
| )
| ]
| ```
|
| translation(self, text: str, *, model: str | None = None, src_lang: str | None = None, tgt_lang: str | None = None, clean_up_tokenization_spaces: bool | None = None, truncation: Optional[ForwardRef('TranslationTruncationStrategy')] = None, generate_parameters: dict[str, typing.Any] | None = None) -> huggingface_hub.inference._generated.types.translation.TranslationOutput
| Convert text from one language to another.
|
| Check out https://huggingface.co/tasks/translation for more information on how to choose the best model for
| your specific use case. Source and target languages usually depend on the model.
| However, it is possible to specify source and target languages for certain models. If you are working with one of these models,
| you can use `src_lang` and `tgt_lang` arguments to pass the relevant information.
|
| Args:
| text (`str`):
| A string to be translated.
| model (`str`, *optional*):
| The model to use for the translation task. Can be a model ID hosted on the Hugging Face Hub or a URL to
| a deployed Inference Endpoint. If not provided, the default recommended translation model will be used.
| Defaults to None.
| src_lang (`str`, *optional*):
| The source language of the text. Required for models that can translate from multiple languages.
| tgt_lang (`str`, *optional*):
| Target language to translate to. Required for models that can translate to multiple languages.
| clean_up_tokenization_spaces (`bool`, *optional*):
| Whether to clean up the potential extra spaces in the text output.
| truncation (`"TranslationTruncationStrategy"`, *optional*):
| The truncation strategy to use.
| generate_parameters (`dict[str, Any]`, *optional*):
| Additional parametrization of the text generation algorithm.
|
| Returns:
| [`TranslationOutput`]: The generated translated text.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
| `ValueError`:
| If only one of the `src_lang` and `tgt_lang` arguments are provided.
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
| >>> client.translation("My name is Wolfgang and I live in Berlin")
| 'Mein Name ist Wolfgang und ich lebe in Berlin.'
| >>> client.translation("My name is Wolfgang and I live in Berlin", model="Helsinki-NLP/opus-mt-en-fr")
| TranslationOutput(translation_text='Je m'appelle Wolfgang et je vis à Berlin.')
| ```
|
| Specifying languages:
| ```py
| >>> client.translation("My name is Sarah Jessica Parker but you can call me Jessica", model="facebook/mbart-large-50-many-to-many-mmt", src_lang="en_XX", tgt_lang="fr_XX")
| "Mon nom est Sarah Jessica Parker mais vous pouvez m'appeler Jessica"
| ```
|
| visual_question_answering(self, image: Union[bytes, BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], question: str, *, model: str | None = None, top_k: int | None = None) -> list[huggingface_hub.inference._generated.types.visual_question_answering.VisualQuestionAnsweringOutputElement]
| Answering open-ended questions based on an image.
|
| Args:
| image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`):
| The input image for the context. It can be raw bytes, an image file, a URL to an online image, or a PIL Image.
| question (`str`):
| Question to be answered.
| model (`str`, *optional*):
| The model to use for the visual question answering task. Can be a model ID hosted on the Hugging Face Hub or a URL to
| a deployed Inference Endpoint. If not provided, the default recommended visual question answering model will be used.
| Defaults to None.
| top_k (`int`, *optional*):
| The number of answers to return (will be chosen by order of likelihood). Note that we return less than
| topk answers if there are not enough options available within the context.
| Returns:
| `list[VisualQuestionAnsweringOutputElement]`: a list of [`VisualQuestionAnsweringOutputElement`] items containing the predicted label and associated probability.
|
| Raises:
| `InferenceTimeoutError`:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
| >>> client.visual_question_answering(
| ... image="https://huggingface.co/datasets/mishig/sample_images/resolve/main/tiger.jpg",
| ... question="What is the animal doing?"
| ... )
| [
| VisualQuestionAnsweringOutputElement(score=0.778609573841095, answer='laying down'),
| VisualQuestionAnsweringOutputElement(score=0.6957435607910156, answer='sitting'),
| ]
| ```
|
| zero_shot_classification(self, text: str, candidate_labels: list[str], *, multi_label: bool | None = False, hypothesis_template: str | None = None, model: str | None = None) -> list[huggingface_hub.inference._generated.types.zero_shot_classification.ZeroShotClassificationOutputElement]
| Provide as input a text and a set of candidate labels to classify the input text.
|
| Args:
| text (`str`):
| The input text to classify.
| candidate_labels (`list[str]`):
| The set of possible class labels to classify the text into.
| labels (`list[str]`, *optional*):
| (deprecated) List of strings. Each string is the verbalization of a possible label for the input text.
| multi_label (`bool`, *optional*):
| Whether multiple candidate labels can be true. If false, the scores are normalized such that the sum of
| the label likelihoods for each sequence is 1. If true, the labels are considered independent and
| probabilities are normalized for each candidate.
| hypothesis_template (`str`, *optional*):
| The sentence used in conjunction with `candidate_labels` to attempt the text classification by
| replacing the placeholder with the candidate labels.
| model (`str`, *optional*):
| The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. This parameter overrides the model defined at the instance level. If not provided, the default recommended zero-shot classification model will be used.
|
|
| Returns:
| `list[ZeroShotClassificationOutputElement]`: List of [`ZeroShotClassificationOutputElement`] items containing the predicted labels and their confidence.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example with `multi_label=False`:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
| >>> text = (
| ... "A new model offers an explanation for how the Galilean satellites formed around the solar system's"
| ... "largest world. Konstantin Batygin did not set out to solve one of the solar system's most puzzling"
| ... " mysteries when he went for a run up a hill in Nice, France."
| ... )
| >>> labels = ["space & cosmos", "scientific discovery", "microbiology", "robots", "archeology"]
| >>> client.zero_shot_classification(text, labels)
| [
| ZeroShotClassificationOutputElement(label='scientific discovery', score=0.7961668968200684),
| ZeroShotClassificationOutputElement(label='space & cosmos', score=0.18570658564567566),
| ZeroShotClassificationOutputElement(label='microbiology', score=0.00730885099619627),
| ZeroShotClassificationOutputElement(label='archeology', score=0.006258360575884581),
| ZeroShotClassificationOutputElement(label='robots', score=0.004559356719255447),
| ]
| >>> client.zero_shot_classification(text, labels, multi_label=True)
| [
| ZeroShotClassificationOutputElement(label='scientific discovery', score=0.9829297661781311),
| ZeroShotClassificationOutputElement(label='space & cosmos', score=0.755190908908844),
| ZeroShotClassificationOutputElement(label='microbiology', score=0.0005462635890580714),
| ZeroShotClassificationOutputElement(label='archeology', score=0.00047131875180639327),
| ZeroShotClassificationOutputElement(label='robots', score=0.00030448526376858354),
| ]
| ```
|
| Example with `multi_label=True` and a custom `hypothesis_template`:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
| >>> client.zero_shot_classification(
| ... text="I really like our dinner and I'm very happy. I don't like the weather though.",
| ... labels=["positive", "negative", "pessimistic", "optimistic"],
| ... multi_label=True,
| ... hypothesis_template="This text is {} towards the weather"
| ... )
| [
| ZeroShotClassificationOutputElement(label='negative', score=0.9231801629066467),
| ZeroShotClassificationOutputElement(label='pessimistic', score=0.8760990500450134),
| ZeroShotClassificationOutputElement(label='optimistic', score=0.0008674879791215062),
| ZeroShotClassificationOutputElement(label='positive', score=0.0005250611575320363)
| ]
| ```
|
| zero_shot_image_classification(self, image: Union[bytes, BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], candidate_labels: list[str], *, model: str | None = None, hypothesis_template: str | None = None, labels: list[str] = None) -> list[huggingface_hub.inference._generated.types.zero_shot_image_classification.ZeroShotImageClassificationOutputElement]
| Provide input image and text labels to predict text labels for the image.
|
| Args:
| image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`):
| The input image to caption. It can be raw bytes, an image file, a URL to an online image, or a PIL Image.
| candidate_labels (`list[str]`):
| The candidate labels for this image
| labels (`list[str]`, *optional*):
| (deprecated) List of string possible labels. There must be at least 2 labels.
| model (`str`, *optional*):
| The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
| Inference Endpoint. This parameter overrides the model defined at the instance level. If not provided, the default recommended zero-shot image classification model will be used.
| hypothesis_template (`str`, *optional*):
| The sentence used in conjunction with `candidate_labels` to attempt the image classification by
| replacing the placeholder with the candidate labels.
|
| Returns:
| `list[ZeroShotImageClassificationOutputElement]`: List of [`ZeroShotImageClassificationOutputElement`] items containing the predicted labels and their confidence.
|
| Raises:
| [`InferenceTimeoutError`]:
| If the model is unavailable or the request times out.
| [`HfHubHTTPError`]:
| If the request fails with an HTTP error status code other than HTTP 503.
|
| Example:
| ```py
| >>> from huggingface_hub import InferenceClient
| >>> client = InferenceClient()
|
| >>> client.zero_shot_image_classification(
| ... "https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg",
| ... labels=["dog", "cat", "horse"],
| ... )
| [ZeroShotImageClassificationOutputElement(label='dog', score=0.956),...]
| ```
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| chat
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'provider': typing.Union[typing.Literal['cerebras',...
huggingface-hub.InferenceEndpoint
Python Library Documentation: class InferenceEndpoint in module huggingface_hub._inference_endpoints
class InferenceEndpoint(builtins.object)
| InferenceEndpoint(namespace: str, raw: dict, _token: str | bool | None, _api: 'HfApi') -> None
|
| Contains information about a deployed Inference Endpoint.
|
| Args:
| name (`str`):
| The unique name of the Inference Endpoint.
| namespace (`str`):
| The namespace where the Inference Endpoint is located.
| repository (`str`):
| The name of the model repository deployed on this Inference Endpoint.
| status ([`InferenceEndpointStatus`]):
| The current status of the Inference Endpoint.
| url (`str`, *optional*):
| The URL of the Inference Endpoint, if available. Only a deployed Inference Endpoint will have a URL.
| framework (`str`):
| The machine learning framework used for the model.
| revision (`str`):
| The specific model revision deployed on the Inference Endpoint.
| task (`str`):
| The task associated with the deployed model.
| created_at (`datetime.datetime`):
| The timestamp when the Inference Endpoint was created.
| updated_at (`datetime.datetime`):
| The timestamp of the last update of the Inference Endpoint.
| type ([`InferenceEndpointType`]):
| The type of the Inference Endpoint (public, authenticated, private).
| raw (`dict`):
| The raw dictionary data returned from the API.
| token (`str` or `bool`, *optional*):
| Authentication token for the Inference Endpoint, if set when requesting the API. Will default to the
| locally saved token if not provided. Pass `token=False` if you don't want to send your token to the server.
|
| Example:
| ```python
| >>> from huggingface_hub import get_inference_endpoint
| >>> endpoint = get_inference_endpoint("my-text-to-image")
| >>> endpoint
| InferenceEndpoint(name='my-text-to-image', ...)
|
| # Get status
| >>> endpoint.status
| 'running'
| >>> endpoint.url
| 'https://my-text-to-image.region.vendor.endpoints.huggingface.cloud'
|
| # Run inference
| >>> endpoint.client.text_to_image(...)
|
| # Pause endpoint to save $$$
| >>> endpoint.pause()
|
| # ...
| # Resume and wait for deployment
| >>> endpoint.resume()
| >>> endpoint.wait()
| >>> endpoint.client.text_to_image(...)
| ```
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, namespace: str, raw: dict, _token: str | bool | None, _api: 'HfApi') -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __post_init__(self) -> None
| Populate fields from raw dictionary.
|
| __repr__(self)
| Return repr(self).
|
| delete(self) -> None
| Delete the Inference Endpoint.
|
| This operation is not reversible. If you don't want to be charged for an Inference Endpoint, it is preferable
| to pause it with [`InferenceEndpoint.pause`] or scale it to zero with [`InferenceEndpoint.scale_to_zero`].
|
| This is an alias for [`HfApi.delete_inference_endpoint`].
|
| fetch(self) -> 'InferenceEndpoint'
| Fetch latest information about the Inference Endpoint.
|
| Returns:
| [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
|
| pause(self) -> 'InferenceEndpoint'
| Pause the Inference Endpoint.
|
| A paused Inference Endpoint will not be charged. It can be resumed at any time using [`InferenceEndpoint.resume`].
| This is different from scaling the Inference Endpoint to zero with [`InferenceEndpoint.scale_to_zero`], which
| would be automatically restarted when a request is made to it.
|
| This is an alias for [`HfApi.pause_inference_endpoint`]. The current object is mutated in place with the
| latest data from the server.
|
| Returns:
| [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
|
| resume(self, running_ok: bool = True) -> 'InferenceEndpoint'
| Resume the Inference Endpoint.
|
| This is an alias for [`HfApi.resume_inference_endpoint`]. The current object is mutated in place with the
| latest data from the server.
|
| Args:
| running_ok (`bool`, *optional*):
| If `True`, the method will not raise an error if the Inference Endpoint is already running. Defaults to
| `True`.
|
| Returns:
| [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
|
| scale_to_zero(self) -> 'InferenceEndpoint'
| Scale Inference Endpoint to zero.
|
| An Inference Endpoint scaled to zero will not be charged. It will be resumed on the next request to it, with a
| cold start delay. This is different from pausing the Inference Endpoint with [`InferenceEndpoint.pause`], which
| would require a manual resume with [`InferenceEndpoint.resume`].
|
| This is an alias for [`HfApi.scale_to_zero_inference_endpoint`]. The current object is mutated in place with the
| latest data from the server.
|
| Returns:
| [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
|
| update(self, *, accelerator: str | None = None, instance_size: str | None = None, instance_type: str | None = None, min_replica: int | None = None, max_replica: int | None = None, scale_to_zero_timeout: int | None = None, repository: str | None = None, framework: str | None = None, revision: str | None = None, task: str | None = None, custom_image: dict | None = None, secrets: dict[str, str] | None = None) -> 'InferenceEndpoint'
| Update the Inference Endpoint.
|
| This method allows the update of either the compute configuration, the deployed model, or both. All arguments are
| optional but at least one must be provided.
|
| This is an alias for [`HfApi.update_inference_endpoint`]. The current object is mutated in place with the
| latest data from the server.
|
| Args:
| accelerator (`str`, *optional*):
| The hardware accelerator to be used for inference (e.g. `"cpu"`).
| instance_size (`str`, *optional*):
| The size or type of the instance to be used for hosting the model (e.g. `"x4"`).
| instance_type (`str`, *optional*):
| The cloud instance type where the Inference Endpoint will be deployed (e.g. `"intel-icl"`).
| min_replica (`int`, *optional*):
| The minimum number of replicas (instances) to keep running for the Inference Endpoint.
| max_replica (`int`, *optional*):
| The maximum number of replicas (instances) to scale to for the Inference Endpoint.
| scale_to_zero_timeout (`int`, *optional*):
| The duration in minutes before an inactive endpoint is scaled to zero.
|
| repository (`str`, *optional*):
| The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`).
| framework (`str`, *optional*):
| The machine learning framework used for the model (e.g. `"custom"`).
| revision (`str`, *optional*):
| The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`).
| task (`str`, *optional*):
| The task on which to deploy the model (e.g. `"text-classification"`).
| custom_image (`dict`, *optional*):
| A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an
| Inference Endpoint running on the `text-generation-inference` (TGI) framework (see examples).
| secrets (`dict[str, str]`, *optional*):
| Secret values to inject in the container environment.
| Returns:
| [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
|
| wait(self, timeout: int | None = None, refresh_every: int = 5) -> 'InferenceEndpoint'
| Wait for the Inference Endpoint to be deployed.
|
| Information from the server will be fetched every 1s. If the Inference Endpoint is not deployed after `timeout`
| seconds, a [`InferenceEndpointTimeoutError`] will be raised. The [`InferenceEndpoint`] will be mutated in place with the latest
| data.
|
| Args:
| timeout (`int`, *optional*):
| The maximum time to wait for the Inference Endpoint to be deployed, in seconds. If `None`, will wait
| indefinitely.
| refresh_every (`int`, *optional*):
| The time to wait between each fetch of the Inference Endpoint status, in seconds. Defaults to 5s.
|
| Returns:
| [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
|
| Raises:
| [`InferenceEndpointError`]
| If the Inference Endpoint ended up in a failed state.
| [`InferenceEndpointTimeoutError`]
| If the Inference Endpoint is not deployed after `timeout` seconds.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_raw(raw: dict, namespace: str, token: str | bool | None = None, api: Optional[ForwardRef('HfApi')] = None) -> 'InferenceEndpoint'
| Initialize object from raw dictionary.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| async_client
| Returns a client to make predictions on this Inference Endpoint.
|
| Returns:
| [`AsyncInferenceClient`]: an asyncio-compatible inference client pointing to the deployed endpoint.
|
| Raises:
| [`InferenceEndpointError`]: If the Inference Endpoint is not yet deployed.
|
| client
| Returns a client to make predictions on this Inference Endpoint.
|
| Returns:
| [`InferenceClient`]: an inference client pointing to the deployed endpoint.
|
| Raises:
| [`InferenceEndpointError`]: If the Inference Endpoint is not yet deployed.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_api': 'HfApi', '_token': str | bool | None, 'crea...
|
| __dataclass_fields__ = {'_api': Field(name='_api',type='HfApi',default...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('namespace', 'raw', '_token', '_api')
huggingface-hub.InferenceEndpointError
Python Library Documentation: class InferenceEndpointError in module huggingface_hub.errors class InferenceEndpointError(builtins.Exception) | Generic exception when dealing with Inference Endpoints. | | Method resolution order: | InferenceEndpointError | builtins.Exception | builtins.BaseException | builtins.object | | Data descriptors defined here: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.Exception: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
huggingface-hub.InferenceEndpointStatus
Python Library Documentation: class InferenceEndpointStatus in module huggingface_hub._inference_endpoints
class InferenceEndpointStatus(builtins.str, enum.Enum)
| InferenceEndpointStatus(*values)
|
| Method resolution order:
| InferenceEndpointStatus
| builtins.str
| enum.Enum
| builtins.object
|
| Methods defined here:
|
| __format__(self, format_spec) from enum.Enum
| Default object formatter.
|
| Return str(self) if format_spec is empty. Raise TypeError otherwise.
|
| __new__(cls, value) from enum.Enum
| Create and return a new object. See help(type) for accurate signature.
|
| __repr__(self) from enum.Enum
| Return repr(self).
|
| __str__(self) from enum.Enum
| Return str(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| FAILED = <InferenceEndpointStatus.FAILED: 'failed'>
|
| INITIALIZING = <InferenceEndpointStatus.INITIALIZING: 'initializing'>
|
| PAUSED = <InferenceEndpointStatus.PAUSED: 'paused'>
|
| PENDING = <InferenceEndpointStatus.PENDING: 'pending'>
|
| RUNNING = <InferenceEndpointStatus.RUNNING: 'running'>
|
| SCALED_TO_ZERO = <InferenceEndpointStatus.SCALED_TO_ZERO: 'scaledToZer...
|
| UPDATE_FAILED = <InferenceEndpointStatus.UPDATE_FAILED: 'updateFailed'...
|
| UPDATING = <InferenceEndpointStatus.UPDATING: 'updating'>
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.str:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(...)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __sizeof__(self, /)
| Return the size of the string in memory, in bytes.
|
| capitalize(self, /)
| Return a capitalized version of the string.
|
| More specifically, make the first character have upper case and the rest lower
| case.
|
| casefold(self, /)
| Return a version of the string suitable for caseless comparisons.
|
| center(self, width, fillchar=' ', /)
| Return a centered string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| count(...)
| S.count(sub[, start[, end]]) -> int
|
| Return the number of non-overlapping occurrences of substring sub in
| string S[start:end]. Optional arguments start and end are
| interpreted as in slice notation.
|
| encode(self, /, encoding='utf-8', errors='strict')
| Encode the string using the codec registered for encoding.
|
| encoding
| The encoding in which to encode the string.
| errors
| The error handling scheme to use for encoding errors.
| The default is 'strict' meaning that encoding errors raise a
| UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
| 'xmlcharrefreplace' as well as any other name registered with
| codecs.register_error that can handle UnicodeEncodeErrors.
|
| endswith(...)
| S.endswith(suffix[, start[, end]]) -> bool
|
| Return True if S ends with the specified suffix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| suffix can also be a tuple of strings to try.
|
| expandtabs(self, /, tabsize=8)
| Return a copy where all tab characters are expanded using spaces.
|
| If tabsize is not given, a tab size of 8 characters is assumed.
|
| find(...)
| S.find(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| format(...)
| S.format(*args, **kwargs) -> str
|
| Return a formatted version of S, using substitutions from args and kwargs.
| The substitutions are identified by braces ('{' and '}').
|
| format_map(...)
| S.format_map(mapping) -> str
|
| Return a formatted version of S, using substitutions from mapping.
| The substitutions are identified by braces ('{' and '}').
|
| index(...)
| S.index(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| isalnum(self, /)
| Return True if the string is an alpha-numeric string, False otherwise.
|
| A string is alpha-numeric if all characters in the string are alpha-numeric and
| there is at least one character in the string.
|
| isalpha(self, /)
| Return True if the string is an alphabetic string, False otherwise.
|
| A string is alphabetic if all characters in the string are alphabetic and there
| is at least one character in the string.
|
| isascii(self, /)
| Return True if all characters in the string are ASCII, False otherwise.
|
| ASCII characters have code points in the range U+0000-U+007F.
| Empty string is ASCII too.
|
| isdecimal(self, /)
| Return True if the string is a decimal string, False otherwise.
|
| A string is a decimal string if all characters in the string are decimal and
| there is at least one character in the string.
|
| isdigit(self, /)
| Return True if the string is a digit string, False otherwise.
|
| A string is a digit string if all characters in the string are digits and there
| is at least one character in the string.
|
| isidentifier(self, /)
| Return True if the string is a valid Python identifier, False otherwise.
|
| Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
| such as "def" or "class".
|
| islower(self, /)
| Return True if the string is a lowercase string, False otherwise.
|
| A string is lowercase if all cased characters in the string are lowercase and
| there is at least one cased character in the string.
|
| isnumeric(self, /)
| Return True if the string is a numeric string, False otherwise.
|
| A string is numeric if all characters in the string are numeric and there is at
| least one character in the string.
|
| isprintable(self, /)
| Return True if the string is printable, False otherwise.
|
| A string is printable if all of its characters are considered printable in
| repr() or if it is empty.
|
| isspace(self, /)
| Return True if the string is a whitespace string, False otherwise.
|
| A string is whitespace if all characters in the string are whitespace and there
| is at least one character in the string.
|
| istitle(self, /)
| Return True if the string is a title-cased string, False otherwise.
|
| In a title-cased string, upper- and title-case characters may only
| follow uncased characters and lowercase characters only cased ones.
|
| isupper(self, /)
| Return True if the string is an uppercase string, False otherwise.
|
| A string is uppercase if all cased characters in the string are uppercase and
| there is at least one cased character in the string.
|
| join(self, iterable, /)
| Concatenate any number of strings.
|
| The string whose method is called is inserted in between each given string.
| The result is returned as a new string.
|
| Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
|
| ljust(self, width, fillchar=' ', /)
| Return a left-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| lower(self, /)
| Return a copy of the string converted to lowercase.
|
| lstrip(self, chars=None, /)
| Return a copy of the string with leading whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| partition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string. If the separator is found,
| returns a 3-tuple containing the part before the separator, the separator
| itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing the original string
| and two empty strings.
|
| removeprefix(self, prefix, /)
| Return a str with the given prefix string removed if present.
|
| If the string starts with the prefix string, return string[len(prefix):].
| Otherwise, return a copy of the original string.
|
| removesuffix(self, suffix, /)
| Return a str with the given suffix string removed if present.
|
| If the string ends with the suffix string and that suffix is not empty,
| return string[:-len(suffix)]. Otherwise, return a copy of the original
| string.
|
| replace(self, old, new, count=-1, /)
| Return a copy with all occurrences of substring old replaced by new.
|
| count
| Maximum number of occurrences to replace.
| -1 (the default value) means replace all occurrences.
|
| If the optional argument count is given, only the first count occurrences are
| replaced.
|
| rfind(...)
| S.rfind(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| rindex(...)
| S.rindex(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| rjust(self, width, fillchar=' ', /)
| Return a right-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| rpartition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string, starting at the end. If
| the separator is found, returns a 3-tuple containing the part before the
| separator, the separator itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing two empty strings
| and the original string.
|
| rsplit(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the end of the string and works to the front.
|
| rstrip(self, chars=None, /)
| Return a copy of the string with trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| split(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the front of the string and works to the end.
|
| Note, str.split() is mainly useful for data that has been intentionally
| delimited. With natural text that includes punctuation, consider using
| the regular expression module.
|
| splitlines(self, /, keepends=False)
| Return a list of the lines in the string, breaking at line boundaries.
|
| Line breaks are not included in the resulting list unless keepends is given and
| true.
|
| startswith(...)
| S.startswith(prefix[, start[, end]]) -> bool
|
| Return True if S starts with the specified prefix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| prefix can also be a tuple of strings to try.
|
| strip(self, chars=None, /)
| Return a copy of the string with leading and trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| swapcase(self, /)
| Convert uppercase characters to lowercase and lowercase characters to uppercase.
|
| title(self, /)
| Return a version of the string where each word is titlecased.
|
| More specifically, words start with uppercased characters and all remaining
| cased characters have lower case.
|
| translate(self, table, /)
| Replace each character in the string using the given translation table.
|
| table
| Translation table, which must be a mapping of Unicode ordinals to
| Unicode ordinals, strings, or None.
|
| The table must implement lookup/indexing via __getitem__, for instance a
| dictionary or list. If this operation raises LookupError, the character is
| left untouched. Characters mapped to None are deleted.
|
| upper(self, /)
| Return a copy of the string converted to uppercase.
|
| zfill(self, width, /)
| Pad a numeric string with zeros on the left, to fill a field of the given width.
|
| The string is never truncated.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.str:
|
| maketrans(...)
| Return a translation table usable for str.translate().
|
| If there is only one argument, it must be a dictionary mapping Unicode
| ordinals (integers) or characters to Unicode ordinals, strings or None.
| Character keys will be then converted to ordinals.
| If there are two arguments, they must be strings of equal length, and
| in the resulting dictionary, each character in x will be mapped to the
| character at the same position in y. If there is a third argument, it
| must be a string, whose characters will be mapped to None in the result.
|
| ----------------------------------------------------------------------
| Methods inherited from enum.Enum:
|
| __dir__(self)
| Returns public methods and other interesting attributes.
|
| __init__(self, *args, **kwds)
| Initialize self. See help(type(self)) for accurate signature.
|
| __reduce_ex__(self, proto)
| Helper for pickle.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from enum.Enum:
|
| name
| The name of the Enum member.
|
| value
| The value of the Enum member.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from enum.EnumType:
|
| __members__
| Returns a mapping of member name->value.
|
| This mapping lists all enum members, including aliases. Note that this
| is a read-only view of the internal mapping.
huggingface-hub.InferenceEndpointTimeoutError
Python Library Documentation: class InferenceEndpointTimeoutError in module huggingface_hub.errors class InferenceEndpointTimeoutError(InferenceEndpointError, builtins.TimeoutError) | Exception for timeouts while waiting for Inference Endpoint. | | Method resolution order: | InferenceEndpointTimeoutError | InferenceEndpointError | builtins.TimeoutError | builtins.OSError | builtins.Exception | builtins.BaseException | builtins.object | | Data descriptors defined here: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.TimeoutError: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.OSError: | | __reduce__(...) | Helper for pickle. | | __str__(self, /) | Return str(self). | | ---------------------------------------------------------------------- | Static methods inherited from builtins.OSError: | | __new__(*args, **kwargs) class method of builtins.OSError | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.OSError: | | characters_written | | errno | POSIX exception code | | filename | exception filename | | filename2 | second exception filename | | strerror | exception strerror | | winerror | Win32 exception code | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
huggingface-hub.InferenceEndpointType
Python Library Documentation: class InferenceEndpointType in module huggingface_hub._inference_endpoints
class InferenceEndpointType(builtins.str, enum.Enum)
| InferenceEndpointType(*values)
|
| Method resolution order:
| InferenceEndpointType
| builtins.str
| enum.Enum
| builtins.object
|
| Methods defined here:
|
| __format__(self, format_spec) from enum.Enum
| Default object formatter.
|
| Return str(self) if format_spec is empty. Raise TypeError otherwise.
|
| __new__(cls, value) from enum.Enum
| Create and return a new object. See help(type) for accurate signature.
|
| __repr__(self) from enum.Enum
| Return repr(self).
|
| __str__(self) from enum.Enum
| Return str(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| AUTHENTICATED = <InferenceEndpointType.AUTHENTICATED: 'authenticated'>
|
| PRIVATE = <InferenceEndpointType.PRIVATE: 'private'>
|
| PROTECTED = <InferenceEndpointType.PROTECTED: 'protected'>
|
| PUBlIC = <InferenceEndpointType.PUBlIC: 'public'>
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.str:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(...)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __sizeof__(self, /)
| Return the size of the string in memory, in bytes.
|
| capitalize(self, /)
| Return a capitalized version of the string.
|
| More specifically, make the first character have upper case and the rest lower
| case.
|
| casefold(self, /)
| Return a version of the string suitable for caseless comparisons.
|
| center(self, width, fillchar=' ', /)
| Return a centered string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| count(...)
| S.count(sub[, start[, end]]) -> int
|
| Return the number of non-overlapping occurrences of substring sub in
| string S[start:end]. Optional arguments start and end are
| interpreted as in slice notation.
|
| encode(self, /, encoding='utf-8', errors='strict')
| Encode the string using the codec registered for encoding.
|
| encoding
| The encoding in which to encode the string.
| errors
| The error handling scheme to use for encoding errors.
| The default is 'strict' meaning that encoding errors raise a
| UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
| 'xmlcharrefreplace' as well as any other name registered with
| codecs.register_error that can handle UnicodeEncodeErrors.
|
| endswith(...)
| S.endswith(suffix[, start[, end]]) -> bool
|
| Return True if S ends with the specified suffix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| suffix can also be a tuple of strings to try.
|
| expandtabs(self, /, tabsize=8)
| Return a copy where all tab characters are expanded using spaces.
|
| If tabsize is not given, a tab size of 8 characters is assumed.
|
| find(...)
| S.find(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| format(...)
| S.format(*args, **kwargs) -> str
|
| Return a formatted version of S, using substitutions from args and kwargs.
| The substitutions are identified by braces ('{' and '}').
|
| format_map(...)
| S.format_map(mapping) -> str
|
| Return a formatted version of S, using substitutions from mapping.
| The substitutions are identified by braces ('{' and '}').
|
| index(...)
| S.index(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| isalnum(self, /)
| Return True if the string is an alpha-numeric string, False otherwise.
|
| A string is alpha-numeric if all characters in the string are alpha-numeric and
| there is at least one character in the string.
|
| isalpha(self, /)
| Return True if the string is an alphabetic string, False otherwise.
|
| A string is alphabetic if all characters in the string are alphabetic and there
| is at least one character in the string.
|
| isascii(self, /)
| Return True if all characters in the string are ASCII, False otherwise.
|
| ASCII characters have code points in the range U+0000-U+007F.
| Empty string is ASCII too.
|
| isdecimal(self, /)
| Return True if the string is a decimal string, False otherwise.
|
| A string is a decimal string if all characters in the string are decimal and
| there is at least one character in the string.
|
| isdigit(self, /)
| Return True if the string is a digit string, False otherwise.
|
| A string is a digit string if all characters in the string are digits and there
| is at least one character in the string.
|
| isidentifier(self, /)
| Return True if the string is a valid Python identifier, False otherwise.
|
| Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
| such as "def" or "class".
|
| islower(self, /)
| Return True if the string is a lowercase string, False otherwise.
|
| A string is lowercase if all cased characters in the string are lowercase and
| there is at least one cased character in the string.
|
| isnumeric(self, /)
| Return True if the string is a numeric string, False otherwise.
|
| A string is numeric if all characters in the string are numeric and there is at
| least one character in the string.
|
| isprintable(self, /)
| Return True if the string is printable, False otherwise.
|
| A string is printable if all of its characters are considered printable in
| repr() or if it is empty.
|
| isspace(self, /)
| Return True if the string is a whitespace string, False otherwise.
|
| A string is whitespace if all characters in the string are whitespace and there
| is at least one character in the string.
|
| istitle(self, /)
| Return True if the string is a title-cased string, False otherwise.
|
| In a title-cased string, upper- and title-case characters may only
| follow uncased characters and lowercase characters only cased ones.
|
| isupper(self, /)
| Return True if the string is an uppercase string, False otherwise.
|
| A string is uppercase if all cased characters in the string are uppercase and
| there is at least one cased character in the string.
|
| join(self, iterable, /)
| Concatenate any number of strings.
|
| The string whose method is called is inserted in between each given string.
| The result is returned as a new string.
|
| Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
|
| ljust(self, width, fillchar=' ', /)
| Return a left-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| lower(self, /)
| Return a copy of the string converted to lowercase.
|
| lstrip(self, chars=None, /)
| Return a copy of the string with leading whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| partition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string. If the separator is found,
| returns a 3-tuple containing the part before the separator, the separator
| itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing the original string
| and two empty strings.
|
| removeprefix(self, prefix, /)
| Return a str with the given prefix string removed if present.
|
| If the string starts with the prefix string, return string[len(prefix):].
| Otherwise, return a copy of the original string.
|
| removesuffix(self, suffix, /)
| Return a str with the given suffix string removed if present.
|
| If the string ends with the suffix string and that suffix is not empty,
| return string[:-len(suffix)]. Otherwise, return a copy of the original
| string.
|
| replace(self, old, new, count=-1, /)
| Return a copy with all occurrences of substring old replaced by new.
|
| count
| Maximum number of occurrences to replace.
| -1 (the default value) means replace all occurrences.
|
| If the optional argument count is given, only the first count occurrences are
| replaced.
|
| rfind(...)
| S.rfind(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| rindex(...)
| S.rindex(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| rjust(self, width, fillchar=' ', /)
| Return a right-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| rpartition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string, starting at the end. If
| the separator is found, returns a 3-tuple containing the part before the
| separator, the separator itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing two empty strings
| and the original string.
|
| rsplit(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the end of the string and works to the front.
|
| rstrip(self, chars=None, /)
| Return a copy of the string with trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| split(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the front of the string and works to the end.
|
| Note, str.split() is mainly useful for data that has been intentionally
| delimited. With natural text that includes punctuation, consider using
| the regular expression module.
|
| splitlines(self, /, keepends=False)
| Return a list of the lines in the string, breaking at line boundaries.
|
| Line breaks are not included in the resulting list unless keepends is given and
| true.
|
| startswith(...)
| S.startswith(prefix[, start[, end]]) -> bool
|
| Return True if S starts with the specified prefix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| prefix can also be a tuple of strings to try.
|
| strip(self, chars=None, /)
| Return a copy of the string with leading and trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| swapcase(self, /)
| Convert uppercase characters to lowercase and lowercase characters to uppercase.
|
| title(self, /)
| Return a version of the string where each word is titlecased.
|
| More specifically, words start with uppercased characters and all remaining
| cased characters have lower case.
|
| translate(self, table, /)
| Replace each character in the string using the given translation table.
|
| table
| Translation table, which must be a mapping of Unicode ordinals to
| Unicode ordinals, strings, or None.
|
| The table must implement lookup/indexing via __getitem__, for instance a
| dictionary or list. If this operation raises LookupError, the character is
| left untouched. Characters mapped to None are deleted.
|
| upper(self, /)
| Return a copy of the string converted to uppercase.
|
| zfill(self, width, /)
| Pad a numeric string with zeros on the left, to fill a field of the given width.
|
| The string is never truncated.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.str:
|
| maketrans(...)
| Return a translation table usable for str.translate().
|
| If there is only one argument, it must be a dictionary mapping Unicode
| ordinals (integers) or characters to Unicode ordinals, strings or None.
| Character keys will be then converted to ordinals.
| If there are two arguments, they must be strings of equal length, and
| in the resulting dictionary, each character in x will be mapped to the
| character at the same position in y. If there is a third argument, it
| must be a string, whose characters will be mapped to None in the result.
|
| ----------------------------------------------------------------------
| Methods inherited from enum.Enum:
|
| __dir__(self)
| Returns public methods and other interesting attributes.
|
| __init__(self, *args, **kwds)
| Initialize self. See help(type(self)) for accurate signature.
|
| __reduce_ex__(self, proto)
| Helper for pickle.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from enum.Enum:
|
| name
| The name of the Enum member.
|
| value
| The value of the Enum member.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from enum.EnumType:
|
| __members__
| Returns a mapping of member name->value.
|
| This mapping lists all enum members, including aliases. Note that this
| is a read-only view of the internal mapping.
huggingface-hub.InferenceTimeoutError
Python Library Documentation: class InferenceTimeoutError in module huggingface_hub.errors class InferenceTimeoutError(httpx.HTTPError, builtins.TimeoutError) | InferenceTimeoutError(message: 'str') -> 'None' | | Error raised when a model is unavailable or the request times out. | | Method resolution order: | InferenceTimeoutError | httpx.HTTPError | builtins.TimeoutError | builtins.OSError | builtins.Exception | builtins.BaseException | builtins.object | | Data descriptors defined here: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from httpx.HTTPError: | | __init__(self, message: 'str') -> 'None' from httpx._exceptions.HTTPError | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Data descriptors inherited from httpx.HTTPError: | | request | | ---------------------------------------------------------------------- | Methods inherited from builtins.OSError: | | __reduce__(...) | Helper for pickle. | | __str__(self, /) | Return str(self). | | ---------------------------------------------------------------------- | Static methods inherited from builtins.OSError: | | __new__(*args, **kwargs) class method of builtins.OSError | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.OSError: | | characters_written | | errno | POSIX exception code | | filename | exception filename | | filename2 | second exception filename | | strerror | exception strerror | | winerror | Win32 exception code | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
huggingface-hub.JobAccelerator
Python Library Documentation: class JobAccelerator in module huggingface_hub._jobs_api
class JobAccelerator(builtins.object)
| JobAccelerator(**kwargs) -> None
|
| Contains information about a Job accelerator (GPU).
|
| Args:
| type (`str`):
| Type of accelerator, e.g. `"gpu"`.
| model (`str`):
| Model of accelerator, e.g. `"T4"`, `"A10G"`, `"A100"`, `"L4"`, `"L40S"`.
| quantity (`str`):
| Number of accelerators, e.g. `"1"`, `"2"`, `"4"`, `"8"`.
| vram (`str`):
| Total VRAM, e.g. `"16 GB"`, `"24 GB"`.
| manufacturer (`str`):
| Manufacturer of the accelerator, e.g. `"Nvidia"`.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, **kwargs) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'manufacturer': <class 'str'>, 'model': <class 'str...
|
| __dataclass_fields__ = {'manufacturer': Field(name='manufacturer',type...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('type', 'model', 'quantity', 'vram', 'manufacturer')
huggingface-hub.JobDurations
Python Library Documentation: class JobDurations in module huggingface_hub._jobs_api
class JobDurations(builtins.object)
| JobDurations(**kwargs) -> None
|
| Timing breakdown for a Job, computed server-side.
|
| Args:
| scheduling_secs (`int` or `None`):
| Seconds the job spent in the scheduling stage before starting to run.
| `None` if the job never reached the running stage.
| running_secs (`int` or `None`):
| Seconds the job has been or was running. Recomputed on each request
| while the job is in progress. `None` if the job never started running.
| total_secs (`int` or `None`):
| Total seconds elapsed since the job was created. Recomputed on each
| request while the job is in progress.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, **kwargs) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'running_secs': int | None, 'scheduling_secs': int ...
|
| __dataclass_fields__ = {'running_secs': Field(name='running_secs',type...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('scheduling_secs', 'running_secs', 'total_secs')
huggingface-hub.JobHardware
Python Library Documentation: class JobHardware in module huggingface_hub._jobs_api
class JobHardware(builtins.str, enum.Enum)
| JobHardware(*values)
|
| Enumeration of hardware flavors available to run Jobs on the Hub.
|
| Value can be compared to a string:
| ```py
| assert JobHardware.CPU_BASIC == "cpu-basic"
| ```
|
| Both enums are kept in sync with the Hub API by `utils/check_hardware_flavors.py`.
|
| Method resolution order:
| JobHardware
| builtins.str
| enum.Enum
| builtins.object
|
| Methods defined here:
|
| __format__(self, format_spec) from enum.Enum
| Default object formatter.
|
| Return str(self) if format_spec is empty. Raise TypeError otherwise.
|
| __new__(cls, value) from enum.Enum
| Create and return a new object. See help(type) for accurate signature.
|
| __repr__(self) from enum.Enum
| Return repr(self).
|
| __str__(self) from enum.Enum
| Return str(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| A100X4 = <JobHardware.A100X4: 'a100x4'>
|
| A100X8 = <JobHardware.A100X8: 'a100x8'>
|
| A100_LARGE = <JobHardware.A100_LARGE: 'a100-large'>
|
| A10G_LARGE = <JobHardware.A10G_LARGE: 'a10g-large'>
|
| A10G_LARGEX2 = <JobHardware.A10G_LARGEX2: 'a10g-largex2'>
|
| A10G_LARGEX4 = <JobHardware.A10G_LARGEX4: 'a10g-largex4'>
|
| A10G_SMALL = <JobHardware.A10G_SMALL: 'a10g-small'>
|
| CPU_BASIC = <JobHardware.CPU_BASIC: 'cpu-basic'>
|
| CPU_PERFORMANCE = <JobHardware.CPU_PERFORMANCE: 'cpu-performance'>
|
| CPU_UPGRADE = <JobHardware.CPU_UPGRADE: 'cpu-upgrade'>
|
| CPU_XL = <JobHardware.CPU_XL: 'cpu-xl'>
|
| H200 = <JobHardware.H200: 'h200'>
|
| H200X2 = <JobHardware.H200X2: 'h200x2'>
|
| H200X4 = <JobHardware.H200X4: 'h200x4'>
|
| H200X8 = <JobHardware.H200X8: 'h200x8'>
|
| L40SX1 = <JobHardware.L40SX1: 'l40sx1'>
|
| L40SX4 = <JobHardware.L40SX4: 'l40sx4'>
|
| L40SX8 = <JobHardware.L40SX8: 'l40sx8'>
|
| L4X1 = <JobHardware.L4X1: 'l4x1'>
|
| L4X4 = <JobHardware.L4X4: 'l4x4'>
|
| RTX_PRO_6000 = <JobHardware.RTX_PRO_6000: 'rtx-pro-6000'>
|
| RTX_PRO_6000X2 = <JobHardware.RTX_PRO_6000X2: 'rtx-pro-6000x2'>
|
| RTX_PRO_6000X4 = <JobHardware.RTX_PRO_6000X4: 'rtx-pro-6000x4'>
|
| RTX_PRO_6000X8 = <JobHardware.RTX_PRO_6000X8: 'rtx-pro-6000x8'>
|
| T4_MEDIUM = <JobHardware.T4_MEDIUM: 't4-medium'>
|
| T4_SMALL = <JobHardware.T4_SMALL: 't4-small'>
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.str:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(...)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __sizeof__(self, /)
| Return the size of the string in memory, in bytes.
|
| capitalize(self, /)
| Return a capitalized version of the string.
|
| More specifically, make the first character have upper case and the rest lower
| case.
|
| casefold(self, /)
| Return a version of the string suitable for caseless comparisons.
|
| center(self, width, fillchar=' ', /)
| Return a centered string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| count(...)
| S.count(sub[, start[, end]]) -> int
|
| Return the number of non-overlapping occurrences of substring sub in
| string S[start:end]. Optional arguments start and end are
| interpreted as in slice notation.
|
| encode(self, /, encoding='utf-8', errors='strict')
| Encode the string using the codec registered for encoding.
|
| encoding
| The encoding in which to encode the string.
| errors
| The error handling scheme to use for encoding errors.
| The default is 'strict' meaning that encoding errors raise a
| UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
| 'xmlcharrefreplace' as well as any other name registered with
| codecs.register_error that can handle UnicodeEncodeErrors.
|
| endswith(...)
| S.endswith(suffix[, start[, end]]) -> bool
|
| Return True if S ends with the specified suffix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| suffix can also be a tuple of strings to try.
|
| expandtabs(self, /, tabsize=8)
| Return a copy where all tab characters are expanded using spaces.
|
| If tabsize is not given, a tab size of 8 characters is assumed.
|
| find(...)
| S.find(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| format(...)
| S.format(*args, **kwargs) -> str
|
| Return a formatted version of S, using substitutions from args and kwargs.
| The substitutions are identified by braces ('{' and '}').
|
| format_map(...)
| S.format_map(mapping) -> str
|
| Return a formatted version of S, using substitutions from mapping.
| The substitutions are identified by braces ('{' and '}').
|
| index(...)
| S.index(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| isalnum(self, /)
| Return True if the string is an alpha-numeric string, False otherwise.
|
| A string is alpha-numeric if all characters in the string are alpha-numeric and
| there is at least one character in the string.
|
| isalpha(self, /)
| Return True if the string is an alphabetic string, False otherwise.
|
| A string is alphabetic if all characters in the string are alphabetic and there
| is at least one character in the string.
|
| isascii(self, /)
| Return True if all characters in the string are ASCII, False otherwise.
|
| ASCII characters have code points in the range U+0000-U+007F.
| Empty string is ASCII too.
|
| isdecimal(self, /)
| Return True if the string is a decimal string, False otherwise.
|
| A string is a decimal string if all characters in the string are decimal and
| there is at least one character in the string.
|
| isdigit(self, /)
| Return True if the string is a digit string, False otherwise.
|
| A string is a digit string if all characters in the string are digits and there
| is at least one character in the string.
|
| isidentifier(self, /)
| Return True if the string is a valid Python identifier, False otherwise.
|
| Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
| such as "def" or "class".
|
| islower(self, /)
| Return True if the string is a lowercase string, False otherwise.
|
| A string is lowercase if all cased characters in the string are lowercase and
| there is at least one cased character in the string.
|
| isnumeric(self, /)
| Return True if the string is a numeric string, False otherwise.
|
| A string is numeric if all characters in the string are numeric and there is at
| least one character in the string.
|
| isprintable(self, /)
| Return True if the string is printable, False otherwise.
|
| A string is printable if all of its characters are considered printable in
| repr() or if it is empty.
|
| isspace(self, /)
| Return True if the string is a whitespace string, False otherwise.
|
| A string is whitespace if all characters in the string are whitespace and there
| is at least one character in the string.
|
| istitle(self, /)
| Return True if the string is a title-cased string, False otherwise.
|
| In a title-cased string, upper- and title-case characters may only
| follow uncased characters and lowercase characters only cased ones.
|
| isupper(self, /)
| Return True if the string is an uppercase string, False otherwise.
|
| A string is uppercase if all cased characters in the string are uppercase and
| there is at least one cased character in the string.
|
| join(self, iterable, /)
| Concatenate any number of strings.
|
| The string whose method is called is inserted in between each given string.
| The result is returned as a new string.
|
| Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
|
| ljust(self, width, fillchar=' ', /)
| Return a left-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| lower(self, /)
| Return a copy of the string converted to lowercase.
|
| lstrip(self, chars=None, /)
| Return a copy of the string with leading whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| partition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string. If the separator is found,
| returns a 3-tuple containing the part before the separator, the separator
| itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing the original string
| and two empty strings.
|
| removeprefix(self, prefix, /)
| Return a str with the given prefix string removed if present.
|
| If the string starts with the prefix string, return string[len(prefix):].
| Otherwise, return a copy of the original string.
|
| removesuffix(self, suffix, /)
| Return a str with the given suffix string removed if present.
|
| If the string ends with the suffix string and that suffix is not empty,
| return string[:-len(suffix)]. Otherwise, return a copy of the original
| string.
|
| replace(self, old, new, count=-1, /)
| Return a copy with all occurrences of substring old replaced by new.
|
| count
| Maximum number of occurrences to replace.
| -1 (the default value) means replace all occurrences.
|
| If the optional argument count is given, only the first count occurrences are
| replaced.
|
| rfind(...)
| S.rfind(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| rindex(...)
| S.rindex(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| rjust(self, width, fillchar=' ', /)
| Return a right-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| rpartition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string, starting at the end. If
| the separator is found, returns a 3-tuple containing the part before the
| separator, the separator itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing two empty strings
| and the original string.
|
| rsplit(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the end of the string and works to the front.
|
| rstrip(self, chars=None, /)
| Return a copy of the string with trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| split(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the front of the string and works to the end.
|
| Note, str.split() is mainly useful for data that has been intentionally
| delimited. With natural text that includes punctuation, consider using
| the regular expression module.
|
| splitlines(self, /, keepends=False)
| Return a list of the lines in the string, breaking at line boundaries.
|
| Line breaks are not included in the resulting list unless keepends is given and
| true.
|
| startswith(...)
| S.startswith(prefix[, start[, end]]) -> bool
|
| Return True if S starts with the specified prefix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| prefix can also be a tuple of strings to try.
|
| strip(self, chars=None, /)
| Return a copy of the string with leading and trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| swapcase(self, /)
| Convert uppercase characters to lowercase and lowercase characters to uppercase.
|
| title(self, /)
| Return a version of the string where each word is titlecased.
|
| More specifically, words start with uppercased characters and all remaining
| cased characters have lower case.
|
| translate(self, table, /)
| Replace each character in the string using the given translation table.
|
| table
| Translation table, which must be a mapping of Unicode ordinals to
| Unicode ordinals, strings, or None.
|
| The table must implement lookup/indexing via __getitem__, for instance a
| dictionary or list. If this operation raises LookupError, the character is
| left untouched. Characters mapped to None are deleted.
|
| upper(self, /)
| Return a copy of the string converted to uppercase.
|
| zfill(self, width, /)
| Pad a numeric string with zeros on the left, to fill a field of the given width.
|
| The string is never truncated.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.str:
|
| maketrans(...)
| Return a translation table usable for str.translate().
|
| If there is only one argument, it must be a dictionary mapping Unicode
| ordinals (integers) or characters to Unicode ordinals, strings or None.
| Character keys will be then converted to ordinals.
| If there are two arguments, they must be strings of equal length, and
| in the resulting dictionary, each character in x will be mapped to the
| character at the same position in y. If there is a third argument, it
| must be a string, whose characters will be mapped to None in the result.
|
| ----------------------------------------------------------------------
| Methods inherited from enum.Enum:
|
| __dir__(self)
| Returns public methods and other interesting attributes.
|
| __init__(self, *args, **kwds)
| Initialize self. See help(type(self)) for accurate signature.
|
| __reduce_ex__(self, proto)
| Helper for pickle.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from enum.Enum:
|
| name
| The name of the Enum member.
|
| value
| The value of the Enum member.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from enum.EnumType:
|
| __members__
| Returns a mapping of member name->value.
|
| This mapping lists all enum members, including aliases. Note that this
| is a read-only view of the internal mapping.
huggingface-hub.JobHardwareInfo
Python Library Documentation: class JobHardwareInfo in module huggingface_hub._jobs_api
class JobHardwareInfo(builtins.object)
| JobHardwareInfo(**kwargs) -> None
|
| Contains information about available Job hardware.
|
| Args:
| name (`str`):
| Machine identifier, e.g. `"cpu-basic"`, `"a10g-large"`.
| pretty_name (`str`):
| Human-readable name, e.g. `"CPU Basic"`, `"Nvidia A10G - large"`.
| cpu (`str`):
| CPU specification, e.g. `"2 vCPU"`, `"12 vCPU"`.
| ram (`str`):
| RAM specification, e.g. `"16 GB"`, `"46 GB"`.
| ephemeral_storage (`str`):
| Ephemeral storage specification, e.g. `"20 GB"`, `"100 GB"`.
| accelerator (`JobAccelerator` or `None`):
| GPU/accelerator details if available.
| unit_cost_micro_usd (`int`):
| Cost in micro-dollars per unit, e.g. `167` (= $0.000167).
| unit_cost_usd (`float`):
| Cost in USD per unit, e.g. `0.000167`.
| unit_label (`str`):
| Cost unit period, e.g. `"minute"`.
|
| Example:
|
| ```python
| >>> from huggingface_hub import list_jobs_hardware
| >>> hardware_list = list_jobs_hardware()
| >>> hardware_list[0]
| JobHardwareInfo(name='cpu-basic', pretty_name='CPU Basic', cpu='2 vCPU', ram='16 GB', ephemeral_storage='20 GB', accelerator=None, unit_cost_micro_usd=167, unit_cost_usd=0.000167, unit_label='minute')
| >>> hardware_list[0].name
| 'cpu-basic'
| ```
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, **kwargs) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'accelerator': huggingface_hub._jobs_api.JobAcceler...
|
| __dataclass_fields__ = {'accelerator': Field(name='accelerator',type=h...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('name', 'pretty_name', 'cpu', 'ram', 'ephemeral_stor...
huggingface-hub.JobInfo
Python Library Documentation: class JobInfo in module huggingface_hub._jobs_api
class JobInfo(builtins.object)
| JobInfo(**kwargs) -> None
|
| Contains information about a Job.
|
| Args:
| id (`str`):
| Job ID.
| created_at (`datetime` or `None`):
| When the Job was created.
| started_at (`datetime` or `None`):
| When the Job started running. None while the Job is still scheduling.
| finished_at (`datetime` or `None`):
| When the Job finished. None while the Job is still scheduling or running.
| docker_image (`str` or `None`):
| The Docker image from Docker Hub used for the Job.
| Can be None if space_id is present instead.
| space_id (`str` or `None`):
| The Docker image from Hugging Face Spaces used for the Job.
| Can be None if docker_image is present instead.
| command (`list[str]` or `None`):
| Command of the Job, e.g. `["python", "-c", "print('hello world')"]`
| arguments (`list[str]` or `None`):
| Arguments passed to the command
| environment (`dict[str]` or `None`):
| Environment variables of the Job as a dictionary.
| secrets (`dict[str]` or `None`):
| Secret environment variables of the Job (encrypted).
| flavor (`str` or `None`):
| Flavor for the hardware. See [`JobHardware`] for possible values.
| E.g. `"cpu-basic"`.
| labels (`dict[str, str]` or `None`):
| Labels to attach to the job (key-value pairs).
| volumes (`list[Volume]` or `None`):
| Volumes mounted in the job container (buckets, models, datasets, spaces).
| status: (`JobStatus` or `None`):
| Status of the Job, e.g. `JobStatus(stage="RUNNING", message=None)`
| See [`JobStage`] for possible stage values.
| durations (`JobDurations` or `None`):
| Timing breakdown of the Job. Present for all job states including SCHEDULING.
| owner: (`JobOwner` or `None`):
| Owner of the Job, e.g. `JobOwner(id="5e9ecfc04957053f60648a3e", name="lhoestq", type="user")`
| initiator (`JobInitiator` or `None`):
| What triggered the Job, e.g. `JobInitiator(type="scheduled-job", id="...")` for a cron-triggered run.
| expose_urls (`list[str]` or `None`):
| Public URLs through which the Job's exposed ports are reachable (one per port exposed via `expose=`),
| e.g. `["https://687fb701029421ae5549d998--8000.hf.jobs"]`. `None` when no port is exposed.
| Accessing a URL requires an HF token with read access to the Job's namespace.
| ssh_url (`str` or `None`):
| SSH endpoint of the Job, e.g. `"ssh://687fb701029421ae5549d998@ssh.hf.jobs"`. Only present when the Job
| was started with `ssh=True`. Connecting requires write access to the Job's namespace and an SSH public
| key registered on the Hub (https://huggingface.co/settings/keys).
|
| Example:
|
| ```python
| >>> from huggingface_hub import run_job
| >>> job = run_job(
| ... image="python:3.12",
| ... command=["python", "-c", "print('Hello from the cloud!')"]
| ... )
| >>> job
| JobInfo(id='687fb701029421ae5549d998', created_at=datetime.datetime(2025, 7, 22, 16, 6, 25, 79000, tzinfo=datetime.timezone.utc), started_at=datetime.datetime(2025, 7, 22, 16, 6, 31, 79000, tzinfo=datetime.timezone.utc), finished_at=None, docker_image='python:3.12', space_id=None, command=['python', '-c', "print('Hello from the cloud!')"], arguments=[], environment={}, secrets={}, flavor='cpu-basic', labels=None, status=JobStatus(stage='RUNNING', message=None), durations=JobDurations(scheduling_secs=6, running_secs=2, total_secs=8), owner=JobOwner(id='5e9ecfc04957053f60648a3e', name='lhoestq', type='user'), initiator=JobInitiator(type='user', id='5e9ecfc04957053f60648a3e', name='lhoestq'), endpoint='https://huggingface.co', url='https://huggingface.co/jobs/lhoestq/687fb701029421ae5549d998')
| >>> job.id
| '687fb701029421ae5549d998'
| >>> job.url
| 'https://huggingface.co/jobs/lhoestq/687fb701029421ae5549d998'
| >>> job.status.stage
| 'RUNNING'
| ```
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, **kwargs) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'arguments': list[str] | None, 'command': list[str]...
|
| __dataclass_fields__ = {'arguments': Field(name='arguments',type=list[...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('id', 'created_at', 'started_at', 'finished_at', 'do...
huggingface-hub.JobInitiator
Python Library Documentation: class JobInitiator in module huggingface_hub._jobs_api
class JobInitiator(builtins.object)
| JobInitiator(type: str, id: str, name: str | None = None) -> None
|
| Contains information about what triggered a Job.
|
| Args:
| type (`str`): Initiator kind, for example `"user"`, `"org"`, `"scheduled-job"`, or `"duplicated-job"`.
| id (`str`): Identifier of the initiator.
| name (`str` or `None`): Human-readable name when available, usually for user/org initiators.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, type: str, id: str, name: str | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'id': <class 'str'>, 'name': str | None, 'type': <c...
|
| __dataclass_fields__ = {'id': Field(name='id',type=<class 'str'>,defau...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('type', 'id', 'name')
|
| name = None
huggingface-hub.JobOwner
Python Library Documentation: class JobOwner in module huggingface_hub._jobs_api
class JobOwner(builtins.object)
| JobOwner(id: str, name: str, type: str) -> None
|
| JobOwner(id: str, name: str, type: str)
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, id: str, name: str, type: str) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'id': <class 'str'>, 'name': <class 'str'>, 'type':...
|
| __dataclass_fields__ = {'id': Field(name='id',type=<class 'str'>,defau...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('id', 'name', 'type')
huggingface-hub.JobStage
Python Library Documentation: class JobStage in module huggingface_hub._jobs_api
class JobStage(builtins.str, enum.Enum)
| JobStage(*values)
|
| Enumeration of possible stage of a Job on the Hub.
|
| Value can be compared to a string:
| ```py
| assert JobStage.COMPLETED == "COMPLETED"
| ```
| Possible values are: `COMPLETED`, `CANCELED`, `ERROR`, `DELETED`, `SCHEDULING`, `RUNNING`.
| Taken from https://github.com/huggingface/moon-landing/blob/main/server/job_types/JobInfo.ts#L61 (private url).
|
| Method resolution order:
| JobStage
| builtins.str
| enum.Enum
| builtins.object
|
| Methods defined here:
|
| __format__(self, format_spec) from enum.Enum
| Default object formatter.
|
| Return str(self) if format_spec is empty. Raise TypeError otherwise.
|
| __new__(cls, value) from enum.Enum
| Create and return a new object. See help(type) for accurate signature.
|
| __repr__(self) from enum.Enum
| Return repr(self).
|
| __str__(self) from enum.Enum
| Return str(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| CANCELED = <JobStage.CANCELED: 'CANCELED'>
|
| COMPLETED = <JobStage.COMPLETED: 'COMPLETED'>
|
| DELETED = <JobStage.DELETED: 'DELETED'>
|
| ERROR = <JobStage.ERROR: 'ERROR'>
|
| RUNNING = <JobStage.RUNNING: 'RUNNING'>
|
| SCHEDULING = <JobStage.SCHEDULING: 'SCHEDULING'>
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.str:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(...)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __sizeof__(self, /)
| Return the size of the string in memory, in bytes.
|
| capitalize(self, /)
| Return a capitalized version of the string.
|
| More specifically, make the first character have upper case and the rest lower
| case.
|
| casefold(self, /)
| Return a version of the string suitable for caseless comparisons.
|
| center(self, width, fillchar=' ', /)
| Return a centered string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| count(...)
| S.count(sub[, start[, end]]) -> int
|
| Return the number of non-overlapping occurrences of substring sub in
| string S[start:end]. Optional arguments start and end are
| interpreted as in slice notation.
|
| encode(self, /, encoding='utf-8', errors='strict')
| Encode the string using the codec registered for encoding.
|
| encoding
| The encoding in which to encode the string.
| errors
| The error handling scheme to use for encoding errors.
| The default is 'strict' meaning that encoding errors raise a
| UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
| 'xmlcharrefreplace' as well as any other name registered with
| codecs.register_error that can handle UnicodeEncodeErrors.
|
| endswith(...)
| S.endswith(suffix[, start[, end]]) -> bool
|
| Return True if S ends with the specified suffix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| suffix can also be a tuple of strings to try.
|
| expandtabs(self, /, tabsize=8)
| Return a copy where all tab characters are expanded using spaces.
|
| If tabsize is not given, a tab size of 8 characters is assumed.
|
| find(...)
| S.find(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| format(...)
| S.format(*args, **kwargs) -> str
|
| Return a formatted version of S, using substitutions from args and kwargs.
| The substitutions are identified by braces ('{' and '}').
|
| format_map(...)
| S.format_map(mapping) -> str
|
| Return a formatted version of S, using substitutions from mapping.
| The substitutions are identified by braces ('{' and '}').
|
| index(...)
| S.index(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| isalnum(self, /)
| Return True if the string is an alpha-numeric string, False otherwise.
|
| A string is alpha-numeric if all characters in the string are alpha-numeric and
| there is at least one character in the string.
|
| isalpha(self, /)
| Return True if the string is an alphabetic string, False otherwise.
|
| A string is alphabetic if all characters in the string are alphabetic and there
| is at least one character in the string.
|
| isascii(self, /)
| Return True if all characters in the string are ASCII, False otherwise.
|
| ASCII characters have code points in the range U+0000-U+007F.
| Empty string is ASCII too.
|
| isdecimal(self, /)
| Return True if the string is a decimal string, False otherwise.
|
| A string is a decimal string if all characters in the string are decimal and
| there is at least one character in the string.
|
| isdigit(self, /)
| Return True if the string is a digit string, False otherwise.
|
| A string is a digit string if all characters in the string are digits and there
| is at least one character in the string.
|
| isidentifier(self, /)
| Return True if the string is a valid Python identifier, False otherwise.
|
| Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
| such as "def" or "class".
|
| islower(self, /)
| Return True if the string is a lowercase string, False otherwise.
|
| A string is lowercase if all cased characters in the string are lowercase and
| there is at least one cased character in the string.
|
| isnumeric(self, /)
| Return True if the string is a numeric string, False otherwise.
|
| A string is numeric if all characters in the string are numeric and there is at
| least one character in the string.
|
| isprintable(self, /)
| Return True if the string is printable, False otherwise.
|
| A string is printable if all of its characters are considered printable in
| repr() or if it is empty.
|
| isspace(self, /)
| Return True if the string is a whitespace string, False otherwise.
|
| A string is whitespace if all characters in the string are whitespace and there
| is at least one character in the string.
|
| istitle(self, /)
| Return True if the string is a title-cased string, False otherwise.
|
| In a title-cased string, upper- and title-case characters may only
| follow uncased characters and lowercase characters only cased ones.
|
| isupper(self, /)
| Return True if the string is an uppercase string, False otherwise.
|
| A string is uppercase if all cased characters in the string are uppercase and
| there is at least one cased character in the string.
|
| join(self, iterable, /)
| Concatenate any number of strings.
|
| The string whose method is called is inserted in between each given string.
| The result is returned as a new string.
|
| Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
|
| ljust(self, width, fillchar=' ', /)
| Return a left-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| lower(self, /)
| Return a copy of the string converted to lowercase.
|
| lstrip(self, chars=None, /)
| Return a copy of the string with leading whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| partition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string. If the separator is found,
| returns a 3-tuple containing the part before the separator, the separator
| itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing the original string
| and two empty strings.
|
| removeprefix(self, prefix, /)
| Return a str with the given prefix string removed if present.
|
| If the string starts with the prefix string, return string[len(prefix):].
| Otherwise, return a copy of the original string.
|
| removesuffix(self, suffix, /)
| Return a str with the given suffix string removed if present.
|
| If the string ends with the suffix string and that suffix is not empty,
| return string[:-len(suffix)]. Otherwise, return a copy of the original
| string.
|
| replace(self, old, new, count=-1, /)
| Return a copy with all occurrences of substring old replaced by new.
|
| count
| Maximum number of occurrences to replace.
| -1 (the default value) means replace all occurrences.
|
| If the optional argument count is given, only the first count occurrences are
| replaced.
|
| rfind(...)
| S.rfind(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| rindex(...)
| S.rindex(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| rjust(self, width, fillchar=' ', /)
| Return a right-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| rpartition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string, starting at the end. If
| the separator is found, returns a 3-tuple containing the part before the
| separator, the separator itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing two empty strings
| and the original string.
|
| rsplit(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the end of the string and works to the front.
|
| rstrip(self, chars=None, /)
| Return a copy of the string with trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| split(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the front of the string and works to the end.
|
| Note, str.split() is mainly useful for data that has been intentionally
| delimited. With natural text that includes punctuation, consider using
| the regular expression module.
|
| splitlines(self, /, keepends=False)
| Return a list of the lines in the string, breaking at line boundaries.
|
| Line breaks are not included in the resulting list unless keepends is given and
| true.
|
| startswith(...)
| S.startswith(prefix[, start[, end]]) -> bool
|
| Return True if S starts with the specified prefix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| prefix can also be a tuple of strings to try.
|
| strip(self, chars=None, /)
| Return a copy of the string with leading and trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| swapcase(self, /)
| Convert uppercase characters to lowercase and lowercase characters to uppercase.
|
| title(self, /)
| Return a version of the string where each word is titlecased.
|
| More specifically, words start with uppercased characters and all remaining
| cased characters have lower case.
|
| translate(self, table, /)
| Replace each character in the string using the given translation table.
|
| table
| Translation table, which must be a mapping of Unicode ordinals to
| Unicode ordinals, strings, or None.
|
| The table must implement lookup/indexing via __getitem__, for instance a
| dictionary or list. If this operation raises LookupError, the character is
| left untouched. Characters mapped to None are deleted.
|
| upper(self, /)
| Return a copy of the string converted to uppercase.
|
| zfill(self, width, /)
| Pad a numeric string with zeros on the left, to fill a field of the given width.
|
| The string is never truncated.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.str:
|
| maketrans(...)
| Return a translation table usable for str.translate().
|
| If there is only one argument, it must be a dictionary mapping Unicode
| ordinals (integers) or characters to Unicode ordinals, strings or None.
| Character keys will be then converted to ordinals.
| If there are two arguments, they must be strings of equal length, and
| in the resulting dictionary, each character in x will be mapped to the
| character at the same position in y. If there is a third argument, it
| must be a string, whose characters will be mapped to None in the result.
|
| ----------------------------------------------------------------------
| Methods inherited from enum.Enum:
|
| __dir__(self)
| Returns public methods and other interesting attributes.
|
| __init__(self, *args, **kwds)
| Initialize self. See help(type(self)) for accurate signature.
|
| __reduce_ex__(self, proto)
| Helper for pickle.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from enum.Enum:
|
| name
| The name of the Enum member.
|
| value
| The value of the Enum member.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from enum.EnumType:
|
| __members__
| Returns a mapping of member name->value.
|
| This mapping lists all enum members, including aliases. Note that this
| is a read-only view of the internal mapping.
huggingface-hub.JobStatus
Python Library Documentation: class JobStatus in module huggingface_hub._jobs_api
class JobStatus(builtins.object)
| JobStatus(stage: huggingface_hub._jobs_api.JobStage, message: str | None, expose_urls: list[str] | None, ssh_url: str | None) -> None
|
| JobStatus(stage: huggingface_hub._jobs_api.JobStage, message: str | None, expose_urls: list[str] | None, ssh_url: str | None)
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, stage: huggingface_hub._jobs_api.JobStage, message: str | None, expose_urls: list[str] | None, ssh_url: str | None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'expose_urls': list[str] | None, 'message': str | N...
|
| __dataclass_fields__ = {'expose_urls': Field(name='expose_urls',type=l...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('stage', 'message', 'expose_urls', 'ssh_url')
huggingface-hub.KernelInfo
Python Library Documentation: class KernelInfo in module huggingface_hub.hf_api
class KernelInfo(builtins.object)
| KernelInfo(**kwargs)
|
| Contains information about a kernel repo on the Hub. This object is returned by [`kernel_info`].
|
| Attributes:
| id (`str`):
| ID of the kernel repo.
| author (`str`, *optional*):
| Author of the kernel repo.
| downloads (`int`, *optional*):
| Number of downloads of the kernel repo over the last 30 days.
| gated (`Literal["auto", "manual", False]`, *optional*):
| Is the repo gated. If so, whether there is manual or automatic approval.
| last_modified (`datetime`, *optional*):
| Date of last commit to the repo.
| likes (`int`, *optional*):
| Number of likes of the kernel repo.
| private (`bool`, *optional*):
| Is the repo private.
| sha (`str`, *optional*):
| Repo SHA at this particular revision.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'author': 'str | None', 'downloads': 'int | None', ...
|
| __dataclass_fields__ = {'author': Field(name='author',type='str | None...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('id', 'author', 'downloads', 'gated', 'last_modified...
huggingface-hub.MCPClient
Python Library Documentation: class MCPClient in module huggingface_hub.inference._mcp.mcp_client class MCPClient(builtins.object) | MCPClient(*, model: Optional[str] = None, provider: Union[Literal['cerebras', 'cohere', 'deepinfra', 'fal-ai', 'featherless-ai', 'fireworks-ai', 'groq', 'hf-inference', 'novita', 'nscale', 'openai', 'ovhcloud', 'publicai', 'replicate', 'scaleway', 'together', 'wavespeed', 'zai-org'], Literal['auto'], NoneType] = None, base_url: Optional[str] = None, api_key: Optional[str] = None) | | Client for connecting to one or more MCP servers and processing chat completions with tools. | | > [!WARNING] | > This class is experimental and might be subject to breaking changes in the future without prior notice. | | Args: | model (`str`, `optional`): | The model to run inference with. Can be a model id hosted on the Hugging Face Hub, e.g. `meta-llama/Meta-Llama-3-8B-Instruct` | or a URL to a deployed Inference Endpoint or other local or remote endpoint. | provider (`str`, *optional*): | Name of the provider to use for inference. Defaults to "auto" i.e. the first of the providers available for the model, sorted by the user's order in https://hf.co/settings/inference-providers. | If model is a URL or `base_url` is passed, then `provider` is not used. | base_url (`str`, *optional*): | The base URL to run inference. Defaults to None. | api_key (`str`, `optional`): | Token to use for authentication. Will default to the locally Hugging Face saved token if not provided. You can also use your own provider API key to interact directly with the provider's service. | | Methods defined here: | | async __aenter__(self) | Enter the context manager | | async __aexit__(self, exc_type, exc_val, exc_tb) | Exit the context manager | | __init__(self, *, model: Optional[str] = None, provider: Union[Literal['cerebras', 'cohere', 'deepinfra', 'fal-ai', 'featherless-ai', 'fireworks-ai', 'groq', 'hf-inference', 'novita', 'nscale', 'openai', 'ovhcloud', 'publicai', 'replicate', 'scaleway', 'together', 'wavespeed', 'zai-org'], Literal['auto'], NoneType] = None, base_url: Optional[str] = None, api_key: Optional[str] = None) | Initialize self. See help(type(self)) for accurate signature. | | async add_mcp_server(self, type: Literal['stdio', 'sse', 'http'], **params: Any) | Connect to an MCP server | | Args: | type (`str`): | Type of the server to connect to. Can be one of: | - "stdio": Standard input/output server (local) | - "sse": Server-sent events (SSE) server | - "http": StreamableHTTP server | **params (`dict[str, Any]`): | Server parameters that can be either: | - For stdio servers: | - command (str): The command to run the MCP server | - args (list[str], optional): Arguments for the command | - env (dict[str, str], optional): Environment variables for the command | - cwd (Union[str, Path, None], optional): Working directory for the command | - allowed_tools (list[str], optional): List of tool names to allow from this server | - For SSE servers: | - url (str): The URL of the SSE server | - headers (dict[str, Any], optional): Headers for the SSE connection | - timeout (float, optional): Connection timeout | - sse_read_timeout (float, optional): SSE read timeout | - allowed_tools (list[str], optional): List of tool names to allow from this server | - For StreamableHTTP servers: | - url (str): The URL of the StreamableHTTP server | - headers (dict[str, Any], optional): Headers for the StreamableHTTP connection | - timeout (timedelta, optional): Connection timeout | - sse_read_timeout (timedelta, optional): SSE read timeout | - terminate_on_close (bool, optional): Whether to terminate on close | - allowed_tools (list[str], optional): List of tool names to allow from this server | | async cleanup(self) | Clean up resources | | async process_single_turn_with_tools(self, messages: list[typing.Union[dict, huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputMessage]], exit_loop_tools: Optional[list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputTool]] = None, exit_if_first_chunk_no_tool: bool = False) -> AsyncIterable[Union[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionStreamOutput, huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputMessage]] | Process a query using `self.model` and available tools, yielding chunks and tool outputs. | | Args: | messages (`list[dict]`): | List of message objects representing the conversation history | exit_loop_tools (`list[ChatCompletionInputTool]`, *optional*): | List of tools that should exit the generator when called | exit_if_first_chunk_no_tool (`bool`, *optional*): | Exit if no tool is present in the first chunks. Default to False. | | Yields: | [`ChatCompletionStreamOutput`] chunks or [`ChatCompletionInputMessage`] objects | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
huggingface-hub.ModelCard
Python Library Documentation: class ModelCard in module huggingface_hub.repocard
class ModelCard(RepoCard)
| ModelCard(content: str, ignore_metadata_errors: bool = False)
|
| Method resolution order:
| ModelCard
| RepoCard
| builtins.object
|
| Class methods defined here:
|
| from_template(card_data: huggingface_hub.repocard_data.ModelCardData, template_path: str | None = None, template_str: str | None = None, **template_kwargs)
| Initialize a ModelCard from a template. By default, it uses the default template, which can be found here:
| https://github.com/huggingface/huggingface_hub/blob/main/src/huggingface_hub/templates/modelcard_template.md
|
| Templates are Jinja2 templates that can be customized by passing keyword arguments.
|
| Args:
| card_data (`huggingface_hub.ModelCardData`):
| A huggingface_hub.ModelCardData instance containing the metadata you want to include in the YAML
| header of the model card on the Hugging Face Hub.
| template_path (`str`, *optional*):
| A path to a markdown file with optional Jinja template variables that can be filled
| in with `template_kwargs`. Defaults to the default template.
| template_str (`str`, *optional*):
| A raw Jinja template string with optional variables. Used when neither `template_path`
| nor the default template is appropriate. Ignored if `template_path` is also provided.
|
| Returns:
| [`huggingface_hub.ModelCard`]: A ModelCard instance with the specified card data and content from the
| template.
|
| Example:
| ```python
| >>> from huggingface_hub import ModelCard, ModelCardData, EvalResult
|
| >>> # Using the Default Template
| >>> card_data = ModelCardData(
| ... language='en',
| ... license='mit',
| ... library_name='timm',
| ... tags=['image-classification', 'resnet'],
| ... datasets=['beans'],
| ... metrics=['accuracy'],
| ... )
| >>> card = ModelCard.from_template(
| ... card_data,
| ... model_description='This model does x + y...'
| ... )
|
| >>> # Including Evaluation Results
| >>> card_data = ModelCardData(
| ... language='en',
| ... tags=['image-classification', 'resnet'],
| ... eval_results=[
| ... EvalResult(
| ... task_type='image-classification',
| ... dataset_type='beans',
| ... dataset_name='Beans',
| ... metric_type='accuracy',
| ... metric_value=0.9,
| ... ),
| ... ],
| ... model_name='my-cool-model',
| ... )
| >>> card = ModelCard.from_template(card_data)
|
| >>> # Using a Custom Template
| >>> card_data = ModelCardData(
| ... language='en',
| ... tags=['image-classification', 'resnet']
| ... )
| >>> card = ModelCard.from_template(
| ... card_data=card_data,
| ... template_path='./src/huggingface_hub/templates/modelcard_template.md',
| ... custom_template_var='custom value', # will be replaced in template if it exists
| ... )
|
| ```
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| card_data_class = <class 'huggingface_hub.repocard_data.ModelCardData'...
| Model Card Metadata that is used by Hugging Face Hub when included at the top of your README.md
|
| 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 your model derives from multiple models). Defaults to None.
| datasets (`Union[str, list[str]]`, *optional*):
| Dataset or list of datasets that were used to train this model. Should be a dataset ID
| found on https://hf.co/datasets. Defaults to None.
| eval_results (`Union[list[EvalResult], EvalResult]`, *optional*):
| List of `huggingface_hub.EvalResult` that define evaluation results of the model. If provided,
| `model_name` is used to as a name on PapersWithCode's leaderboards. Defaults to `None`.
| language (`Union[str, list[str]]`, *optional*):
| 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
| https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/src/model-libraries.ts.
| Defaults to None.
| license (`str`, *optional*):
| License of this model. Example: apache-2.0 or any license from
| https://huggingface.co/docs/hub/repositories-licenses. Defaults to None.
| license_name (`str`, *optional*):
| Name of the license of this model. Defaults to None. To be used in conjunction with `license_link`.
| Common licenses (Apache-2.0, MIT, CC-BY-SA-4.0) do not need a name. In that case, use `license` instead.
| license_link (`str`, *optional*):
| 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. Should be a metric name that can be found
| at https://hf.co/metrics. Example: 'accuracy'. Defaults to None.
| model_name (`str`, *optional*):
| A name for this model. It is used along with
| `eval_results` to construct the `model-index` within the card's metadata. The name
| you supply here is what will be used on PapersWithCode's leaderboards. If None is provided
| then the repo name is used as a default. Defaults to None.
| pipeline_tag (`str`, *optional*):
| The pipeline tag associated with the model. Example: "text-classification".
| tags (`list[str]`, *optional*):
| 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 own risk.
| kwargs (`dict`, *optional*):
| Additional metadata that will be added to the model card. Defaults to None.
|
| 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()
| {'language': 'en', 'license': 'mit', 'library_name': 'timm', 'tags': ['image-classification', 'resnet']}
|
| ```
|
|
| default_template_path = WindowsPath('C:/Users/Youse/AppData/Local/Prog...
|
| repo_type = 'model'
|
| ----------------------------------------------------------------------
| Methods inherited from RepoCard:
|
| __init__(self, content: str, ignore_metadata_errors: bool = False)
| Initialize a RepoCard from string content. The content should be a
| Markdown file with a YAML block at the beginning and a Markdown body.
|
| Args:
| content (`str`): The content of the Markdown file.
|
| Example:
| ```python
| >>> from huggingface_hub.repocard import RepoCard
| >>> text = '''
| ... ---
| ... language: en
| ... license: mit
| ... ---
| ...
| ... # My repo
| ... '''
| >>> card = RepoCard(text)
| >>> card.data.to_dict()
| {'language': 'en', 'license': 'mit'}
| >>> card.text
| '\n# My repo\n'
|
| ```
| > [!TIP]
| > Raises the following error:
| >
| > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| > when the content of the repo card metadata is not a dictionary.
|
| __str__(self)
| Return str(self).
|
| push_to_hub(self, repo_id: str, token: str | None = None, repo_type: str | None = None, commit_message: str | None = None, commit_description: str | None = None, revision: str | None = None, create_pr: bool | None = None, parent_commit: str | None = None)
| Push a RepoCard to a Hugging Face Hub repo.
|
| Args:
| repo_id (`str`):
| The repo ID of the Hugging Face Hub repo to push to. Example: "nateraw/food".
| token (`str`, *optional*):
| Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to
| the stored token.
| repo_type (`str`, *optional*, defaults to "model"):
| The type of Hugging Face repo to push to. Options are "model", "dataset", and "space". If this
| function is called by a child class, it will default to the child class's `repo_type`.
| commit_message (`str`, *optional*):
| The summary / title / first line of the generated commit.
| commit_description (`str`, *optional*)
| The description of the generated commit.
| revision (`str`, *optional*):
| The git revision to commit from. Defaults to the head of the `"main"` branch.
| create_pr (`bool`, *optional*):
| Whether or not to create a Pull Request with this commit. Defaults to `False`.
| parent_commit (`str`, *optional*):
| The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
| If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
| If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
| Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
| especially useful if the repo is updated / committed too concurrently.
| Returns:
| `str`: URL of the commit which updated the card metadata.
|
| save(self, filepath: pathlib.Path | str)
| Save a RepoCard to a file.
|
| Args:
| filepath (`Union[Path, str]`): Filepath to the markdown file to save.
|
| Example:
| ```python
| >>> from huggingface_hub.repocard import RepoCard
| >>> card = RepoCard("---\nlanguage: en\n---\n# This is a test repo card")
| >>> card.save("/tmp/test.md")
|
| ```
|
| validate(self, repo_type: str | None = None)
| Validates card against Hugging Face Hub's card validation logic.
| Using this function requires access to the internet, so it is only called
| internally by [`huggingface_hub.repocard.RepoCard.push_to_hub`].
|
| Args:
| repo_type (`str`, *optional*, defaults to "model"):
| The type of Hugging Face repo to push to. Options are "model", "dataset", and "space".
| If this function is called from a child class, the default will be the child class's `repo_type`.
|
| > [!TIP]
| > Raises the following errors:
| >
| > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| > if the card fails validation checks.
| > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
| > if the request to the Hub API fails for any other reason.
|
| ----------------------------------------------------------------------
| Class methods inherited from RepoCard:
|
| load(repo_id_or_path: str | pathlib.Path, repo_type: str | None = None, token: str | None = None, ignore_metadata_errors: bool = False)
| Initialize a RepoCard from a Hugging Face Hub repo's README.md or a local filepath.
|
| Args:
| repo_id_or_path (`Union[str, Path]`):
| The repo ID associated with a Hugging Face Hub repo or a local filepath.
| repo_type (`str`, *optional*):
| The type of Hugging Face repo to push to. Defaults to None, which will use "model". Other options
| are "dataset" and "space". Not used when loading from a local filepath. If this is called from a child
| class, the default value will be the child class's `repo_type`.
| 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.
|
| Returns:
| [`huggingface_hub.repocard.RepoCard`]: The RepoCard (or subclass) initialized from the repo's
| README.md file or filepath.
|
| Example:
| ```python
| >>> from huggingface_hub.repocard import RepoCard
| >>> card = RepoCard.load("nateraw/food")
| >>> assert card.data.tags == ["generated_from_trainer", "image-classification", "pytorch"]
|
| ```
|
| ----------------------------------------------------------------------
| Data descriptors inherited from RepoCard:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| content
| The content of the RepoCard, including the YAML block and the Markdown body.
huggingface-hub.ModelCardData
Python Library Documentation: class ModelCardData in module huggingface_hub.repocard_data
class ModelCardData(CardData)
| ModelCardData(*, base_model: str | list[str] | None = None, datasets: str | list[str] | None = None, eval_results: list[huggingface_hub.repocard_data.EvalResult] | None = None, language: str | list[str] | None = None, library_name: str | None = None, license: str | None = None, license_name: str | None = None, license_link: str | None = None, metrics: list[str] | None = None, model_name: str | None = None, pipeline_tag: str | None = None, tags: list[str] | None = None, ignore_metadata_errors: bool = False, **kwargs)
|
| Model Card Metadata that is used by Hugging Face Hub when included at the top of your README.md
|
| 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 your model derives from multiple models). Defaults to None.
| datasets (`Union[str, list[str]]`, *optional*):
| Dataset or list of datasets that were used to train this model. Should be a dataset ID
| found on https://hf.co/datasets. Defaults to None.
| eval_results (`Union[list[EvalResult], EvalResult]`, *optional*):
| List of `huggingface_hub.EvalResult` that define evaluation results of the model. If provided,
| `model_name` is used to as a name on PapersWithCode's leaderboards. Defaults to `None`.
| language (`Union[str, list[str]]`, *optional*):
| 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
| https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/src/model-libraries.ts.
| Defaults to None.
| license (`str`, *optional*):
| License of this model. Example: apache-2.0 or any license from
| https://huggingface.co/docs/hub/repositories-licenses. Defaults to None.
| license_name (`str`, *optional*):
| Name of the license of this model. Defaults to None. To be used in conjunction with `license_link`.
| Common licenses (Apache-2.0, MIT, CC-BY-SA-4.0) do not need a name. In that case, use `license` instead.
| license_link (`str`, *optional*):
| 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. Should be a metric name that can be found
| at https://hf.co/metrics. Example: 'accuracy'. Defaults to None.
| model_name (`str`, *optional*):
| A name for this model. It is used along with
| `eval_results` to construct the `model-index` within the card's metadata. The name
| you supply here is what will be used on PapersWithCode's leaderboards. If None is provided
| then the repo name is used as a default. Defaults to None.
| pipeline_tag (`str`, *optional*):
| The pipeline tag associated with the model. Example: "text-classification".
| tags (`list[str]`, *optional*):
| 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 own risk.
| kwargs (`dict`, *optional*):
| Additional metadata that will be added to the model card. Defaults to None.
|
| 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()
| {'language': 'en', 'license': 'mit', 'library_name': 'timm', 'tags': ['image-classification', 'resnet']}
|
| ```
|
| Method resolution order:
| ModelCardData
| CardData
| builtins.object
|
| Methods defined here:
|
| __init__(self, *, base_model: str | list[str] | None = None, datasets: str | list[str] | None = None, eval_results: list[huggingface_hub.repocard_data.EvalResult] | None = None, language: str | list[str] | None = None, library_name: str | None = None, license: str | None = None, license_name: str | None = None, license_link: str | None = None, metrics: list[str] | None = None, model_name: str | None = None, pipeline_tag: str | None = None, tags: list[str] | None = None, ignore_metadata_errors: bool = False, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from CardData:
|
| __contains__(self, key: str) -> bool
| Check if a given metadata key is set.
|
| __eq__(self, other)
| Return self==value.
|
| __getitem__(self, key: str) -> Any
| Get value for a given metadata key.
|
| __len__(self) -> int
| Return the number of metadata keys set.
|
| __repr__(self)
| Return repr(self).
|
| __setitem__(self, key: str, value: Any) -> None
| Set value for a given metadata key.
|
| __str__(self)
| Return str(self).
|
| get(self, key: str, default: Any = None) -> Any
| Get value for a given metadata key.
|
| pop(self, key: str, default: Any = None) -> Any
| Pop value for a given metadata key.
|
| to_dict(self)
| Converts CardData to a dict.
|
| Returns:
| `dict`: CardData represented as a dictionary ready to be dumped to a YAML
| block for inclusion in a README.md file.
|
| to_yaml(self, line_break=None, original_order: list[str] | None = None) -> str
| Dumps CardData to a YAML block for inclusion in a README.md file.
|
| Args:
| line_break (str, *optional*):
| The line break to use when dumping to yaml.
| original_order (`list[str]`, *optional*):
| If provided, reorder the metadata fields to match this list before dumping.
| Any keys not in `original_order` are appended after the listed keys, preserving
| their existing relative order. Useful for round-tripping a YAML block without
| shuffling its keys.
|
| Returns:
| `str`: CardData represented as a YAML block.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from CardData:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from CardData:
|
| __dataclass_fields__ = {}
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ()
huggingface-hub.ModelHubMixin
Python Library Documentation: class ModelHubMixin in module huggingface_hub.hub_mixin
class ModelHubMixin(builtins.object)
| ModelHubMixin(*args, **kwargs) -> ~T
|
| 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`]. [`PyTorchModelHubMixin`] is a good example
| of mixin integration with the Hub. Check out our [integration guide](../guides/integrations) for more instructions.
|
| When inheriting from [`ModelHubMixin`], you can define class-level attributes. These attributes are not passed to
| `__init__` but to the class definition itself. This is useful to define metadata about the library integrating
| [`ModelHubMixin`].
|
| For more details on how to integrate the mixin with your library, checkout the [integration guide](../guides/integrations).
|
| Args:
| repo_url (`str`, *optional*):
| URL of the library repository. Used to generate model card.
| paper_url (`str`, *optional*):
| URL of the library paper. 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. Used to generate model card. Defaults to a generic template.
| language (`str` or `list[str]`, *optional*):
| Language supported by the library. Used to generate model card.
| library_name (`str`, *optional*):
| Name of the library integrating ModelHubMixin. Used to generate model card.
| license (`str`, *optional*):
| License of the library integrating ModelHubMixin. Used to generate model card.
| E.g: "apache-2.0"
| license_name (`str`, *optional*):
| Name of the library integrating ModelHubMixin. Used to generate model card.
| Only used if `license` is set to `other`.
| 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_tag (`str`, *optional*):
| Tag of the pipeline. Used to generate model card. E.g. "text-classification".
| tags (`list[str]`, *optional*):
| Tags to be added to the model card. Used to generate model card. E.g. ["computer-vision"]
| coders (`dict[Type, tuple[Callable, Callable]]`, *optional*):
| Dictionary of custom types and their encoders/decoders. Used to encode/decode arguments that are not
| jsonable by default. E.g. dataclasses, argparse.Namespace, OmegaConf, etc.
|
| Example:
|
| ```python
| >>> from huggingface_hub import ModelHubMixin
|
| # Inherit from ModelHubMixin
| >>> class MyCustomModel(
| ... ModelHubMixin,
| ... library_name="my-library",
| ... tags=["computer-vision"],
| ... repo_url="https://github.com/huggingface/my-cool-library",
| ... paper_url="https://arxiv.org/abs/2304.12244",
| ... docs_url="https://huggingface.co/docs/my-cool-library",
| ... # ^ optional metadata to generate model card
| ... ):
| ... def __init__(self, size: int = 512, device: str = "cpu"):
| ... # define how to initialize your model
| ... super().__init__()
| ... ...
| ...
| ... def _save_pretrained(self, save_directory: Path) -> None:
| ... # define how to serialize your model
| ... ...
| ...
| ... @classmethod
| ... def from_pretrained(
| ... cls: type[T],
| ... pretrained_model_name_or_path: Union[str, Path],
| ... *,
| ... force_download: bool = False,
| ... token: Optional[Union[str, bool]] = None,
| ... cache_dir: Optional[Union[str, Path]] = None,
| ... local_files_only: bool = False,
| ... revision: Optional[str] = None,
| ... **model_kwargs,
| ... ) -> T:
| ... # define how to deserialize your model
| ... ...
|
| >>> 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.from_pretrained("username/my-awesome-model")
| >>> reloaded_model.size
| 256
|
| # Model card has been correctly populated
| >>> from huggingface_hub import ModelCard
| >>> card = ModelCard.load("username/my-awesome-model")
| >>> card.data.tags
| ["x-custom-tag", "pytorch_model_hub_mixin", "model_hub_mixin"]
| >>> card.data.library_name
| "my-library"
| ```
|
| Methods defined here:
|
| generate_model_card(self, *args, **kwargs) -> huggingface_hub.repocard.ModelCard
|
| push_to_hub(self, repo_id: str, *, config: dict | huggingface_hub.hub_mixin.DataclassInstance | None = None, commit_message: str = 'Push model using huggingface_hub.', private: bool | None = None, token: str | None = None, branch: str | None = None, create_pr: bool | None = None, allow_patterns: list[str] | str | None = None, ignore_patterns: list[str] | str | None = None, delete_patterns: list[str] | str | None = None, model_card_kwargs: dict[str, typing.Any] | None = None) -> str
| Upload model checkpoint 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:
| 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`, *optional*):
| Message to commit while pushing.
| private (`bool`, *optional*):
| Whether the repository created should be private.
| If `None` (default), the repo will be public unless the organization's default is private.
| token (`str`, *optional*):
| The token to use as HTTP bearer authorization for remote files. By default, it will use the token
| cached when running `hf auth login`.
| branch (`str`, *optional*):
| The git branch on which to push the model. This defaults to `"main"`.
| create_pr (`boolean`, *optional*):
| 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 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.
| model_card_kwargs (`dict[str, Any]`, *optional*):
| Additional arguments passed to the model card template to customize the model card.
|
| Returns:
| The url of the commit of your model in the given repository.
|
| save_pretrained(self, save_directory: str | pathlib.Path, *, config: dict | huggingface_hub.hub_mixin.DataclassInstance | None = None, repo_id: str | None = None, push_to_hub: bool = False, model_card_kwargs: dict[str, typing.Any] | None = None, **push_to_hub_kwargs) -> str | None
| Save weights in local directory.
|
| 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.
| push_to_hub (`bool`, *optional*, defaults to `False`):
| Whether or not to push your model to the Huggingface Hub after saving it.
| repo_id (`str`, *optional*):
| ID of your repository on the Hub. Used only if `push_to_hub=True`. Will default to the folder name if
| not provided.
| model_card_kwargs (`dict[str, Any]`, *optional*):
| Additional arguments passed to the model card template to customize the model card.
| push_to_hub_kwargs:
| Additional key word arguments passed along to the [`~ModelHubMixin.push_to_hub`] method.
| Returns:
| `str` or `None`: url of the commit on the Hub if `push_to_hub=True`, `None` otherwise.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __init_subclass__(*, repo_url: str | None = None, paper_url: str | None = None, docs_url: str | None = None, model_card_template: str = '\n---\n# For reference on model card metadata, see the spec: https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1\n# Doc / guide: https://huggingface.co/docs/hub/model-cards\n{{ card_data }}\n---\n\nThis model has been pushed to the Hub using the [PytorchModelHubMixin](https://huggingface.co/docs/huggingface_hub/package_reference/mixins#huggingface_hub.PyTorchModelHubMixin) integration:\n- Code: {{ repo_url | default("[More Information Needed]", true) }}\n- Paper: {{ paper_url | default("[More Information Needed]", true) }}\n- Docs: {{ docs_url | default("[More Information Needed]", true) }}\n', language: list[str] | None = None, library_name: str | None = None, license: str | None = None, license_name: str | None = None, license_link: str | None = None, pipeline_tag: str | None = None, tags: list[str] | None = None, coders: None | dict[type, tuple[collections.abc.Callable[[~ARGS_T], typing.Any], collections.abc.Callable[[typing.Any], ~ARGS_T]]] = None) -> None
| Inspect __init__ signature only once when subclassing + handle modelcard.
|
| from_pretrained(pretrained_model_name_or_path: str | pathlib.Path, *, force_download: bool = False, token: str | bool | None = None, cache_dir: str | pathlib.Path | None = None, local_files_only: bool = False, revision: str | None = None, **model_kwargs) -> ~T
| Download a model from the Huggingface Hub and instantiate it.
|
| 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`], e.g., `../path/to/my_model_directory/`.
| 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 `main` branch.
| force_download (`bool`, *optional*, defaults to `False`):
| Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding
| the existing cache.
| 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 `hf auth login`.
| 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 (`dict`, *optional*):
| Additional kwargs to pass to the model during initialization.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(cls: type[~T], *args, **kwargs) -> ~T
| Create a new instance of the class and handle config.
|
| 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.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_hub_mixin_coders': dict[type, tuple[collections.a...
huggingface-hub.ModelInfo
Python Library Documentation: class ModelInfo in module huggingface_hub.hf_api
class ModelInfo(builtins.object)
| ModelInfo(**kwargs)
|
| Contains information about a model on the Hub. This object is returned by [`model_info`] and [`list_models`].
|
| > [!TIP]
| > Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made.
| > In general, the more specific the query, the more information is returned. On the contrary, when listing models
| > using [`list_models`] only a subset of the attributes are returned.
|
| Attributes:
| id (`str`):
| ID of model.
| author (`str`, *optional*):
| Author of the model.
| base_models (`list[str]`, *optional*):
| List of base models this model is derived from.
| card_data (`ModelCardData`, *optional*):
| Model Card Metadata as a [`huggingface_hub.repocard_data.ModelCardData`] object.
| children_model_count (`int`, *optional*):
| Number of children models derived from this model.
| config (`dict`, *optional*):
| Model configuration.
| created_at (`datetime`, *optional*):
| Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`,
| corresponding to the date when we began to store creation dates.
| disabled (`bool`, *optional*):
| Is the repo disabled.
| downloads (`int`):
| Number of downloads of the model over the last 30 days.
| downloads_all_time (`int`):
| Cumulated number of downloads of the model since its creation.
| eval_results (`list[EvalResultEntry]`, *optional*):
| Model's evaluation results.
| gated (`Literal["auto", "manual", False]`, *optional*):
| Is the repo gated.
| If so, whether there is manual or automatic approval.
| gguf (`dict`, *optional*):
| GGUF information of the model.
| inference (`Literal["warm"]`, *optional*):
| Status of the model on Inference Providers. Warm if the model is served by at least one provider.
| inference_provider_mapping (`list[InferenceProviderMapping]`, *optional*):
| A list of [`InferenceProviderMapping`] ordered after the user's provider order.
| last_modified (`datetime`, *optional*):
| Date of last commit to the repo.
| library_name (`str`, *optional*):
| Library associated with the model.
| likes (`int`):
| Number of likes of the model.
| mask_token (`str`, *optional*):
| Mask token used by the model.
| model_index (`dict`, *optional*):
| Model index for evaluation.
| pipeline_tag (`str`, *optional*):
| Pipeline tag associated with the model.
| private (`bool`):
| Is the repo private.
| resource_group (`dict`, *optional*):
| Resource group information for the model.
| safetensors (`SafeTensorsInfo`, *optional*):
| Model's safetensors information.
| security_repo_status (`dict`, *optional*):
| Model's security scan status.
| sha (`str`, *optional*):
| Repo SHA at this particular revision.
| siblings (`list[RepoSibling]`):
| List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the model.
| spaces (`list[str]`, *optional*):
| List of spaces using the model.
| tags (`list[str]`):
| List of tags of the model. Compared to `card_data.tags`, contains extra tags computed by the Hub
| (e.g. supported libraries, model's arXiv).
| transformers_info (`TransformersInfo`, *optional*):
| Transformers-specific info (auto class, processor, etc.) associated with the model.
| trending_score (`int`, *optional*):
| Trending score of the model.
| used_storage (`int`, *optional*):
| Size in bytes of the model on the Hub.
| widget_data (`Any`, *optional*):
| Widget data associated with the model.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'author': 'str | None', 'base_models': 'list[str] |...
|
| __dataclass_fields__ = {'author': Field(name='author',type='str | None...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('id', 'author', 'base_models', 'card_data', 'childre...
huggingface-hub.OAuthInfo
Python Library Documentation: class OAuthInfo in module huggingface_hub._oauth
class OAuthInfo(builtins.object)
| OAuthInfo(access_token: str, access_token_expires_at: datetime.datetime, user_info: huggingface_hub._oauth.OAuthUserInfo, state: str | None, scope: str) -> None
|
| Information about the OAuth login.
|
| Attributes:
| access_token (`str`):
| The access token.
| access_token_expires_at (`datetime.datetime`):
| The expiration date of the access token.
| user_info ([`OAuthUserInfo`]):
| The user information.
| state (`str`, *optional*):
| State passed to the OAuth provider in the original request to the OAuth provider.
| scope (`str`):
| Granted scope.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, access_token: str, access_token_expires_at: datetime.datetime, user_info: huggingface_hub._oauth.OAuthUserInfo, state: str | None, scope: str) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'access_token': <class 'str'>, 'access_token_expire...
|
| __dataclass_fields__ = {'access_token': Field(name='access_token',type...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('access_token', 'access_token_expires_at', 'user_inf...
huggingface-hub.OAuthOrgInfo
Python Library Documentation: class OAuthOrgInfo in module huggingface_hub._oauth
class OAuthOrgInfo(builtins.object)
| OAuthOrgInfo(sub: str, name: str, preferred_username: str, picture: str, plan: str | None = None, can_pay: bool | None = None, role_in_org: str | None = None, security_restrictions: list[typing.Literal['ip', 'token-policy', 'mfa', 'sso']] | None = None) -> None
|
| Information about an organization linked to a user logged in with OAuth.
|
| Attributes:
| sub (`str`):
| Unique identifier for the org. OpenID Connect field.
| name (`str`):
| The org's full name. OpenID Connect field.
| preferred_username (`str`):
| The org's username. OpenID Connect field.
| picture (`str`):
| The org's profile picture URL. OpenID Connect field.
| plan (`str`, *optional*):
| The org's plan (e.g., "enterprise", "team"). Hugging Face field.
| can_pay (`Optional[bool]`, *optional*):
| Whether the org has a payment method set up. Hugging Face field.
| role_in_org (`Optional[str]`, *optional*):
| The user's role in the org. Hugging Face field.
| security_restrictions (`Optional[list[Literal["ip", "token-policy", "mfa", "sso"]]]`, *optional*):
| Array of security restrictions that the user hasn't completed for this org. Possible values: "ip", "token-policy", "mfa", "sso". Hugging Face field.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, sub: str, name: str, preferred_username: str, picture: str, plan: str | None = None, can_pay: bool | None = None, role_in_org: str | None = None, security_restrictions: list[typing.Literal['ip', 'token-policy', 'mfa', 'sso']] | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'can_pay': bool | None, 'name': <class 'str'>, 'pic...
|
| __dataclass_fields__ = {'can_pay': Field(name='can_pay',type=bool | No...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('sub', 'name', 'preferred_username', 'picture', 'pla...
|
| can_pay = None
|
| plan = None
|
| role_in_org = None
|
| security_restrictions = None
huggingface-hub.OAuthUserInfo
Python Library Documentation: class OAuthUserInfo in module huggingface_hub._oauth
class OAuthUserInfo(builtins.object)
| OAuthUserInfo(sub: str, name: str, preferred_username: str, email_verified: bool | None, email: str | None, picture: str, profile: str, website: str | None, is_pro: bool, can_pay: bool | None, orgs: list[huggingface_hub._oauth.OAuthOrgInfo] | None) -> None
|
| Information about a user logged in with OAuth.
|
| Attributes:
| sub (`str`):
| Unique identifier for the user, even in case of rename. OpenID Connect field.
| name (`str`):
| The user's full name. OpenID Connect field.
| preferred_username (`str`):
| The user's username. OpenID Connect field.
| email_verified (`Optional[bool]`, *optional*):
| Indicates if the user's email is verified. OpenID Connect field.
| email (`Optional[str]`, *optional*):
| The user's email address. OpenID Connect field.
| picture (`str`):
| The user's profile picture URL. OpenID Connect field.
| profile (`str`):
| The user's profile URL. OpenID Connect field.
| website (`Optional[str]`, *optional*):
| The user's website URL. OpenID Connect field.
| is_pro (`bool`):
| Whether the user is a pro user. Hugging Face field.
| can_pay (`Optional[bool]`, *optional*):
| Whether the user has a payment method set up. Hugging Face field.
| orgs (`Optional[list[OrgInfo]]`, *optional*):
| List of organizations the user is part of. Hugging Face field.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, sub: str, name: str, preferred_username: str, email_verified: bool | None, email: str | None, picture: str, profile: str, website: str | None, is_pro: bool, can_pay: bool | None, orgs: list[huggingface_hub._oauth.OAuthOrgInfo] | None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'can_pay': bool | None, 'email': str | None, 'email...
|
| __dataclass_fields__ = {'can_pay': Field(name='can_pay',type=bool | No...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('sub', 'name', 'preferred_username', 'email_verified...
huggingface-hub.ObjectDetectionBoundingBox
Python Library Documentation: class ObjectDetectionBoundingBox in module huggingface_hub.inference._generated.types.object_detection
class ObjectDetectionBoundingBox(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ObjectDetectionBoundingBox(xmax: int, xmin: int, ymax: int, ymin: int) -> None
|
| The predicted bounding box. Coordinates are relative to the top left corner of the input
| image.
|
| Method resolution order:
| ObjectDetectionBoundingBox
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, xmax: int, xmin: int, ymax: int, ymin: int) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'xmax': <class 'int'>, 'xmin': <class 'int'>, 'ymax...
|
| __dataclass_fields__ = {'xmax': Field(name='xmax',type=<class 'int'>,d...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('xmax', 'xmin', 'ymax', 'ymin')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ObjectDetectionInput
Python Library Documentation: class ObjectDetectionInput in module huggingface_hub.inference._generated.types.object_detection
class ObjectDetectionInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ObjectDetectionInput(inputs: str, parameters: huggingface_hub.inference._generated.types.object_detection.ObjectDetectionParameters | None = None) -> None
|
| Inputs for Object Detection inference
|
| Method resolution order:
| ObjectDetectionInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: str, parameters: huggingface_hub.inference._generated.types.object_detection.ObjectDetectionParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'str'>, 'parameters': huggingface_...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ObjectDetectionOutputElement
Python Library Documentation: class ObjectDetectionOutputElement in module huggingface_hub.inference._generated.types.object_detection
class ObjectDetectionOutputElement(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ObjectDetectionOutputElement(box: huggingface_hub.inference._generated.types.object_detection.ObjectDetectionBoundingBox, label: str, score: float) -> None
|
| Outputs of inference for the Object Detection task
|
| Method resolution order:
| ObjectDetectionOutputElement
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, box: huggingface_hub.inference._generated.types.object_detection.ObjectDetectionBoundingBox, label: str, score: float) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'box': <class 'huggingface_hub.inference._generated...
|
| __dataclass_fields__ = {'box': Field(name='box',type=<class 'huggingfa...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('box', 'label', 'score')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ObjectDetectionParameters
Python Library Documentation: class ObjectDetectionParameters in module huggingface_hub.inference._generated.types.object_detection
class ObjectDetectionParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ObjectDetectionParameters(threshold: float | None = None) -> None
|
| Additional inference parameters for Object Detection
|
| Method resolution order:
| ObjectDetectionParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, threshold: float | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'threshold': float | None}
|
| __dataclass_fields__ = {'threshold': Field(name='threshold',type=float...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('threshold',)
|
| threshold = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.Organization
Python Library Documentation: class Organization in module huggingface_hub.hf_api
class Organization(builtins.object)
| Organization(**kwargs) -> 'None'
|
| Contains information about an organization on the Hub.
|
| Attributes:
| avatar_url (`str`):
| URL of the organization's avatar.
| name (`str`):
| Name of the organization on the Hub (unique).
| fullname (`str`):
| Organization's full name.
| details (`str`, *optional*):
| Organization's description.
| is_verified (`bool`, *optional*):
| Whether the organization is verified.
| is_following (`bool`, *optional*):
| Whether the authenticated user follows this organization.
| num_users (`int`, *optional*):
| Number of members in the organization.
| num_models (`int`, *optional*):
| Number of models owned by the organization.
| num_spaces (`int`, *optional*):
| Number of Spaces owned by the organization.
| num_datasets (`int`, *optional*):
| Number of datasets owned by the organization.
| num_followers (`int`, *optional*):
| Number of followers of the organization.
| num_papers (`int`, *optional*):
| Number of papers authored by the organization.
| plan (`str`, *optional*):
| The organization's plan (e.g., "enterprise", "team").
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, **kwargs) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'avatar_url': 'str', 'details': 'str | None', 'full...
|
| __dataclass_fields__ = {'avatar_url': Field(name='avatar_url',type='st...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('avatar_url', 'name', 'fullname', 'details', 'is_ver...
|
| details = None
|
| is_following = None
|
| is_verified = None
|
| num_datasets = None
|
| num_followers = None
|
| num_models = None
|
| num_papers = None
|
| num_spaces = None
|
| num_users = None
|
| plan = None
huggingface-hub.PYTORCH_WEIGHTS_NAME
Error rendering doc: No Python documentation found for 'pytorch_model.bin'. Use help() to get the interactive help utility. Use help(str) for help on the str class.
huggingface-hub.Padding
Python Library Documentation: _LiteralGenericAlias in module typing
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
huggingface-hub.PyTorchModelHubMixin
Python Library Documentation: class PyTorchModelHubMixin in module huggingface_hub.hub_mixin
class PyTorchModelHubMixin(ModelHubMixin)
| PyTorchModelHubMixin(*args, **kwargs) -> ~T
|
| 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 in training mode with `model.train()`.
|
| See [`ModelHubMixin`] for more details on how to use the mixin.
|
| Example:
|
| ```python
| >>> import torch
| >>> import torch.nn as nn
| >>> from huggingface_hub import PyTorchModelHubMixin
|
| >>> class MyModel(
| ... nn.Module,
| ... PyTorchModelHubMixin,
| ... library_name="keras-nlp",
| ... repo_url="https://github.com/keras-team/keras-nlp",
| ... paper_url="https://arxiv.org/abs/2304.12244",
| ... docs_url="https://keras.io/keras_nlp/",
| ... # ^ optional metadata to generate model card
| ... ):
| ... def __init__(self, hidden_size: int = 512, vocab_size: int = 30000, output_size: int = 4):
| ... super().__init__()
| ... self.param = nn.Parameter(torch.rand(hidden_size, vocab_size))
| ... self.linear = nn.Linear(output_size, vocab_size)
|
| ... def forward(self, x):
| ... return self.linear(x + self.param)
| >>> model = MyModel(hidden_size=256)
|
| # 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
| >>> model = MyModel.from_pretrained("username/my-awesome-model")
| >>> model.hidden_size
| 256
| ```
|
| Method resolution order:
| PyTorchModelHubMixin
| ModelHubMixin
| builtins.object
|
| Class methods defined here:
|
| __init_subclass__(*args, tags: list[str] | None = None, **kwargs) -> None
| Inspect __init__ signature only once when subclassing + handle modelcard.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from ModelHubMixin:
|
| generate_model_card(self, *args, **kwargs) -> huggingface_hub.repocard.ModelCard
|
| push_to_hub(self, repo_id: str, *, config: dict | huggingface_hub.hub_mixin.DataclassInstance | None = None, commit_message: str = 'Push model using huggingface_hub.', private: bool | None = None, token: str | None = None, branch: str | None = None, create_pr: bool | None = None, allow_patterns: list[str] | str | None = None, ignore_patterns: list[str] | str | None = None, delete_patterns: list[str] | str | None = None, model_card_kwargs: dict[str, typing.Any] | None = None) -> str
| Upload model checkpoint 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:
| 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`, *optional*):
| Message to commit while pushing.
| private (`bool`, *optional*):
| Whether the repository created should be private.
| If `None` (default), the repo will be public unless the organization's default is private.
| token (`str`, *optional*):
| The token to use as HTTP bearer authorization for remote files. By default, it will use the token
| cached when running `hf auth login`.
| branch (`str`, *optional*):
| The git branch on which to push the model. This defaults to `"main"`.
| create_pr (`boolean`, *optional*):
| 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 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.
| model_card_kwargs (`dict[str, Any]`, *optional*):
| Additional arguments passed to the model card template to customize the model card.
|
| Returns:
| The url of the commit of your model in the given repository.
|
| save_pretrained(self, save_directory: str | pathlib.Path, *, config: dict | huggingface_hub.hub_mixin.DataclassInstance | None = None, repo_id: str | None = None, push_to_hub: bool = False, model_card_kwargs: dict[str, typing.Any] | None = None, **push_to_hub_kwargs) -> str | None
| Save weights in local directory.
|
| 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.
| push_to_hub (`bool`, *optional*, defaults to `False`):
| Whether or not to push your model to the Huggingface Hub after saving it.
| repo_id (`str`, *optional*):
| ID of your repository on the Hub. Used only if `push_to_hub=True`. Will default to the folder name if
| not provided.
| model_card_kwargs (`dict[str, Any]`, *optional*):
| Additional arguments passed to the model card template to customize the model card.
| push_to_hub_kwargs:
| Additional key word arguments passed along to the [`~ModelHubMixin.push_to_hub`] method.
| Returns:
| `str` or `None`: url of the commit on the Hub if `push_to_hub=True`, `None` otherwise.
|
| ----------------------------------------------------------------------
| Class methods inherited from ModelHubMixin:
|
| from_pretrained(pretrained_model_name_or_path: str | pathlib.Path, *, force_download: bool = False, token: str | bool | None = None, cache_dir: str | pathlib.Path | None = None, local_files_only: bool = False, revision: str | None = None, **model_kwargs) -> ~T
| Download a model from the Huggingface Hub and instantiate it.
|
| 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`], e.g., `../path/to/my_model_directory/`.
| 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 `main` branch.
| force_download (`bool`, *optional*, defaults to `False`):
| Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding
| the existing cache.
| 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 `hf auth login`.
| 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 (`dict`, *optional*):
| Additional kwargs to pass to the model during initialization.
|
| ----------------------------------------------------------------------
| Static methods inherited from ModelHubMixin:
|
| __new__(cls: type[~T], *args, **kwargs) -> ~T
| Create a new instance of the class and handle config.
|
| 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.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from ModelHubMixin:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
huggingface-hub.QuestionAnsweringInput
Python Library Documentation: class QuestionAnsweringInput in module huggingface_hub.inference._generated.types.question_answering
class QuestionAnsweringInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| QuestionAnsweringInput(inputs: huggingface_hub.inference._generated.types.question_answering.QuestionAnsweringInputData, parameters: huggingface_hub.inference._generated.types.question_answering.QuestionAnsweringParameters | None = None) -> None
|
| Inputs for Question Answering inference
|
| Method resolution order:
| QuestionAnsweringInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: huggingface_hub.inference._generated.types.question_answering.QuestionAnsweringInputData, parameters: huggingface_hub.inference._generated.types.question_answering.QuestionAnsweringParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'huggingface_hub.inference._genera...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'hug...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.QuestionAnsweringInputData
Python Library Documentation: class QuestionAnsweringInputData in module huggingface_hub.inference._generated.types.question_answering
class QuestionAnsweringInputData(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| QuestionAnsweringInputData(context: str, question: str) -> None
|
| One (context, question) pair to answer
|
| Method resolution order:
| QuestionAnsweringInputData
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, context: str, question: str) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'context': <class 'str'>, 'question': <class 'str'>...
|
| __dataclass_fields__ = {'context': Field(name='context',type=<class 's...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('context', 'question')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.QuestionAnsweringOutputElement
Python Library Documentation: class QuestionAnsweringOutputElement in module huggingface_hub.inference._generated.types.question_answering
class QuestionAnsweringOutputElement(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| QuestionAnsweringOutputElement(answer: str, end: int, score: float, start: int) -> None
|
| Outputs of inference for the Question Answering task
|
| Method resolution order:
| QuestionAnsweringOutputElement
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, answer: str, end: int, score: float, start: int) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'answer': <class 'str'>, 'end': <class 'int'>, 'sco...
|
| __dataclass_fields__ = {'answer': Field(name='answer',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('answer', 'end', 'score', 'start')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.QuestionAnsweringParameters
Python Library Documentation: class QuestionAnsweringParameters in module huggingface_hub.inference._generated.types.question_answering
class QuestionAnsweringParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| QuestionAnsweringParameters(align_to_words: bool | None = None, doc_stride: int | None = None, handle_impossible_answer: bool | None = None, max_answer_len: int | None = None, max_question_len: int | None = None, max_seq_len: int | None = None, top_k: int | None = None) -> None
|
| Additional inference parameters for Question Answering
|
| Method resolution order:
| QuestionAnsweringParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, align_to_words: bool | None = None, doc_stride: int | None = None, handle_impossible_answer: bool | None = None, max_answer_len: int | None = None, max_question_len: int | None = None, max_seq_len: int | None = None, top_k: int | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'align_to_words': bool | None, 'doc_stride': int | ...
|
| __dataclass_fields__ = {'align_to_words': Field(name='align_to_words',...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('align_to_words', 'doc_stride', 'handle_impossible_a...
|
| align_to_words = None
|
| doc_stride = None
|
| handle_impossible_answer = None
|
| max_answer_len = None
|
| max_question_len = None
|
| max_seq_len = None
|
| top_k = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.REPO_TYPE_DATASET
Error rendering doc: No Python documentation found for 'dataset'. Use help() to get the interactive help utility. Use help(str) for help on the str class.
huggingface-hub.REPO_TYPE_MODEL
Error rendering doc: No Python documentation found for 'model'. Use help() to get the interactive help utility. Use help(str) for help on the str class.
huggingface-hub.REPO_TYPE_SPACE
Error rendering doc: No Python documentation found for 'space'. Use help() to get the interactive help utility. Use help(str) for help on the str class.
huggingface-hub.RepoCard
Python Library Documentation: class RepoCard in module huggingface_hub.repocard
class RepoCard(builtins.object)
| RepoCard(content: str, ignore_metadata_errors: bool = False)
|
| Methods defined here:
|
| __init__(self, content: str, ignore_metadata_errors: bool = False)
| Initialize a RepoCard from string content. The content should be a
| Markdown file with a YAML block at the beginning and a Markdown body.
|
| Args:
| content (`str`): The content of the Markdown file.
|
| Example:
| ```python
| >>> from huggingface_hub.repocard import RepoCard
| >>> text = '''
| ... ---
| ... language: en
| ... license: mit
| ... ---
| ...
| ... # My repo
| ... '''
| >>> card = RepoCard(text)
| >>> card.data.to_dict()
| {'language': 'en', 'license': 'mit'}
| >>> card.text
| '\n# My repo\n'
|
| ```
| > [!TIP]
| > Raises the following error:
| >
| > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| > when the content of the repo card metadata is not a dictionary.
|
| __str__(self)
| Return str(self).
|
| push_to_hub(self, repo_id: str, token: str | None = None, repo_type: str | None = None, commit_message: str | None = None, commit_description: str | None = None, revision: str | None = None, create_pr: bool | None = None, parent_commit: str | None = None)
| Push a RepoCard to a Hugging Face Hub repo.
|
| Args:
| repo_id (`str`):
| The repo ID of the Hugging Face Hub repo to push to. Example: "nateraw/food".
| token (`str`, *optional*):
| Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to
| the stored token.
| repo_type (`str`, *optional*, defaults to "model"):
| The type of Hugging Face repo to push to. Options are "model", "dataset", and "space". If this
| function is called by a child class, it will default to the child class's `repo_type`.
| commit_message (`str`, *optional*):
| The summary / title / first line of the generated commit.
| commit_description (`str`, *optional*)
| The description of the generated commit.
| revision (`str`, *optional*):
| The git revision to commit from. Defaults to the head of the `"main"` branch.
| create_pr (`bool`, *optional*):
| Whether or not to create a Pull Request with this commit. Defaults to `False`.
| parent_commit (`str`, *optional*):
| The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
| If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
| If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
| Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
| especially useful if the repo is updated / committed too concurrently.
| Returns:
| `str`: URL of the commit which updated the card metadata.
|
| save(self, filepath: pathlib.Path | str)
| Save a RepoCard to a file.
|
| Args:
| filepath (`Union[Path, str]`): Filepath to the markdown file to save.
|
| Example:
| ```python
| >>> from huggingface_hub.repocard import RepoCard
| >>> card = RepoCard("---\nlanguage: en\n---\n# This is a test repo card")
| >>> card.save("/tmp/test.md")
|
| ```
|
| validate(self, repo_type: str | None = None)
| Validates card against Hugging Face Hub's card validation logic.
| Using this function requires access to the internet, so it is only called
| internally by [`huggingface_hub.repocard.RepoCard.push_to_hub`].
|
| Args:
| repo_type (`str`, *optional*, defaults to "model"):
| The type of Hugging Face repo to push to. Options are "model", "dataset", and "space".
| If this function is called from a child class, the default will be the child class's `repo_type`.
|
| > [!TIP]
| > Raises the following errors:
| >
| > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| > if the card fails validation checks.
| > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
| > if the request to the Hub API fails for any other reason.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_template(card_data: huggingface_hub.repocard_data.CardData, template_path: str | None = None, template_str: str | None = None, **template_kwargs)
| Initialize a RepoCard from a template. By default, it uses the default template.
|
| Templates are Jinja2 templates that can be customized by passing keyword arguments.
|
| Args:
| card_data (`huggingface_hub.CardData`):
| A huggingface_hub.CardData instance containing the metadata you want to include in the YAML
| header of the repo card on the Hugging Face Hub.
| template_path (`str`, *optional*):
| A path to a markdown file with optional Jinja template variables that can be filled
| in with `template_kwargs`. Defaults to the default template.
| template_str (`str`, *optional*):
| A raw Jinja template string with optional variables. Used when neither `template_path`
| nor the default template is appropriate. Ignored if `template_path` is also provided.
|
| Returns:
| [`huggingface_hub.repocard.RepoCard`]: A RepoCard instance with the specified card data and content from the
| template.
|
| load(repo_id_or_path: str | pathlib.Path, repo_type: str | None = None, token: str | None = None, ignore_metadata_errors: bool = False)
| Initialize a RepoCard from a Hugging Face Hub repo's README.md or a local filepath.
|
| Args:
| repo_id_or_path (`Union[str, Path]`):
| The repo ID associated with a Hugging Face Hub repo or a local filepath.
| repo_type (`str`, *optional*):
| The type of Hugging Face repo to push to. Defaults to None, which will use "model". Other options
| are "dataset" and "space". Not used when loading from a local filepath. If this is called from a child
| class, the default value will be the child class's `repo_type`.
| 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.
|
| Returns:
| [`huggingface_hub.repocard.RepoCard`]: The RepoCard (or subclass) initialized from the repo's
| README.md file or filepath.
|
| Example:
| ```python
| >>> from huggingface_hub.repocard import RepoCard
| >>> card = RepoCard.load("nateraw/food")
| >>> assert card.data.tags == ["generated_from_trainer", "image-classification", "pytorch"]
|
| ```
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| content
| The content of the RepoCard, including the YAML block and the Markdown body.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| card_data_class = <class 'huggingface_hub.repocard_data.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). `CardData` behaves as a dictionary (can get, pop, set values) but do not
| inherit from `dict` to allow this export step.
|
|
| default_template_path = WindowsPath('C:/Users/Youse/AppData/Local/Prog...
|
| repo_type = 'model'
huggingface-hub.RepoFile
Python Library Documentation: class RepoFile in module huggingface_hub.hf_api
class RepoFile(builtins.object)
| RepoFile(**kwargs)
|
| Contains information about a file on the Hub.
|
| Attributes:
| path (str):
| file path relative to the repo root.
| size (`int`):
| The file's size, in bytes.
| blob_id (`str`):
| The file's git OID.
| lfs (`BlobLfsInfo`, *optional*):
| The file's LFS metadata.
| xet_hash (`str`, *optional*):
| The file's Xet hash.
| last_commit (`LastCommitInfo`, *optional*):
| The file's last commit metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`]
| are called with `expand=True`.
| security (`BlobSecurityInfo`, *optional*):
| The file's security scan metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`]
| are called with `expand=True`.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'blob_id': 'str', 'last_commit': 'LastCommitInfo | ...
|
| __dataclass_fields__ = {'blob_id': Field(name='blob_id',type='str',def...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('path', 'size', 'blob_id', 'lfs', 'xet_hash', 'last_...
|
| last_commit = None
|
| lfs = None
|
| security = None
|
| xet_hash = None
huggingface-hub.RepoFolder
Python Library Documentation: class RepoFolder in module huggingface_hub.hf_api
class RepoFolder(builtins.object)
| RepoFolder(**kwargs)
|
| Contains information about a folder on the Hub.
|
| Attributes:
| path (str):
| folder path relative to the repo root.
| tree_id (`str`):
| The folder's git OID.
| last_commit (`LastCommitInfo`, *optional*):
| The folder's last commit metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`]
| are called with `expand=True`.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'last_commit': 'LastCommitInfo | None', 'path': 'st...
|
| __dataclass_fields__ = {'last_commit': Field(name='last_commit',type='...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('path', 'tree_id', 'last_commit')
|
| last_commit = None
huggingface-hub.RepoStorageInfo
Python Library Documentation: class RepoStorageInfo in module huggingface_hub.hf_api
class RepoStorageInfo(builtins.object)
| RepoStorageInfo(**kwargs: 'Any') -> 'None'
|
| Contains storage information about a repository on the Hub.
|
| Returned by [`list_user_repos`].
|
| Attributes:
| id (`str`):
| ID of the repo (e.g. `username/repo-name`).
| type (`str`):
| Type of the repo (`model`, `dataset`, `space`, or `bucket`).
| updated_at (`datetime`):
| Last update time of the repo.
| visibility (`str`):
| Visibility of the repo (`public` or `private`).
| storage (`int`):
| Storage used by the repo in bytes.
| storage_percent (`float`):
| Percentage of the namespace's total storage used by this repo.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, **kwargs: 'Any') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'id': 'str', 'storage': 'int', 'storage_percent': '...
|
| __dataclass_fields__ = {'id': Field(name='id',type='str',default=<data...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('id', 'type', 'updated_at', 'visibility', 'storage',...
huggingface-hub.RepoUrl
Python Library Documentation: class RepoUrl in module huggingface_hub.hf_api
class RepoUrl(builtins.str)
| RepoUrl(url: 'Any', endpoint: 'str | None' = None)
|
| Subclass of `str` describing a repo URL on the Hub.
|
| `RepoUrl` is returned by `HfApi.create_repo`. It inherits from `str` for backward
| compatibility. At initialization, the URL is parsed to populate properties:
| - endpoint (`str`)
| - namespace (`str`)
| - repo_name (`str`)
| - repo_id (`str`)
| - repo_type (`Literal["model", "dataset", "space"]`)
| - url (`str`)
|
| Args:
| url (`Any`):
| String value of the repo url.
| endpoint (`str`, *optional*):
| Endpoint of the Hub. Defaults to <https://huggingface.co>.
|
| Example:
| ```py
| >>> RepoUrl('https://huggingface.co/openai-community/gpt2')
| RepoUrl('https://huggingface.co/openai-community/gpt2', endpoint='https://huggingface.co', repo_type='model', repo_id='openai-community/gpt2')
|
| >>> RepoUrl('https://hub-ci.huggingface.co/datasets/dummy_user/dummy_dataset', endpoint='https://hub-ci.huggingface.co')
| RepoUrl('https://hub-ci.huggingface.co/datasets/dummy_user/dummy_dataset', endpoint='https://hub-ci.huggingface.co', repo_type='dataset', repo_id='dummy_user/dummy_dataset')
|
| >>> RepoUrl('hf://datasets/my-user/my-dataset')
| RepoUrl('hf://datasets/my-user/my-dataset', endpoint='https://huggingface.co', repo_type='dataset', repo_id='user/dataset')
|
| >>> HfApi.create_repo("dummy_model")
| RepoUrl('https://huggingface.co/Wauplin/dummy_model', endpoint='https://huggingface.co', repo_type='model', repo_id='Wauplin/dummy_model')
| ```
|
| Raises:
| [`~errors.HfUriError`]:
| If the URL cannot be parsed (e.g. canonical single-segment repo, or unknown `repo_type`).
|
| Method resolution order:
| RepoUrl
| builtins.str
| builtins.object
|
| Methods defined here:
|
| __init__(self, url: 'Any', endpoint: 'str | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(cls, url: 'Any', endpoint: 'str | None' = None)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.str:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __eq__(self, value, /)
| Return self==value.
|
| __format__(self, format_spec, /)
| Return a formatted version of the string as described by format_spec.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(...)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __sizeof__(self, /)
| Return the size of the string in memory, in bytes.
|
| __str__(self, /)
| Return str(self).
|
| capitalize(self, /)
| Return a capitalized version of the string.
|
| More specifically, make the first character have upper case and the rest lower
| case.
|
| casefold(self, /)
| Return a version of the string suitable for caseless comparisons.
|
| center(self, width, fillchar=' ', /)
| Return a centered string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| count(...)
| S.count(sub[, start[, end]]) -> int
|
| Return the number of non-overlapping occurrences of substring sub in
| string S[start:end]. Optional arguments start and end are
| interpreted as in slice notation.
|
| encode(self, /, encoding='utf-8', errors='strict')
| Encode the string using the codec registered for encoding.
|
| encoding
| The encoding in which to encode the string.
| errors
| The error handling scheme to use for encoding errors.
| The default is 'strict' meaning that encoding errors raise a
| UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
| 'xmlcharrefreplace' as well as any other name registered with
| codecs.register_error that can handle UnicodeEncodeErrors.
|
| endswith(...)
| S.endswith(suffix[, start[, end]]) -> bool
|
| Return True if S ends with the specified suffix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| suffix can also be a tuple of strings to try.
|
| expandtabs(self, /, tabsize=8)
| Return a copy where all tab characters are expanded using spaces.
|
| If tabsize is not given, a tab size of 8 characters is assumed.
|
| find(...)
| S.find(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| format(...)
| S.format(*args, **kwargs) -> str
|
| Return a formatted version of S, using substitutions from args and kwargs.
| The substitutions are identified by braces ('{' and '}').
|
| format_map(...)
| S.format_map(mapping) -> str
|
| Return a formatted version of S, using substitutions from mapping.
| The substitutions are identified by braces ('{' and '}').
|
| index(...)
| S.index(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| isalnum(self, /)
| Return True if the string is an alpha-numeric string, False otherwise.
|
| A string is alpha-numeric if all characters in the string are alpha-numeric and
| there is at least one character in the string.
|
| isalpha(self, /)
| Return True if the string is an alphabetic string, False otherwise.
|
| A string is alphabetic if all characters in the string are alphabetic and there
| is at least one character in the string.
|
| isascii(self, /)
| Return True if all characters in the string are ASCII, False otherwise.
|
| ASCII characters have code points in the range U+0000-U+007F.
| Empty string is ASCII too.
|
| isdecimal(self, /)
| Return True if the string is a decimal string, False otherwise.
|
| A string is a decimal string if all characters in the string are decimal and
| there is at least one character in the string.
|
| isdigit(self, /)
| Return True if the string is a digit string, False otherwise.
|
| A string is a digit string if all characters in the string are digits and there
| is at least one character in the string.
|
| isidentifier(self, /)
| Return True if the string is a valid Python identifier, False otherwise.
|
| Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
| such as "def" or "class".
|
| islower(self, /)
| Return True if the string is a lowercase string, False otherwise.
|
| A string is lowercase if all cased characters in the string are lowercase and
| there is at least one cased character in the string.
|
| isnumeric(self, /)
| Return True if the string is a numeric string, False otherwise.
|
| A string is numeric if all characters in the string are numeric and there is at
| least one character in the string.
|
| isprintable(self, /)
| Return True if the string is printable, False otherwise.
|
| A string is printable if all of its characters are considered printable in
| repr() or if it is empty.
|
| isspace(self, /)
| Return True if the string is a whitespace string, False otherwise.
|
| A string is whitespace if all characters in the string are whitespace and there
| is at least one character in the string.
|
| istitle(self, /)
| Return True if the string is a title-cased string, False otherwise.
|
| In a title-cased string, upper- and title-case characters may only
| follow uncased characters and lowercase characters only cased ones.
|
| isupper(self, /)
| Return True if the string is an uppercase string, False otherwise.
|
| A string is uppercase if all cased characters in the string are uppercase and
| there is at least one cased character in the string.
|
| join(self, iterable, /)
| Concatenate any number of strings.
|
| The string whose method is called is inserted in between each given string.
| The result is returned as a new string.
|
| Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
|
| ljust(self, width, fillchar=' ', /)
| Return a left-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| lower(self, /)
| Return a copy of the string converted to lowercase.
|
| lstrip(self, chars=None, /)
| Return a copy of the string with leading whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| partition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string. If the separator is found,
| returns a 3-tuple containing the part before the separator, the separator
| itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing the original string
| and two empty strings.
|
| removeprefix(self, prefix, /)
| Return a str with the given prefix string removed if present.
|
| If the string starts with the prefix string, return string[len(prefix):].
| Otherwise, return a copy of the original string.
|
| removesuffix(self, suffix, /)
| Return a str with the given suffix string removed if present.
|
| If the string ends with the suffix string and that suffix is not empty,
| return string[:-len(suffix)]. Otherwise, return a copy of the original
| string.
|
| replace(self, old, new, count=-1, /)
| Return a copy with all occurrences of substring old replaced by new.
|
| count
| Maximum number of occurrences to replace.
| -1 (the default value) means replace all occurrences.
|
| If the optional argument count is given, only the first count occurrences are
| replaced.
|
| rfind(...)
| S.rfind(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| rindex(...)
| S.rindex(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| rjust(self, width, fillchar=' ', /)
| Return a right-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| rpartition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string, starting at the end. If
| the separator is found, returns a 3-tuple containing the part before the
| separator, the separator itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing two empty strings
| and the original string.
|
| rsplit(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the end of the string and works to the front.
|
| rstrip(self, chars=None, /)
| Return a copy of the string with trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| split(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the front of the string and works to the end.
|
| Note, str.split() is mainly useful for data that has been intentionally
| delimited. With natural text that includes punctuation, consider using
| the regular expression module.
|
| splitlines(self, /, keepends=False)
| Return a list of the lines in the string, breaking at line boundaries.
|
| Line breaks are not included in the resulting list unless keepends is given and
| true.
|
| startswith(...)
| S.startswith(prefix[, start[, end]]) -> bool
|
| Return True if S starts with the specified prefix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| prefix can also be a tuple of strings to try.
|
| strip(self, chars=None, /)
| Return a copy of the string with leading and trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| swapcase(self, /)
| Convert uppercase characters to lowercase and lowercase characters to uppercase.
|
| title(self, /)
| Return a version of the string where each word is titlecased.
|
| More specifically, words start with uppercased characters and all remaining
| cased characters have lower case.
|
| translate(self, table, /)
| Replace each character in the string using the given translation table.
|
| table
| Translation table, which must be a mapping of Unicode ordinals to
| Unicode ordinals, strings, or None.
|
| The table must implement lookup/indexing via __getitem__, for instance a
| dictionary or list. If this operation raises LookupError, the character is
| left untouched. Characters mapped to None are deleted.
|
| upper(self, /)
| Return a copy of the string converted to uppercase.
|
| zfill(self, width, /)
| Pad a numeric string with zeros on the left, to fill a field of the given width.
|
| The string is never truncated.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.str:
|
| maketrans(...)
| Return a translation table usable for str.translate().
|
| If there is only one argument, it must be a dictionary mapping Unicode
| ordinals (integers) or characters to Unicode ordinals, strings or None.
| Character keys will be then converted to ordinals.
| If there are two arguments, they must be strings of equal length, and
| in the resulting dictionary, each character in x will be mapped to the
| character at the same position in y. If there is a third argument, it
| must be a string, whose characters will be mapped to None in the result.
huggingface-hub.ResolvedRevision
Python Library Documentation: class ResolvedRevision in module huggingface_hub._revision
class ResolvedRevision(builtins.str)
| ResolvedRevision(resolved: str, initial: str | None = None) -> 'ResolvedRevision'
|
| A git revision that has already been resolved to a commit hash.
|
| `ResolvedRevision` is a `str` subclass, so it can be passed to any `huggingface_hub` method taking a `revision`
| argument. Its string value is the revision initially requested by the user (e.g. `"main"`, `"refs/pr/4"`),
| which keeps URLs and error messages readable, while `.resolved` holds the commit hash it points to.
|
| Instances are built by [`HfApi.resolve_revision`], which also caches the `revision` -> `commit hash` mapping
| in the local cache (`refs/` folder).
|
| Attributes:
| initial (`str` or `None`):
| The revision initially requested by the user. If `None`, the string value defaults to `"main"`.
| resolved (`str`):
| The commit hash that `initial` resolves to.
|
| Example:
| ```python
| >>> from huggingface_hub import resolve_revision
| >>> revision = resolve_revision("openai-community/gpt2")
| >>> revision
| ResolvedRevision(initial=None, resolved='607a30d783dfa663caf39e06633721c8d4cfcd7e')
| >>> revision == "main" # it's a string
| True
| >>> revision.resolved
| '607a30d783dfa663caf39e06633721c8d4cfcd7e'
| ```
|
| Method resolution order:
| ResolvedRevision
| builtins.str
| builtins.object
|
| Methods defined here:
|
| __repr__(self) -> str
| Return repr(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(cls, resolved: str, initial: str | None = None) -> 'ResolvedRevision'
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'initial': str | None, 'resolved': <class 'str'>}
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.str:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __eq__(self, value, /)
| Return self==value.
|
| __format__(self, format_spec, /)
| Return a formatted version of the string as described by format_spec.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(...)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __sizeof__(self, /)
| Return the size of the string in memory, in bytes.
|
| __str__(self, /)
| Return str(self).
|
| capitalize(self, /)
| Return a capitalized version of the string.
|
| More specifically, make the first character have upper case and the rest lower
| case.
|
| casefold(self, /)
| Return a version of the string suitable for caseless comparisons.
|
| center(self, width, fillchar=' ', /)
| Return a centered string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| count(...)
| S.count(sub[, start[, end]]) -> int
|
| Return the number of non-overlapping occurrences of substring sub in
| string S[start:end]. Optional arguments start and end are
| interpreted as in slice notation.
|
| encode(self, /, encoding='utf-8', errors='strict')
| Encode the string using the codec registered for encoding.
|
| encoding
| The encoding in which to encode the string.
| errors
| The error handling scheme to use for encoding errors.
| The default is 'strict' meaning that encoding errors raise a
| UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
| 'xmlcharrefreplace' as well as any other name registered with
| codecs.register_error that can handle UnicodeEncodeErrors.
|
| endswith(...)
| S.endswith(suffix[, start[, end]]) -> bool
|
| Return True if S ends with the specified suffix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| suffix can also be a tuple of strings to try.
|
| expandtabs(self, /, tabsize=8)
| Return a copy where all tab characters are expanded using spaces.
|
| If tabsize is not given, a tab size of 8 characters is assumed.
|
| find(...)
| S.find(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| format(...)
| S.format(*args, **kwargs) -> str
|
| Return a formatted version of S, using substitutions from args and kwargs.
| The substitutions are identified by braces ('{' and '}').
|
| format_map(...)
| S.format_map(mapping) -> str
|
| Return a formatted version of S, using substitutions from mapping.
| The substitutions are identified by braces ('{' and '}').
|
| index(...)
| S.index(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| isalnum(self, /)
| Return True if the string is an alpha-numeric string, False otherwise.
|
| A string is alpha-numeric if all characters in the string are alpha-numeric and
| there is at least one character in the string.
|
| isalpha(self, /)
| Return True if the string is an alphabetic string, False otherwise.
|
| A string is alphabetic if all characters in the string are alphabetic and there
| is at least one character in the string.
|
| isascii(self, /)
| Return True if all characters in the string are ASCII, False otherwise.
|
| ASCII characters have code points in the range U+0000-U+007F.
| Empty string is ASCII too.
|
| isdecimal(self, /)
| Return True if the string is a decimal string, False otherwise.
|
| A string is a decimal string if all characters in the string are decimal and
| there is at least one character in the string.
|
| isdigit(self, /)
| Return True if the string is a digit string, False otherwise.
|
| A string is a digit string if all characters in the string are digits and there
| is at least one character in the string.
|
| isidentifier(self, /)
| Return True if the string is a valid Python identifier, False otherwise.
|
| Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
| such as "def" or "class".
|
| islower(self, /)
| Return True if the string is a lowercase string, False otherwise.
|
| A string is lowercase if all cased characters in the string are lowercase and
| there is at least one cased character in the string.
|
| isnumeric(self, /)
| Return True if the string is a numeric string, False otherwise.
|
| A string is numeric if all characters in the string are numeric and there is at
| least one character in the string.
|
| isprintable(self, /)
| Return True if the string is printable, False otherwise.
|
| A string is printable if all of its characters are considered printable in
| repr() or if it is empty.
|
| isspace(self, /)
| Return True if the string is a whitespace string, False otherwise.
|
| A string is whitespace if all characters in the string are whitespace and there
| is at least one character in the string.
|
| istitle(self, /)
| Return True if the string is a title-cased string, False otherwise.
|
| In a title-cased string, upper- and title-case characters may only
| follow uncased characters and lowercase characters only cased ones.
|
| isupper(self, /)
| Return True if the string is an uppercase string, False otherwise.
|
| A string is uppercase if all cased characters in the string are uppercase and
| there is at least one cased character in the string.
|
| join(self, iterable, /)
| Concatenate any number of strings.
|
| The string whose method is called is inserted in between each given string.
| The result is returned as a new string.
|
| Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
|
| ljust(self, width, fillchar=' ', /)
| Return a left-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| lower(self, /)
| Return a copy of the string converted to lowercase.
|
| lstrip(self, chars=None, /)
| Return a copy of the string with leading whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| partition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string. If the separator is found,
| returns a 3-tuple containing the part before the separator, the separator
| itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing the original string
| and two empty strings.
|
| removeprefix(self, prefix, /)
| Return a str with the given prefix string removed if present.
|
| If the string starts with the prefix string, return string[len(prefix):].
| Otherwise, return a copy of the original string.
|
| removesuffix(self, suffix, /)
| Return a str with the given suffix string removed if present.
|
| If the string ends with the suffix string and that suffix is not empty,
| return string[:-len(suffix)]. Otherwise, return a copy of the original
| string.
|
| replace(self, old, new, count=-1, /)
| Return a copy with all occurrences of substring old replaced by new.
|
| count
| Maximum number of occurrences to replace.
| -1 (the default value) means replace all occurrences.
|
| If the optional argument count is given, only the first count occurrences are
| replaced.
|
| rfind(...)
| S.rfind(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| rindex(...)
| S.rindex(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| rjust(self, width, fillchar=' ', /)
| Return a right-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| rpartition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string, starting at the end. If
| the separator is found, returns a 3-tuple containing the part before the
| separator, the separator itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing two empty strings
| and the original string.
|
| rsplit(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the end of the string and works to the front.
|
| rstrip(self, chars=None, /)
| Return a copy of the string with trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| split(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the front of the string and works to the end.
|
| Note, str.split() is mainly useful for data that has been intentionally
| delimited. With natural text that includes punctuation, consider using
| the regular expression module.
|
| splitlines(self, /, keepends=False)
| Return a list of the lines in the string, breaking at line boundaries.
|
| Line breaks are not included in the resulting list unless keepends is given and
| true.
|
| startswith(...)
| S.startswith(prefix[, start[, end]]) -> bool
|
| Return True if S starts with the specified prefix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| prefix can also be a tuple of strings to try.
|
| strip(self, chars=None, /)
| Return a copy of the string with leading and trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| swapcase(self, /)
| Convert uppercase characters to lowercase and lowercase characters to uppercase.
|
| title(self, /)
| Return a version of the string where each word is titlecased.
|
| More specifically, words start with uppercased characters and all remaining
| cased characters have lower case.
|
| translate(self, table, /)
| Replace each character in the string using the given translation table.
|
| table
| Translation table, which must be a mapping of Unicode ordinals to
| Unicode ordinals, strings, or None.
|
| The table must implement lookup/indexing via __getitem__, for instance a
| dictionary or list. If this operation raises LookupError, the character is
| left untouched. Characters mapped to None are deleted.
|
| upper(self, /)
| Return a copy of the string converted to uppercase.
|
| zfill(self, width, /)
| Pad a numeric string with zeros on the left, to fill a field of the given width.
|
| The string is never truncated.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.str:
|
| maketrans(...)
| Return a translation table usable for str.translate().
|
| If there is only one argument, it must be a dictionary mapping Unicode
| ordinals (integers) or characters to Unicode ordinals, strings or None.
| Character keys will be then converted to ordinals.
| If there are two arguments, they must be strings of equal length, and
| in the resulting dictionary, each character in x will be mapped to the
| character at the same position in y. If there is a third argument, it
| must be a string, whose characters will be mapped to None in the result.
huggingface-hub.Sandbox
Python Library Documentation: class Sandbox in module huggingface_hub._sandbox
class Sandbox(builtins.object)
| Sandbox(*, id: str, server: huggingface_hub._sandbox._SandboxServer, local_id: str | None, owns_sandbox: bool, owns_server: bool) -> None
|
| An isolated cloud machine running on Hugging Face Jobs.
|
| Create a dedicated one with [`Sandbox.create`] (one job per sandbox), or get many cheap shared ones from a [`SandboxPool`].
| Reattach to a running sandbox from anywhere with [`Sandbox.connect`]. Use as a context manager to terminate it on exit:
|
| ```python
| >>> from huggingface_hub import Sandbox
| >>> with Sandbox.create(image="python:3.12") as sbx:
| ... print(sbx.run("python --version").stdout)
| ```
|
| Methods defined here:
|
| __enter__(self) -> 'Sandbox'
|
| __exit__(self, *exc_info) -> None
|
| __init__(self, *, id: str, server: huggingface_hub._sandbox._SandboxServer, local_id: str | None, owns_sandbox: bool, owns_server: bool) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> str
| Return repr(self).
|
| close(self) -> None
| Release the local HTTP client without terminating the sandbox. Idempotent.
|
| No-op for pool sandboxes (the client belongs to the pool's host).
|
| kill(sandbox_id: str, *, namespace: str | None = None, token: str | None = None) -> None from huggingface_hub._sandbox._KillMethod.__get__.<locals>
|
| processes(self) -> List[huggingface_hub._sandbox.SandboxProcess]
| List the background processes of this sandbox.
|
| Returns the processes started with [`Sandbox.run`]`(..., background=True)`; stop one
| with [`SandboxProcess.kill`]. Completed processes stay listed (with `running=False` and
| their `exit_code`) until the sandbox is deleted.
|
| proxy_url_for(self, port: int | str, path: str = '/', *, scheme: str = 'https://') -> str
| Public URL that proxies through to a server running *inside* this sandbox.
|
| Requests to the returned URL are forwarded by the in-job sandbox server to a
| server you started in the sandbox on `port`, including WebSocket (`ws(s)://`)
| upgrades and streamed responses. Pair it with [`proxy_headers`] for auth.
|
| How the sandbox must listen on `port`:
|
| - **Pool / shared sandbox**: it cannot bind a TCP port (Landlock), so bind a
| **unix socket** at `$SBX_PROXY_DIR/<port>.sock` (the `SBX_PROXY_DIR` env var
| is set in every sandbox). E.g. `uvicorn app:app --uds $SBX_PROXY_DIR/8000.sock`.
| - **Dedicated sandbox**: bind a normal TCP port on `127.0.0.1:<port>`. (You can
| also expose the port directly via the job proxy without going through here.)
|
| Args:
| port (`int` or `str`):
| The port (pool: the `<port>` of the unix socket) the inner server listens on.
| path (`str`, *optional*, defaults to `"/"`):
| Path on the inner server to point at, e.g. `"/ws"`.
| scheme (`str`, *optional*, defaults to `"https://"`):
| URL scheme to build the link with. Defaults to `"https://"`; pass
| `"wss://"` for a WebSocket client (the proxy is protocol-agnostic, so only
| the client-side scheme changes).
|
| Returns:
| `str`: a URL like `https://<job_id>--49983.hf.jobs/v1/.../proxy/8000/ws` (or
| `wss://...` with `scheme="wss://"`).
|
| Example:
| ```python
| >>> url = sandbox.proxy_url_for(8000, "/ws", scheme="wss://")
| >>> import websockets
| >>> async with websockets.connect(url, additional_headers=sandbox.proxy_headers) as ws:
| ... await ws.send("hello")
| ```
|
| run(self, cmd: Union[str, List[str]], *, shell: bool | None = None, env: dict[str, typing.Any] | None = None, cwd: str | None = None, timeout: float | None = None, stdin: str | None = None, on_stdout: Optional[Callable[[str], NoneType]] = None, on_stderr: Optional[Callable[[str], NoneType]] = None, check: bool = True, background: bool = False) -> huggingface_hub._sandbox.SandboxCommandResult | huggingface_hub._sandbox.SandboxProcess
| Run a command in the sandbox and wait for it, streaming output live.
|
| With `background=True` the command is started detached and `run` returns a
| [`SandboxProcess`] immediately, without waiting for it to finish — handy for
| servers and other long-running processes. List them later with [`Sandbox.processes`]
| and stop one with [`SandboxProcess.kill`]. The streaming/wait-only options
| (`timeout`, `stdin`, `on_stdout`, `on_stderr`, `check`) don't apply in that mode.
|
| Args:
| cmd (`str` or `List[str]`):
| A shell command string (run with `/bin/sh -c`) or an argv list (exec'd directly).
| shell (`bool`, *optional*):
| Force the execution mode instead of inferring it from the type of `cmd`.
| `True` runs through `/bin/sh -c` and requires `cmd` to be a string; `False`
| exec's `cmd` directly and requires it to be an argv list. `None` (default)
| infers from the type. Set it explicitly to avoid the type-driven footgun (e.g.
| `["echo hi"]` being exec'd as a single program named `"echo hi"`).
| env (`dict[str, Any]`, *optional*):
| Extra environment variables for this command.
| cwd (`str`, *optional*):
| Working directory.
| timeout (`float`, *optional*):
| Kill the command (whole process group) after this many seconds.
| stdin (`str`, *optional*):
| Data to write to the command's stdin.
| on_stdout (`Callable[[str], None]`, *optional*):
| Callback invoked with stdout chunks as they arrive.
| on_stderr (`Callable[[str], None]`, *optional*):
| Callback invoked with stderr chunks as they arrive.
| check (`bool`, *optional*, defaults to `True`):
| If True, raise [`SandboxCommandError`] on non-zero exit.
| background (`bool`, *optional*, defaults to `False`):
| If True, start the command detached and return a [`SandboxProcess`] right
| away instead of waiting for it and returning a [`SandboxCommandResult`].
|
| Returns: a [`SandboxCommandResult`] (with `exit_code`, `stdout`, `stderr`,
| `duration_ms`), or a [`SandboxProcess`] when `background=True`.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| connect(sandbox_id: str, *, namespace: str | None = None, token: str | None = None) -> 'Sandbox'
| Reattach to a running sandbox from anywhere, using only its id.
|
| create(image: str = 'python:3.12', *, flavor: str = 'cpu-basic', idle_timeout: int | float | str | None = 600, env: dict[str, typing.Any] | None = None, secrets: dict[str, typing.Any] | None = None, volumes: Optional[List[huggingface_hub._space_api.Volume]] = None, namespace: str | None = None, forward_hf_token: bool = False, start_timeout: float = 120.0, token: str | None = None) -> 'Sandbox'
| Create a dedicated sandbox (one HF Job) and block until it is ready (~7s on cpu-basic).
|
| Each sandbox is a full isolated VM, so this is the right choice for GPU
| workloads or untrusted code. To fan out many cheap CPU sandboxes instead, use
| [`SandboxPool`].
|
| The job runs with a fixed 24h maximum lifetime; `idle_timeout` is the real
| keeper — an idle sandbox shuts itself down well before that.
|
| Args:
| image (`str`, *optional*, defaults to `"python:3.12"`):
| Any Docker image with `/bin/sh` (Docker Hub or `hf.co/spaces/...`).
| flavor (`str`, *optional*, defaults to `"cpu-basic"`):
| Hardware flavor, e.g. `"cpu-basic"`, `"a10g-small"`. See `hf jobs hardware`.
| idle_timeout (`int` or `float` or `str`, *optional*, defaults to `600`):
| Auto-shutdown after this much inactivity (no API calls, no running
| processes). Defaults to 10 minutes; pass `None` to disable.
| env (`dict[str, Any]`, *optional*):
| Environment variables available in the sandbox.
| secrets (`dict[str, Any]`, *optional*):
| Secret environment variables (encrypted server-side).
| volumes (`List[Volume]`, *optional*):
| HF repos/buckets to mount, see [`Volume`].
| namespace (`str`, *optional*):
| User or org namespace to run under (defaults to current user).
| forward_hf_token (`bool`, *optional*, defaults to `False`):
| If True, your HF token is injected as `HF_TOKEN` (opt-in).
| start_timeout (`float`, *optional*, defaults to `120.0`):
| Max seconds to wait for the sandbox to become ready.
| token (`str`, *optional*):
| HF token override.
|
| The image only needs `/bin/sh`. The sandbox server is downloaded at startup with
| `wget`/`curl` if available, otherwise read off an always-mounted server bucket (which
| adds ~2-3s to cold start, so shipping `wget`/`curl` keeps it fast).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| host_id
| For a shared/pool sandbox, the job id of the host running it (else None).
|
| image
|
| proxy_headers
| Auth headers to send with [`proxy_url_for`] requests (HF token + sandbox token).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
huggingface-hub.SandboxCommandResult
Python Library Documentation: class SandboxCommandResult in module huggingface_hub._sandbox
class SandboxCommandResult(builtins.object)
| SandboxCommandResult(exit_code: int | None, stdout: str, stderr: str, signal: int | None = None, timed_out: bool = False, duration_ms: int = 0) -> None
|
| Result of a command executed in a sandbox with [`Sandbox.run`].
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, exit_code: int | None, stdout: str, stderr: str, signal: int | None = None, timed_out: bool = False, duration_ms: int = 0) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> str
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| ok
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'duration_ms': <class 'int'>, 'exit_code': int | No...
|
| __dataclass_fields__ = {'duration_ms': Field(name='duration_ms',type=<...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('exit_code', 'stdout', 'stderr', 'signal', 'timed_ou...
|
| duration_ms = 0
|
| signal = None
|
| timed_out = False
huggingface-hub.SandboxPool
Python Library Documentation: class SandboxPool in module huggingface_hub._sandbox
class SandboxPool(builtins.object)
| SandboxPool(image: str = 'python:3.12', *, flavor: str = 'cpu-basic', sandboxes_per_host: int = 50, warm_up: int = 1, max_hosts: int | None = None, name: str | None = None, idle_timeout: int | float | str | None = 600, namespace: str | None = None, start_timeout: float = 120.0, token: str | None = None, _connect_mode: bool = False) -> None
|
| A fleet of shared "host" jobs, each packing many landlock-isolated sandboxes.
|
| One host is one billed HF Job (a VM); it runs the sandbox server and multiplexes
| up to `sandboxes_per_host` lightweight sandboxes, isolated from each other by
| uid + the Landlock LSM. This makes large fan-outs cheap (the VM cost is shared
| across all its sandboxes) and fast (creating a sandbox is ~one proxy round-trip
| once a host is warm). Best for many parallel CPU sandboxes such as RL rollouts;
| for GPU or strong VM-level isolation between mutually-distrusting workloads, use
| [`Sandbox.create`] instead.
|
| The constructor pre-provisions `warm_up` hosts (default 1) and blocks until they are
| ready; further hosts are then provisioned on demand as sandboxes are requested, and all
| are torn down on `close()` (or when idle, via `idle_timeout`). The user never manages jobs:
|
| ```python
| >>> from huggingface_hub import SandboxPool
| >>> with SandboxPool(image="python:3.12", flavor="cpu-basic", warm_up=2) as pool:
| ... boxes = [pool.create() for _ in range(100)] # packed across the warm hosts
| ... print(boxes[0].run("echo hi").stdout)
| hi
| ```
|
| `create()` makes **one** sandbox at a time: it reuses a host that still has free
| capacity before booting a new one, so you grow on demand as work arrives. To avoid
| a cold start on the first few calls, pre-provision hosts with `warm_up` (or
| [`warm`]). Warm hosts are discovered via job labels, so reuse works **across
| processes** too (a fresh pool with the same `image`/`flavor`/`name` attaches to
| hosts an earlier run left behind):
|
| ```python
| >>> pool = SandboxPool(image="python:3.12")
| >>> sbx = pool.create() # finds a warm host (here or in another process), else boots one
| ```
|
| Methods defined here:
|
| __enter__(self) -> 'SandboxPool'
|
| __exit__(self, *exc_info) -> None
|
| __init__(self, image: str = 'python:3.12', *, flavor: str = 'cpu-basic', sandboxes_per_host: int = 50, warm_up: int = 1, max_hosts: int | None = None, name: str | None = None, idle_timeout: int | float | str | None = 600, namespace: str | None = None, start_timeout: float = 120.0, token: str | None = None, _connect_mode: bool = False) -> None
| Configure a pool and pre-provision `warm_up` hosts (blocks until they are ready).
|
| Env/secrets are *not* set here: they belong to each sandbox and are passed to
| `create(env=...)`, so sandboxes in the same pool can have different environments.
|
| Args:
| image (`str`, *optional*, defaults to `"python:3.12"`):
| Docker image for the hosts (needs `/bin/sh`). All sandboxes in the
| pool share this image.
| flavor (`str`, *optional*, defaults to `"cpu-basic"`):
| Hardware flavor for the host jobs (e.g. `"cpu-basic"`).
| sandboxes_per_host (`int`, *optional*, defaults to `50`):
| How many sandboxes to pack per host (per VM density).
| warm_up (`int`, *optional*, defaults to `1`):
| How many hosts to pre-provision in the constructor (which blocks
| until they are ready), so an initial burst of `create()` calls doesn't pay
| a host cold start each. Existing warm hosts (from the cache / other processes)
| count towards it, so only the shortfall is booted; capped by `max_hosts`.
| Defaults to 1 (a single host).
| max_hosts (`int`, *optional*):
| Optional cap on the number of host jobs (a cost ceiling). When
| reached and all hosts are full, `create()` raises.
| name (`str`, *optional*):
| Pool name, used as the `hf-sandbox-pool` job label so the pool is
| discoverable (e.g. `hf sandbox pool ls`, `connect()`). `create()` reuses
| running hosts carrying this label (including from other processes) before
| booting new ones, so distinct names keep separate pools from sharing hosts.
| A random name is generated when omitted.
| idle_timeout (`int` or `float` or `str`, *optional*, defaults to `600`):
| Host idle timeout — a host shuts down once it has had no
| sandboxes for this long (a billing backstop). Each sandbox also has its
| own idle timeout, set at `create()`. Pass `None` to disable.
| namespace (`str`, *optional*):
| User or org namespace to run hosts under.
| start_timeout (`float`, *optional*, defaults to `120.0`):
| Max seconds to wait for a host to become ready.
| token (`str`, *optional*):
| HF token override.
|
| close(self) -> None
| Release the pool. Idempotent.
|
| For a pool we created, this terminates all host jobs (and therefore all their
| sandboxes). For a `connect()`'d handle it only releases the local HTTP clients: the
| shared hosts may be serving other clients, so — like [`Sandbox.connect`] — leaving a
| `with` block must not tear them down. Terminate a connected pool's hosts explicitly
| with `hf sandbox pool delete <id>`.
|
| create(self, *, env: dict[str, typing.Any] | None = None, idle_timeout: int | float | str | None = 600, forward_hf_token: bool = False) -> 'Sandbox'
| Create one sandbox, provisioning a host if needed.
|
| Reuses a host with free capacity (this pool's, or a warm host found via job labels
| / the local cache) before booting a new one, so a `create()` against a warm host
| costs ~one round-trip. Call it repeatedly to fan out; use `warm_up` (or [`warm`])
| to pre-provision hosts and avoid a cold start on the first calls. If a host fills
| up under us (another process packed it) or a cached host is gone, the sandbox is
| re-placed on another host (or a fresh one).
|
| Args:
| env (`dict[str, Any]`, *optional*):
| Environment variables for this sandbox (each sandbox gets its own).
| idle_timeout (`int` or `float` or `str`, *optional*, defaults to `600`):
| Per-sandbox idle timeout — a sandbox is evicted from its host
| after this much inactivity (no API calls, no running process). Distinct
| from the host idle timeout. Pass `None` to disable.
| forward_hf_token (`bool`, *optional*, defaults to `False`):
| If True, inject your HF token as `HF_TOKEN` in the sandbox
| (opt-in). Unlike a dedicated sandbox's `secrets`, a pooled sandbox's env is
| delivered to the host server at creation (never stored in the host job), so
| it doesn't appear in any job's metadata.
|
| warm(self, num_hosts: int = 1) -> List[str]
| Ensure `num_hosts` empty host(s) are running and leave them running. Returns the
| pool's host job ids.
|
| Used to "create" a pool up front: the hosts carry the pool label and config (in
| their env vars), so a later `SandboxPool.connect(pool_id)` (even from another
| machine) finds them and spawns sandboxes without a cold start. The hosts keep
| billing until killed or idle.
|
| Adopts hosts already running for this pool (found via job labels) before booting,
| so a `warm()` after `connect()` — or a repeated `warm()` — tops up to `num_hosts`
| instead of duplicating live hosts and blowing past `max_hosts`.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| connect(pool_id: str, *, namespace: str | None = None, token: str | None = None) -> 'SandboxPool'
| Reattach to a running pool by id, from any machine — no local state needed.
|
| Finds a running host labelled with `pool_id` and rebuilds the pool's config
| (image/flavor/density/host-idle) from that host job's spec and env vars, returning
| a [`SandboxPool`] ready to `create()` more sandboxes — packing onto the running
| hosts, or booting a duplicate (same config) when they are full.
|
| Raises [`SandboxError`] if no running host is found (a pool stops existing once
| all of its hosts are gone — idle-timed-out or killed).
|
| Args:
| pool_id (`str`):
| The id returned when the pool was first created.
| namespace (`str`, *optional*):
| Namespace to search for the pool's hosts (defaults to yours).
| token (`str`, *optional*):
| HF token override.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| host_ids
| Job ids of the provisioned hosts.
|
| num_hosts
| Number of host jobs currently provisioned.
|
| num_sandboxes
| Number of sandboxes currently handed out (across all hosts).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
huggingface-hub.SandboxProcess
Python Library Documentation: class SandboxProcess in module huggingface_hub._sandbox
class SandboxProcess(builtins.object)
| SandboxProcess(pid: int, cmd: Union[str, List[str]], _sandbox: 'Sandbox', tag: str | None = None, started_at_ms: int | None = None, running: bool = True, exit_code: int | None = None) -> None
|
| A background process started in a sandbox with [`Sandbox.run`]`(..., background=True)`.
|
| List a sandbox's processes with [`Sandbox.processes`] and stop one with [`SandboxProcess.kill`].
| Completed processes stay in the listing until the sandbox is deleted, so `running` and
| `exit_code` tell whether a process is still alive or already exited (as of when it was listed).
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, pid: int, cmd: Union[str, List[str]], _sandbox: 'Sandbox', tag: str | None = None, started_at_ms: int | None = None, running: bool = True, exit_code: int | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| kill(self) -> None
| Terminate the background process (idempotent server-side).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_sandbox': 'Sandbox', 'cmd': typing.Union[str, typ...
|
| __dataclass_fields__ = {'_sandbox': Field(name='_sandbox',type='Sandbo...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('pid', 'cmd', '_sandbox', 'tag', 'started_at_ms', 'r...
|
| exit_code = None
|
| running = True
|
| started_at_ms = None
|
| tag = None
huggingface-hub.SentenceSimilarityInput
Python Library Documentation: class SentenceSimilarityInput in module huggingface_hub.inference._generated.types.sentence_similarity
class SentenceSimilarityInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| SentenceSimilarityInput(inputs: huggingface_hub.inference._generated.types.sentence_similarity.SentenceSimilarityInputData, parameters: dict[str, typing.Any] | None = None) -> None
|
| Inputs for Sentence similarity inference
|
| Method resolution order:
| SentenceSimilarityInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: huggingface_hub.inference._generated.types.sentence_similarity.SentenceSimilarityInputData, parameters: dict[str, typing.Any] | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'huggingface_hub.inference._genera...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'hug...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.SentenceSimilarityInputData
Python Library Documentation: class SentenceSimilarityInputData in module huggingface_hub.inference._generated.types.sentence_similarity
class SentenceSimilarityInputData(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| SentenceSimilarityInputData(sentences: list[str], source_sentence: str) -> None
|
| SentenceSimilarityInputData(sentences: list[str], source_sentence: str)
|
| Method resolution order:
| SentenceSimilarityInputData
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, sentences: list[str], source_sentence: str) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'sentences': list[str], 'source_sentence': <class '...
|
| __dataclass_fields__ = {'sentences': Field(name='sentences',type=list[...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('sentences', 'source_sentence')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.SpaceCard
Python Library Documentation: class SpaceCard in module huggingface_hub.repocard
class SpaceCard(RepoCard)
| SpaceCard(content: str, ignore_metadata_errors: bool = False)
|
| Method resolution order:
| SpaceCard
| RepoCard
| builtins.object
|
| Data and other attributes defined here:
|
| card_data_class = <class 'huggingface_hub.repocard_data.SpaceCardData'...
| 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.
|
| 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`, *optional*)
| Python version used in the Space (if Gradio/Streamlit sdk).
| app_file (`str`, *optional*)
| Path to your main application file (which contains either gradio or streamlit Python code, or static html code).
| Path is relative to the root of the repository.
| app_port (`str`, *optional*)
| Port on which your application is running. Used only if sdk is `docker`.
| license (`str`, *optional*)
| License of this model. Example: apache-2.0 or any license from
| https://huggingface.co/docs/hub/repositories-licenses.
| duplicated_from (`str`, *optional*)
| 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 found on https://hf.co/datasets.
| tags (`list[str]`, *optional*)
| List of tags to add to your Space that can be used when filtering on the Hub.
| 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.
| kwargs (`dict`, *optional*):
| Additional metadata that will be added to the space card.
|
| Example:
| ```python
| >>> from huggingface_hub import SpaceCardData
| >>> card_data = SpaceCardData(
| ... title="Dreambooth Training",
| ... license="mit",
| ... sdk="gradio",
| ... duplicated_from="multimodalart/dreambooth-training"
| ... )
| >>> card_data.to_dict()
| {'title': 'Dreambooth Training', 'sdk': 'gradio', 'license': 'mit', 'duplicated_from': 'multimodalart/dreambooth-training'}
| ```
|
|
| default_template_path = WindowsPath('C:/Users/Youse/AppData/Local/Prog...
|
| repo_type = 'space'
|
| ----------------------------------------------------------------------
| Methods inherited from RepoCard:
|
| __init__(self, content: str, ignore_metadata_errors: bool = False)
| Initialize a RepoCard from string content. The content should be a
| Markdown file with a YAML block at the beginning and a Markdown body.
|
| Args:
| content (`str`): The content of the Markdown file.
|
| Example:
| ```python
| >>> from huggingface_hub.repocard import RepoCard
| >>> text = '''
| ... ---
| ... language: en
| ... license: mit
| ... ---
| ...
| ... # My repo
| ... '''
| >>> card = RepoCard(text)
| >>> card.data.to_dict()
| {'language': 'en', 'license': 'mit'}
| >>> card.text
| '\n# My repo\n'
|
| ```
| > [!TIP]
| > Raises the following error:
| >
| > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| > when the content of the repo card metadata is not a dictionary.
|
| __str__(self)
| Return str(self).
|
| push_to_hub(self, repo_id: str, token: str | None = None, repo_type: str | None = None, commit_message: str | None = None, commit_description: str | None = None, revision: str | None = None, create_pr: bool | None = None, parent_commit: str | None = None)
| Push a RepoCard to a Hugging Face Hub repo.
|
| Args:
| repo_id (`str`):
| The repo ID of the Hugging Face Hub repo to push to. Example: "nateraw/food".
| token (`str`, *optional*):
| Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to
| the stored token.
| repo_type (`str`, *optional*, defaults to "model"):
| The type of Hugging Face repo to push to. Options are "model", "dataset", and "space". If this
| function is called by a child class, it will default to the child class's `repo_type`.
| commit_message (`str`, *optional*):
| The summary / title / first line of the generated commit.
| commit_description (`str`, *optional*)
| The description of the generated commit.
| revision (`str`, *optional*):
| The git revision to commit from. Defaults to the head of the `"main"` branch.
| create_pr (`bool`, *optional*):
| Whether or not to create a Pull Request with this commit. Defaults to `False`.
| parent_commit (`str`, *optional*):
| The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
| If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
| If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
| Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
| especially useful if the repo is updated / committed too concurrently.
| Returns:
| `str`: URL of the commit which updated the card metadata.
|
| save(self, filepath: pathlib.Path | str)
| Save a RepoCard to a file.
|
| Args:
| filepath (`Union[Path, str]`): Filepath to the markdown file to save.
|
| Example:
| ```python
| >>> from huggingface_hub.repocard import RepoCard
| >>> card = RepoCard("---\nlanguage: en\n---\n# This is a test repo card")
| >>> card.save("/tmp/test.md")
|
| ```
|
| validate(self, repo_type: str | None = None)
| Validates card against Hugging Face Hub's card validation logic.
| Using this function requires access to the internet, so it is only called
| internally by [`huggingface_hub.repocard.RepoCard.push_to_hub`].
|
| Args:
| repo_type (`str`, *optional*, defaults to "model"):
| The type of Hugging Face repo to push to. Options are "model", "dataset", and "space".
| If this function is called from a child class, the default will be the child class's `repo_type`.
|
| > [!TIP]
| > Raises the following errors:
| >
| > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
| > if the card fails validation checks.
| > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
| > if the request to the Hub API fails for any other reason.
|
| ----------------------------------------------------------------------
| Class methods inherited from RepoCard:
|
| from_template(card_data: huggingface_hub.repocard_data.CardData, template_path: str | None = None, template_str: str | None = None, **template_kwargs)
| Initialize a RepoCard from a template. By default, it uses the default template.
|
| Templates are Jinja2 templates that can be customized by passing keyword arguments.
|
| Args:
| card_data (`huggingface_hub.CardData`):
| A huggingface_hub.CardData instance containing the metadata you want to include in the YAML
| header of the repo card on the Hugging Face Hub.
| template_path (`str`, *optional*):
| A path to a markdown file with optional Jinja template variables that can be filled
| in with `template_kwargs`. Defaults to the default template.
| template_str (`str`, *optional*):
| A raw Jinja template string with optional variables. Used when neither `template_path`
| nor the default template is appropriate. Ignored if `template_path` is also provided.
|
| Returns:
| [`huggingface_hub.repocard.RepoCard`]: A RepoCard instance with the specified card data and content from the
| template.
|
| load(repo_id_or_path: str | pathlib.Path, repo_type: str | None = None, token: str | None = None, ignore_metadata_errors: bool = False)
| Initialize a RepoCard from a Hugging Face Hub repo's README.md or a local filepath.
|
| Args:
| repo_id_or_path (`Union[str, Path]`):
| The repo ID associated with a Hugging Face Hub repo or a local filepath.
| repo_type (`str`, *optional*):
| The type of Hugging Face repo to push to. Defaults to None, which will use "model". Other options
| are "dataset" and "space". Not used when loading from a local filepath. If this is called from a child
| class, the default value will be the child class's `repo_type`.
| 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.
|
| Returns:
| [`huggingface_hub.repocard.RepoCard`]: The RepoCard (or subclass) initialized from the repo's
| README.md file or filepath.
|
| Example:
| ```python
| >>> from huggingface_hub.repocard import RepoCard
| >>> card = RepoCard.load("nateraw/food")
| >>> assert card.data.tags == ["generated_from_trainer", "image-classification", "pytorch"]
|
| ```
|
| ----------------------------------------------------------------------
| Data descriptors inherited from RepoCard:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| content
| The content of the RepoCard, including the YAML block and the Markdown body.
huggingface-hub.SpaceCardData
Python Library Documentation: class SpaceCardData in module huggingface_hub.repocard_data
class SpaceCardData(CardData)
| SpaceCardData(*, title: str | None = None, sdk: str | None = None, sdk_version: str | None = None, python_version: str | None = None, app_file: str | None = None, app_port: int | None = None, license: str | None = None, duplicated_from: str | None = None, models: list[str] | None = None, datasets: list[str] | None = None, tags: list[str] | None = None, ignore_metadata_errors: bool = False, **kwargs)
|
| 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.
|
| 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`, *optional*)
| Python version used in the Space (if Gradio/Streamlit sdk).
| app_file (`str`, *optional*)
| Path to your main application file (which contains either gradio or streamlit Python code, or static html code).
| Path is relative to the root of the repository.
| app_port (`str`, *optional*)
| Port on which your application is running. Used only if sdk is `docker`.
| license (`str`, *optional*)
| License of this model. Example: apache-2.0 or any license from
| https://huggingface.co/docs/hub/repositories-licenses.
| duplicated_from (`str`, *optional*)
| 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 found on https://hf.co/datasets.
| tags (`list[str]`, *optional*)
| List of tags to add to your Space that can be used when filtering on the Hub.
| 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.
| kwargs (`dict`, *optional*):
| Additional metadata that will be added to the space card.
|
| Example:
| ```python
| >>> from huggingface_hub import SpaceCardData
| >>> card_data = SpaceCardData(
| ... title="Dreambooth Training",
| ... license="mit",
| ... sdk="gradio",
| ... duplicated_from="multimodalart/dreambooth-training"
| ... )
| >>> card_data.to_dict()
| {'title': 'Dreambooth Training', 'sdk': 'gradio', 'license': 'mit', 'duplicated_from': 'multimodalart/dreambooth-training'}
| ```
|
| Method resolution order:
| SpaceCardData
| CardData
| builtins.object
|
| Methods defined here:
|
| __init__(self, *, title: str | None = None, sdk: str | None = None, sdk_version: str | None = None, python_version: str | None = None, app_file: str | None = None, app_port: int | None = None, license: str | None = None, duplicated_from: str | None = None, models: list[str] | None = None, datasets: list[str] | None = None, tags: list[str] | None = None, ignore_metadata_errors: bool = False, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from CardData:
|
| __contains__(self, key: str) -> bool
| Check if a given metadata key is set.
|
| __eq__(self, other)
| Return self==value.
|
| __getitem__(self, key: str) -> Any
| Get value for a given metadata key.
|
| __len__(self) -> int
| Return the number of metadata keys set.
|
| __repr__(self)
| Return repr(self).
|
| __setitem__(self, key: str, value: Any) -> None
| Set value for a given metadata key.
|
| __str__(self)
| Return str(self).
|
| get(self, key: str, default: Any = None) -> Any
| Get value for a given metadata key.
|
| pop(self, key: str, default: Any = None) -> Any
| Pop value for a given metadata key.
|
| to_dict(self)
| Converts CardData to a dict.
|
| Returns:
| `dict`: CardData represented as a dictionary ready to be dumped to a YAML
| block for inclusion in a README.md file.
|
| to_yaml(self, line_break=None, original_order: list[str] | None = None) -> str
| Dumps CardData to a YAML block for inclusion in a README.md file.
|
| Args:
| line_break (str, *optional*):
| The line break to use when dumping to yaml.
| original_order (`list[str]`, *optional*):
| If provided, reorder the metadata fields to match this list before dumping.
| Any keys not in `original_order` are appended after the listed keys, preserving
| their existing relative order. Useful for round-tripping a YAML block without
| shuffling its keys.
|
| Returns:
| `str`: CardData represented as a YAML block.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from CardData:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from CardData:
|
| __dataclass_fields__ = {}
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ()
huggingface-hub.SpaceHardware
Python Library Documentation: class SpaceHardware in module huggingface_hub._space_api
class SpaceHardware(builtins.str, enum.Enum)
| SpaceHardware(*values)
|
| Enumeration of hardwares available to run your Space on the Hub.
|
| Value can be compared to a string:
| ```py
| assert SpaceHardware.CPU_BASIC == "cpu-basic"
| ```
|
| Taken from https://github.com/huggingface-internal/moon-landing/blob/main/server/repo_types/SpaceHardwareFlavor.ts (private url).
|
| Method resolution order:
| SpaceHardware
| builtins.str
| enum.Enum
| builtins.object
|
| Methods defined here:
|
| __format__(self, format_spec) from enum.Enum
| Default object formatter.
|
| Return str(self) if format_spec is empty. Raise TypeError otherwise.
|
| __new__(cls, value) from enum.Enum
| Create and return a new object. See help(type) for accurate signature.
|
| __repr__(self) from enum.Enum
| Return repr(self).
|
| __str__(self) from enum.Enum
| Return str(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| A100X4 = <SpaceHardware.A100X4: 'a100x4'>
|
| A100X8 = <SpaceHardware.A100X8: 'a100x8'>
|
| A100_LARGE = <SpaceHardware.A100_LARGE: 'a100-large'>
|
| A10G_LARGE = <SpaceHardware.A10G_LARGE: 'a10g-large'>
|
| A10G_LARGEX2 = <SpaceHardware.A10G_LARGEX2: 'a10g-largex2'>
|
| A10G_LARGEX4 = <SpaceHardware.A10G_LARGEX4: 'a10g-largex4'>
|
| A10G_SMALL = <SpaceHardware.A10G_SMALL: 'a10g-small'>
|
| CPU_BASIC = <SpaceHardware.CPU_BASIC: 'cpu-basic'>
|
| CPU_UPGRADE = <SpaceHardware.CPU_UPGRADE: 'cpu-upgrade'>
|
| L40SX1 = <SpaceHardware.L40SX1: 'l40sx1'>
|
| L40SX4 = <SpaceHardware.L40SX4: 'l40sx4'>
|
| L40SX8 = <SpaceHardware.L40SX8: 'l40sx8'>
|
| L4X1 = <SpaceHardware.L4X1: 'l4x1'>
|
| L4X4 = <SpaceHardware.L4X4: 'l4x4'>
|
| T4_MEDIUM = <SpaceHardware.T4_MEDIUM: 't4-medium'>
|
| T4_SMALL = <SpaceHardware.T4_SMALL: 't4-small'>
|
| ZERO_A10G = <SpaceHardware.ZERO_A10G: 'zero-a10g'>
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.str:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(...)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __sizeof__(self, /)
| Return the size of the string in memory, in bytes.
|
| capitalize(self, /)
| Return a capitalized version of the string.
|
| More specifically, make the first character have upper case and the rest lower
| case.
|
| casefold(self, /)
| Return a version of the string suitable for caseless comparisons.
|
| center(self, width, fillchar=' ', /)
| Return a centered string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| count(...)
| S.count(sub[, start[, end]]) -> int
|
| Return the number of non-overlapping occurrences of substring sub in
| string S[start:end]. Optional arguments start and end are
| interpreted as in slice notation.
|
| encode(self, /, encoding='utf-8', errors='strict')
| Encode the string using the codec registered for encoding.
|
| encoding
| The encoding in which to encode the string.
| errors
| The error handling scheme to use for encoding errors.
| The default is 'strict' meaning that encoding errors raise a
| UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
| 'xmlcharrefreplace' as well as any other name registered with
| codecs.register_error that can handle UnicodeEncodeErrors.
|
| endswith(...)
| S.endswith(suffix[, start[, end]]) -> bool
|
| Return True if S ends with the specified suffix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| suffix can also be a tuple of strings to try.
|
| expandtabs(self, /, tabsize=8)
| Return a copy where all tab characters are expanded using spaces.
|
| If tabsize is not given, a tab size of 8 characters is assumed.
|
| find(...)
| S.find(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| format(...)
| S.format(*args, **kwargs) -> str
|
| Return a formatted version of S, using substitutions from args and kwargs.
| The substitutions are identified by braces ('{' and '}').
|
| format_map(...)
| S.format_map(mapping) -> str
|
| Return a formatted version of S, using substitutions from mapping.
| The substitutions are identified by braces ('{' and '}').
|
| index(...)
| S.index(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| isalnum(self, /)
| Return True if the string is an alpha-numeric string, False otherwise.
|
| A string is alpha-numeric if all characters in the string are alpha-numeric and
| there is at least one character in the string.
|
| isalpha(self, /)
| Return True if the string is an alphabetic string, False otherwise.
|
| A string is alphabetic if all characters in the string are alphabetic and there
| is at least one character in the string.
|
| isascii(self, /)
| Return True if all characters in the string are ASCII, False otherwise.
|
| ASCII characters have code points in the range U+0000-U+007F.
| Empty string is ASCII too.
|
| isdecimal(self, /)
| Return True if the string is a decimal string, False otherwise.
|
| A string is a decimal string if all characters in the string are decimal and
| there is at least one character in the string.
|
| isdigit(self, /)
| Return True if the string is a digit string, False otherwise.
|
| A string is a digit string if all characters in the string are digits and there
| is at least one character in the string.
|
| isidentifier(self, /)
| Return True if the string is a valid Python identifier, False otherwise.
|
| Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
| such as "def" or "class".
|
| islower(self, /)
| Return True if the string is a lowercase string, False otherwise.
|
| A string is lowercase if all cased characters in the string are lowercase and
| there is at least one cased character in the string.
|
| isnumeric(self, /)
| Return True if the string is a numeric string, False otherwise.
|
| A string is numeric if all characters in the string are numeric and there is at
| least one character in the string.
|
| isprintable(self, /)
| Return True if the string is printable, False otherwise.
|
| A string is printable if all of its characters are considered printable in
| repr() or if it is empty.
|
| isspace(self, /)
| Return True if the string is a whitespace string, False otherwise.
|
| A string is whitespace if all characters in the string are whitespace and there
| is at least one character in the string.
|
| istitle(self, /)
| Return True if the string is a title-cased string, False otherwise.
|
| In a title-cased string, upper- and title-case characters may only
| follow uncased characters and lowercase characters only cased ones.
|
| isupper(self, /)
| Return True if the string is an uppercase string, False otherwise.
|
| A string is uppercase if all cased characters in the string are uppercase and
| there is at least one cased character in the string.
|
| join(self, iterable, /)
| Concatenate any number of strings.
|
| The string whose method is called is inserted in between each given string.
| The result is returned as a new string.
|
| Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
|
| ljust(self, width, fillchar=' ', /)
| Return a left-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| lower(self, /)
| Return a copy of the string converted to lowercase.
|
| lstrip(self, chars=None, /)
| Return a copy of the string with leading whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| partition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string. If the separator is found,
| returns a 3-tuple containing the part before the separator, the separator
| itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing the original string
| and two empty strings.
|
| removeprefix(self, prefix, /)
| Return a str with the given prefix string removed if present.
|
| If the string starts with the prefix string, return string[len(prefix):].
| Otherwise, return a copy of the original string.
|
| removesuffix(self, suffix, /)
| Return a str with the given suffix string removed if present.
|
| If the string ends with the suffix string and that suffix is not empty,
| return string[:-len(suffix)]. Otherwise, return a copy of the original
| string.
|
| replace(self, old, new, count=-1, /)
| Return a copy with all occurrences of substring old replaced by new.
|
| count
| Maximum number of occurrences to replace.
| -1 (the default value) means replace all occurrences.
|
| If the optional argument count is given, only the first count occurrences are
| replaced.
|
| rfind(...)
| S.rfind(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| rindex(...)
| S.rindex(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| rjust(self, width, fillchar=' ', /)
| Return a right-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| rpartition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string, starting at the end. If
| the separator is found, returns a 3-tuple containing the part before the
| separator, the separator itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing two empty strings
| and the original string.
|
| rsplit(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the end of the string and works to the front.
|
| rstrip(self, chars=None, /)
| Return a copy of the string with trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| split(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the front of the string and works to the end.
|
| Note, str.split() is mainly useful for data that has been intentionally
| delimited. With natural text that includes punctuation, consider using
| the regular expression module.
|
| splitlines(self, /, keepends=False)
| Return a list of the lines in the string, breaking at line boundaries.
|
| Line breaks are not included in the resulting list unless keepends is given and
| true.
|
| startswith(...)
| S.startswith(prefix[, start[, end]]) -> bool
|
| Return True if S starts with the specified prefix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| prefix can also be a tuple of strings to try.
|
| strip(self, chars=None, /)
| Return a copy of the string with leading and trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| swapcase(self, /)
| Convert uppercase characters to lowercase and lowercase characters to uppercase.
|
| title(self, /)
| Return a version of the string where each word is titlecased.
|
| More specifically, words start with uppercased characters and all remaining
| cased characters have lower case.
|
| translate(self, table, /)
| Replace each character in the string using the given translation table.
|
| table
| Translation table, which must be a mapping of Unicode ordinals to
| Unicode ordinals, strings, or None.
|
| The table must implement lookup/indexing via __getitem__, for instance a
| dictionary or list. If this operation raises LookupError, the character is
| left untouched. Characters mapped to None are deleted.
|
| upper(self, /)
| Return a copy of the string converted to uppercase.
|
| zfill(self, width, /)
| Pad a numeric string with zeros on the left, to fill a field of the given width.
|
| The string is never truncated.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.str:
|
| maketrans(...)
| Return a translation table usable for str.translate().
|
| If there is only one argument, it must be a dictionary mapping Unicode
| ordinals (integers) or characters to Unicode ordinals, strings or None.
| Character keys will be then converted to ordinals.
| If there are two arguments, they must be strings of equal length, and
| in the resulting dictionary, each character in x will be mapped to the
| character at the same position in y. If there is a third argument, it
| must be a string, whose characters will be mapped to None in the result.
|
| ----------------------------------------------------------------------
| Methods inherited from enum.Enum:
|
| __dir__(self)
| Returns public methods and other interesting attributes.
|
| __init__(self, *args, **kwds)
| Initialize self. See help(type(self)) for accurate signature.
|
| __reduce_ex__(self, proto)
| Helper for pickle.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from enum.Enum:
|
| name
| The name of the Enum member.
|
| value
| The value of the Enum member.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from enum.EnumType:
|
| __members__
| Returns a mapping of member name->value.
|
| This mapping lists all enum members, including aliases. Note that this
| is a read-only view of the internal mapping.
huggingface-hub.SpaceInfo
Python Library Documentation: class SpaceInfo in module huggingface_hub.hf_api
class SpaceInfo(builtins.object)
| SpaceInfo(**kwargs)
|
| Contains information about a Space on the Hub. This object is returned by [`space_info`] and [`list_spaces`].
|
| > [!TIP]
| > Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made.
| > In general, the more specific the query, the more information is returned. On the contrary, when listing spaces
| > using [`list_spaces`] only a subset of the attributes are returned.
|
| Attributes:
| id (`str`):
| ID of the Space.
| author (`str`, *optional*):
| Author of the Space.
| card_data (`SpaceCardData`, *optional*):
| Space Card Metadata as a [`huggingface_hub.repocard_data.SpaceCardData`] object.
| created_at (`datetime`, *optional*):
| Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`,
| corresponding to the date when we began to store creation dates.
| datasets (`list[str]`, *optional*):
| List of datasets used by the Space.
| disabled (`bool`, *optional*):
| Is the Space disabled.
| gated (`Literal["auto", "manual", False]`, *optional*):
| Is the repo gated.
| If so, whether there is manual or automatic approval.
| host (`str`, *optional*):
| Host URL of the Space.
| last_modified (`datetime`, *optional*):
| Date of last commit to the repo.
| likes (`int`):
| Number of likes of the Space.
| models (`list[str]`, *optional*):
| List of models used by the Space.
| private (`bool`):
| Is the repo private.
| resource_group (`dict`, *optional*):
| Resource group information for the Space.
| runtime (`SpaceRuntime`, *optional*):
| Space runtime information as a [`huggingface_hub.hf_api.SpaceRuntime`] object.
| sdk (`str`, *optional*):
| SDK used by the Space.
| sha (`str`, *optional*):
| Repo SHA at this particular revision.
| siblings (`list[RepoSibling]`):
| List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the Space.
| subdomain (`str`, *optional*):
| Subdomain of the Space.
| tags (`list[str]`):
| List of tags of the Space.
| trending_score (`int`, *optional*):
| Trending score of the Space.
| used_storage (`int`, *optional*):
| Size in bytes of the Space on the Hub.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'author': 'str | None', 'card_data': 'SpaceCardData...
|
| __dataclass_fields__ = {'author': Field(name='author',type='str | None...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('id', 'author', 'card_data', 'created_at', 'datasets...
huggingface-hub.SpaceRuntime
Python Library Documentation: class SpaceRuntime in module huggingface_hub._space_api
class SpaceRuntime(builtins.object)
| SpaceRuntime(data: dict) -> None
|
| Contains information about the current runtime of a Space.
|
| Args:
| stage (`str`):
| Current stage of the space. Example: RUNNING.
| hardware (`str` or `None`):
| Current hardware of the space. Example: "cpu-basic". Can be `None` if Space
| is `BUILDING` for the first time.
| requested_hardware (`str` or `None`):
| Requested hardware. Can be different from `hardware` especially if the request
| has just been made. Example: "t4-medium". Can be `None` if no hardware has
| been requested yet.
| sleep_time (`int` or `None`):
| Number of seconds the Space will be kept alive after the last request. By default (if value is `None`), the
| Space will never go to sleep if it's running on an upgraded hardware, while it will go to sleep after 48
| hours on a free 'cpu-basic' hardware. For more details, see https://huggingface.co/docs/hub/spaces-gpus#sleep-time.
| volumes (`list[Volume]` or `None`):
| List of volumes mounted in the Space. Each volume is a [`Volume`] object describing its type, source,
| mount path, and optional settings. `None` if no volumes are attached.
| raw (`dict`):
| Raw response from the server. Contains more information about the Space
| runtime like number of replicas, number of cpu, memory size,...
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, data: dict) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'dev_mode': <class 'bool'>, 'hardware': huggingface...
|
| __dataclass_fields__ = {'dev_mode': Field(name='dev_mode',type=<class ...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('stage', 'hardware', 'requested_hardware', 'sleep_ti...
huggingface-hub.SpaceSearchResult
Python Library Documentation: class SpaceSearchResult in module huggingface_hub._space_api
class SpaceSearchResult(builtins.object)
| SpaceSearchResult(data: dict) -> None
|
| A single result from the Spaces semantic search API.
|
| Returned by [`HfApi.search_spaces`].
|
| Attributes:
| id (`str`):
| ID of the Space (e.g. `"username/repo-name"`).
| author (`str`):
| Author of the Space.
| title (`str`):
| Display title of the Space.
| emoji (`str` or `None`):
| Emoji icon of the Space.
| sdk (`str` or `None`):
| SDK used by the Space (e.g. `"gradio"`, `"docker"`, `"static"`).
| likes (`int`):
| Number of likes.
| private (`bool`):
| Whether the Space is private.
| tags (`list[str]` or `None`):
| List of tags.
| runtime ([`SpaceRuntime`] or `None`):
| Runtime information (stage, hardware, etc.).
| ai_short_description (`str` or `None`):
| AI-generated short description.
| ai_category (`str` or `None`):
| AI-generated category (e.g. `"Image Generation"`).
| semantic_relevancy_score (`float` or `None`):
| Semantic relevancy score (0-1) relative to the search query.
| trending_score (`int` or `None`):
| Trending score.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, data: dict) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'ai_category': str | None, 'ai_short_description': ...
|
| __dataclass_fields__ = {'ai_category': Field(name='ai_category',type=s...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('id', 'author', 'title', 'emoji', 'sdk', 'likes', 'p...
huggingface-hub.SpaceSecret
Python Library Documentation: class SpaceSecret in module huggingface_hub._space_api
class SpaceSecret(builtins.object)
| SpaceSecret(key: str, values: dict) -> None
|
| Contains information about a secret of a Space.
|
| Secret values are write-only and cannot be read back. Only the key, description,
| and last update time are returned by the API.
|
| Args:
| key (`str`):
| Secret key. Example: `"GITHUB_API_KEY"`
| description (`str` or None):
| Description of the secret. Example: `"Github API key to access the Github API"`.
| updated_at (`datetime` or None):
| datetime of the last update of the secret (if the secret has been updated at least once).
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, key: str, values: dict) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'description': str | None, 'key': <class 'str'>, 'u...
|
| __dataclass_fields__ = {'description': Field(name='description',type=s...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('key', 'description', 'updated_at')
huggingface-hub.SpaceStage
Python Library Documentation: class SpaceStage in module huggingface_hub._space_api
class SpaceStage(builtins.str, enum.Enum)
| SpaceStage(*values)
|
| Enumeration of possible stage of a Space on the Hub.
|
| Value can be compared to a string:
| ```py
| assert SpaceStage.BUILDING == "BUILDING"
| ```
|
| Taken from https://github.com/huggingface/moon-landing/blob/main/server/repo_types/SpaceInfo.ts#L61 (private url).
|
| Method resolution order:
| SpaceStage
| builtins.str
| enum.Enum
| builtins.object
|
| Methods defined here:
|
| __format__(self, format_spec) from enum.Enum
| Default object formatter.
|
| Return str(self) if format_spec is empty. Raise TypeError otherwise.
|
| __new__(cls, value) from enum.Enum
| Create and return a new object. See help(type) for accurate signature.
|
| __repr__(self) from enum.Enum
| Return repr(self).
|
| __str__(self) from enum.Enum
| Return str(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| APP_STARTING = <SpaceStage.APP_STARTING: 'APP_STARTING'>
|
| BUILDING = <SpaceStage.BUILDING: 'BUILDING'>
|
| BUILD_ERROR = <SpaceStage.BUILD_ERROR: 'BUILD_ERROR'>
|
| CONFIG_ERROR = <SpaceStage.CONFIG_ERROR: 'CONFIG_ERROR'>
|
| DELETING = <SpaceStage.DELETING: 'DELETING'>
|
| NO_APP_FILE = <SpaceStage.NO_APP_FILE: 'NO_APP_FILE'>
|
| PAUSED = <SpaceStage.PAUSED: 'PAUSED'>
|
| RUNNING = <SpaceStage.RUNNING: 'RUNNING'>
|
| RUNNING_APP_STARTING = <SpaceStage.RUNNING_APP_STARTING: 'RUNNING_APP_...
|
| RUNNING_BUILDING = <SpaceStage.RUNNING_BUILDING: 'RUNNING_BUILDING'>
|
| RUNTIME_ERROR = <SpaceStage.RUNTIME_ERROR: 'RUNTIME_ERROR'>
|
| STOPPED = <SpaceStage.STOPPED: 'STOPPED'>
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.str:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(...)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __sizeof__(self, /)
| Return the size of the string in memory, in bytes.
|
| capitalize(self, /)
| Return a capitalized version of the string.
|
| More specifically, make the first character have upper case and the rest lower
| case.
|
| casefold(self, /)
| Return a version of the string suitable for caseless comparisons.
|
| center(self, width, fillchar=' ', /)
| Return a centered string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| count(...)
| S.count(sub[, start[, end]]) -> int
|
| Return the number of non-overlapping occurrences of substring sub in
| string S[start:end]. Optional arguments start and end are
| interpreted as in slice notation.
|
| encode(self, /, encoding='utf-8', errors='strict')
| Encode the string using the codec registered for encoding.
|
| encoding
| The encoding in which to encode the string.
| errors
| The error handling scheme to use for encoding errors.
| The default is 'strict' meaning that encoding errors raise a
| UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
| 'xmlcharrefreplace' as well as any other name registered with
| codecs.register_error that can handle UnicodeEncodeErrors.
|
| endswith(...)
| S.endswith(suffix[, start[, end]]) -> bool
|
| Return True if S ends with the specified suffix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| suffix can also be a tuple of strings to try.
|
| expandtabs(self, /, tabsize=8)
| Return a copy where all tab characters are expanded using spaces.
|
| If tabsize is not given, a tab size of 8 characters is assumed.
|
| find(...)
| S.find(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| format(...)
| S.format(*args, **kwargs) -> str
|
| Return a formatted version of S, using substitutions from args and kwargs.
| The substitutions are identified by braces ('{' and '}').
|
| format_map(...)
| S.format_map(mapping) -> str
|
| Return a formatted version of S, using substitutions from mapping.
| The substitutions are identified by braces ('{' and '}').
|
| index(...)
| S.index(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| isalnum(self, /)
| Return True if the string is an alpha-numeric string, False otherwise.
|
| A string is alpha-numeric if all characters in the string are alpha-numeric and
| there is at least one character in the string.
|
| isalpha(self, /)
| Return True if the string is an alphabetic string, False otherwise.
|
| A string is alphabetic if all characters in the string are alphabetic and there
| is at least one character in the string.
|
| isascii(self, /)
| Return True if all characters in the string are ASCII, False otherwise.
|
| ASCII characters have code points in the range U+0000-U+007F.
| Empty string is ASCII too.
|
| isdecimal(self, /)
| Return True if the string is a decimal string, False otherwise.
|
| A string is a decimal string if all characters in the string are decimal and
| there is at least one character in the string.
|
| isdigit(self, /)
| Return True if the string is a digit string, False otherwise.
|
| A string is a digit string if all characters in the string are digits and there
| is at least one character in the string.
|
| isidentifier(self, /)
| Return True if the string is a valid Python identifier, False otherwise.
|
| Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
| such as "def" or "class".
|
| islower(self, /)
| Return True if the string is a lowercase string, False otherwise.
|
| A string is lowercase if all cased characters in the string are lowercase and
| there is at least one cased character in the string.
|
| isnumeric(self, /)
| Return True if the string is a numeric string, False otherwise.
|
| A string is numeric if all characters in the string are numeric and there is at
| least one character in the string.
|
| isprintable(self, /)
| Return True if the string is printable, False otherwise.
|
| A string is printable if all of its characters are considered printable in
| repr() or if it is empty.
|
| isspace(self, /)
| Return True if the string is a whitespace string, False otherwise.
|
| A string is whitespace if all characters in the string are whitespace and there
| is at least one character in the string.
|
| istitle(self, /)
| Return True if the string is a title-cased string, False otherwise.
|
| In a title-cased string, upper- and title-case characters may only
| follow uncased characters and lowercase characters only cased ones.
|
| isupper(self, /)
| Return True if the string is an uppercase string, False otherwise.
|
| A string is uppercase if all cased characters in the string are uppercase and
| there is at least one cased character in the string.
|
| join(self, iterable, /)
| Concatenate any number of strings.
|
| The string whose method is called is inserted in between each given string.
| The result is returned as a new string.
|
| Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
|
| ljust(self, width, fillchar=' ', /)
| Return a left-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| lower(self, /)
| Return a copy of the string converted to lowercase.
|
| lstrip(self, chars=None, /)
| Return a copy of the string with leading whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| partition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string. If the separator is found,
| returns a 3-tuple containing the part before the separator, the separator
| itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing the original string
| and two empty strings.
|
| removeprefix(self, prefix, /)
| Return a str with the given prefix string removed if present.
|
| If the string starts with the prefix string, return string[len(prefix):].
| Otherwise, return a copy of the original string.
|
| removesuffix(self, suffix, /)
| Return a str with the given suffix string removed if present.
|
| If the string ends with the suffix string and that suffix is not empty,
| return string[:-len(suffix)]. Otherwise, return a copy of the original
| string.
|
| replace(self, old, new, count=-1, /)
| Return a copy with all occurrences of substring old replaced by new.
|
| count
| Maximum number of occurrences to replace.
| -1 (the default value) means replace all occurrences.
|
| If the optional argument count is given, only the first count occurrences are
| replaced.
|
| rfind(...)
| S.rfind(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| rindex(...)
| S.rindex(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| rjust(self, width, fillchar=' ', /)
| Return a right-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| rpartition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string, starting at the end. If
| the separator is found, returns a 3-tuple containing the part before the
| separator, the separator itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing two empty strings
| and the original string.
|
| rsplit(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the end of the string and works to the front.
|
| rstrip(self, chars=None, /)
| Return a copy of the string with trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| split(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the front of the string and works to the end.
|
| Note, str.split() is mainly useful for data that has been intentionally
| delimited. With natural text that includes punctuation, consider using
| the regular expression module.
|
| splitlines(self, /, keepends=False)
| Return a list of the lines in the string, breaking at line boundaries.
|
| Line breaks are not included in the resulting list unless keepends is given and
| true.
|
| startswith(...)
| S.startswith(prefix[, start[, end]]) -> bool
|
| Return True if S starts with the specified prefix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| prefix can also be a tuple of strings to try.
|
| strip(self, chars=None, /)
| Return a copy of the string with leading and trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| swapcase(self, /)
| Convert uppercase characters to lowercase and lowercase characters to uppercase.
|
| title(self, /)
| Return a version of the string where each word is titlecased.
|
| More specifically, words start with uppercased characters and all remaining
| cased characters have lower case.
|
| translate(self, table, /)
| Replace each character in the string using the given translation table.
|
| table
| Translation table, which must be a mapping of Unicode ordinals to
| Unicode ordinals, strings, or None.
|
| The table must implement lookup/indexing via __getitem__, for instance a
| dictionary or list. If this operation raises LookupError, the character is
| left untouched. Characters mapped to None are deleted.
|
| upper(self, /)
| Return a copy of the string converted to uppercase.
|
| zfill(self, width, /)
| Pad a numeric string with zeros on the left, to fill a field of the given width.
|
| The string is never truncated.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.str:
|
| maketrans(...)
| Return a translation table usable for str.translate().
|
| If there is only one argument, it must be a dictionary mapping Unicode
| ordinals (integers) or characters to Unicode ordinals, strings or None.
| Character keys will be then converted to ordinals.
| If there are two arguments, they must be strings of equal length, and
| in the resulting dictionary, each character in x will be mapped to the
| character at the same position in y. If there is a third argument, it
| must be a string, whose characters will be mapped to None in the result.
|
| ----------------------------------------------------------------------
| Methods inherited from enum.Enum:
|
| __dir__(self)
| Returns public methods and other interesting attributes.
|
| __init__(self, *args, **kwds)
| Initialize self. See help(type(self)) for accurate signature.
|
| __reduce_ex__(self, proto)
| Helper for pickle.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from enum.Enum:
|
| name
| The name of the Enum member.
|
| value
| The value of the Enum member.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from enum.EnumType:
|
| __members__
| Returns a mapping of member name->value.
|
| This mapping lists all enum members, including aliases. Note that this
| is a read-only view of the internal mapping.
huggingface-hub.SpaceStorage
Python Library Documentation: class SpaceStorage in module huggingface_hub._space_api
class SpaceStorage(builtins.str, enum.Enum)
| SpaceStorage(*values)
|
| Enumeration of persistent storage available for your Space on the Hub.
|
| Value can be compared to a string:
| ```py
| assert SpaceStorage.SMALL == "small"
| ```
|
| Taken from https://github.com/huggingface/moon-landing/blob/main/server/repo_types/SpaceHardwareFlavor.ts#L24 (private url).
|
| Method resolution order:
| SpaceStorage
| builtins.str
| enum.Enum
| builtins.object
|
| Methods defined here:
|
| __format__(self, format_spec) from enum.Enum
| Default object formatter.
|
| Return str(self) if format_spec is empty. Raise TypeError otherwise.
|
| __new__(cls, value) from enum.Enum
| Create and return a new object. See help(type) for accurate signature.
|
| __repr__(self) from enum.Enum
| Return repr(self).
|
| __str__(self) from enum.Enum
| Return str(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| LARGE = <SpaceStorage.LARGE: 'large'>
|
| MEDIUM = <SpaceStorage.MEDIUM: 'medium'>
|
| SMALL = <SpaceStorage.SMALL: 'small'>
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.str:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(...)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __sizeof__(self, /)
| Return the size of the string in memory, in bytes.
|
| capitalize(self, /)
| Return a capitalized version of the string.
|
| More specifically, make the first character have upper case and the rest lower
| case.
|
| casefold(self, /)
| Return a version of the string suitable for caseless comparisons.
|
| center(self, width, fillchar=' ', /)
| Return a centered string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| count(...)
| S.count(sub[, start[, end]]) -> int
|
| Return the number of non-overlapping occurrences of substring sub in
| string S[start:end]. Optional arguments start and end are
| interpreted as in slice notation.
|
| encode(self, /, encoding='utf-8', errors='strict')
| Encode the string using the codec registered for encoding.
|
| encoding
| The encoding in which to encode the string.
| errors
| The error handling scheme to use for encoding errors.
| The default is 'strict' meaning that encoding errors raise a
| UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
| 'xmlcharrefreplace' as well as any other name registered with
| codecs.register_error that can handle UnicodeEncodeErrors.
|
| endswith(...)
| S.endswith(suffix[, start[, end]]) -> bool
|
| Return True if S ends with the specified suffix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| suffix can also be a tuple of strings to try.
|
| expandtabs(self, /, tabsize=8)
| Return a copy where all tab characters are expanded using spaces.
|
| If tabsize is not given, a tab size of 8 characters is assumed.
|
| find(...)
| S.find(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| format(...)
| S.format(*args, **kwargs) -> str
|
| Return a formatted version of S, using substitutions from args and kwargs.
| The substitutions are identified by braces ('{' and '}').
|
| format_map(...)
| S.format_map(mapping) -> str
|
| Return a formatted version of S, using substitutions from mapping.
| The substitutions are identified by braces ('{' and '}').
|
| index(...)
| S.index(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| isalnum(self, /)
| Return True if the string is an alpha-numeric string, False otherwise.
|
| A string is alpha-numeric if all characters in the string are alpha-numeric and
| there is at least one character in the string.
|
| isalpha(self, /)
| Return True if the string is an alphabetic string, False otherwise.
|
| A string is alphabetic if all characters in the string are alphabetic and there
| is at least one character in the string.
|
| isascii(self, /)
| Return True if all characters in the string are ASCII, False otherwise.
|
| ASCII characters have code points in the range U+0000-U+007F.
| Empty string is ASCII too.
|
| isdecimal(self, /)
| Return True if the string is a decimal string, False otherwise.
|
| A string is a decimal string if all characters in the string are decimal and
| there is at least one character in the string.
|
| isdigit(self, /)
| Return True if the string is a digit string, False otherwise.
|
| A string is a digit string if all characters in the string are digits and there
| is at least one character in the string.
|
| isidentifier(self, /)
| Return True if the string is a valid Python identifier, False otherwise.
|
| Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
| such as "def" or "class".
|
| islower(self, /)
| Return True if the string is a lowercase string, False otherwise.
|
| A string is lowercase if all cased characters in the string are lowercase and
| there is at least one cased character in the string.
|
| isnumeric(self, /)
| Return True if the string is a numeric string, False otherwise.
|
| A string is numeric if all characters in the string are numeric and there is at
| least one character in the string.
|
| isprintable(self, /)
| Return True if the string is printable, False otherwise.
|
| A string is printable if all of its characters are considered printable in
| repr() or if it is empty.
|
| isspace(self, /)
| Return True if the string is a whitespace string, False otherwise.
|
| A string is whitespace if all characters in the string are whitespace and there
| is at least one character in the string.
|
| istitle(self, /)
| Return True if the string is a title-cased string, False otherwise.
|
| In a title-cased string, upper- and title-case characters may only
| follow uncased characters and lowercase characters only cased ones.
|
| isupper(self, /)
| Return True if the string is an uppercase string, False otherwise.
|
| A string is uppercase if all cased characters in the string are uppercase and
| there is at least one cased character in the string.
|
| join(self, iterable, /)
| Concatenate any number of strings.
|
| The string whose method is called is inserted in between each given string.
| The result is returned as a new string.
|
| Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
|
| ljust(self, width, fillchar=' ', /)
| Return a left-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| lower(self, /)
| Return a copy of the string converted to lowercase.
|
| lstrip(self, chars=None, /)
| Return a copy of the string with leading whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| partition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string. If the separator is found,
| returns a 3-tuple containing the part before the separator, the separator
| itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing the original string
| and two empty strings.
|
| removeprefix(self, prefix, /)
| Return a str with the given prefix string removed if present.
|
| If the string starts with the prefix string, return string[len(prefix):].
| Otherwise, return a copy of the original string.
|
| removesuffix(self, suffix, /)
| Return a str with the given suffix string removed if present.
|
| If the string ends with the suffix string and that suffix is not empty,
| return string[:-len(suffix)]. Otherwise, return a copy of the original
| string.
|
| replace(self, old, new, count=-1, /)
| Return a copy with all occurrences of substring old replaced by new.
|
| count
| Maximum number of occurrences to replace.
| -1 (the default value) means replace all occurrences.
|
| If the optional argument count is given, only the first count occurrences are
| replaced.
|
| rfind(...)
| S.rfind(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| rindex(...)
| S.rindex(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| rjust(self, width, fillchar=' ', /)
| Return a right-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| rpartition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string, starting at the end. If
| the separator is found, returns a 3-tuple containing the part before the
| separator, the separator itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing two empty strings
| and the original string.
|
| rsplit(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the end of the string and works to the front.
|
| rstrip(self, chars=None, /)
| Return a copy of the string with trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| split(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the front of the string and works to the end.
|
| Note, str.split() is mainly useful for data that has been intentionally
| delimited. With natural text that includes punctuation, consider using
| the regular expression module.
|
| splitlines(self, /, keepends=False)
| Return a list of the lines in the string, breaking at line boundaries.
|
| Line breaks are not included in the resulting list unless keepends is given and
| true.
|
| startswith(...)
| S.startswith(prefix[, start[, end]]) -> bool
|
| Return True if S starts with the specified prefix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| prefix can also be a tuple of strings to try.
|
| strip(self, chars=None, /)
| Return a copy of the string with leading and trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| swapcase(self, /)
| Convert uppercase characters to lowercase and lowercase characters to uppercase.
|
| title(self, /)
| Return a version of the string where each word is titlecased.
|
| More specifically, words start with uppercased characters and all remaining
| cased characters have lower case.
|
| translate(self, table, /)
| Replace each character in the string using the given translation table.
|
| table
| Translation table, which must be a mapping of Unicode ordinals to
| Unicode ordinals, strings, or None.
|
| The table must implement lookup/indexing via __getitem__, for instance a
| dictionary or list. If this operation raises LookupError, the character is
| left untouched. Characters mapped to None are deleted.
|
| upper(self, /)
| Return a copy of the string converted to uppercase.
|
| zfill(self, width, /)
| Pad a numeric string with zeros on the left, to fill a field of the given width.
|
| The string is never truncated.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.str:
|
| maketrans(...)
| Return a translation table usable for str.translate().
|
| If there is only one argument, it must be a dictionary mapping Unicode
| ordinals (integers) or characters to Unicode ordinals, strings or None.
| Character keys will be then converted to ordinals.
| If there are two arguments, they must be strings of equal length, and
| in the resulting dictionary, each character in x will be mapped to the
| character at the same position in y. If there is a third argument, it
| must be a string, whose characters will be mapped to None in the result.
|
| ----------------------------------------------------------------------
| Methods inherited from enum.Enum:
|
| __dir__(self)
| Returns public methods and other interesting attributes.
|
| __init__(self, *args, **kwds)
| Initialize self. See help(type(self)) for accurate signature.
|
| __reduce_ex__(self, proto)
| Helper for pickle.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from enum.Enum:
|
| name
| The name of the Enum member.
|
| value
| The value of the Enum member.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from enum.EnumType:
|
| __members__
| Returns a mapping of member name->value.
|
| This mapping lists all enum members, including aliases. Note that this
| is a read-only view of the internal mapping.
huggingface-hub.SpaceTemplate
Python Library Documentation: class SpaceTemplate in module huggingface_hub._space_api
class SpaceTemplate(builtins.object)
| SpaceTemplate(data: dict) -> None
|
| Contains information about a Space template available on the Hub.
|
| Returned by [`HfApi.list_space_templates`]. The `repo_id` can be passed as `space_template`
| to [`HfApi.create_repo`] to seed a new Space from that template.
|
| Args:
| name (`str`):
| Human-friendly name of the template (e.g. `"JupyterLab"`, `"chatbot"`).
| repo_id (`str`):
| Repo id of the template Space (e.g. `"SpacesExamples/jupyterlab"`).
| sdk (`str`):
| SDK the template is built with (e.g. `"gradio"`, `"docker"`, `"static"`).
| preferred_private (`bool`):
| Whether Spaces created from this template are recommended to be private.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, data: dict) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'name': <class 'str'>, 'preferred_private': <class ...
|
| __dataclass_fields__ = {'name': Field(name='name',type=<class 'str'>,d...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('name', 'repo_id', 'sdk', 'preferred_private')
huggingface-hub.SpaceVariable
Python Library Documentation: class SpaceVariable in module huggingface_hub._space_api
class SpaceVariable(builtins.object)
| SpaceVariable(key: str, values: dict) -> None
|
| Contains information about the current variables of a Space.
|
| Args:
| key (`str`):
| Variable key. Example: `"MODEL_REPO_ID"`
| value (`str`):
| Variable value. Example: `"the_model_repo_id"`.
| description (`str` or None):
| Description of the variable. Example: `"Model Repo ID of the implemented model"`.
| updatedAt (`datetime` or None):
| datetime of the last update of the variable (if the variable has been updated at least once).
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, key: str, values: dict) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'description': str | None, 'key': <class 'str'>, 'u...
|
| __dataclass_fields__ = {'description': Field(name='description',type=s...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('key', 'value', 'description', 'updated_at')
huggingface-hub.StateDictSplit
Python Library Documentation: class StateDictSplit in module huggingface_hub.serialization._base
class StateDictSplit(builtins.object)
| StateDictSplit(metadata: dict[str, typing.Any], filename_to_tensors: dict[str, list[str]], tensor_to_filename: dict[str, str]) -> None
|
| StateDictSplit(metadata: dict[str, typing.Any], filename_to_tensors: dict[str, list[str]], tensor_to_filename: dict[str, str])
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, metadata: dict[str, typing.Any], filename_to_tensors: dict[str, list[str]], tensor_to_filename: dict[str, str]) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __post_init__(self)
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'filename_to_tensors': dict[str, list[str]], 'is_sh...
|
| __dataclass_fields__ = {'filename_to_tensors': Field(name='filename_to...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('metadata', 'filename_to_tensors', 'tensor_to_filena...
huggingface-hub.SummarizationInput
Python Library Documentation: class SummarizationInput in module huggingface_hub.inference._generated.types.summarization
class SummarizationInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| SummarizationInput(inputs: str, parameters: huggingface_hub.inference._generated.types.summarization.SummarizationParameters | None = None) -> None
|
| Inputs for Summarization inference
|
| Method resolution order:
| SummarizationInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: str, parameters: huggingface_hub.inference._generated.types.summarization.SummarizationParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'str'>, 'parameters': huggingface_...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.SummarizationOutput
Python Library Documentation: class SummarizationOutput in module huggingface_hub.inference._generated.types.summarization
class SummarizationOutput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| SummarizationOutput(summary_text: str) -> None
|
| Outputs of inference for the Summarization task
|
| Method resolution order:
| SummarizationOutput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, summary_text: str) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'summary_text': <class 'str'>}
|
| __dataclass_fields__ = {'summary_text': Field(name='summary_text',type...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('summary_text',)
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.SummarizationParameters
Python Library Documentation: class SummarizationParameters in module huggingface_hub.inference._generated.types.summarization
class SummarizationParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| SummarizationParameters(clean_up_tokenization_spaces: bool | None = None, generate_parameters: dict[str, typing.Any] | None = None, truncation: Optional[ForwardRef('SummarizationTruncationStrategy')] = None) -> None
|
| Additional inference parameters for summarization.
|
| Method resolution order:
| SummarizationParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, clean_up_tokenization_spaces: bool | None = None, generate_parameters: dict[str, typing.Any] | None = None, truncation: Optional[ForwardRef('SummarizationTruncationStrategy')] = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'clean_up_tokenization_spaces': bool | None, 'gener...
|
| __dataclass_fields__ = {'clean_up_tokenization_spaces': Field(name='cl...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('clean_up_tokenization_spaces', 'generate_parameters...
|
| clean_up_tokenization_spaces = None
|
| generate_parameters = None
|
| truncation = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.SummarizationTruncationStrategy
Python Library Documentation: _LiteralGenericAlias in module typing
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
huggingface-hub.SyncOperation
Python Library Documentation: class SyncOperation in module huggingface_hub._buckets
class SyncOperation(builtins.object)
| SyncOperation(action: Literal['upload', 'download', 'delete', 'skip'], path: str, size: int | None = None, reason: str = '', local_mtime: str | None = None, remote_mtime: str | None = None, bucket_file: huggingface_hub._buckets.BucketFile | None = None) -> None
|
| Represents a sync operation to be performed.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, action: Literal['upload', 'download', 'delete', 'skip'], path: str, size: int | None = None, reason: str = '', local_mtime: str | None = None, remote_mtime: str | None = None, bucket_file: huggingface_hub._buckets.BucketFile | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'action': typing.Literal['upload', 'download', 'del...
|
| __dataclass_fields__ = {'action': Field(name='action',type=typing.Lite...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('action', 'path', 'size', 'reason', 'local_mtime', '...
|
| bucket_file = None
|
| local_mtime = None
|
| reason = ''
|
| remote_mtime = None
|
| size = None
huggingface-hub.SyncPlan
Python Library Documentation: class SyncPlan in module huggingface_hub._buckets
class SyncPlan(builtins.object)
| SyncPlan(source: str, dest: str, timestamp: str, operations: list[huggingface_hub._buckets.SyncOperation] = <factory>) -> None
|
| Represents a complete sync plan.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, source: str, dest: str, timestamp: str, operations: list[huggingface_hub._buckets.SyncOperation] = <factory>) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| summary(self) -> dict[str, int | str]
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'dest': <class 'str'>, 'operations': list[huggingfa...
|
| __dataclass_fields__ = {'dest': Field(name='dest',type=<class 'str'>,d...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('source', 'dest', 'timestamp', 'operations')
huggingface-hub.TF2_WEIGHTS_NAME
Error rendering doc: No Python documentation found for 'tf_model.h5'. Use help() to get the interactive help utility. Use help(str) for help on the str class.
huggingface-hub.TF_WEIGHTS_NAME
Error rendering doc: No Python documentation found for 'model.ckpt'. Use help() to get the interactive help utility. Use help(str) for help on the str class.
huggingface-hub.TableQuestionAnsweringInput
Python Library Documentation: class TableQuestionAnsweringInput in module huggingface_hub.inference._generated.types.table_question_answering
class TableQuestionAnsweringInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TableQuestionAnsweringInput(inputs: huggingface_hub.inference._generated.types.table_question_answering.TableQuestionAnsweringInputData, parameters: huggingface_hub.inference._generated.types.table_question_answering.TableQuestionAnsweringParameters | None = None) -> None
|
| Inputs for Table Question Answering inference
|
| Method resolution order:
| TableQuestionAnsweringInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: huggingface_hub.inference._generated.types.table_question_answering.TableQuestionAnsweringInputData, parameters: huggingface_hub.inference._generated.types.table_question_answering.TableQuestionAnsweringParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'huggingface_hub.inference._genera...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'hug...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TableQuestionAnsweringInputData
Python Library Documentation: class TableQuestionAnsweringInputData in module huggingface_hub.inference._generated.types.table_question_answering
class TableQuestionAnsweringInputData(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TableQuestionAnsweringInputData(question: str, table: dict[str, list[str]]) -> None
|
| One (table, question) pair to answer
|
| Method resolution order:
| TableQuestionAnsweringInputData
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, question: str, table: dict[str, list[str]]) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'question': <class 'str'>, 'table': dict[str, list[...
|
| __dataclass_fields__ = {'question': Field(name='question',type=<class ...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('question', 'table')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TableQuestionAnsweringOutputElement
Python Library Documentation: class TableQuestionAnsweringOutputElement in module huggingface_hub.inference._generated.types.table_question_answering
class TableQuestionAnsweringOutputElement(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TableQuestionAnsweringOutputElement(answer: str, cells: list[str], coordinates: list[list[int]], aggregator: str | None = None) -> None
|
| Outputs of inference for the Table Question Answering task
|
| Method resolution order:
| TableQuestionAnsweringOutputElement
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, answer: str, cells: list[str], coordinates: list[list[int]], aggregator: str | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'aggregator': str | None, 'answer': <class 'str'>, ...
|
| __dataclass_fields__ = {'aggregator': Field(name='aggregator',type=str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('answer', 'cells', 'coordinates', 'aggregator')
|
| aggregator = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TableQuestionAnsweringParameters
Python Library Documentation: class TableQuestionAnsweringParameters in module huggingface_hub.inference._generated.types.table_question_answering
class TableQuestionAnsweringParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TableQuestionAnsweringParameters(padding: Optional[ForwardRef('Padding')] = None, sequential: bool | None = None, truncation: bool | None = None) -> None
|
| Additional inference parameters for Table Question Answering
|
| Method resolution order:
| TableQuestionAnsweringParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, padding: Optional[ForwardRef('Padding')] = None, sequential: bool | None = None, truncation: bool | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'padding': typing.Optional[ForwardRef('Padding')], ...
|
| __dataclass_fields__ = {'padding': Field(name='padding',type=typing.Op...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('padding', 'sequential', 'truncation')
|
| padding = None
|
| sequential = None
|
| truncation = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.Text2TextGenerationInput
Python Library Documentation: class Text2TextGenerationInput in module huggingface_hub.inference._generated.types.text2text_generation
class Text2TextGenerationInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| Text2TextGenerationInput(inputs: str, parameters: huggingface_hub.inference._generated.types.text2text_generation.Text2TextGenerationParameters | None = None) -> None
|
| Inputs for Text2text Generation inference
|
| Method resolution order:
| Text2TextGenerationInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: str, parameters: huggingface_hub.inference._generated.types.text2text_generation.Text2TextGenerationParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'str'>, 'parameters': huggingface_...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.Text2TextGenerationOutput
Python Library Documentation: class Text2TextGenerationOutput in module huggingface_hub.inference._generated.types.text2text_generation
class Text2TextGenerationOutput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| Text2TextGenerationOutput(generated_text: Any, text2_text_generation_output_generated_text: str | None = None) -> None
|
| Outputs of inference for the Text2text Generation task
|
| Method resolution order:
| Text2TextGenerationOutput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, generated_text: Any, text2_text_generation_output_generated_text: str | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'generated_text': typing.Any, 'text2_text_generatio...
|
| __dataclass_fields__ = {'generated_text': Field(name='generated_text',...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('generated_text', 'text2_text_generation_output_gene...
|
| text2_text_generation_output_generated_text = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.Text2TextGenerationParameters
Python Library Documentation: class Text2TextGenerationParameters in module huggingface_hub.inference._generated.types.text2text_generation
class Text2TextGenerationParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| Text2TextGenerationParameters(clean_up_tokenization_spaces: bool | None = None, generate_parameters: dict[str, typing.Any] | None = None, truncation: Optional[ForwardRef('Text2TextGenerationTruncationStrategy')] = None) -> None
|
| Additional inference parameters for Text2text Generation
|
| Method resolution order:
| Text2TextGenerationParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, clean_up_tokenization_spaces: bool | None = None, generate_parameters: dict[str, typing.Any] | None = None, truncation: Optional[ForwardRef('Text2TextGenerationTruncationStrategy')] = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'clean_up_tokenization_spaces': bool | None, 'gener...
|
| __dataclass_fields__ = {'clean_up_tokenization_spaces': Field(name='cl...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('clean_up_tokenization_spaces', 'generate_parameters...
|
| clean_up_tokenization_spaces = None
|
| generate_parameters = None
|
| truncation = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.Text2TextGenerationTruncationStrategy
Python Library Documentation: _LiteralGenericAlias in module typing
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
huggingface-hub.TextClassificationInput
Python Library Documentation: class TextClassificationInput in module huggingface_hub.inference._generated.types.text_classification
class TextClassificationInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextClassificationInput(inputs: str, parameters: huggingface_hub.inference._generated.types.text_classification.TextClassificationParameters | None = None) -> None
|
| Inputs for Text Classification inference
|
| Method resolution order:
| TextClassificationInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: str, parameters: huggingface_hub.inference._generated.types.text_classification.TextClassificationParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'str'>, 'parameters': huggingface_...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextClassificationOutputElement
Python Library Documentation: class TextClassificationOutputElement in module huggingface_hub.inference._generated.types.text_classification
class TextClassificationOutputElement(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextClassificationOutputElement(label: str, score: float) -> None
|
| Outputs of inference for the Text Classification task
|
| Method resolution order:
| TextClassificationOutputElement
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, label: str, score: float) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'label': <class 'str'>, 'score': <class 'float'>}
|
| __dataclass_fields__ = {'label': Field(name='label',type=<class 'str'>...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('label', 'score')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextClassificationOutputTransform
Python Library Documentation: _LiteralGenericAlias in module typing
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
huggingface-hub.TextClassificationParameters
Python Library Documentation: class TextClassificationParameters in module huggingface_hub.inference._generated.types.text_classification
class TextClassificationParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextClassificationParameters(function_to_apply: Optional[ForwardRef('TextClassificationOutputTransform')] = None, top_k: int | None = None) -> None
|
| Additional inference parameters for Text Classification
|
| Method resolution order:
| TextClassificationParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, function_to_apply: Optional[ForwardRef('TextClassificationOutputTransform')] = None, top_k: int | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'function_to_apply': typing.Optional[ForwardRef('Te...
|
| __dataclass_fields__ = {'function_to_apply': Field(name='function_to_a...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('function_to_apply', 'top_k')
|
| function_to_apply = None
|
| top_k = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextGenerationInput
Python Library Documentation: class TextGenerationInput in module huggingface_hub.inference._generated.types.text_generation
class TextGenerationInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextGenerationInput(inputs: str, parameters: huggingface_hub.inference._generated.types.text_generation.TextGenerationInputGenerateParameters | None = None, stream: bool | None = None) -> None
|
| Text Generation Input.
| Auto-generated from TGI specs.
| For more details, check out
| https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tgi-import.ts.
|
| Method resolution order:
| TextGenerationInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: str, parameters: huggingface_hub.inference._generated.types.text_generation.TextGenerationInputGenerateParameters | None = None, stream: bool | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'str'>, 'parameters': huggingface_...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters', 'stream')
|
| parameters = None
|
| stream = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextGenerationInputGenerateParameters
Python Library Documentation: class TextGenerationInputGenerateParameters in module huggingface_hub.inference._generated.types.text_generation
class TextGenerationInputGenerateParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextGenerationInputGenerateParameters(adapter_id: str | None = None, best_of: int | None = None, decoder_input_details: bool | None = None, details: bool | None = None, do_sample: bool | None = None, frequency_penalty: float | None = None, grammar: huggingface_hub.inference._generated.types.text_generation.TextGenerationInputGrammarType | None = None, max_new_tokens: int | None = None, repetition_penalty: float | None = None, return_full_text: bool | None = None, seed: int | None = None, stop: list[str] | None = None, temperature: float | None = None, top_k: int | None = None, top_n_tokens: int | None = None, top_p: float | None = None, truncate: int | None = None, typical_p: float | None = None, watermark: bool | None = None) -> None
|
| TextGenerationInputGenerateParameters(adapter_id: str | None = None, best_of: int | None = None, decoder_input_details: bool | None = None, details: bool | None = None, do_sample: bool | None = None, frequency_penalty: float | None = None, grammar: huggingface_hub.inference._generated.types.text_generation.TextGenerationInputGrammarType | None = None, max_new_tokens: int | None = None, repetition_penalty: float | None = None, return_full_text: bool | None = None, seed: int | None = None, stop: list[str] | None = None, temperature: float | None = None, top_k: int | None = None, top_n_tokens: int | None = None, top_p: float | None = None, truncate: int | None = None, typical_p: float | None = None, watermark: bool | None = None)
|
| Method resolution order:
| TextGenerationInputGenerateParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, adapter_id: str | None = None, best_of: int | None = None, decoder_input_details: bool | None = None, details: bool | None = None, do_sample: bool | None = None, frequency_penalty: float | None = None, grammar: huggingface_hub.inference._generated.types.text_generation.TextGenerationInputGrammarType | None = None, max_new_tokens: int | None = None, repetition_penalty: float | None = None, return_full_text: bool | None = None, seed: int | None = None, stop: list[str] | None = None, temperature: float | None = None, top_k: int | None = None, top_n_tokens: int | None = None, top_p: float | None = None, truncate: int | None = None, typical_p: float | None = None, watermark: bool | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'adapter_id': str | None, 'best_of': int | None, 'd...
|
| __dataclass_fields__ = {'adapter_id': Field(name='adapter_id',type=str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('adapter_id', 'best_of', 'decoder_input_details', 'd...
|
| adapter_id = None
|
| best_of = None
|
| decoder_input_details = None
|
| details = None
|
| do_sample = None
|
| frequency_penalty = None
|
| grammar = None
|
| max_new_tokens = None
|
| repetition_penalty = None
|
| return_full_text = None
|
| seed = None
|
| stop = None
|
| temperature = None
|
| top_k = None
|
| top_n_tokens = None
|
| top_p = None
|
| truncate = None
|
| typical_p = None
|
| watermark = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextGenerationInputGrammarType
Python Library Documentation: class TextGenerationInputGrammarType in module huggingface_hub.inference._generated.types.text_generation
class TextGenerationInputGrammarType(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextGenerationInputGrammarType(type: 'TypeEnum', value: Any) -> None
|
| TextGenerationInputGrammarType(type: 'TypeEnum', value: Any)
|
| Method resolution order:
| TextGenerationInputGrammarType
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, type: 'TypeEnum', value: Any) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'type': 'TypeEnum', 'value': typing.Any}
|
| __dataclass_fields__ = {'type': Field(name='type',type='TypeEnum',defa...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('type', 'value')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextGenerationOutput
Python Library Documentation: class TextGenerationOutput in module huggingface_hub.inference._generated.types.text_generation
class TextGenerationOutput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextGenerationOutput(generated_text: str, details: huggingface_hub.inference._generated.types.text_generation.TextGenerationOutputDetails | None = None) -> None
|
| Text Generation Output.
| Auto-generated from TGI specs.
| For more details, check out
| https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tgi-import.ts.
|
| Method resolution order:
| TextGenerationOutput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, generated_text: str, details: huggingface_hub.inference._generated.types.text_generation.TextGenerationOutputDetails | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'details': huggingface_hub.inference._generated.typ...
|
| __dataclass_fields__ = {'details': Field(name='details',type=huggingfa...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('generated_text', 'details')
|
| details = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextGenerationOutputBestOfSequence
Python Library Documentation: class TextGenerationOutputBestOfSequence in module huggingface_hub.inference._generated.types.text_generation
class TextGenerationOutputBestOfSequence(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextGenerationOutputBestOfSequence(finish_reason: 'TextGenerationOutputFinishReason', generated_text: str, generated_tokens: int, prefill: list[huggingface_hub.inference._generated.types.text_generation.TextGenerationOutputPrefillToken], tokens: list[huggingface_hub.inference._generated.types.text_generation.TextGenerationOutputToken], seed: int | None = None, top_tokens: list[list[huggingface_hub.inference._generated.types.text_generation.TextGenerationOutputToken]] | None = None) -> None
|
| TextGenerationOutputBestOfSequence(finish_reason: 'TextGenerationOutputFinishReason', generated_text: str, generated_tokens: int, prefill: list[huggingface_hub.inference._generated.types.text_generation.TextGenerationOutputPrefillToken], tokens: list[huggingface_hub.inference._generated.types.text_generation.TextGenerationOutputToken], seed: int | None = None, top_tokens: list[list[huggingface_hub.inference._generated.types.text_generation.TextGenerationOutputToken]] | None = None)
|
| Method resolution order:
| TextGenerationOutputBestOfSequence
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, finish_reason: 'TextGenerationOutputFinishReason', generated_text: str, generated_tokens: int, prefill: list[huggingface_hub.inference._generated.types.text_generation.TextGenerationOutputPrefillToken], tokens: list[huggingface_hub.inference._generated.types.text_generation.TextGenerationOutputToken], seed: int | None = None, top_tokens: list[list[huggingface_hub.inference._generated.types.text_generation.TextGenerationOutputToken]] | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'finish_reason': 'TextGenerationOutputFinishReason'...
|
| __dataclass_fields__ = {'finish_reason': Field(name='finish_reason',ty...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('finish_reason', 'generated_text', 'generated_tokens...
|
| seed = None
|
| top_tokens = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextGenerationOutputDetails
Python Library Documentation: class TextGenerationOutputDetails in module huggingface_hub.inference._generated.types.text_generation
class TextGenerationOutputDetails(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextGenerationOutputDetails(finish_reason: 'TextGenerationOutputFinishReason', generated_tokens: int, prefill: list[huggingface_hub.inference._generated.types.text_generation.TextGenerationOutputPrefillToken], tokens: list[huggingface_hub.inference._generated.types.text_generation.TextGenerationOutputToken], best_of_sequences: list[huggingface_hub.inference._generated.types.text_generation.TextGenerationOutputBestOfSequence] | None = None, seed: int | None = None, top_tokens: list[list[huggingface_hub.inference._generated.types.text_generation.TextGenerationOutputToken]] | None = None) -> None
|
| TextGenerationOutputDetails(finish_reason: 'TextGenerationOutputFinishReason', generated_tokens: int, prefill: list[huggingface_hub.inference._generated.types.text_generation.TextGenerationOutputPrefillToken], tokens: list[huggingface_hub.inference._generated.types.text_generation.TextGenerationOutputToken], best_of_sequences: list[huggingface_hub.inference._generated.types.text_generation.TextGenerationOutputBestOfSequence] | None = None, seed: int | None = None, top_tokens: list[list[huggingface_hub.inference._generated.types.text_generation.TextGenerationOutputToken]] | None = None)
|
| Method resolution order:
| TextGenerationOutputDetails
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, finish_reason: 'TextGenerationOutputFinishReason', generated_tokens: int, prefill: list[huggingface_hub.inference._generated.types.text_generation.TextGenerationOutputPrefillToken], tokens: list[huggingface_hub.inference._generated.types.text_generation.TextGenerationOutputToken], best_of_sequences: list[huggingface_hub.inference._generated.types.text_generation.TextGenerationOutputBestOfSequence] | None = None, seed: int | None = None, top_tokens: list[list[huggingface_hub.inference._generated.types.text_generation.TextGenerationOutputToken]] | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'best_of_sequences': list[huggingface_hub.inference...
|
| __dataclass_fields__ = {'best_of_sequences': Field(name='best_of_seque...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('finish_reason', 'generated_tokens', 'prefill', 'tok...
|
| best_of_sequences = None
|
| seed = None
|
| top_tokens = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextGenerationOutputFinishReason
Python Library Documentation: _LiteralGenericAlias in module typing
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
huggingface-hub.TextGenerationOutputPrefillToken
Python Library Documentation: class TextGenerationOutputPrefillToken in module huggingface_hub.inference._generated.types.text_generation
class TextGenerationOutputPrefillToken(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextGenerationOutputPrefillToken(id: int, logprob: float, text: str) -> None
|
| TextGenerationOutputPrefillToken(id: int, logprob: float, text: str)
|
| Method resolution order:
| TextGenerationOutputPrefillToken
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, id: int, logprob: float, text: str) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'id': <class 'int'>, 'logprob': <class 'float'>, 't...
|
| __dataclass_fields__ = {'id': Field(name='id',type=<class 'int'>,defau...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('id', 'logprob', 'text')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextGenerationOutputToken
Python Library Documentation: class TextGenerationOutputToken in module huggingface_hub.inference._generated.types.text_generation
class TextGenerationOutputToken(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextGenerationOutputToken(id: int, logprob: float, special: bool, text: str) -> None
|
| TextGenerationOutputToken(id: int, logprob: float, special: bool, text: str)
|
| Method resolution order:
| TextGenerationOutputToken
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, id: int, logprob: float, special: bool, text: str) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'id': <class 'int'>, 'logprob': <class 'float'>, 's...
|
| __dataclass_fields__ = {'id': Field(name='id',type=<class 'int'>,defau...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('id', 'logprob', 'special', 'text')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextGenerationStreamOutput
Python Library Documentation: class TextGenerationStreamOutput in module huggingface_hub.inference._generated.types.text_generation
class TextGenerationStreamOutput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextGenerationStreamOutput(index: int, token: huggingface_hub.inference._generated.types.text_generation.TextGenerationStreamOutputToken, details: huggingface_hub.inference._generated.types.text_generation.TextGenerationStreamOutputStreamDetails | None = None, generated_text: str | None = None, top_tokens: list[huggingface_hub.inference._generated.types.text_generation.TextGenerationStreamOutputToken] | None = None) -> None
|
| Text Generation Stream Output.
| Auto-generated from TGI specs.
| For more details, check out
| https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tgi-import.ts.
|
| Method resolution order:
| TextGenerationStreamOutput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, index: int, token: huggingface_hub.inference._generated.types.text_generation.TextGenerationStreamOutputToken, details: huggingface_hub.inference._generated.types.text_generation.TextGenerationStreamOutputStreamDetails | None = None, generated_text: str | None = None, top_tokens: list[huggingface_hub.inference._generated.types.text_generation.TextGenerationStreamOutputToken] | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'details': huggingface_hub.inference._generated.typ...
|
| __dataclass_fields__ = {'details': Field(name='details',type=huggingfa...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('index', 'token', 'details', 'generated_text', 'top_...
|
| details = None
|
| generated_text = None
|
| top_tokens = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextGenerationStreamOutputStreamDetails
Python Library Documentation: class TextGenerationStreamOutputStreamDetails in module huggingface_hub.inference._generated.types.text_generation
class TextGenerationStreamOutputStreamDetails(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextGenerationStreamOutputStreamDetails(finish_reason: 'TextGenerationOutputFinishReason', generated_tokens: int, input_length: int, seed: int | None = None) -> None
|
| TextGenerationStreamOutputStreamDetails(finish_reason: 'TextGenerationOutputFinishReason', generated_tokens: int, input_length: int, seed: int | None = None)
|
| Method resolution order:
| TextGenerationStreamOutputStreamDetails
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, finish_reason: 'TextGenerationOutputFinishReason', generated_tokens: int, input_length: int, seed: int | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'finish_reason': 'TextGenerationOutputFinishReason'...
|
| __dataclass_fields__ = {'finish_reason': Field(name='finish_reason',ty...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('finish_reason', 'generated_tokens', 'input_length',...
|
| seed = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextGenerationStreamOutputToken
Python Library Documentation: class TextGenerationStreamOutputToken in module huggingface_hub.inference._generated.types.text_generation
class TextGenerationStreamOutputToken(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextGenerationStreamOutputToken(id: int, logprob: float, special: bool, text: str) -> None
|
| TextGenerationStreamOutputToken(id: int, logprob: float, special: bool, text: str)
|
| Method resolution order:
| TextGenerationStreamOutputToken
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, id: int, logprob: float, special: bool, text: str) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'id': <class 'int'>, 'logprob': <class 'float'>, 's...
|
| __dataclass_fields__ = {'id': Field(name='id',type=<class 'int'>,defau...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('id', 'logprob', 'special', 'text')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextToAudioEarlyStoppingEnum
Python Library Documentation: _LiteralGenericAlias in module typing
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
huggingface-hub.TextToAudioGenerationParameters
Python Library Documentation: class TextToAudioGenerationParameters in module huggingface_hub.inference._generated.types.text_to_audio
class TextToAudioGenerationParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextToAudioGenerationParameters(do_sample: bool | None = None, early_stopping: Union[bool, ForwardRef('TextToAudioEarlyStoppingEnum'), NoneType] = None, epsilon_cutoff: float | None = None, eta_cutoff: float | None = None, max_length: int | None = None, max_new_tokens: int | None = None, min_length: int | None = None, min_new_tokens: int | None = None, num_beam_groups: int | None = None, num_beams: int | None = None, penalty_alpha: float | None = None, temperature: float | None = None, top_k: int | None = None, top_p: float | None = None, typical_p: float | None = None, use_cache: bool | None = None) -> None
|
| Parametrization of the text generation process
|
| Method resolution order:
| TextToAudioGenerationParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, do_sample: bool | None = None, early_stopping: Union[bool, ForwardRef('TextToAudioEarlyStoppingEnum'), NoneType] = None, epsilon_cutoff: float | None = None, eta_cutoff: float | None = None, max_length: int | None = None, max_new_tokens: int | None = None, min_length: int | None = None, min_new_tokens: int | None = None, num_beam_groups: int | None = None, num_beams: int | None = None, penalty_alpha: float | None = None, temperature: float | None = None, top_k: int | None = None, top_p: float | None = None, typical_p: float | None = None, use_cache: bool | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'do_sample': bool | None, 'early_stopping': typing....
|
| __dataclass_fields__ = {'do_sample': Field(name='do_sample',type=bool ...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('do_sample', 'early_stopping', 'epsilon_cutoff', 'et...
|
| do_sample = None
|
| early_stopping = None
|
| epsilon_cutoff = None
|
| eta_cutoff = None
|
| max_length = None
|
| max_new_tokens = None
|
| min_length = None
|
| min_new_tokens = None
|
| num_beam_groups = None
|
| num_beams = None
|
| penalty_alpha = None
|
| temperature = None
|
| top_k = None
|
| top_p = None
|
| typical_p = None
|
| use_cache = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextToAudioInput
Python Library Documentation: class TextToAudioInput in module huggingface_hub.inference._generated.types.text_to_audio
class TextToAudioInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextToAudioInput(inputs: str, parameters: huggingface_hub.inference._generated.types.text_to_audio.TextToAudioParameters | None = None) -> None
|
| Inputs for Text To Audio inference
|
| Method resolution order:
| TextToAudioInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: str, parameters: huggingface_hub.inference._generated.types.text_to_audio.TextToAudioParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'str'>, 'parameters': huggingface_...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextToAudioOutput
Python Library Documentation: class TextToAudioOutput in module huggingface_hub.inference._generated.types.text_to_audio
class TextToAudioOutput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextToAudioOutput(audio: Any, sampling_rate: float) -> None
|
| Outputs of inference for the Text To Audio task
|
| Method resolution order:
| TextToAudioOutput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, audio: Any, sampling_rate: float) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'audio': typing.Any, 'sampling_rate': <class 'float...
|
| __dataclass_fields__ = {'audio': Field(name='audio',type=typing.Any,de...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('audio', 'sampling_rate')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextToAudioParameters
Python Library Documentation: class TextToAudioParameters in module huggingface_hub.inference._generated.types.text_to_audio
class TextToAudioParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextToAudioParameters(generation_parameters: huggingface_hub.inference._generated.types.text_to_audio.TextToAudioGenerationParameters | None = None) -> None
|
| Additional inference parameters for Text To Audio
|
| Method resolution order:
| TextToAudioParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, generation_parameters: huggingface_hub.inference._generated.types.text_to_audio.TextToAudioGenerationParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'generation_parameters': huggingface_hub.inference....
|
| __dataclass_fields__ = {'generation_parameters': Field(name='generatio...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('generation_parameters',)
|
| generation_parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextToImageInput
Python Library Documentation: class TextToImageInput in module huggingface_hub.inference._generated.types.text_to_image
class TextToImageInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextToImageInput(inputs: str, parameters: huggingface_hub.inference._generated.types.text_to_image.TextToImageParameters | None = None) -> None
|
| Inputs for Text To Image inference
|
| Method resolution order:
| TextToImageInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: str, parameters: huggingface_hub.inference._generated.types.text_to_image.TextToImageParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'str'>, 'parameters': huggingface_...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextToImageOutput
Python Library Documentation: class TextToImageOutput in module huggingface_hub.inference._generated.types.text_to_image
class TextToImageOutput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextToImageOutput(image: Any) -> None
|
| Outputs of inference for the Text To Image task
|
| Method resolution order:
| TextToImageOutput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, image: Any) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'image': typing.Any}
|
| __dataclass_fields__ = {'image': Field(name='image',type=typing.Any,de...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('image',)
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextToImageParameters
Python Library Documentation: class TextToImageParameters in module huggingface_hub.inference._generated.types.text_to_image
class TextToImageParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextToImageParameters(guidance_scale: float | None = None, height: int | None = None, negative_prompt: str | None = None, num_inference_steps: int | None = None, scheduler: str | None = None, seed: int | None = None, width: int | None = None) -> None
|
| Additional inference parameters for Text To Image
|
| Method resolution order:
| TextToImageParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, guidance_scale: float | None = None, height: int | None = None, negative_prompt: str | None = None, num_inference_steps: int | None = None, scheduler: str | None = None, seed: int | None = None, width: int | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'guidance_scale': float | None, 'height': int | Non...
|
| __dataclass_fields__ = {'guidance_scale': Field(name='guidance_scale',...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('guidance_scale', 'height', 'negative_prompt', 'num_...
|
| guidance_scale = None
|
| height = None
|
| negative_prompt = None
|
| num_inference_steps = None
|
| scheduler = None
|
| seed = None
|
| width = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextToSpeechEarlyStoppingEnum
Python Library Documentation: _LiteralGenericAlias in module typing
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
huggingface-hub.TextToSpeechGenerationParameters
Python Library Documentation: class TextToSpeechGenerationParameters in module huggingface_hub.inference._generated.types.text_to_speech
class TextToSpeechGenerationParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextToSpeechGenerationParameters(do_sample: bool | None = None, early_stopping: Union[bool, ForwardRef('TextToSpeechEarlyStoppingEnum'), NoneType] = None, epsilon_cutoff: float | None = None, eta_cutoff: float | None = None, max_length: int | None = None, max_new_tokens: int | None = None, min_length: int | None = None, min_new_tokens: int | None = None, num_beam_groups: int | None = None, num_beams: int | None = None, penalty_alpha: float | None = None, temperature: float | None = None, top_k: int | None = None, top_p: float | None = None, typical_p: float | None = None, use_cache: bool | None = None) -> None
|
| Parametrization of the text generation process
|
| Method resolution order:
| TextToSpeechGenerationParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, do_sample: bool | None = None, early_stopping: Union[bool, ForwardRef('TextToSpeechEarlyStoppingEnum'), NoneType] = None, epsilon_cutoff: float | None = None, eta_cutoff: float | None = None, max_length: int | None = None, max_new_tokens: int | None = None, min_length: int | None = None, min_new_tokens: int | None = None, num_beam_groups: int | None = None, num_beams: int | None = None, penalty_alpha: float | None = None, temperature: float | None = None, top_k: int | None = None, top_p: float | None = None, typical_p: float | None = None, use_cache: bool | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'do_sample': bool | None, 'early_stopping': typing....
|
| __dataclass_fields__ = {'do_sample': Field(name='do_sample',type=bool ...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('do_sample', 'early_stopping', 'epsilon_cutoff', 'et...
|
| do_sample = None
|
| early_stopping = None
|
| epsilon_cutoff = None
|
| eta_cutoff = None
|
| max_length = None
|
| max_new_tokens = None
|
| min_length = None
|
| min_new_tokens = None
|
| num_beam_groups = None
|
| num_beams = None
|
| penalty_alpha = None
|
| temperature = None
|
| top_k = None
|
| top_p = None
|
| typical_p = None
|
| use_cache = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextToSpeechInput
Python Library Documentation: class TextToSpeechInput in module huggingface_hub.inference._generated.types.text_to_speech
class TextToSpeechInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextToSpeechInput(inputs: str, parameters: huggingface_hub.inference._generated.types.text_to_speech.TextToSpeechParameters | None = None) -> None
|
| Inputs for Text To Speech inference
|
| Method resolution order:
| TextToSpeechInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: str, parameters: huggingface_hub.inference._generated.types.text_to_speech.TextToSpeechParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'str'>, 'parameters': huggingface_...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextToSpeechOutput
Python Library Documentation: class TextToSpeechOutput in module huggingface_hub.inference._generated.types.text_to_speech
class TextToSpeechOutput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextToSpeechOutput(audio: Any, sampling_rate: float | None = None) -> None
|
| Outputs of inference for the Text To Speech task
|
| Method resolution order:
| TextToSpeechOutput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, audio: Any, sampling_rate: float | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'audio': typing.Any, 'sampling_rate': float | None}
|
| __dataclass_fields__ = {'audio': Field(name='audio',type=typing.Any,de...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('audio', 'sampling_rate')
|
| sampling_rate = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextToSpeechParameters
Python Library Documentation: class TextToSpeechParameters in module huggingface_hub.inference._generated.types.text_to_speech
class TextToSpeechParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextToSpeechParameters(generation_parameters: huggingface_hub.inference._generated.types.text_to_speech.TextToSpeechGenerationParameters | None = None) -> None
|
| Additional inference parameters for Text To Speech
|
| Method resolution order:
| TextToSpeechParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, generation_parameters: huggingface_hub.inference._generated.types.text_to_speech.TextToSpeechGenerationParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'generation_parameters': huggingface_hub.inference....
|
| __dataclass_fields__ = {'generation_parameters': Field(name='generatio...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('generation_parameters',)
|
| generation_parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextToVideoInput
Python Library Documentation: class TextToVideoInput in module huggingface_hub.inference._generated.types.text_to_video
class TextToVideoInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextToVideoInput(inputs: str, parameters: huggingface_hub.inference._generated.types.text_to_video.TextToVideoParameters | None = None) -> None
|
| Inputs for Text To Video inference
|
| Method resolution order:
| TextToVideoInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: str, parameters: huggingface_hub.inference._generated.types.text_to_video.TextToVideoParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'str'>, 'parameters': huggingface_...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextToVideoOutput
Python Library Documentation: class TextToVideoOutput in module huggingface_hub.inference._generated.types.text_to_video
class TextToVideoOutput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextToVideoOutput(video: Any) -> None
|
| Outputs of inference for the Text To Video task
|
| Method resolution order:
| TextToVideoOutput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, video: Any) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'video': typing.Any}
|
| __dataclass_fields__ = {'video': Field(name='video',type=typing.Any,de...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('video',)
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TextToVideoParameters
Python Library Documentation: class TextToVideoParameters in module huggingface_hub.inference._generated.types.text_to_video
class TextToVideoParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TextToVideoParameters(guidance_scale: float | None = None, negative_prompt: list[str] | None = None, num_frames: float | None = None, num_inference_steps: int | None = None, seed: int | None = None) -> None
|
| Additional inference parameters for Text To Video
|
| Method resolution order:
| TextToVideoParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, guidance_scale: float | None = None, negative_prompt: list[str] | None = None, num_frames: float | None = None, num_inference_steps: int | None = None, seed: int | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'guidance_scale': float | None, 'negative_prompt': ...
|
| __dataclass_fields__ = {'guidance_scale': Field(name='guidance_scale',...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('guidance_scale', 'negative_prompt', 'num_frames', '...
|
| guidance_scale = None
|
| negative_prompt = None
|
| num_frames = None
|
| num_inference_steps = None
|
| seed = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TokenClassificationAggregationStrategy
Python Library Documentation: _LiteralGenericAlias in module typing
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
huggingface-hub.TokenClassificationInput
Python Library Documentation: class TokenClassificationInput in module huggingface_hub.inference._generated.types.token_classification
class TokenClassificationInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TokenClassificationInput(inputs: str, parameters: huggingface_hub.inference._generated.types.token_classification.TokenClassificationParameters | None = None) -> None
|
| Inputs for Token Classification inference
|
| Method resolution order:
| TokenClassificationInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: str, parameters: huggingface_hub.inference._generated.types.token_classification.TokenClassificationParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'str'>, 'parameters': huggingface_...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TokenClassificationOutputElement
Python Library Documentation: class TokenClassificationOutputElement in module huggingface_hub.inference._generated.types.token_classification
class TokenClassificationOutputElement(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TokenClassificationOutputElement(end: int, score: float, start: int, word: str, entity: str | None = None, entity_group: str | None = None) -> None
|
| Outputs of inference for the Token Classification task
|
| Method resolution order:
| TokenClassificationOutputElement
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, end: int, score: float, start: int, word: str, entity: str | None = None, entity_group: str | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'end': <class 'int'>, 'entity': str | None, 'entity...
|
| __dataclass_fields__ = {'end': Field(name='end',type=<class 'int'>,def...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('end', 'score', 'start', 'word', 'entity', 'entity_g...
|
| entity = None
|
| entity_group = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TokenClassificationParameters
Python Library Documentation: class TokenClassificationParameters in module huggingface_hub.inference._generated.types.token_classification
class TokenClassificationParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TokenClassificationParameters(aggregation_strategy: Optional[ForwardRef('TokenClassificationAggregationStrategy')] = None, ignore_labels: list[str] | None = None, stride: int | None = None) -> None
|
| Additional inference parameters for Token Classification
|
| Method resolution order:
| TokenClassificationParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, aggregation_strategy: Optional[ForwardRef('TokenClassificationAggregationStrategy')] = None, ignore_labels: list[str] | None = None, stride: int | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'aggregation_strategy': typing.Optional[ForwardRef(...
|
| __dataclass_fields__ = {'aggregation_strategy': Field(name='aggregatio...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('aggregation_strategy', 'ignore_labels', 'stride')
|
| aggregation_strategy = None
|
| ignore_labels = None
|
| stride = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TranslationInput
Python Library Documentation: class TranslationInput in module huggingface_hub.inference._generated.types.translation
class TranslationInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TranslationInput(inputs: str, parameters: huggingface_hub.inference._generated.types.translation.TranslationParameters | None = None) -> None
|
| Inputs for Translation inference
|
| Method resolution order:
| TranslationInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: str, parameters: huggingface_hub.inference._generated.types.translation.TranslationParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'str'>, 'parameters': huggingface_...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TranslationOutput
Python Library Documentation: class TranslationOutput in module huggingface_hub.inference._generated.types.translation
class TranslationOutput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TranslationOutput(translation_text: str) -> None
|
| Outputs of inference for the Translation task
|
| Method resolution order:
| TranslationOutput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, translation_text: str) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'translation_text': <class 'str'>}
|
| __dataclass_fields__ = {'translation_text': Field(name='translation_te...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('translation_text',)
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TranslationParameters
Python Library Documentation: class TranslationParameters in module huggingface_hub.inference._generated.types.translation
class TranslationParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| TranslationParameters(clean_up_tokenization_spaces: bool | None = None, generate_parameters: dict[str, typing.Any] | None = None, src_lang: str | None = None, tgt_lang: str | None = None, truncation: Optional[ForwardRef('TranslationTruncationStrategy')] = None) -> None
|
| Additional inference parameters for Translation
|
| Method resolution order:
| TranslationParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, clean_up_tokenization_spaces: bool | None = None, generate_parameters: dict[str, typing.Any] | None = None, src_lang: str | None = None, tgt_lang: str | None = None, truncation: Optional[ForwardRef('TranslationTruncationStrategy')] = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'clean_up_tokenization_spaces': bool | None, 'gener...
|
| __dataclass_fields__ = {'clean_up_tokenization_spaces': Field(name='cl...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('clean_up_tokenization_spaces', 'generate_parameters...
|
| clean_up_tokenization_spaces = None
|
| generate_parameters = None
|
| src_lang = None
|
| tgt_lang = None
|
| truncation = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.TranslationTruncationStrategy
Python Library Documentation: _LiteralGenericAlias in module typing
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
huggingface-hub.TypeEnum
Python Library Documentation: _LiteralGenericAlias in module typing
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
huggingface-hub.User
Python Library Documentation: class User in module huggingface_hub.hf_api
class User(builtins.object)
| User(**kwargs) -> 'None'
|
| Contains information about a user on the Hub.
|
| Attributes:
| username (`str`):
| Name of the user on the Hub (unique).
| fullname (`str`):
| User's full name.
| avatar_url (`str`):
| URL of the user's avatar.
| details (`str`, *optional*):
| User's details.
| is_following (`bool`, *optional*):
| Whether the authenticated user is following this user.
| is_pro (`bool`, *optional*):
| Whether the user is a pro user.
| num_models (`int`, *optional*):
| Number of models created by the user.
| num_datasets (`int`, *optional*):
| Number of datasets created by the user.
| num_spaces (`int`, *optional*):
| Number of spaces created by the user.
| num_discussions (`int`, *optional*):
| Number of discussions initiated by the user.
| num_papers (`int`, *optional*):
| Number of papers authored by the user.
| num_upvotes (`int`, *optional*):
| Number of upvotes received by the user.
| num_likes (`int`, *optional*):
| Number of likes given by the user.
| num_following (`int`, *optional*):
| Number of users this user is following.
| num_followers (`int`, *optional*):
| Number of users following this user.
| orgs (list of [`Organization`]):
| List of organizations the user is part of.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, **kwargs) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'avatar_url': 'str', 'details': 'str | None', 'full...
|
| __dataclass_fields__ = {'avatar_url': Field(name='avatar_url',type='st...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('username', 'fullname', 'avatar_url', 'details', 'is...
|
| details = None
|
| is_following = None
|
| is_pro = None
|
| num_datasets = None
|
| num_discussions = None
|
| num_followers = None
|
| num_following = None
|
| num_likes = None
|
| num_models = None
|
| num_papers = None
|
| num_spaces = None
|
| num_upvotes = None
huggingface-hub.UserLikes
Python Library Documentation: class UserLikes in module huggingface_hub.hf_api
class UserLikes(builtins.object)
| UserLikes(user: 'str', total: 'int', datasets: 'list[str]', kernels: 'list[str]', models: 'list[str]', spaces: 'list[str]') -> None
|
| Contains information about a user likes on the Hub.
|
| Attributes:
| user (`str`):
| Name of the user for which we fetched the likes.
| total (`int`):
| Total number of likes.
| datasets (`list[str]`):
| List of datasets liked by the user (as repo_ids).
| kernels (`list[str]`):
| List of kernels liked by the user (as repo_ids).
| models (`list[str]`):
| List of models liked by the user (as repo_ids).
| spaces (`list[str]`):
| List of spaces liked by the user (as repo_ids).
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, user: 'str', total: 'int', datasets: 'list[str]', kernels: 'list[str]', models: 'list[str]', spaces: 'list[str]') -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'datasets': 'list[str]', 'kernels': 'list[str]', 'm...
|
| __dataclass_fields__ = {'datasets': Field(name='datasets',type='list[s...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('user', 'total', 'datasets', 'kernels', 'models', 's...
huggingface-hub.VideoClassificationInput
Python Library Documentation: class VideoClassificationInput in module huggingface_hub.inference._generated.types.video_classification
class VideoClassificationInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| VideoClassificationInput(inputs: Any, parameters: huggingface_hub.inference._generated.types.video_classification.VideoClassificationParameters | None = None) -> None
|
| Inputs for Video Classification inference
|
| Method resolution order:
| VideoClassificationInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: Any, parameters: huggingface_hub.inference._generated.types.video_classification.VideoClassificationParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': typing.Any, 'parameters': huggingface_hub...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=typing.Any,...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.VideoClassificationOutputElement
Python Library Documentation: class VideoClassificationOutputElement in module huggingface_hub.inference._generated.types.video_classification
class VideoClassificationOutputElement(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| VideoClassificationOutputElement(label: str, score: float) -> None
|
| Outputs of inference for the Video Classification task
|
| Method resolution order:
| VideoClassificationOutputElement
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, label: str, score: float) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'label': <class 'str'>, 'score': <class 'float'>}
|
| __dataclass_fields__ = {'label': Field(name='label',type=<class 'str'>...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('label', 'score')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.VideoClassificationOutputTransform
Python Library Documentation: _LiteralGenericAlias in module typing
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
huggingface-hub.VideoClassificationParameters
Python Library Documentation: class VideoClassificationParameters in module huggingface_hub.inference._generated.types.video_classification
class VideoClassificationParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| VideoClassificationParameters(frame_sampling_rate: int | None = None, function_to_apply: Optional[ForwardRef('VideoClassificationOutputTransform')] = None, num_frames: int | None = None, top_k: int | None = None) -> None
|
| Additional inference parameters for Video Classification
|
| Method resolution order:
| VideoClassificationParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, frame_sampling_rate: int | None = None, function_to_apply: Optional[ForwardRef('VideoClassificationOutputTransform')] = None, num_frames: int | None = None, top_k: int | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'frame_sampling_rate': int | None, 'function_to_app...
|
| __dataclass_fields__ = {'frame_sampling_rate': Field(name='frame_sampl...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('frame_sampling_rate', 'function_to_apply', 'num_fra...
|
| frame_sampling_rate = None
|
| function_to_apply = None
|
| num_frames = None
|
| top_k = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.VisualQuestionAnsweringInput
Python Library Documentation: class VisualQuestionAnsweringInput in module huggingface_hub.inference._generated.types.visual_question_answering
class VisualQuestionAnsweringInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| VisualQuestionAnsweringInput(inputs: huggingface_hub.inference._generated.types.visual_question_answering.VisualQuestionAnsweringInputData, parameters: huggingface_hub.inference._generated.types.visual_question_answering.VisualQuestionAnsweringParameters | None = None) -> None
|
| Inputs for Visual Question Answering inference
|
| Method resolution order:
| VisualQuestionAnsweringInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: huggingface_hub.inference._generated.types.visual_question_answering.VisualQuestionAnsweringInputData, parameters: huggingface_hub.inference._generated.types.visual_question_answering.VisualQuestionAnsweringParameters | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'huggingface_hub.inference._genera...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'hug...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| parameters = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.VisualQuestionAnsweringInputData
Python Library Documentation: class VisualQuestionAnsweringInputData in module huggingface_hub.inference._generated.types.visual_question_answering
class VisualQuestionAnsweringInputData(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| VisualQuestionAnsweringInputData(image: Any, question: str) -> None
|
| One (image, question) pair to answer
|
| Method resolution order:
| VisualQuestionAnsweringInputData
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, image: Any, question: str) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'image': typing.Any, 'question': <class 'str'>}
|
| __dataclass_fields__ = {'image': Field(name='image',type=typing.Any,de...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('image', 'question')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.VisualQuestionAnsweringOutputElement
Python Library Documentation: class VisualQuestionAnsweringOutputElement in module huggingface_hub.inference._generated.types.visual_question_answering
class VisualQuestionAnsweringOutputElement(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| VisualQuestionAnsweringOutputElement(score: float, answer: str | None = None) -> None
|
| Outputs of inference for the Visual Question Answering task
|
| Method resolution order:
| VisualQuestionAnsweringOutputElement
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, score: float, answer: str | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'answer': str | None, 'score': <class 'float'>}
|
| __dataclass_fields__ = {'answer': Field(name='answer',type=str | None,...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('score', 'answer')
|
| answer = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.VisualQuestionAnsweringParameters
Python Library Documentation: class VisualQuestionAnsweringParameters in module huggingface_hub.inference._generated.types.visual_question_answering
class VisualQuestionAnsweringParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| VisualQuestionAnsweringParameters(top_k: int | None = None) -> None
|
| Additional inference parameters for Visual Question Answering
|
| Method resolution order:
| VisualQuestionAnsweringParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, top_k: int | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'top_k': int | None}
|
| __dataclass_fields__ = {'top_k': Field(name='top_k',type=int | None,de...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('top_k',)
|
| top_k = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.Volume
Python Library Documentation: class Volume in module huggingface_hub._space_api
class Volume(builtins.object)
| Volume(**kwargs) -> None
|
| Describes a volume to mount in a Space or Job container.
|
| Args:
| type (`str`):
| Type of volume: `"bucket"`, `"model"`, `"dataset"`, or `"space"`.
| source (`str`):
| Source identifier, e.g. `"username/my-bucket"` or `"username/my-model"`.
| mount_path (`str`):
| Mount path inside the container, e.g. `"/data"`. Must start with `/`.
| revision (`str` or `None`):
| Git revision (only for repos, defaults to `"main"`).
| read_only (`bool` or `None`):
| Read-only mount. Forced `True` for repos, defaults to `False` for buckets.
| path (`str` or `None`):
| Subfolder prefix inside the bucket/repo to mount, e.g. `"path/to/dir"`.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, **kwargs) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| to_dict(self) -> dict
| Serialize to the JSON payload expected by the Hub API.
|
| to_uri(self) -> str
| Return the volume as an HF mount URI in the format expected by the CLI.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'mount_path': <class 'str'>, 'path': str | None, 'r...
|
| __dataclass_fields__ = {'mount_path': Field(name='mount_path',type=<cl...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('type', 'source', 'mount_path', 'revision', 'read_on...
|
| path = None
|
| read_only = None
|
| revision = None
huggingface-hub.WebhookInfo
Python Library Documentation: class WebhookInfo in module huggingface_hub.hf_api
class WebhookInfo(builtins.object)
| WebhookInfo(id: 'str', url: 'str | None', job: 'JobSpec | None', watched: 'list[WebhookWatchedItem]', domains: 'list[constants.WEBHOOK_DOMAIN_T]', secret: 'str | None', disabled: 'bool') -> None
|
| Data structure containing information about a webhook.
|
| One of `url` or `job` is specified, but not both.
|
| Attributes:
| id (`str`):
| ID of the webhook.
| url (`str`, *optional*):
| URL of the webhook.
| job (`JobSpec`, *optional*):
| Specifications of the Job to trigger.
| watched (`list[WebhookWatchedItem]`):
| List of items watched by the webhook, see [`WebhookWatchedItem`].
| domains (`list[WEBHOOK_DOMAIN_T]`):
| List of domains the webhook is watching. Can be one of `["repo", "discussions"]`.
| secret (`str`, *optional*):
| Secret of the webhook.
| disabled (`bool`):
| Whether the webhook is disabled or not.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, id: 'str', url: 'str | None', job: 'JobSpec | None', watched: 'list[WebhookWatchedItem]', domains: 'list[constants.WEBHOOK_DOMAIN_T]', secret: 'str | None', disabled: 'bool') -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'disabled': 'bool', 'domains': 'list[constants.WEBH...
|
| __dataclass_fields__ = {'disabled': Field(name='disabled',type='bool',...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('id', 'url', 'job', 'watched', 'domains', 'secret', ...
huggingface-hub.WebhookPayload
Python Library Documentation: class WebhookPayload in module huggingface_hub._webhooks_payload
class WebhookPayload(pydantic.main.BaseModel)
| WebhookPayload(*, event: huggingface_hub._webhooks_payload.WebhookPayloadEvent, repo: huggingface_hub._webhooks_payload.WebhookPayloadRepo, discussion: huggingface_hub._webhooks_payload.WebhookPayloadDiscussion | None = None, comment: huggingface_hub._webhooks_payload.WebhookPayloadComment | None = None, webhook: huggingface_hub._webhooks_payload.WebhookPayloadWebhook, movedTo: huggingface_hub._webhooks_payload.WebhookPayloadMovedTo | None = None, updatedRefs: list[huggingface_hub._webhooks_payload.WebhookPayloadUpdatedRef] | None = None) -> None
|
| Method resolution order:
| WebhookPayload
| pydantic.main.BaseModel
| builtins.object
|
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'comment': huggingface_hub._webhooks_payload.Webhoo...
|
| __class_vars__ = set()
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'cls': <class 'huggingface_hub._webhooks_p...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'comment': FieldInfo(annotation=Union[WebhookPa...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="WebhookPayload", valid...
|
| __signature__ = <Signature (*, event: huggingface_hub._webhooks_...Web...
|
| model_config = {}
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| __str__(self) -> 'str'
| Return str(self).
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'Any') -> 'Self'
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_construct(_fields_set: 'set[str] | None' = None, **values: 'Any') -> 'Self'
| Creates a new instance of the `Model` class with validated data.
|
| Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
| Default values are respected, but no other validation is performed.
|
| !!! note
| `model_construct()` generally respects the `model_config.extra` setting on the provided model.
| That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
| and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
| Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
| an error if extra values are passed, but they will be ignored.
|
| Args:
| _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
| this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
| Otherwise, the field names from the `values` argument will be used.
| values: Trusted or pre-validated data dictionary.
|
| Returns:
| A new instance of the `Model` class with validated data.
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'comment': FieldInfo(annotation=Union[WebhookPayloadCo...
huggingface-hub.WebhookPayloadComment
Python Library Documentation: class WebhookPayloadComment in module huggingface_hub._webhooks_payload
class WebhookPayloadComment(ObjectId)
| WebhookPayloadComment(*, id: str, author: huggingface_hub._webhooks_payload.ObjectId, hidden: bool, content: str | None = None, url: huggingface_hub._webhooks_payload.WebhookPayloadUrl) -> None
|
| Method resolution order:
| WebhookPayloadComment
| ObjectId
| pydantic.main.BaseModel
| builtins.object
|
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'author': <class 'huggingface_hub._webhooks_payload...
|
| __class_vars__ = set()
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'cls': <class 'huggingface_hub._webhooks_p...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'author': FieldInfo(annotation=ObjectId, requir...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="WebhookPayloadComment"...
|
| __signature__ = <Signature (*, id: str, author: huggingface_hub....hub...
|
| model_config = {}
|
| ----------------------------------------------------------------------
| Data descriptors inherited from ObjectId:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| __str__(self) -> 'str'
| Return str(self).
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'Any') -> 'Self'
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_construct(_fields_set: 'set[str] | None' = None, **values: 'Any') -> 'Self'
| Creates a new instance of the `Model` class with validated data.
|
| Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
| Default values are respected, but no other validation is performed.
|
| !!! note
| `model_construct()` generally respects the `model_config.extra` setting on the provided model.
| That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
| and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
| Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
| an error if extra values are passed, but they will be ignored.
|
| Args:
| _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
| this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
| Otherwise, the field names from the `values` argument will be used.
| values: Trusted or pre-validated data dictionary.
|
| Returns:
| A new instance of the `Model` class with validated data.
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'author': FieldInfo(annotation=ObjectId, required=True...
huggingface-hub.WebhookPayloadDiscussion
Python Library Documentation: class WebhookPayloadDiscussion in module huggingface_hub._webhooks_payload
class WebhookPayloadDiscussion(ObjectId)
| WebhookPayloadDiscussion(*, id: str, num: int, author: huggingface_hub._webhooks_payload.ObjectId, url: huggingface_hub._webhooks_payload.WebhookPayloadUrl, title: str, isPullRequest: bool, status: Literal['closed', 'draft', 'open', 'merged'], changes: huggingface_hub._webhooks_payload.WebhookPayloadDiscussionChanges | None = None, pinned: bool | None = None) -> None
|
| Method resolution order:
| WebhookPayloadDiscussion
| ObjectId
| pydantic.main.BaseModel
| builtins.object
|
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'author': <class 'huggingface_hub._webhooks_payload...
|
| __class_vars__ = set()
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'cls': <class 'huggingface_hub._webhooks_p...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'author': FieldInfo(annotation=ObjectId, requir...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="WebhookPayloadDiscussi...
|
| __signature__ = <Signature (*, id: str, num: int, author: huggin...Non...
|
| model_config = {}
|
| ----------------------------------------------------------------------
| Data descriptors inherited from ObjectId:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| __str__(self) -> 'str'
| Return str(self).
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'Any') -> 'Self'
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_construct(_fields_set: 'set[str] | None' = None, **values: 'Any') -> 'Self'
| Creates a new instance of the `Model` class with validated data.
|
| Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
| Default values are respected, but no other validation is performed.
|
| !!! note
| `model_construct()` generally respects the `model_config.extra` setting on the provided model.
| That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
| and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
| Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
| an error if extra values are passed, but they will be ignored.
|
| Args:
| _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
| this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
| Otherwise, the field names from the `values` argument will be used.
| values: Trusted or pre-validated data dictionary.
|
| Returns:
| A new instance of the `Model` class with validated data.
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'author': FieldInfo(annotation=ObjectId, required=True...
huggingface-hub.WebhookPayloadDiscussionChanges
Python Library Documentation: class WebhookPayloadDiscussionChanges in module huggingface_hub._webhooks_payload
class WebhookPayloadDiscussionChanges(pydantic.main.BaseModel)
| WebhookPayloadDiscussionChanges(*, base: str, mergeCommitId: str | None = None) -> None
|
| Method resolution order:
| WebhookPayloadDiscussionChanges
| pydantic.main.BaseModel
| builtins.object
|
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'base': <class 'str'>, 'mergeCommitId': str | None}
|
| __class_vars__ = set()
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'cls': <class 'huggingface_hub._webhooks_p...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'base': FieldInfo(annotation=str, required=True...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="WebhookPayloadDiscussi...
|
| __signature__ = <Signature (*, base: str, mergeCommitId: str | None = ...
|
| model_config = {}
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| __str__(self) -> 'str'
| Return str(self).
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'Any') -> 'Self'
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_construct(_fields_set: 'set[str] | None' = None, **values: 'Any') -> 'Self'
| Creates a new instance of the `Model` class with validated data.
|
| Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
| Default values are respected, but no other validation is performed.
|
| !!! note
| `model_construct()` generally respects the `model_config.extra` setting on the provided model.
| That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
| and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
| Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
| an error if extra values are passed, but they will be ignored.
|
| Args:
| _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
| this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
| Otherwise, the field names from the `values` argument will be used.
| values: Trusted or pre-validated data dictionary.
|
| Returns:
| A new instance of the `Model` class with validated data.
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'base': FieldInfo(annotation=str, required=True), 'mer...
huggingface-hub.WebhookPayloadEvent
Python Library Documentation: class WebhookPayloadEvent in module huggingface_hub._webhooks_payload
class WebhookPayloadEvent(pydantic.main.BaseModel)
| WebhookPayloadEvent(*, action: Literal['create', 'delete', 'move', 'update'], scope: str) -> None
|
| Method resolution order:
| WebhookPayloadEvent
| pydantic.main.BaseModel
| builtins.object
|
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'action': typing.Literal['create', 'delete', 'move'...
|
| __class_vars__ = set()
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'cls': <class 'huggingface_hub._webhooks_p...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'action': FieldInfo(annotation=Literal['create'...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="WebhookPayloadEvent", ...
|
| __signature__ = <Signature (*, action: Literal['create', 'delete', 'mo...
|
| model_config = {}
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| __str__(self) -> 'str'
| Return str(self).
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'Any') -> 'Self'
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_construct(_fields_set: 'set[str] | None' = None, **values: 'Any') -> 'Self'
| Creates a new instance of the `Model` class with validated data.
|
| Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
| Default values are respected, but no other validation is performed.
|
| !!! note
| `model_construct()` generally respects the `model_config.extra` setting on the provided model.
| That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
| and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
| Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
| an error if extra values are passed, but they will be ignored.
|
| Args:
| _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
| this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
| Otherwise, the field names from the `values` argument will be used.
| values: Trusted or pre-validated data dictionary.
|
| Returns:
| A new instance of the `Model` class with validated data.
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'action': FieldInfo(annotation=Literal['create', 'dele...
huggingface-hub.WebhookPayloadMovedTo
Python Library Documentation: class WebhookPayloadMovedTo in module huggingface_hub._webhooks_payload
class WebhookPayloadMovedTo(pydantic.main.BaseModel)
| WebhookPayloadMovedTo(*, name: str, owner: huggingface_hub._webhooks_payload.ObjectId) -> None
|
| Method resolution order:
| WebhookPayloadMovedTo
| pydantic.main.BaseModel
| builtins.object
|
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'name': <class 'str'>, 'owner': <class 'huggingface...
|
| __class_vars__ = set()
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'cls': <class 'huggingface_hub._webhooks_p...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'name': FieldInfo(annotation=str, required=True...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="WebhookPayloadMovedTo"...
|
| __signature__ = <Signature (*, name: str, owner: huggingface_hub._webh...
|
| model_config = {}
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| __str__(self) -> 'str'
| Return str(self).
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'Any') -> 'Self'
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_construct(_fields_set: 'set[str] | None' = None, **values: 'Any') -> 'Self'
| Creates a new instance of the `Model` class with validated data.
|
| Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
| Default values are respected, but no other validation is performed.
|
| !!! note
| `model_construct()` generally respects the `model_config.extra` setting on the provided model.
| That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
| and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
| Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
| an error if extra values are passed, but they will be ignored.
|
| Args:
| _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
| this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
| Otherwise, the field names from the `values` argument will be used.
| values: Trusted or pre-validated data dictionary.
|
| Returns:
| A new instance of the `Model` class with validated data.
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'name': FieldInfo(annotation=str, required=True), 'own...
huggingface-hub.WebhookPayloadRepo
Python Library Documentation: class WebhookPayloadRepo in module huggingface_hub._webhooks_payload
class WebhookPayloadRepo(ObjectId)
| WebhookPayloadRepo(*, id: str, owner: huggingface_hub._webhooks_payload.ObjectId, head_sha: str | None = None, name: str, private: bool, subdomain: str | None = None, tags: list[str] | None = None, type: Literal['dataset', 'model', 'space'], url: huggingface_hub._webhooks_payload.WebhookPayloadUrl) -> None
|
| Method resolution order:
| WebhookPayloadRepo
| ObjectId
| pydantic.main.BaseModel
| builtins.object
|
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'head_sha': str | None, 'name': <class 'str'>, 'own...
|
| __class_vars__ = set()
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'cls': <class 'huggingface_hub._webhooks_p...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'head_sha': FieldInfo(annotation=Union[str, Non...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="WebhookPayloadRepo", v...
|
| __signature__ = <Signature (*, id: str, owner: huggingface_hub._...hub...
|
| model_config = {}
|
| ----------------------------------------------------------------------
| Data descriptors inherited from ObjectId:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| __str__(self) -> 'str'
| Return str(self).
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'Any') -> 'Self'
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_construct(_fields_set: 'set[str] | None' = None, **values: 'Any') -> 'Self'
| Creates a new instance of the `Model` class with validated data.
|
| Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
| Default values are respected, but no other validation is performed.
|
| !!! note
| `model_construct()` generally respects the `model_config.extra` setting on the provided model.
| That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
| and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
| Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
| an error if extra values are passed, but they will be ignored.
|
| Args:
| _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
| this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
| Otherwise, the field names from the `values` argument will be used.
| values: Trusted or pre-validated data dictionary.
|
| Returns:
| A new instance of the `Model` class with validated data.
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'head_sha': FieldInfo(annotation=Union[str, NoneType],...
huggingface-hub.WebhookPayloadUrl
Python Library Documentation: class WebhookPayloadUrl in module huggingface_hub._webhooks_payload
class WebhookPayloadUrl(pydantic.main.BaseModel)
| WebhookPayloadUrl(*, web: str, api: str | None = None) -> None
|
| Method resolution order:
| WebhookPayloadUrl
| pydantic.main.BaseModel
| builtins.object
|
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'api': str | None, 'web': <class 'str'>}
|
| __class_vars__ = set()
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'cls': <class 'huggingface_hub._webhooks_p...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'api': FieldInfo(annotation=Union[str, NoneType...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="WebhookPayloadUrl", va...
|
| __signature__ = <Signature (*, web: str, api: str | None = None) -> No...
|
| model_config = {}
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| __str__(self) -> 'str'
| Return str(self).
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'Any') -> 'Self'
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_construct(_fields_set: 'set[str] | None' = None, **values: 'Any') -> 'Self'
| Creates a new instance of the `Model` class with validated data.
|
| Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
| Default values are respected, but no other validation is performed.
|
| !!! note
| `model_construct()` generally respects the `model_config.extra` setting on the provided model.
| That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
| and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
| Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
| an error if extra values are passed, but they will be ignored.
|
| Args:
| _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
| this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
| Otherwise, the field names from the `values` argument will be used.
| values: Trusted or pre-validated data dictionary.
|
| Returns:
| A new instance of the `Model` class with validated data.
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'api': FieldInfo(annotation=Union[str, NoneType], requ...
huggingface-hub.WebhookPayloadWebhook
Python Library Documentation: class WebhookPayloadWebhook in module huggingface_hub._webhooks_payload
class WebhookPayloadWebhook(ObjectId)
| WebhookPayloadWebhook(*, id: str, version: Literal[3]) -> None
|
| Method resolution order:
| WebhookPayloadWebhook
| ObjectId
| pydantic.main.BaseModel
| builtins.object
|
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'version': typing.Literal[3]}
|
| __class_vars__ = set()
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'cls': <class 'huggingface_hub._webhooks_p...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'id': FieldInfo(annotation=str, required=True),...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="WebhookPayloadWebhook"...
|
| __signature__ = <Signature (*, id: str, version: Literal[3]) -> None>
|
| model_config = {}
|
| ----------------------------------------------------------------------
| Data descriptors inherited from ObjectId:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| __str__(self) -> 'str'
| Return str(self).
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'Any') -> 'Self'
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_construct(_fields_set: 'set[str] | None' = None, **values: 'Any') -> 'Self'
| Creates a new instance of the `Model` class with validated data.
|
| Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
| Default values are respected, but no other validation is performed.
|
| !!! note
| `model_construct()` generally respects the `model_config.extra` setting on the provided model.
| That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
| and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
| Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
| an error if extra values are passed, but they will be ignored.
|
| Args:
| _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
| this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
| Otherwise, the field names from the `values` argument will be used.
| values: Trusted or pre-validated data dictionary.
|
| Returns:
| A new instance of the `Model` class with validated data.
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'id': FieldInfo(annotation=str, required=True), 'versi...
huggingface-hub.WebhookWatchedItem
Python Library Documentation: class WebhookWatchedItem in module huggingface_hub.hf_api
class WebhookWatchedItem(builtins.object)
| WebhookWatchedItem(type: "Literal['dataset', 'model', 'org', 'space', 'user']", name: 'str') -> None
|
| Data structure containing information about the items watched by a webhook.
|
| Attributes:
| type (`Literal["dataset", "model", "org", "space", "user"]`):
| Type of the item to be watched. Can be one of `["dataset", "model", "org", "space", "user"]`.
| name (`str`):
| Name of the item to be watched. Can be the username, organization name, model name, dataset name or space name.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, type: "Literal['dataset', 'model', 'org', 'space', 'user']", name: 'str') -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'name': 'str', 'type': "Literal['dataset', 'model',...
|
| __dataclass_fields__ = {'name': Field(name='name',type='str',default=<...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('type', 'name')
huggingface-hub.WebhooksServer
Python Library Documentation: function WebhooksServer in module huggingface_hub._webhooks_server
WebhooksServer(*args, **kwargs) -> '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. Once all the webhooks are registered, the `launch` method has to be
called to start the app.
It is recommended to accept [`WebhookPayload`] as the first argument of the webhook function. It is a Pydantic
model that contains all the information about the webhook event. The data will be parsed automatically for you.
Check out the [webhooks guide](../guides/webhooks_server) for a step-by-step tutorial on how to set up your
WebhooksServer and deploy it on a Space.
> [!WARNING]
> `WebhooksServer` is experimental. Its API is subject to change in the future.
> [!WARNING]
> You must have `gradio` installed to use `WebhooksServer` (`pip install --upgrade gradio`).
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.
webhook_secret (`str`, optional):
A secret key to verify incoming webhook requests. You can set this value to any secret you want as long as
you also configure it in your [webhooks settings panel](https://huggingface.co/settings/webhooks). You
can also set this value as the `WEBHOOK_SECRET` environment variable. If no secret is provided, the
webhook endpoints are opened without any security.
Example:
```python
import gradio as gr
from huggingface_hub import WebhooksServer, WebhookPayload
with gr.Blocks() as ui:
...
app = WebhooksServer(ui=ui, webhook_secret="my_secret_key")
@app.add_webhook("/say_hello")
async def hello(payload: WebhookPayload):
return {"message": "hello"}
app.launch()
```
huggingface-hub.ZeroShotClassificationInput
Python Library Documentation: class ZeroShotClassificationInput in module huggingface_hub.inference._generated.types.zero_shot_classification
class ZeroShotClassificationInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ZeroShotClassificationInput(inputs: str, parameters: huggingface_hub.inference._generated.types.zero_shot_classification.ZeroShotClassificationParameters) -> None
|
| Inputs for Zero Shot Classification inference
|
| Method resolution order:
| ZeroShotClassificationInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: str, parameters: huggingface_hub.inference._generated.types.zero_shot_classification.ZeroShotClassificationParameters) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'str'>, 'parameters': <class 'hugg...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ZeroShotClassificationOutputElement
Python Library Documentation: class ZeroShotClassificationOutputElement in module huggingface_hub.inference._generated.types.zero_shot_classification
class ZeroShotClassificationOutputElement(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ZeroShotClassificationOutputElement(label: str, score: float) -> None
|
| Outputs of inference for the Zero Shot Classification task
|
| Method resolution order:
| ZeroShotClassificationOutputElement
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, label: str, score: float) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'label': <class 'str'>, 'score': <class 'float'>}
|
| __dataclass_fields__ = {'label': Field(name='label',type=<class 'str'>...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('label', 'score')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ZeroShotClassificationParameters
Python Library Documentation: class ZeroShotClassificationParameters in module huggingface_hub.inference._generated.types.zero_shot_classification
class ZeroShotClassificationParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ZeroShotClassificationParameters(candidate_labels: list[str], hypothesis_template: str | None = None, multi_label: bool | None = None) -> None
|
| Additional inference parameters for Zero Shot Classification
|
| Method resolution order:
| ZeroShotClassificationParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, candidate_labels: list[str], hypothesis_template: str | None = None, multi_label: bool | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'candidate_labels': list[str], 'hypothesis_template...
|
| __dataclass_fields__ = {'candidate_labels': Field(name='candidate_labe...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('candidate_labels', 'hypothesis_template', 'multi_la...
|
| hypothesis_template = None
|
| multi_label = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ZeroShotImageClassificationInput
Python Library Documentation: class ZeroShotImageClassificationInput in module huggingface_hub.inference._generated.types.zero_shot_image_classification
class ZeroShotImageClassificationInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ZeroShotImageClassificationInput(inputs: str, parameters: huggingface_hub.inference._generated.types.zero_shot_image_classification.ZeroShotImageClassificationParameters) -> None
|
| Inputs for Zero Shot Image Classification inference
|
| Method resolution order:
| ZeroShotImageClassificationInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: str, parameters: huggingface_hub.inference._generated.types.zero_shot_image_classification.ZeroShotImageClassificationParameters) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'str'>, 'parameters': <class 'hugg...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ZeroShotImageClassificationOutputElement
Python Library Documentation: class ZeroShotImageClassificationOutputElement in module huggingface_hub.inference._generated.types.zero_shot_image_classification
class ZeroShotImageClassificationOutputElement(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ZeroShotImageClassificationOutputElement(label: str, score: float) -> None
|
| Outputs of inference for the Zero Shot Image Classification task
|
| Method resolution order:
| ZeroShotImageClassificationOutputElement
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, label: str, score: float) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'label': <class 'str'>, 'score': <class 'float'>}
|
| __dataclass_fields__ = {'label': Field(name='label',type=<class 'str'>...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('label', 'score')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ZeroShotImageClassificationParameters
Python Library Documentation: class ZeroShotImageClassificationParameters in module huggingface_hub.inference._generated.types.zero_shot_image_classification
class ZeroShotImageClassificationParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ZeroShotImageClassificationParameters(candidate_labels: list[str], hypothesis_template: str | None = None) -> None
|
| Additional inference parameters for Zero Shot Image Classification
|
| Method resolution order:
| ZeroShotImageClassificationParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, candidate_labels: list[str], hypothesis_template: str | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'candidate_labels': list[str], 'hypothesis_template...
|
| __dataclass_fields__ = {'candidate_labels': Field(name='candidate_labe...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('candidate_labels', 'hypothesis_template')
|
| hypothesis_template = None
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ZeroShotObjectDetectionBoundingBox
Python Library Documentation: class ZeroShotObjectDetectionBoundingBox in module huggingface_hub.inference._generated.types.zero_shot_object_detection
class ZeroShotObjectDetectionBoundingBox(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ZeroShotObjectDetectionBoundingBox(xmax: int, xmin: int, ymax: int, ymin: int) -> None
|
| The predicted bounding box. Coordinates are relative to the top left corner of the input
| image.
|
| Method resolution order:
| ZeroShotObjectDetectionBoundingBox
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, xmax: int, xmin: int, ymax: int, ymin: int) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'xmax': <class 'int'>, 'xmin': <class 'int'>, 'ymax...
|
| __dataclass_fields__ = {'xmax': Field(name='xmax',type=<class 'int'>,d...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('xmax', 'xmin', 'ymax', 'ymin')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ZeroShotObjectDetectionInput
Python Library Documentation: class ZeroShotObjectDetectionInput in module huggingface_hub.inference._generated.types.zero_shot_object_detection
class ZeroShotObjectDetectionInput(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ZeroShotObjectDetectionInput(inputs: str, parameters: huggingface_hub.inference._generated.types.zero_shot_object_detection.ZeroShotObjectDetectionParameters) -> None
|
| Inputs for Zero Shot Object Detection inference
|
| Method resolution order:
| ZeroShotObjectDetectionInput
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, inputs: str, parameters: huggingface_hub.inference._generated.types.zero_shot_object_detection.ZeroShotObjectDetectionParameters) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'inputs': <class 'str'>, 'parameters': <class 'hugg...
|
| __dataclass_fields__ = {'inputs': Field(name='inputs',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('inputs', 'parameters')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ZeroShotObjectDetectionOutputElement
Python Library Documentation: class ZeroShotObjectDetectionOutputElement in module huggingface_hub.inference._generated.types.zero_shot_object_detection
class ZeroShotObjectDetectionOutputElement(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ZeroShotObjectDetectionOutputElement(box: huggingface_hub.inference._generated.types.zero_shot_object_detection.ZeroShotObjectDetectionBoundingBox, label: str, score: float) -> None
|
| Outputs of inference for the Zero Shot Object Detection task
|
| Method resolution order:
| ZeroShotObjectDetectionOutputElement
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, box: huggingface_hub.inference._generated.types.zero_shot_object_detection.ZeroShotObjectDetectionBoundingBox, label: str, score: float) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'box': <class 'huggingface_hub.inference._generated...
|
| __dataclass_fields__ = {'box': Field(name='box',type=<class 'huggingfa...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('box', 'label', 'score')
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.ZeroShotObjectDetectionParameters
Python Library Documentation: class ZeroShotObjectDetectionParameters in module huggingface_hub.inference._generated.types.zero_shot_object_detection
class ZeroShotObjectDetectionParameters(huggingface_hub.inference._generated.types.base.BaseInferenceType)
| ZeroShotObjectDetectionParameters(candidate_labels: list[str]) -> None
|
| Additional inference parameters for Zero Shot Object Detection
|
| Method resolution order:
| ZeroShotObjectDetectionParameters
| huggingface_hub.inference._generated.types.base.BaseInferenceType
| builtins.dict
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, candidate_labels: list[str]) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = _repr_with_extra(self) from huggingface_hub.inference._generated.types.base
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'candidate_labels': list[str]}
|
| __dataclass_fields__ = {'candidate_labels': Field(name='candidate_labe...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('candidate_labels',)
|
| ----------------------------------------------------------------------
| Methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __post_init__(self)
|
| __setattr__(self, _BaseInferenceType__name: str, _BaseInferenceType__value: Any) -> None
| Implement setattr(self, name, value).
|
| __setitem__(self, _BaseInferenceType__key: Any, _BaseInferenceType__value: Any) -> None
| Set self[key] to value.
|
| ----------------------------------------------------------------------
| Class methods inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| parse_obj(data: bytes | str | list | dict) -> Union[list[~T], ~T]
| Parse server response as a dataclass or list of dataclasses.
|
| To enable future-compatibility, we want to handle cases where the server return more fields than expected.
| In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
| added as dict attributes.
|
| parse_obj_as_instance(data: bytes | str | list | dict) -> ~T
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| parse_obj_as_list(data: bytes | str | list | dict) -> list[~T]
| Alias to parse server response and return a single instance.
|
| See `parse_obj` for more details.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from huggingface_hub.inference._generated.types.base.BaseInferenceType:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
huggingface-hub.accept_access_request
Python Library Documentation: method accept_access_request in module huggingface_hub.hf_api
accept_access_request(repo_id: 'str', user: 'str', *, repo_type: 'str | None' = None, token: 'bool | str | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Accept an access request from a user for a given gated repo.
Once the request is accepted, the user will be able to download any file of the repo and access the community
tab. If the approval mode is automatic, you don't have to accept requests manually. An accepted request can be
cancelled or rejected at any time using [`cancel_access_request`] and [`reject_access_request`].
For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
Args:
repo_id (`str`):
The id of the repo to accept access request for.
user (`str`):
The username of the user which access request should be accepted.
repo_type (`str`, *optional*):
The type of the repo to accept access request for. Must be one of `model`, `dataset` or `space`.
Defaults to `model`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Raises:
[`HfHubHTTPError`]:
HTTP 400 if the repo is not gated.
[`HfHubHTTPError`]:
HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
or `admin` role in the organization the repo belongs to or if you passed a `read` token.
[`HfHubHTTPError`]:
HTTP 404 if the user does not exist on the Hub.
[`HfHubHTTPError`]:
HTTP 404 if the user access request cannot be found.
[`HfHubHTTPError`]:
HTTP 404 if the user access request is already in the accepted list.
huggingface-hub.add_collection_item
Python Library Documentation: method add_collection_item in module huggingface_hub.hf_api
add_collection_item(collection_slug: 'str', item_id: 'str', item_type: 'CollectionItemType_T', *, note: 'str | None' = None, exists_ok: 'bool' = False, token: 'bool | str | None' = None) -> 'Collection' method of huggingface_hub.hf_api.HfApi instance
Add an item to a collection on the Hub.
Args:
collection_slug (`str`):
Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
item_id (`str`):
Id of the item to add to the collection. Use the repo_id for repos/spaces/datasets,
the paper id for papers, the slug of another collection (e.g. `"moonshotai/kimi-k2"`)
or a bucket id (e.g. `"namespace/bucket-name"`).
item_type (`str`):
Type of the item to add. Can be one of `"model"`, `"dataset"`, `"space"`, `"paper"`, `"collection"`
or `"bucket"`.
note (`str`, *optional*):
A note to attach to the item in the collection. The maximum size for a note is 500 characters.
exists_ok (`bool`, *optional*):
If `True`, do not raise an error if item already exists.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns: [`Collection`]
Raises:
[`HfHubHTTPError`]:
HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
or `admin` role in the organization the repo belongs to or if you passed a `read` token.
[`HfHubHTTPError`]:
HTTP 404 if the item you try to add to the collection does not exist on the Hub.
[`HfHubHTTPError`]:
HTTP 409 if the item you try to add to the collection is already in the collection (and exists_ok=False)
Example:
```py
>>> from huggingface_hub import add_collection_item
>>> collection = add_collection_item(
... collection_slug="davanstrien/climate-64f99dc2a5067f6b65531bab",
... item_id="pierre-loic/climate-news-articles",
... item_type="dataset"
... )
>>> collection.items[-1].item_id
"pierre-loic/climate-news-articles"
# ^item got added to the collection on last position
# Add item with a note
>>> add_collection_item(
... collection_slug="davanstrien/climate-64f99dc2a5067f6b65531bab",
... item_id="datasets/climate_fever",
... item_type="dataset"
... note="This dataset adopts the FEVER methodology that consists of 1,535 real-world claims regarding climate-change collected on the internet."
... )
(...)
```
huggingface-hub.add_space_secret
Python Library Documentation: method add_space_secret in module huggingface_hub.hf_api
add_space_secret(repo_id: 'str', key: 'str', value: 'str', *, description: 'str | None' = None, token: 'bool | str | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Adds or updates a secret in a Space.
Secrets allow to set secret keys or tokens to a Space without hardcoding them.
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
Args:
repo_id (`str`):
ID of the repo to update. Example: `"bigcode/in-the-stack"`.
key (`str`):
Secret key. Example: `"GITHUB_API_KEY"`
value (`str`):
Secret value. Example: `"your_github_api_key"`.
description (`str`, *optional*):
Secret description. Example: `"Github API key to access the Github API"`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
huggingface-hub.add_space_variable
Python Library Documentation: method add_space_variable in module huggingface_hub.hf_api
add_space_variable(repo_id: 'str', key: 'str', value: 'str', *, description: 'str | None' = None, token: 'bool | str | None' = None) -> 'dict[str, SpaceVariable]' method of huggingface_hub.hf_api.HfApi instance
Adds or updates a variable in a Space.
Variables allow to set environment variables to a Space without hardcoding them.
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables
Args:
repo_id (`str`):
ID of the repo to update. Example: `"bigcode/in-the-stack"`.
key (`str`):
Variable key. Example: `"MODEL_REPO_ID"`
value (`str`):
Variable value. Example: `"the_model_repo_id"`.
description (`str`):
Description of the variable. Example: `"Model Repo ID of the implemented model"`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
huggingface-hub.attach_huggingface_oauth
Python Library Documentation: function attach_huggingface_oauth in module huggingface_hub._oauth
attach_huggingface_oauth(app: 'fastapi.FastAPI', route_prefix: str = '/')
Add OAuth endpoints to a FastAPI app to enable OAuth login with Hugging Face.
How to use:
- Call this method on your FastAPI app to add the OAuth endpoints.
- Inside your route handlers, call `parse_huggingface_oauth(request)` to retrieve the OAuth info.
- If user is logged in, an [`OAuthInfo`] object is returned with the user's info. If not, `None` is returned.
- In your app, make sure to add links to `/oauth/huggingface/login` and `/oauth/huggingface/logout` for the user to log in and out.
Example:
```py
from huggingface_hub import attach_huggingface_oauth, parse_huggingface_oauth
# Create a FastAPI app
app = FastAPI()
# Add OAuth endpoints to the FastAPI app
attach_huggingface_oauth(app)
# Add a route that greets the user if they are logged in
@app.get("/")
def greet_json(request: Request):
# Retrieve the OAuth info from the request
oauth_info = parse_huggingface_oauth(request) # e.g. OAuthInfo dataclass
if oauth_info is None:
return {"msg": "Not logged in!"}
return {"msg": f"Hello, {oauth_info.user_info.preferred_username}!"}
```
huggingface-hub.auth_check
Python Library Documentation: method auth_check in module huggingface_hub.hf_api
auth_check(repo_id: 'str', *, repo_type: 'str | None' = None, token: 'bool | str | None' = None, write: 'bool' = False) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Check if the provided user token has access to a specific repository on the Hugging Face Hub.
This method verifies whether the user, authenticated via the provided token, has access to the specified
repository. If the repository is not found or if the user lacks the required permissions to access it,
the method raises an appropriate exception.
Args:
repo_id (`str`):
The repository to check for access. Format should be `"user/repo_name"`.
Example: `"user/my-cool-model"`.
repo_type (`str`, *optional*):
The type of the repository. Should be one of `"model"`, `"dataset"`, or `"space"`.
If not specified, the default is `"model"`.
token (`Union[bool, str, None]`, *optional*):
A valid user access token. If not provided, the locally saved token will be used, which is the
recommended authentication method. Set to `False` to disable authentication.
Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
write (`bool`, *optional*):
If `True`, checks whether the user has content write permission on the repository.
If `False` (default), only checks for read access.
Raises:
[`~utils.RepositoryNotFoundError`]:
Raised if the repository does not exist, is private, or the user does not have access. This can
occur if the `repo_id` or `repo_type` is incorrect or if the repository is private but the user
is not authenticated.
[`~utils.GatedRepoError`]:
Raised if the repository exists but is gated and the user is not authorized to access it.
Example:
Check if the user has access to a repository:
```python
>>> from huggingface_hub import auth_check
>>> from huggingface_hub.utils import GatedRepoError, RepositoryNotFoundError
try:
auth_check("user/my-cool-model")
except GatedRepoError:
# Handle gated repository error
print("You do not have permission to access this gated repository.")
except RepositoryNotFoundError:
# Handle repository not found error
print("The repository was not found or you do not have access.")
```
In this example:
- If the user has access, the method completes successfully.
- If the repository is gated or does not exist, appropriate exceptions are raised, allowing the user
to handle them accordingly.
huggingface-hub.auth_list
Python Library Documentation: function auth_list in module huggingface_hub._login
auth_list() -> None
List all stored access tokens.
huggingface-hub.auth_switch
Python Library Documentation: function auth_switch in module huggingface_hub._login
auth_switch(token_name: str, add_to_git_credential: bool = False) -> None
Switch to a different access token.
Args:
token_name (`str`):
Name of the access token to switch to.
add_to_git_credential (`bool`, defaults to `False`):
If `True`, token will be set as git credential. If no git credential helper
is configured, a warning will be displayed to the user. If `token` is `None`,
the value of `add_to_git_credential` is ignored and will be prompted again
to the end user.
Raises:
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError):
If the access token name is not found.
huggingface-hub.batch_bucket_files
Python Library Documentation: method batch_bucket_files in module huggingface_hub.hf_api
batch_bucket_files(bucket_id: 'str', *, add: 'list[tuple[str | Path | bytes, str]] | None' = None, copy: 'list[tuple[str, str, str, str]] | None' = None, delete: 'list[str] | None' = None, token: 'str | bool | None' = None) method of huggingface_hub.hf_api.HfApi instance
Add, copy, and/or delete files in a bucket.
This is a non-transactional operation. If an error occurs in the process, some files may have been uploaded,
copied, or deleted while others haven't.
Args:
bucket_id (`str`):
The ID of the bucket (e.g. `"username/my-bucket"`).
add (`list` of `tuple`, *optional*):
Files to upload. Each element is a `(source, destination)` tuple where `source` is a path to a local
file (`str` or `Path`) or raw `bytes` content, and `destination` is the path in the bucket.
copy (`list` of `tuple`, *optional*):
Files to copy by xet hash. Each element is a `(source_repo_type, source_repo_id, xet_hash,
destination)` tuple where:
- `source_repo_type` is the type of the source repository: `"model"`, `"dataset"`, `"space"`, or
`"bucket"`.
- `source_repo_id` is the ID of the source repository or bucket (e.g. `"username/my-model"`).
- `xet_hash` is the xet hash of the file to copy.
- `destination` is the destination path in the bucket.
This is a server-side operation — no data is downloaded or re-uploaded.
delete (`list` of `str`, *optional*):
Paths of files to delete from the bucket.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Example:
```python
>>> from huggingface_hub import batch_bucket_files
# Upload files
>>> batch_bucket_files(
... "username/my-bucket",
... add=[
... ("./model.safetensors", "models/model.safetensors"),
... (b'{{"key": "value"}}', "config.json"),
... ],
... )
# Copy xet files from another bucket or repo (server-side, no data transfer)
>>> batch_bucket_files(
... "username/my-bucket",
... copy=[
... ("bucket", "username/source-bucket", "<xethash_1>", "models/model.safetensors"),
... ("model", "username/my-model", "<xethash_2>", "models/config.safetensors"),
... ],
... )
# Delete files
>>> batch_bucket_files("username/my-bucket", delete=["old-model.bin"])
# Upload and delete in one batch
>>> batch_bucket_files(
... "username/my-bucket",
... add=[("./new.txt", "new.txt")],
... delete=["old.txt"],
... )
```
huggingface-hub.bucket_info
Python Library Documentation: method bucket_info in module huggingface_hub.hf_api
bucket_info(bucket_id: 'str', *, token: 'bool | str | None' = None) -> 'BucketInfo' method of huggingface_hub.hf_api.HfApi instance
Get information about a specific bucket on the Hub.
Args:
bucket_id (`str`):
The ID of the bucket (e.g. `"username/my-bucket"`).
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`BucketInfo`]: The bucket information.
Raises:
[`~errors.BucketNotFoundError`]: If the bucket cannot be found. This may be because it doesn't exist,
or because it is set to `private` and you do not have access.
Example:
```python
>>> from huggingface_hub import bucket_info
>>> info = bucket_info(bucket_id="Wauplin/first-bucket")
>>> info.id
'Wauplin/first-bucket'
>>> info.private
False
>>> info.created_at
datetime.datetime(2026, 2, 6, 17, 37, 57, tzinfo=datetime.timezone.utc)
>>> info.size
551879671
>>> info.total_files
12
```
huggingface-hub.cached_assets_path
Python Library Documentation: function cached_assets_path in module huggingface_hub.utils._cache_assets
cached_assets_path(library_name: str, namespace: str = 'default', subfolder: str = 'default', *, assets_dir: str | pathlib.Path | None = None) -> pathlib.Path
Return a folder path to cache arbitrary files.
`huggingface_hub` provides a canonical folder path to store assets. This is the
recommended way to integrate cache in a downstream library as it will benefit from
the builtins tools to scan and delete the cache properly.
The distinction is made between files cached from the Hub and assets. Files from the
Hub are cached in a git-aware manner and entirely managed by `huggingface_hub`. See
[related documentation](https://huggingface.co/docs/huggingface_hub/how-to-cache).
All other files that a downstream library caches are considered to be "assets"
(files downloaded from external sources, extracted from a .tar archive, preprocessed
for training,...).
Once the folder path is generated, it is guaranteed to exist and to be a directory.
The path is based on 3 levels of depth: the library name, a namespace and a
subfolder. Those 3 levels grants flexibility while allowing `huggingface_hub` to
expect folders when scanning/deleting parts of the assets cache. Within a library,
it is expected that all namespaces share the same subset of subfolder names but this
is not a mandatory rule. The downstream library has then full control on which file
structure to adopt within its cache. Namespace and subfolder are optional (would
default to a `"default/"` subfolder) but library name is mandatory as we want every
downstream library to manage its own cache.
Expected tree:
```text
assets/
└── datasets/
│ ├── SQuAD/
│ │ ├── downloaded/
│ │ ├── extracted/
│ │ └── processed/
│ ├── Helsinki-NLP--tatoeba_mt/
│ ├── downloaded/
│ ├── extracted/
│ └── processed/
└── transformers/
├── default/
│ ├── something/
├── bert-base-cased/
│ ├── default/
│ └── training/
hub/
└── models--julien-c--EsperBERTo-small/
├── blobs/
│ ├── (...)
│ ├── (...)
├── refs/
│ └── (...)
└── [ 128] snapshots/
├── 2439f60ef33a0d46d85da5001d52aeda5b00ce9f/
│ ├── (...)
└── bbc77c8132af1cc5cf678da3f1ddf2de43606d48/
└── (...)
```
Args:
library_name (`str`):
Name of the library that will manage the cache folder. Example: `"dataset"`.
namespace (`str`, *optional*, defaults to "default"):
Namespace to which the data belongs. Example: `"SQuAD"`.
subfolder (`str`, *optional*, defaults to "default"):
Subfolder in which the data will be stored. Example: `extracted`.
assets_dir (`str`, `Path`, *optional*):
Path to the folder where assets are cached. This must not be the same folder
where Hub files are cached. Defaults to `HF_HOME / "assets"` if not provided.
Can also be set with `HF_ASSETS_CACHE` environment variable.
Returns:
Path to the cache folder (`Path`).
Example:
```py
>>> from huggingface_hub import cached_assets_path
>>> cached_assets_path(library_name="datasets", namespace="SQuAD", subfolder="download")
PosixPath('/home/wauplin/.cache/huggingface/extra/datasets/SQuAD/download')
>>> cached_assets_path(library_name="datasets", namespace="SQuAD", subfolder="extracted")
PosixPath('/home/wauplin/.cache/huggingface/extra/datasets/SQuAD/extracted')
>>> cached_assets_path(library_name="datasets", namespace="Helsinki-NLP/tatoeba_mt")
PosixPath('/home/wauplin/.cache/huggingface/extra/datasets/Helsinki-NLP--tatoeba_mt/default')
>>> cached_assets_path(library_name="datasets", assets_dir="/tmp/tmp123456")
PosixPath('/tmp/tmp123456/datasets/default/default')
```
huggingface-hub.cancel_access_request
Python Library Documentation: method cancel_access_request in module huggingface_hub.hf_api
cancel_access_request(repo_id: 'str', user: 'str', *, repo_type: 'str | None' = None, token: 'bool | str | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Cancel an access request from a user for a given gated repo.
A cancelled request will go back to the pending list and the user will lose access to the repo.
For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
Args:
repo_id (`str`):
The id of the repo to cancel access request for.
user (`str`):
The username of the user which access request should be cancelled.
repo_type (`str`, *optional*):
The type of the repo to cancel access request for. Must be one of `model`, `dataset` or `space`.
Defaults to `model`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Raises:
[`HfHubHTTPError`]:
HTTP 400 if the repo is not gated.
[`HfHubHTTPError`]:
HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
or `admin` role in the organization the repo belongs to or if you passed a `read` token.
[`HfHubHTTPError`]:
HTTP 404 if the user does not exist on the Hub.
[`HfHubHTTPError`]:
HTTP 404 if the user access request cannot be found.
[`HfHubHTTPError`]:
HTTP 404 if the user access request is already in the pending list.
huggingface-hub.cancel_job
Python Library Documentation: method cancel_job in module huggingface_hub.hf_api
cancel_job(*, job_id: 'str', namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Cancel a compute Job on Hugging Face infrastructure.
Args:
job_id (`str`):
ID of the Job.
namespace (`str`, *optional*):
The namespace where the Job is running. Defaults to the current user's namespace.
token `(Union[bool, str, None]`, *optional*):
A valid user access token. If not provided, the locally saved token will be used, which is the
recommended authentication method. Set to `False` to disable authentication.
Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
huggingface-hub.change_discussion_status
Python Library Documentation: method change_discussion_status in module huggingface_hub.hf_api
change_discussion_status(repo_id: 'str', discussion_num: 'int', new_status: "Literal['open', 'closed']", *, token: 'bool | str | None' = None, comment: 'str | None' = None, repo_type: 'str | None' = None) -> 'DiscussionStatusChange' method of huggingface_hub.hf_api.HfApi instance
Closes or re-opens a Discussion or Pull Request.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
discussion_num (`int`):
The number of the Discussion or Pull Request . Must be a strictly positive integer.
new_status (`str`):
The new status for the discussion, either `"open"` or `"closed"`.
comment (`str`, *optional*):
An optional comment to post with the status change.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`DiscussionStatusChange`]: the status change event
Examples:
```python
>>> new_title = "New title, fixing a typo"
>>> HfApi().rename_discussion(
... repo_id="username/repo_name",
... discussion_num=34
... new_title=new_title
... )
# DiscussionStatusChange(id='deadbeef0000000', type='status-change', ...)
```
> [!TIP]
> Raises the following errors:
>
> - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
> if the HuggingFace API returned an error
> - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
> if some parameter value is invalid
> - [`~utils.RepositoryNotFoundError`]
> If the repository to download from cannot be found. This may be because it doesn't exist,
> or because it is set to `private` and you do not have access.
huggingface-hub.check_cli_update
Python Library Documentation: function check_cli_update in module huggingface_hub.cli._cli_utils
check_cli_update(library: Literal['huggingface_hub', 'transformers']) -> None
Check whether a newer version of a library is available on PyPI.
If a newer version is found, print a hint pointing at `hf update`.
If current version is a pre-release (e.g. `1.0.0.rc1`), or a dev version (e.g. `1.0.0.dev1`), no check is performed.
If `HF_HUB_DISABLE_UPDATE_CHECK` is set, the check is skipped entirely.
This function is called at the entry point of the CLI. It only performs the check once every 24 hours, and any error
during the check is caught and logged, to avoid breaking the CLI.
Args:
library: The library to check for updates. Currently supports "huggingface_hub" and "transformers".
huggingface-hub.close_session
Python Library Documentation: function close_session in module huggingface_hub.utils._http
close_session() -> None
Close the global `httpx.Client` used by `huggingface_hub`.
If a Client is closed, it will be recreated on the next call to [`get_session`].
Can be useful if e.g. an SSL certificate has been updated.
huggingface-hub.comment_discussion
Python Library Documentation: method comment_discussion in module huggingface_hub.hf_api
comment_discussion(repo_id: 'str', discussion_num: 'int', comment: 'str', *, token: 'bool | str | None' = None, repo_type: 'str | None' = None) -> 'DiscussionComment' method of huggingface_hub.hf_api.HfApi instance
Creates a new comment on the given Discussion.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
discussion_num (`int`):
The number of the Discussion or Pull Request . Must be a strictly positive integer.
comment (`str`):
The content of the comment to create. Comments support markdown formatting.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`DiscussionComment`]: the newly created comment
Examples:
```python
>>> comment = """
... Hello @otheruser!
...
... # This is a title
...
... **This is bold**, *this is italic* and ~this is strikethrough~
... And [this](http://url) is a link
... """
>>> HfApi().comment_discussion(
... repo_id="username/repo_name",
... discussion_num=34
... comment=comment
... )
# DiscussionComment(id='deadbeef0000000', type='comment', ...)
```
> [!TIP]
> Raises the following errors:
>
> - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
> if the HuggingFace API returned an error
> - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
> if some parameter value is invalid
> - [`~utils.RepositoryNotFoundError`]
> If the repository to download from cannot be found. This may be because it doesn't exist,
> or because it is set to `private` and you do not have access.
huggingface-hub.copy_files
Python Library Documentation: method copy_files in module huggingface_hub.hf_api
copy_files(source: 'str', destination: 'str', *, token: 'str | bool | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Copy files between locations on the Hub.
Copy files from a bucket or repository (model, dataset, space) to a bucket or another repository.
Both individual files and entire folders are supported.
When copying folders, a trailing `/` on the source path uses rsync-style semantics: copy the *contents*
of the folder into the destination, without nesting the source folder itself. Without a trailing `/`,
the source folder is nested inside the destination (like `cp -r`).
When copying from a repository to a bucket, `.gitattributes` files are automatically excluded since they
are git-specific metadata and not relevant in a bucket context.
Repo-to-repo copies use [`CommitOperationCopy`] under the hood and create a commit on the destination
repository. Bucket-to-repo copies are not supported.
> [!WARNING]
> Server-side copies only work within the same [storage region](https://huggingface.co/docs/hub/storage-regions).
Args:
source (`str`):
Source location as an `hf://` URI. Can be a bucket path (e.g. `"hf://buckets/my-bucket/path/to/file"`)
or a repo path (e.g. `"hf://username/my-model/weights.bin"`, `"hf://datasets/username/my-dataset/data/"`).
destination (`str`):
Destination location as an `hf://` URI pointing to a bucket (e.g. `"hf://buckets/my-bucket/target/path"`)
or a repository (e.g. `"hf://username/my-model/target/path"`).
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Raises:
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError):
If source/destination URIs are invalid or if copying from a bucket to a repo.
Example:
```python
>>> from huggingface_hub import copy_files
# Copy a single file between buckets
>>> copy_files("hf://buckets/my-bucket/data.bin", "hf://buckets/other-bucket/data.bin")
# Copy a folder into another bucket (nests: backup/models/...)
>>> copy_files("hf://buckets/my-bucket/models", "hf://buckets/other-bucket/backup/")
# Copy folder contents (trailing /): files go directly into backup/
>>> copy_files("hf://buckets/my-bucket/models/", "hf://buckets/other-bucket/backup/")
# Copy a file from a model repo to a bucket
>>> copy_files("hf://username/my-model/model.safetensors", "hf://buckets/my-bucket/")
# Copy an entire dataset to a bucket
>>> copy_files("hf://datasets/username/my-dataset/", "hf://buckets/my-bucket/datasets/")
# Copy files between repositories
>>> copy_files("hf://username/source-model/", "hf://username/dest-model/")
# Copy a file from one repo to another
>>> copy_files("hf://username/source-model/config.json", "hf://username/dest-model/config.json")
```
huggingface-hub.create_branch
Python Library Documentation: method create_branch in module huggingface_hub.hf_api
create_branch(repo_id: 'str', *, branch: 'str', revision: 'str | None' = None, token: 'bool | str | None' = None, repo_type: 'str | None' = None, exist_ok: 'bool' = False) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Create a new branch for a repo on the Hub, starting from the specified revision (defaults to `main`).
To find a revision suiting your needs, you can use [`list_repo_refs`] or [`list_repo_commits`].
Args:
repo_id (`str`):
The repository in which the branch will be created.
Example: `"user/my-cool-model"`.
branch (`str`):
The name of the branch to create.
revision (`str`, *optional*):
The git revision to create the branch from. It can be a branch name or
the OID/SHA of a commit, as a hexadecimal string. Defaults to the head
of the `"main"` branch.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if creating a branch on a dataset or
space, `None` or `"model"` if tagging a model. Default is `None`.
exist_ok (`bool`, *optional*, defaults to `False`):
If `True`, do not raise an error if branch already exists.
Raises:
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private
but not authenticated or repo does not exist.
[`~utils.BadRequestError`]:
If invalid reference for a branch. Ex: `refs/pr/5` or 'refs/foo/bar'.
[`~utils.HfHubHTTPError`]:
If the branch already exists on the repo (error 409) and `exist_ok` is
set to `False`.
huggingface-hub.create_bucket
Python Library Documentation: method create_bucket in module huggingface_hub.hf_api
create_bucket(bucket_id: 'str', *, private: 'bool | None' = None, resource_group_id: 'str | None' = None, region: 'REPO_REGIONS | None' = None, exist_ok: 'bool' = False, token: 'bool | str | None' = None) -> 'BucketUrl' method of huggingface_hub.hf_api.HfApi instance
Create a bucket on the Hub.
Args:
bucket_id (`str`):
A namespace (user or an organization) and a bucket name separated by a `/`.
If no namespace is provided, the bucket will be created in the current user's namespace.
private (`bool`, *optional*):
Whether to make the bucket private. If `None` (default), the bucket will be public unless the
organization's default is private.
resource_group_id (`str`, *optional*):
Resource group in which to create the bucket. Resource groups are only available for Enterprise Hub
organizations and allow to define which members of the organization can access the resource. The ID
of a resource group can be found in the URL of the resource's page on the Hub
(e.g. `"66670e5163145ca562cb1988"`). To learn more about resource groups, see
https://huggingface.co/docs/hub/en/security-resource-groups.
region (`Literal["us", "eu"]`, *optional*):
Cloud region in which to create the bucket. Can be one of `"us"` or `"eu"`. If not specified, the bucket will be
created in the default region. Requires Team plan or above.
exist_ok (`bool`, *optional*, defaults to `False`):
If `True`, do not raise an error if the bucket already exists.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`BucketUrl`]: URL to the newly created bucket containing
attributes like `endpoint`, `namespace`, and `bucket_id`.
Example:
```python
>>> from huggingface_hub import create_bucket
>>> url = create_bucket(bucket_id="my-bucket")
>>> url.bucket_id
'user/my-bucket'
>>> url.url
'https://huggingface.co/buckets/user/my-bucket'
>>> url.uri.to_uri()
'hf://buckets/user/my-bucket'
>>> create_bucket(bucket_id="my-bucket", private=True, exist_ok=True)
BucketUrl(...)
>>> create_bucket(bucket_id="my-bucket", region="us")
BucketUrl(...)
```
huggingface-hub.create_collection
Python Library Documentation: method create_collection in module huggingface_hub.hf_api
create_collection(title: 'str', *, namespace: 'str | None' = None, description: 'str | None' = None, private: 'bool' = False, resource_group_id: 'str | None' = None, exists_ok: 'bool' = False, token: 'bool | str | None' = None) -> 'Collection' method of huggingface_hub.hf_api.HfApi instance
Create a new Collection on the Hub.
Args:
title (`str`):
Title of the collection to create. Example: `"Recent models"`.
namespace (`str`, *optional*):
Namespace of the collection to create (username or org). Will default to the owner name.
description (`str`, *optional*):
Description of the collection to create. The maximum size for a description is 150 characters.
private (`bool`, *optional*):
Whether the collection should be private or not. Defaults to `False` (i.e. public collection).
resource_group_id (`str`, *optional*):
Assign the collection to a resource group of the owning organization. Only valid for
organization-owned collections. The resource group ID is a 24-character hexadecimal string.
exists_ok (`bool`, *optional*):
If `True`, do not raise an error if collection already exists.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns: [`Collection`]
Example:
```py
>>> from huggingface_hub import create_collection
>>> collection = create_collection(
... title="ICCV 2023",
... description="Portfolio of models, papers and demos I presented at ICCV 2023",
... )
>>> collection.slug
"username/iccv-2023-64f9a55bb3115b4f513ec026"
```
huggingface-hub.create_commit
Python Library Documentation: method create_commit in module huggingface_hub.hf_api
create_commit(repo_id: 'str', operations: 'Iterable[CommitOperation]', *, commit_message: 'str', commit_description: 'str | None' = None, token: 'str | bool | None' = None, repo_type: 'str | None' = None, revision: 'str | None' = None, create_pr: 'bool | None' = None, num_threads: 'int' = 5, parent_commit: 'str | None' = None, run_as_future: 'bool' = False, _hot_reload: 'bool | None' = None) -> 'CommitInfo | Future[CommitInfo]' method of huggingface_hub.hf_api.HfApi instance
Creates a commit in the given repo, deleting & uploading files as needed.
> [!WARNING]
> The input list of `CommitOperation` will be mutated during the commit process. Do not reuse the same objects
> for multiple commits.
> [!WARNING]
> `create_commit` assumes that the repo already exists on the Hub. If you get a
> Client error 404, please make sure you are authenticated, that your token has the required permissions,
> and that `repo_id` and `repo_type` are set correctly. If repo does not exist,
> create it first using [`~hf_api.create_repo`].
> [!WARNING]
> `create_commit` is limited to 25k LFS files and a 1GB payload for regular files.
Args:
repo_id (`str`):
The repository in which the commit will be created, for example:
`"username/custom_transformers"`
operations (`Iterable` of [`~hf_api.CommitOperation`]):
An iterable of operations to include in the commit, either:
- [`~hf_api.CommitOperationAdd`] to upload a file
- [`~hf_api.CommitOperationDelete`] to delete a file
- [`~hf_api.CommitOperationCopy`] to copy a file
Operation objects will be mutated to include information relative to the upload. Do not reuse the
same objects for multiple commits.
commit_message (`str`):
The summary (first line) of the commit that will be created.
commit_description (`str`, *optional*):
The description of the commit that will be created
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
revision (`str`, *optional*):
The git revision to commit from. Defaults to the head of the `"main"` branch.
create_pr (`boolean`, *optional*):
Whether or not to create a Pull Request with that commit. Defaults to `False`.
If `revision` is not set, PR is opened against the `"main"` branch. If
`revision` is set and is a branch, PR is opened against this branch. If
`revision` is set and is not a branch name (example: a commit oid), an
`RevisionNotFoundError` is returned by the server.
num_threads (`int`, *optional*):
Number of concurrent threads for uploading files. Defaults to 5.
Setting it to 2 means at most 2 files will be uploaded concurrently.
parent_commit (`str`, *optional*):
The OID / SHA of the parent commit, as a hexadecimal string.
Shorthands (7 first characters) are also supported. If specified and `create_pr` is `False`,
the commit will fail if `revision` does not point to `parent_commit`. If specified and `create_pr`
is `True`, the pull request will be created from `parent_commit`. Specifying `parent_commit`
ensures the repo has not changed before committing the changes, and can be especially useful
if the repo is updated / committed to concurrently.
run_as_future (`bool`, *optional*):
Whether or not to run this method in the background. Background jobs are run sequentially without
blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects)
object. Defaults to `False`.
Returns:
[`CommitInfo`] or `Future`:
Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit
url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will
contain the result when executed.
Raises:
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If commit message is empty.
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If parent commit is not a valid commit OID.
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If a README.md file with an invalid metadata section is committed. In this case, the commit will fail
early, before trying to upload any file.
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If `create_pr` is `True` and revision is neither `None` nor `"main"`.
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private
but not authenticated or repo does not exist.
huggingface-hub.create_discussion
Python Library Documentation: method create_discussion in module huggingface_hub.hf_api
create_discussion(repo_id: 'str', title: 'str', *, token: 'bool | str | None' = None, description: 'str | None' = None, repo_type: 'str | None' = None, pull_request: 'bool' = False) -> 'DiscussionWithDetails' method of huggingface_hub.hf_api.HfApi instance
Creates a Discussion or Pull Request.
Pull Requests created programmatically will be in `"draft"` status.
Creating a Pull Request with changes can also be done at once with [`HfApi.create_commit`].
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
title (`str`):
The title of the discussion. It can be up to 200 characters long,
and must be at least 3 characters long. Leading and trailing whitespaces
will be stripped.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
description (`str`, *optional*):
An optional description for the Pull Request.
Defaults to `"Discussion opened with the huggingface_hub Python library"`
pull_request (`bool`, *optional*):
Whether to create a Pull Request or discussion. If `True`, creates a Pull Request.
If `False`, creates a discussion. Defaults to `False`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
Returns: [`DiscussionWithDetails`]
> [!TIP]
> Raises the following errors:
>
> - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
> if the HuggingFace API returned an error
> - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
> if some parameter value is invalid
> - [`~utils.RepositoryNotFoundError`]
> If the repository to download from cannot be found. This may be because it doesn't exist,
> or because it is set to `private` and you do not have access.
huggingface-hub.create_inference_endpoint
Python Library Documentation: method create_inference_endpoint in module huggingface_hub.hf_api
create_inference_endpoint(name: 'str', *, repository: 'str', framework: 'str', accelerator: 'str', instance_size: 'str', instance_type: 'str', region: 'str', vendor: 'str', account_id: 'str | None' = None, min_replica: 'int' = 1, max_replica: 'int' = 1, scaling_metric: 'InferenceEndpointScalingMetric | None' = None, scaling_threshold: 'float | None' = None, scale_to_zero_timeout: 'int | None' = None, revision: 'str | None' = None, task: 'str | None' = None, custom_image: 'dict | None' = None, container_command: 'list[str] | None' = None, container_args: 'list[str] | None' = None, env: 'dict[str, str] | None' = None, secrets: 'dict[str, str] | None' = None, type: 'InferenceEndpointType | str' = <InferenceEndpointType.AUTHENTICATED: 'authenticated'>, domain: 'str | None' = None, path: 'str | None' = None, cache_http_responses: 'bool | None' = None, tags: 'list[str] | None' = None, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'InferenceEndpoint' method of huggingface_hub.hf_api.HfApi instance
Create a new Inference Endpoint.
Args:
name (`str`):
The unique name for the new Inference Endpoint.
repository (`str`):
The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`).
framework (`str`):
The machine learning framework used for the model (e.g. `"custom"`).
accelerator (`str`):
The hardware accelerator to be used for inference (e.g. `"cpu"`).
instance_size (`str`):
The size or type of the instance to be used for hosting the model (e.g. `"x4"`).
instance_type (`str`):
The cloud instance type where the Inference Endpoint will be deployed (e.g. `"intel-icl"`).
region (`str`):
The cloud region in which the Inference Endpoint will be created (e.g. `"us-east-1"`).
vendor (`str`):
The cloud provider or vendor where the Inference Endpoint will be hosted (e.g. `"aws"`).
account_id (`str`, *optional*):
The account ID used to link a VPC to a private Inference Endpoint (if applicable).
min_replica (`int`, *optional*):
The minimum number of replicas (instances) to keep running for the Inference Endpoint. To enable
scaling to zero, set this value to 0 and adjust `scale_to_zero_timeout` accordingly. Defaults to 1.
max_replica (`int`, *optional*):
The maximum number of replicas (instances) to scale to for the Inference Endpoint. Defaults to 1.
scaling_metric (`str` or [`InferenceEndpointScalingMetric `], *optional*):
The metric reference for scaling. Either "pendingRequests" or "hardwareUsage" when provided. Defaults to
None (meaning: let the HF Endpoints service specify the metric).
scaling_threshold (`float`, *optional*):
The scaling metric threshold used to trigger a scale up. Ignored when scaling metric is not provided.
Defaults to None (meaning: let the HF Endpoints service specify the threshold).
scale_to_zero_timeout (`int`, *optional*):
The duration in minutes before an inactive endpoint is scaled to zero, or no scaling to zero if
set to None and `min_replica` is not 0. Defaults to None.
revision (`str`, *optional*):
The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`).
task (`str`, *optional*):
The task on which to deploy the model (e.g. `"text-classification"`).
custom_image (`dict`, *optional*):
A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an
Inference Endpoint running on the `text-generation-inference` (TGI) framework or a custom container
(see examples).
container_command (`list[str]`, *optional*):
Override the container entrypoint command (maps to `model.command` in the API payload). Typically
used together with `custom_image`.
container_args (`list[str]`, *optional*):
Arguments appended to the container entrypoint (maps to `model.args` in the API payload). Typically
used together with `custom_image` to pass runtime flags to the container.
env (`dict[str, str]`, *optional*):
Non-secret environment variables to inject in the container environment.
secrets (`dict[str, str]`, *optional*):
Secret values to inject in the container environment.
type ([`InferenceEndpointType]`, *optional*):
The type of the Inference Endpoint, which can be `"authenticated"` (default), `"public"` or
`"private"`. `"protected"` is deprecated in favor of `"authenticated"` and will be removed in a
future release.
domain (`str`, *optional*):
The custom domain for the Inference Endpoint deployment, if setup the inference endpoint will be available at this domain (e.g. `"my-new-domain.cool-website.woof"`).
path (`str`, *optional*):
The custom path to the deployed model, should start with a `/` (e.g. `"/models/google-bert/bert-base-uncased"`).
cache_http_responses (`bool`, *optional*):
Whether to cache HTTP responses from the Inference Endpoint. Defaults to `False`.
tags (`list[str]`, *optional*):
A list of tags to associate with the Inference Endpoint.
namespace (`str`, *optional*):
The namespace where the Inference Endpoint will be created. Defaults to the current user's namespace.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`InferenceEndpoint`]: information about the updated Inference Endpoint.
Example:
```python
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> endpoint = api.create_inference_endpoint(
... "my-endpoint-name",
... repository="gpt2",
... framework="pytorch",
... task="text-generation",
... accelerator="cpu",
... vendor="aws",
... region="us-east-1",
... type="authenticated",
... instance_size="x2",
... instance_type="intel-icl",
... )
>>> endpoint
InferenceEndpoint(name='my-endpoint-name', status="pending",...)
# Run inference on the endpoint
>>> endpoint.client.text_generation(...)
"..."
```
```python
# Start an Inference Endpoint running Zephyr-7b-beta on TGI
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> endpoint = api.create_inference_endpoint(
... "aws-zephyr-7b-beta-0486",
... repository="HuggingFaceH4/zephyr-7b-beta",
... framework="pytorch",
... task="text-generation",
... accelerator="gpu",
... vendor="aws",
... region="us-east-1",
... type="authenticated",
... instance_size="x1",
... instance_type="nvidia-a10g",
... env={
... "MAX_BATCH_PREFILL_TOKENS": "2048",
... "MAX_INPUT_LENGTH": "1024",
... "MAX_TOTAL_TOKENS": "1512",
... "MODEL_ID": "/repository"
... },
... custom_image={
... "healthRoute": "/health",
... "url": "ghcr.io/huggingface/text-generation-inference:1.1.0",
... },
... secrets={"MY_SECRET_KEY": "secret_value"},
... tags=["dev", "text-generation"],
... )
```
```python
# Start an Inference Endpoint running ProsusAI/finbert while scaling to zero in 15 minutes
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> endpoint = api.create_inference_endpoint(
... "finbert-classifier",
... repository="ProsusAI/finbert",
... framework="pytorch",
... task="text-classification",
... min_replica=0,
... scale_to_zero_timeout=15,
... accelerator="cpu",
... vendor="aws",
... region="us-east-1",
... type="authenticated",
... instance_size="x2",
... instance_type="intel-icl",
... )
>>> endpoint.wait(timeout=300)
# Run inference on the endpoint
>>> endpoint.client.text_generation(...)
TextClassificationOutputElement(label='positive', score=0.8983615040779114)
```
huggingface-hub.create_inference_endpoint_from_catalog
Python Library Documentation: method create_inference_endpoint_from_catalog in module huggingface_hub.hf_api
create_inference_endpoint_from_catalog(repo_id: 'str', *, name: 'str | None' = None, accelerator: "Literal['cpu', 'gpu', 'neuron'] | str | None" = None, token: 'bool | str | None' = None, namespace: 'str | None' = None) -> 'InferenceEndpoint' method of huggingface_hub.hf_api.HfApi instance
Create a new Inference Endpoint from a model in the Hugging Face Inference Catalog.
The goal of the Inference Catalog is to provide a curated list of models that are optimized for inference
and for which default configurations have been tested. See https://endpoints.huggingface.co/catalog for a list
of available models in the catalog.
Args:
repo_id (`str`):
The ID of the model in the catalog to deploy as an Inference Endpoint.
name (`str`, *optional*):
The unique name for the new Inference Endpoint. If not provided, a random name will be generated.
accelerator (`str`, *optional*):
The hardware accelerator to be used for inference. Possible values include `"cpu"`, `"gpu"`, and
`"neuron"`. If not provided, the server will use a default appropriate for the model.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
namespace (`str`, *optional*):
The namespace where the Inference Endpoint will be created. Defaults to the current user's namespace.
Returns:
[`InferenceEndpoint`]: information about the new Inference Endpoint.
> [!WARNING]
> `create_inference_endpoint_from_catalog` is experimental. Its API is subject to change in the future. Please provide feedback
> if you have any suggestions or requests.
huggingface-hub.create_pull_request
Python Library Documentation: method create_pull_request in module huggingface_hub.hf_api
create_pull_request(repo_id: 'str', title: 'str', *, token: 'bool | str | None' = None, description: 'str | None' = None, repo_type: 'str | None' = None) -> 'DiscussionWithDetails' method of huggingface_hub.hf_api.HfApi instance
Creates a Pull Request . Pull Requests created programmatically will be in `"draft"` status.
Creating a Pull Request with changes can also be done at once with [`HfApi.create_commit`];
This is a wrapper around [`HfApi.create_discussion`].
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
title (`str`):
The title of the discussion. It can be up to 200 characters long,
and must be at least 3 characters long. Leading and trailing whitespaces
will be stripped.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
description (`str`, *optional*):
An optional description for the Pull Request.
Defaults to `"Discussion opened with the huggingface_hub Python library"`
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
Returns: [`DiscussionWithDetails`]
> [!TIP]
> Raises the following errors:
>
> - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
> if the HuggingFace API returned an error
> - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
> if some parameter value is invalid
> - [`~utils.RepositoryNotFoundError`]
> If the repository to download from cannot be found. This may be because it doesn't exist,
> or because it is set to `private` and you do not have access.
huggingface-hub.create_repo
Python Library Documentation: method create_repo in module huggingface_hub.hf_api
create_repo(repo_id: 'str', *, token: 'str | bool | None' = None, private: 'bool | None' = None, visibility: 'RepoVisibility_T | None' = None, repo_type: 'str | None' = None, exist_ok: 'bool' = False, resource_group_id: 'str | None' = None, region: 'REPO_REGIONS | None' = None, space_sdk: 'str | None' = None, space_hardware: 'SpaceHardware | None' = None, space_storage: 'SpaceStorage | None' = None, space_sleep_time: 'int | None' = None, space_secrets: 'list[dict[str, str]] | None' = None, space_variables: 'list[dict[str, str]] | None' = None, space_volumes: 'list[Volume] | None' = None, space_template: 'str | None' = None) -> 'RepoUrl' method of huggingface_hub.hf_api.HfApi instance
Create an empty repo on the HuggingFace Hub.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
private (`bool`, *optional*):
Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists. Cannot be passed together with `visibility`.
visibility (`Literal["public", "private", "protected"]`, *optional*):
Visibility of the repo. Can be `"public"` or `"private"`, or `"protected"` for Spaces. If `None`
(default), the repo will be public unless the organization's default is private. This value is ignored
if the repo already exists.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
exist_ok (`bool`, *optional*, defaults to `False`):
If `True`, do not raise an error if repo already exists.
resource_group_id (`str`, *optional*):
Resource group in which to create the repo. Resource groups is only available for Enterprise Hub organizations and
allow to define which members of the organization can access the resource. The ID of a resource group
can be found in the URL of the resource's page on the Hub (e.g. `"66670e5163145ca562cb1988"`).
To learn more about resource groups, see https://huggingface.co/docs/hub/en/security-resource-groups.
region (`Literal["us", "eu"]`, *optional*):
Cloud region in which to create the repo. Can be one of `"us"` or `"eu"`. If not specified, the repo will be
created in the default region. Requires Team plan or above.
space_sdk (`str`, *optional*):
Choice of SDK to use if repo_type is "space". Can be "streamlit", "gradio", "docker", or "static".
space_hardware (`SpaceHardware` or `str`, *optional*):
Choice of Hardware if repo_type is "space". See [`SpaceHardware`] for a complete list.
space_storage (`SpaceStorage` or `str`, *optional*):
<Deprecated, use `set_space_volumes` instead> Choice of persistent storage tier. Example: `"small"`. See [`SpaceStorage`] for a complete list.
space_sleep_time (`int`, *optional*):
Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure
the sleep time (value is fixed to 48 hours of inactivity).
See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
space_secrets (`list[dict[str, str]]`, *optional*):
A list of secret keys to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
space_variables (`list[dict[str, str]]`, *optional*):
A list of public environment variables to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables.
space_volumes (`list[Volume]`, *optional*):
A list of [`Volume`] objects to mount in the Space at creation time. Each volume has a `type`
(`"bucket"`, `"model"`, `"dataset"`, or `"space"`), a `source` (repo or bucket ID), a `mount_path`
(path inside the container), and optional `revision`, `read_only`, and `path` fields.
Only applicable if repo_type is "space".
space_template (`str`, *optional*):
Seed the new Space from an official template. Can be either the template repo id
(e.g. `"SpacesExamples/jupyterlab"`) or its short name (e.g. `"JupyterLab"`). Use
[`HfApi.list_space_templates`] to list available templates. Only applicable if repo_type is
"space". If the template is recommended to be private and visibility is not explicitly set, the Space
is created as private.
Returns:
[`RepoUrl`]: URL to the newly created repo. Value is a subclass of `str` containing
attributes like `endpoint`, `repo_type` and `repo_id`.
huggingface-hub.create_scheduled_job
Python Library Documentation: method create_scheduled_job in module huggingface_hub.hf_api
create_scheduled_job(*, image: 'str', command: 'list[str]', schedule: 'str', suspend: 'bool | None' = None, concurrency: 'bool | None' = None, env: 'dict[str, Any] | None' = None, secrets: 'dict[str, Any] | None' = None, flavor: 'JobHardware | str | None' = None, timeout: 'int | float | str | None' = None, name: 'str | None' = None, labels: 'dict[str, str] | None' = None, volumes: 'list[Volume] | None' = None, expose: 'list[int] | None' = None, resource_group_id: 'str | None' = None, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'ScheduledJobInfo' method of huggingface_hub.hf_api.HfApi instance
Create scheduled compute Jobs on Hugging Face infrastructure.
Args:
image (`str`):
The Docker image to use.
Examples: `"ubuntu"`, `"python:3.12"`, `"pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"`.
Example with an image from a Space: `"hf.co/spaces/lhoestq/duckdb"`.
command (`list[str]`):
The command to run. Example: `["echo", "hello"]`.
schedule (`str`):
One of "@annually", "@yearly", "@monthly", "@weekly", "@daily", "@hourly", or a
CRON schedule expression (e.g., '0 9 * * 1' for 9 AM every Monday).
suspend (`bool`, *optional*):
If True, the scheduled Job is suspended (paused). Defaults to False.
concurrency (`bool`, *optional*):
If True, multiple instances of this Job can run concurrently. Defaults to False.
env (`dict[str, Any]`, *optional*):
Defines the environment variables for the Job.
secrets (`dict[str, Any]`, *optional*):
Defines the secret environment variables for the Job.
flavor (`str`, *optional*):
Flavor for the hardware. See [`JobHardware`] for possible values.
Defaults to `"cpu-basic"`.
timeout (`Union[int, float, str]`, *optional*):
Max duration for the Job: int with s (seconds, default), m (minutes), h (hours) or d (days).
Example: `300` or `"5m"` for 5 minutes.
name (`str`, *optional*):
A name for the scheduled Job. Stored as the `name` label. Cannot be passed together with a `name`
key in `labels`. Names do not have to be unique. Defaults to a name derived from image and command (with a short hash suffix).
labels (`dict[str, str]`, *optional*):
Labels to attach to the job (key-value pairs).
volumes (`list[Volume]`, *optional*):
Hugging Face Buckets or Repos to mount as volumes in the job container.
Each volume is a [`Volume`] with `type` (`"bucket"`, `"model"`, `"dataset"`, or `"space"`),
`source` (e.g. `"username/my-bucket"`), and `mount_path` (e.g. `"/data"`).
expose (`list[int]`, *optional*):
Container ports to expose through the jobs proxy. Each listed port is reachable
on the public jobs domain (e.g. `https://<job_id>--8000.hf.jobs`). Access always
requires an HF token with read access to the job's namespace.
resource_group_id (`str`, *optional*):
The ID of the resource group to create the scheduled Job in. Used to control access to resources
within an organization and for cost attribution/spending-limit features. If not provided, the
scheduled Job is created outside of any resource group.
namespace (`str`, *optional*):
The namespace where the Job will be created. Defaults to the current user's namespace.
token `(Union[bool, str, None]`, *optional*):
A valid user access token. If not provided, the locally saved token will be used, which is the
recommended authentication method. Set to `False` to disable authentication.
Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
Example:
Create your first scheduled Job:
```python
>>> from huggingface_hub import create_scheduled_job
>>> create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"], schedule="@hourly")
```
Use a CRON schedule expression:
```python
>>> from huggingface_hub import create_scheduled_job
>>> create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('this runs every 5min')"], schedule="*/5 * * * *")
```
Create a scheduled GPU Job:
```python
>>> from huggingface_hub import create_scheduled_job
>>> image = "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"
>>> command = ["python", "-c", "import torch; print(f"This code ran with the following GPU: {torch.cuda.get_device_name()}")"]
>>> create_scheduled_job(image, command, flavor="a10g-small", schedule="@hourly")
```
huggingface-hub.create_scheduled_uv_job
Python Library Documentation: method create_scheduled_uv_job in module huggingface_hub.hf_api
create_scheduled_uv_job(script: 'str', *, script_args: 'list[str] | None' = None, schedule: 'str', suspend: 'bool | None' = None, concurrency: 'bool | None' = None, dependencies: 'list[str] | None' = None, python: 'str | None' = None, image: 'str | None' = None, env: 'dict[str, Any] | None' = None, secrets: 'dict[str, Any] | None' = None, flavor: 'JobHardware | str | None' = None, timeout: 'int | float | str | None' = None, name: 'str | None' = None, labels: 'dict[str, str] | None' = None, volumes: 'list[Volume] | None' = None, expose: 'list[int] | None' = None, resource_group_id: 'str | None' = None, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'ScheduledJobInfo' method of huggingface_hub.hf_api.HfApi instance
Run a UV script Job on Hugging Face infrastructure.
Args:
script (`str`):
Path or URL of the UV script, or a command.
script_args (`list[str]`, *optional*)
Arguments to pass to the script, or a command.
schedule (`str`):
One of "@annually", "@yearly", "@monthly", "@weekly", "@daily", "@hourly", or a
CRON schedule expression (e.g., '0 9 * * 1' for 9 AM every Monday).
suspend (`bool`, *optional*):
If True, the scheduled Job is suspended (paused). Defaults to False.
concurrency (`bool`, *optional*):
If True, multiple instances of this Job can run concurrently. Defaults to False.
dependencies (`list[str]`, *optional*)
Dependencies to use to run the UV script.
python (`str`, *optional*)
Use a specific Python version. Default is 3.12.
image (`str`, *optional*, defaults to "ghcr.io/astral-sh/uv:python3.12-bookworm"):
Use a custom Docker image with `uv` installed.
env (`dict[str, Any]`, *optional*):
Defines the environment variables for the Job.
secrets (`dict[str, Any]`, *optional*):
Defines the secret environment variables for the Job.
flavor (`str`, *optional*):
Flavor for the hardware. See [`JobHardware`] for possible values.
Defaults to `"cpu-basic"`.
timeout (`Union[int, float, str]`, *optional*):
Max duration for the Job: int with s (seconds, default), m (minutes), h (hours) or d (days).
Example: `300` or `"5m"` for 5 minutes.
name (`str`, *optional*):
A name for the scheduled Job. Stored as the `name` label. Cannot be passed together with a `name`
key in `labels`. Names do not have to be unique. Defaults to a name derived from script and its arguments (with a short hash suffix).
labels (`dict[str, str]`, *optional*):
Labels to attach to the job (key-value pairs).
volumes (`list[Volume]`, *optional*):
Hugging Face Buckets or Repos to mount as volumes in the job container.
Each volume is a [`Volume`] with `type` (`"bucket"`, `"model"`, `"dataset"`, or `"space"`),
`source` (e.g. `"username/my-bucket"`), and `mount_path` (e.g. `"/data"`).
expose (`list[int]`, *optional*):
Container ports to expose through the jobs proxy. Each listed port is reachable
on the public jobs domain (e.g. `https://<job_id>--8000.hf.jobs`). Access always
requires an HF token with read access to the job's namespace.
resource_group_id (`str`, *optional*):
The ID of the resource group to create the scheduled Job in. Used to control access to resources
within an organization and for cost attribution/spending-limit features. If not provided, the
scheduled Job is created outside of any resource group.
namespace (`str`, *optional*):
The namespace where the Job will be created. Defaults to the current user's namespace.
token `(Union[bool, str, None]`, *optional*):
A valid user access token. If not provided, the locally saved token will be used, which is the
recommended authentication method. Set to `False` to disable authentication.
Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
Example:
Schedule a script from a URL:
```python
>>> from huggingface_hub import create_scheduled_uv_job
>>> script = "https://raw.githubusercontent.com/huggingface/trl/refs/heads/main/trl/scripts/sft.py"
>>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
>>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small", schedule="@weekly")
```
Schedule a local script:
```python
>>> from huggingface_hub import create_scheduled_uv_job
>>> script = "my_sft.py"
>>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
>>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small", schedule="@weekly")
```
Schedule a command:
```python
>>> from huggingface_hub import create_scheduled_uv_job
>>> script = "lighteval"
>>> script_args= ["endpoint", "inference-providers", "model_name=openai/gpt-oss-20b,provider=auto", "lighteval|gsm8k|0|0"]
>>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["lighteval"], flavor="a10g-small", schedule="@weekly")
```
huggingface-hub.create_tag
Python Library Documentation: method create_tag in module huggingface_hub.hf_api
create_tag(repo_id: 'str', *, tag: 'str', tag_message: 'str | None' = None, revision: 'str | None' = None, token: 'bool | str | None' = None, repo_type: 'str | None' = None, exist_ok: 'bool' = False) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Tag a given commit of a repo on the Hub.
Args:
repo_id (`str`):
The repository in which a commit will be tagged.
Example: `"user/my-cool-model"`.
tag (`str`):
The name of the tag to create.
tag_message (`str`, *optional*):
The description of the tag to create.
revision (`str`, *optional*):
The git revision to tag. It can be a branch name or the OID/SHA of a
commit, as a hexadecimal string. Shorthands (7 first characters) are
also supported. Defaults to the head of the `"main"` branch.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if tagging a dataset or
space, `None` or `"model"` if tagging a model. Default is
`None`.
exist_ok (`bool`, *optional*, defaults to `False`):
If `True`, do not raise an error if tag already exists.
Raises:
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private
but not authenticated or repo does not exist.
[`~utils.RevisionNotFoundError`]:
If revision is not found (error 404) on the repo.
[`~utils.HfHubHTTPError`]:
If the branch already exists on the repo (error 409) and `exist_ok` is
set to `False`.
huggingface-hub.create_webhook
Python Library Documentation: method create_webhook in module huggingface_hub.hf_api
create_webhook(*, url: 'str | None' = None, job_id: 'str | None' = None, watched: 'list[dict | WebhookWatchedItem]', domains: 'list[constants.WEBHOOK_DOMAIN_T] | None' = None, secret: 'str | None' = None, token: 'bool | str | None' = None) -> 'WebhookInfo' method of huggingface_hub.hf_api.HfApi instance
Create a new webhook.
The webhook can either send a payload to a URL, or trigger a Job to run on Hugging Face infrastructure.
This function should be called with one of `url` or `job_id`, but not both.
Args:
url (`str`):
URL to send the payload to.
job_id (`str`):
ID of the source Job to trigger with the webhook payload in the environment variable WEBHOOK_PAYLOAD.
Additional environment variables are available for convenience: WEBHOOK_REPO_ID, WEBHOOK_REPO_TYPE and WEBHOOK_SECRET.
watched (`list[WebhookWatchedItem]`):
List of [`WebhookWatchedItem`] to be watched by the webhook. It can be users, orgs, models, datasets or spaces.
Watched items can also be provided as plain dictionaries.
domains (`list[Literal["repo", "discussion"]]`, optional):
List of domains to watch. It can be "repo", "discussion" or both.
secret (`str`, optional):
A secret to sign the payload with.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved token, which is the recommended
method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`WebhookInfo`]:
Info about the newly created webhook.
Example:
Create a webhook that sends a payload to a URL
```python
>>> from huggingface_hub import create_webhook
>>> payload = create_webhook(
... watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}],
... url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
... domains=["repo", "discussion"],
... secret="my-secret",
... )
>>> print(payload)
WebhookInfo(
id="654bbbc16f2ec14d77f109cc",
url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
job=None,
watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
domains=["repo", "discussion"],
secret="my-secret",
disabled=False,
)
```
Run a Job and then create a webhook that triggers this Job
```python
>>> from huggingface_hub import create_webhook, run_job
>>> job = run_job(
... image="ubuntu",
... command=["bash", "-c", r"echo An event occurred in $WEBHOOK_REPO_ID: $WEBHOOK_PAYLOAD"],
... )
>>> payload = create_webhook(
... watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}],
... job_id=job.id,
... domains=["repo", "discussion"],
... secret="my-secret",
... )
>>> print(payload)
WebhookInfo(
id="654bbbc16f2ec14d77f109cc",
url=None,
job=JobSpec(
docker_image='ubuntu',
space_id=None,
command=['bash', '-c', 'echo An event occurred in $WEBHOOK_REPO_ID: $WEBHOOK_PAYLOAD'],
arguments=[],
environment={},
secrets=[],
flavor='cpu-basic',
timeout=None,
tags=None,
arch=None
),
watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
domains=["repo", "discussion"],
secret="my-secret",
disabled=False,
)
```
huggingface-hub.dataset_info
Python Library Documentation: method dataset_info in module huggingface_hub.hf_api
dataset_info(repo_id: 'str', *, revision: 'str | None' = None, timeout: 'float | None' = None, files_metadata: 'bool' = False, expand: 'list[ExpandDatasetProperty_T] | None' = None, token: 'bool | str | None' = None) -> 'DatasetInfo' method of huggingface_hub.hf_api.HfApi instance
Get info on one specific dataset on huggingface.co.
Dataset can be private if you pass an acceptable token.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
revision (`str`, *optional*):
The revision of the dataset repository from which to get the
information.
timeout (`float`, *optional*):
Whether to set a timeout for the request to the Hub.
files_metadata (`bool`, *optional*):
Whether or not to retrieve metadata for files in the repository
(size, LFS metadata, etc). Defaults to `False`.
expand (`list[ExpandDatasetProperty_T]`, *optional*):
List properties to return in the response. When used, only the properties in the list will be returned.
This parameter cannot be used if `files_metadata` is passed.
Possible values are `"author"`, `"cardData"`, `"citation"`, `"createdAt"`, `"disabled"`, `"description"`, `"downloads"`, `"downloadsAllTime"`, `"gated"`, `"lastModified"`, `"likes"`, `"mainSize"`, `"paperswithcode_id"`, `"private"`, `"siblings"`, `"sha"`, `"tags"`, `"trendingScore"`, `"usedStorage"`, and `"resourceGroup"`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`hf_api.DatasetInfo`]: The dataset repository information.
> [!TIP]
> Raises the following errors:
>
> - [`~utils.RepositoryNotFoundError`]
> If the repository to download from cannot be found. This may be because it doesn't exist,
> or because it is set to `private` and you do not have access.
> - [`~utils.RevisionNotFoundError`]
> If the revision to download from cannot be found.
huggingface-hub.delete_branch
Python Library Documentation: method delete_branch in module huggingface_hub.hf_api
delete_branch(repo_id: 'str', *, branch: 'str', token: 'bool | str | None' = None, repo_type: 'str | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Delete a branch from a repo on the Hub.
Args:
repo_id (`str`):
The repository in which a branch will be deleted.
Example: `"user/my-cool-model"`.
branch (`str`):
The name of the branch to delete.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if creating a branch on a dataset or
space, `None` or `"model"` if tagging a model. Default is `None`.
Raises:
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private
but not authenticated or repo does not exist.
[`~utils.HfHubHTTPError`]:
If trying to delete a protected branch. Ex: `main` cannot be deleted.
[`~utils.HfHubHTTPError`]:
If trying to delete a branch that does not exist.
huggingface-hub.delete_bucket
Python Library Documentation: method delete_bucket in module huggingface_hub.hf_api
delete_bucket(bucket_id: 'str', *, missing_ok: 'bool' = False, token: 'bool | str | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Delete a bucket from the Hub.
Args:
bucket_id (`str`):
The ID of the bucket (e.g. `"username/my-bucket"`).
missing_ok (`bool`, *optional*, defaults to `False`):
If `True`, do not raise an error if the bucket does not exist.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Raises:
[`~errors.BucketNotFoundError`]: If the bucket cannot be found and `missing_ok` is set to `False` (default).
Example:
```python
>>> from huggingface_hub import delete_bucket
>>> delete_bucket(bucket_id="Wauplin/first-bucket")
>>> delete_bucket(bucket_id="Wauplin/first-bucket", missing_ok=True)
```
huggingface-hub.delete_collection
Python Library Documentation: method delete_collection in module huggingface_hub.hf_api
delete_collection(collection_slug: 'str', *, missing_ok: 'bool' = False, token: 'bool | str | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Delete a collection on the Hub.
Args:
collection_slug (`str`):
Slug of the collection to delete. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
missing_ok (`bool`, *optional*):
If `True`, do not raise an error if the collection doesn't exist.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Example:
```py
>>> from huggingface_hub import delete_collection
>>> collection = delete_collection("username/useless-collection-64f9a55bb3115b4f513ec026", missing_ok=True)
```
> [!WARNING]
> This is a non-revertible action. A deleted collection cannot be restored.
huggingface-hub.delete_collection_item
Python Library Documentation: method delete_collection_item in module huggingface_hub.hf_api
delete_collection_item(collection_slug: 'str', item_object_id: 'str', *, missing_ok: 'bool' = False, token: 'bool | str | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Delete an item from a collection.
Args:
collection_slug (`str`):
Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
item_object_id (`str`):
ID of the item in the collection. This is not the id of the item on the Hub (repo_id or paper id).
It must be retrieved from a [`CollectionItem`] object. Example: `collection.items[0].item_object_id`.
missing_ok (`bool`, *optional*):
If `True`, do not raise an error if the item doesn't exist.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Example:
```py
>>> from huggingface_hub import get_collection, delete_collection_item
# Get collection first
>>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")
# Delete item based on its ID
>>> delete_collection_item(
... collection_slug="TheBloke/recent-models-64f9a55bb3115b4f513ec026",
... item_object_id=collection.items[-1].item_object_id,
... )
```
huggingface-hub.delete_file
Python Library Documentation: method delete_file in module huggingface_hub.hf_api
delete_file(path_in_repo: 'str', repo_id: 'str', *, token: 'str | bool | None' = None, repo_type: 'str | None' = None, revision: 'str | None' = None, commit_message: 'str | None' = None, commit_description: 'str | None' = None, create_pr: 'bool | None' = None, parent_commit: 'str | None' = None) -> 'CommitInfo' method of huggingface_hub.hf_api.HfApi instance
Deletes a file in the given repo.
Args:
path_in_repo (`str`):
Relative filepath in the repo, for example:
`"checkpoints/1fec34a/weights.bin"`
repo_id (`str`):
The repository from which the file will be deleted, for example:
`"username/custom_transformers"`
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if the file is in a dataset or
space, `None` or `"model"` if in a model. Default is `None`.
revision (`str`, *optional*):
The git revision to commit from. Defaults to the head of the `"main"` branch.
commit_message (`str`, *optional*):
The summary / title / first line of the generated commit. Defaults to
`f"Delete {path_in_repo} with huggingface_hub"`.
commit_description (`str` *optional*)
The description of the generated commit
create_pr (`boolean`, *optional*):
Whether or not to create a Pull Request with that commit. Defaults to `False`.
If `revision` is not set, PR is opened against the `"main"` branch. If
`revision` is set and is a branch, PR is opened against this branch. If
`revision` is set and is not a branch name (example: a commit oid), an
`RevisionNotFoundError` is returned by the server.
parent_commit (`str`, *optional*):
The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
especially useful if the repo is updated / committed to concurrently.
> [!TIP]
> Raises the following errors:
>
> - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
> if the HuggingFace API returned an error
> - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
> if some parameter value is invalid
> - [`~utils.RepositoryNotFoundError`]
> If the repository to download from cannot be found. This may be because it doesn't exist,
> or because it is set to `private` and you do not have access.
> - [`~utils.RevisionNotFoundError`]
> If the revision to download from cannot be found.
> - [`~utils.EntryNotFoundError`]
> If the file to download cannot be found.
huggingface-hub.delete_folder
Python Library Documentation: method delete_folder in module huggingface_hub.hf_api
delete_folder(path_in_repo: 'str', repo_id: 'str', *, token: 'bool | str | None' = None, repo_type: 'str | None' = None, revision: 'str | None' = None, commit_message: 'str | None' = None, commit_description: 'str | None' = None, create_pr: 'bool | None' = None, parent_commit: 'str | None' = None) -> 'CommitInfo' method of huggingface_hub.hf_api.HfApi instance
Deletes a folder in the given repo.
Simple wrapper around [`create_commit`] method.
Args:
path_in_repo (`str`):
Relative folder path in the repo, for example: `"checkpoints/1fec34a"`.
repo_id (`str`):
The repository from which the folder will be deleted, for example:
`"username/custom_transformers"`
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
to the stored token.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if the folder is in a dataset or
space, `None` or `"model"` if in a model. Default is `None`.
revision (`str`, *optional*):
The git revision to commit from. Defaults to the head of the `"main"` branch.
commit_message (`str`, *optional*):
The summary / title / first line of the generated commit. Defaults to
`f"Delete folder {path_in_repo} with huggingface_hub"`.
commit_description (`str` *optional*)
The description of the generated commit.
create_pr (`boolean`, *optional*):
Whether or not to create a Pull Request with that commit. Defaults to `False`.
If `revision` is not set, PR is opened against the `"main"` branch. If
`revision` is set and is a branch, PR is opened against this branch. If
`revision` is set and is not a branch name (example: a commit oid), an
`RevisionNotFoundError` is returned by the server.
parent_commit (`str`, *optional*):
The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
especially useful if the repo is updated / committed to concurrently.
huggingface-hub.delete_inference_endpoint
Python Library Documentation: method delete_inference_endpoint in module huggingface_hub.hf_api
delete_inference_endpoint(name: 'str', *, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Delete an Inference Endpoint.
This operation is not reversible. If you don't want to be charged for an Inference Endpoint, it is preferable
to pause it with [`pause_inference_endpoint`] or scale it to zero with [`scale_to_zero_inference_endpoint`].
For convenience, you can also delete an Inference Endpoint using [`InferenceEndpoint.delete`].
Args:
name (`str`):
The name of the Inference Endpoint to delete.
namespace (`str`, *optional*):
The namespace in which the Inference Endpoint is located. Defaults to the current user.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
huggingface-hub.delete_repo
Python Library Documentation: method delete_repo in module huggingface_hub.hf_api
delete_repo(repo_id: 'str', *, token: 'str | bool | None' = None, repo_type: 'str | None' = None, missing_ok: 'bool' = False) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Delete a repo from the HuggingFace Hub. CAUTION: this is irreversible.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model.
missing_ok (`bool`, *optional*, defaults to `False`):
If `True`, do not raise an error if repo does not exist.
Raises:
[`~utils.RepositoryNotFoundError`]
If the repository to delete from cannot be found and `missing_ok` is set to False (default).
huggingface-hub.delete_scheduled_job
Python Library Documentation: method delete_scheduled_job in module huggingface_hub.hf_api
delete_scheduled_job(*, scheduled_job_id: 'str', namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Delete a scheduled compute Job on Hugging Face infrastructure.
Args:
scheduled_job_id (`str`):
ID of the scheduled Job.
namespace (`str`, *optional*):
The namespace where the scheduled Job is. Defaults to the current user's namespace.
token `(Union[bool, str, None]`, *optional*):
A valid user access token. If not provided, the locally saved token will be used, which is the
recommended authentication method. Set to `False` to disable authentication.
Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
huggingface-hub.delete_space_secret
Python Library Documentation: method delete_space_secret in module huggingface_hub.hf_api
delete_space_secret(repo_id: 'str', key: 'str', *, token: 'bool | str | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Deletes a secret from a Space.
Secrets allow to set secret keys or tokens to a Space without hardcoding them.
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
Args:
repo_id (`str`):
ID of the repo to update. Example: `"bigcode/in-the-stack"`.
key (`str`):
Secret key. Example: `"GITHUB_API_KEY"`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
huggingface-hub.delete_space_storage
Python Library Documentation: method delete_space_storage in module huggingface_hub.hf_api
delete_space_storage(repo_id: 'str', *, token: 'bool | str | None' = None) -> 'SpaceRuntime' method of huggingface_hub.hf_api.HfApi instance
Delete persistent storage for a Space.
> [!WARNING]
> `delete_space_storage` is deprecated and will be removed in version 2.0. Use [`delete_space_volumes`] instead.
Args:
repo_id (`str`):
ID of the Space to update. Example: `"open-llm-leaderboard/open_llm_leaderboard"`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
Raises:
[`BadRequestError`]
If space has no persistent storage.
huggingface-hub.delete_space_variable
Python Library Documentation: method delete_space_variable in module huggingface_hub.hf_api
delete_space_variable(repo_id: 'str', key: 'str', *, token: 'bool | str | None' = None) -> 'dict[str, SpaceVariable]' method of huggingface_hub.hf_api.HfApi instance
Deletes a variable from a Space.
Variables allow to set environment variables to a Space without hardcoding them.
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables
Args:
repo_id (`str`):
ID of the repo to update. Example: `"bigcode/in-the-stack"`.
key (`str`):
Variable key. Example: `"MODEL_REPO_ID"`
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
huggingface-hub.delete_space_volumes
Python Library Documentation: method delete_space_volumes in module huggingface_hub.hf_api
delete_space_volumes(repo_id: 'str', *, token: 'bool | str | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Remove all volumes from a Space.
Args:
repo_id (`str`):
ID of the Space to update. Example: `"username/my-space"`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Raises:
[`BadRequestError`]:
If the Space has no volumes attached.
Example:
```python
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> api.delete_space_volumes("username/my-space")
```
huggingface-hub.delete_tag
Python Library Documentation: method delete_tag in module huggingface_hub.hf_api
delete_tag(repo_id: 'str', *, tag: 'str', token: 'bool | str | None' = None, repo_type: 'str | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Delete a tag from a repo on the Hub.
Args:
repo_id (`str`):
The repository in which a tag will be deleted.
Example: `"user/my-cool-model"`.
tag (`str`):
The name of the tag to delete.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if tagging a dataset or space, `None` or
`"model"` if tagging a model. Default is `None`.
Raises:
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private
but not authenticated or repo does not exist.
[`~utils.RevisionNotFoundError`]:
If tag is not found.
huggingface-hub.delete_webhook
Python Library Documentation: method delete_webhook in module huggingface_hub.hf_api
delete_webhook(webhook_id: 'str', *, token: 'bool | str | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Delete a webhook.
Args:
webhook_id (`str`):
The unique identifier of the webhook to delete.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved token, which is the recommended
method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`None`
Example:
```python
>>> from huggingface_hub import delete_webhook
>>> delete_webhook("654bbbc16f2ec14d77f109cc")
```
huggingface-hub.disable_space_dev_mode
Python Library Documentation: method disable_space_dev_mode in module huggingface_hub.hf_api
disable_space_dev_mode(repo_id: 'str', *, token: 'bool | str | None' = None) -> 'SpaceRuntime' method of huggingface_hub.hf_api.HfApi instance
Disable dev mode on a Space.
Spaces Dev Mode eases the debugging of your application and makes iterating on Spaces faster by allowing you
to restart your application without stopping the Space container itself. This feature is available as part of
a PRO or Team & Enterprise plan. See https://huggingface.co/docs/hub/spaces-dev-mode for more details.
Args:
repo_id (`str`):
ID of the Space to disable dev mode. Example: `"Salesforce/BLIP2"`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`SpaceRuntime`]: Runtime information about your Space.
Raises:
[`~utils.RepositoryNotFoundError`]:
If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you
are not authenticated.
[`~utils.HfHubHTTPError`]:
403 Forbidden: only the owner of a Space can set dev mode. If you want to handle a Space that you don't
own, either ask the owner by opening a Discussion or duplicate the Space.
[`~utils.BadRequestError`]:
If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide
a static Space, you can set it to private.
huggingface-hub.disable_webhook
Python Library Documentation: method disable_webhook in module huggingface_hub.hf_api
disable_webhook(webhook_id: 'str', *, token: 'bool | str | None' = None) -> 'WebhookInfo' method of huggingface_hub.hf_api.HfApi instance
Disable a webhook (makes it "disabled").
Args:
webhook_id (`str`):
The unique identifier of the webhook to disable.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved token, which is the recommended
method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`WebhookInfo`]:
Info about the disabled webhook.
Example:
```python
>>> from huggingface_hub import disable_webhook
>>> disabled_webhook = disable_webhook("654bbbc16f2ec14d77f109cc")
>>> disabled_webhook
WebhookInfo(
id="654bbbc16f2ec14d77f109cc",
url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
jon=None,
watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
domains=["repo", "discussion"],
secret="my-secret",
disabled=True,
)
```
huggingface-hub.download_bucket_files
Python Library Documentation: method download_bucket_files in module huggingface_hub.hf_api
download_bucket_files(bucket_id: 'str', files: 'list[tuple[str | BucketFile, str | Path]]', *, raise_on_missing_files: 'bool' = False, token: 'str | bool | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Download files from a bucket.
Files input is a list of `(remote file, local file)` tuples where `remote file` is either the path of the file
in the bucket or a [`BucketFile`] object, and `local file` is the destination path on the local filesystem.
When passing a [`BucketFile`] object (obtained from [`list_bucket_tree`]), the method will skip the metadata
fetching step and directly download the files.
Args:
bucket_id (`str`):
The ID of the bucket (e.g. `"username/my-bucket"`).
files (`list[tuple[Union[str, BucketFile], Union[str, Path]]]`):
Files to download as a list of tuple (source, destination). See description above for format details.
raise_on_missing_files (`bool`, *optional*):
If `True`, raise an [`EntryNotFoundError`] when a requested file does not exist in the bucket. If
`False` (default), missing files are skipped with a warning.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Example:
```python
>>> from huggingface_hub import download_bucket_files
>>> download_bucket_files(
... bucket_id="username/my-bucket",
... files=[
... ("models/model.safetensors", "./local/model.safetensors"),
... ("config.json", "./local/config.json"),
... ],
... )
```
```python
>>> from huggingface_hub import download_bucket_files
>>> parquet_files = [file for file in list_bucket_tree(bucket_id="username/my-bucket") if file.path.endswith(".parquet")]
>>> download_bucket_files(
... bucket_id="username/my-bucket",
... files=[(file, f"./local/{file.path}") for file in parquet_files],
... )
```
huggingface-hub.dump_environment_info
Python Library Documentation: function dump_environment_info in module huggingface_hub.utils._runtime
dump_environment_info() -> dict[str, typing.Any]
Dump information about the machine to help debugging issues.
Similar helper exist in:
- `datasets` (https://github.com/huggingface/datasets/blob/main/src/datasets/commands/env.py)
- `diffusers` (https://github.com/huggingface/diffusers/blob/main/src/diffusers/commands/env.py)
- `transformers` (https://github.com/huggingface/transformers/blob/main/src/transformers/commands/env.py)
huggingface-hub.duplicate_repo
Python Library Documentation: method duplicate_repo in module huggingface_hub.hf_api
duplicate_repo(from_id: 'str', to_id: 'str | None' = None, *, repo_type: 'str | None' = None, private: 'bool | None' = None, visibility: 'RepoVisibility_T | None' = None, token: 'bool | str | None' = None, exist_ok: 'bool' = False, space_hardware: 'SpaceHardware | None' = None, space_storage: 'SpaceStorage | None' = None, space_sleep_time: 'int | None' = None, space_secrets: 'list[dict[str, str]] | None' = None, space_variables: 'list[dict[str, str]] | None' = None, space_volumes: 'list[Volume] | None' = None) -> 'RepoUrl' method of huggingface_hub.hf_api.HfApi instance
Duplicate a repo on the Hub (model, dataset, or Space).
This performs a server-side copy that preserves full git history and LFS objects
without requiring a local download/upload round-trip.
Args:
from_id (`str`):
ID of the repo to duplicate. Example: `"openai/gdpval"`.
to_id (`str`, *optional*):
ID of the new repo. Example: `"myorg/my-gdpval"`. If not provided, the new
repo will have the same name as the original repo, but in your account.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if duplicating a dataset or Space,
`None` or `"model"` if duplicating a model. Default is `None`.
private (`bool`, *optional*):
Whether the new repo should be private or not. Defaults to the same
privacy as the original repo. Cannot be passed together with `visibility`.
visibility (`Literal["public", "private", "protected"]`, *optional*):
Visibility of the new repo. Can be `"public"` or `"private"`, or `"protected"` for Spaces. Defaults
to the same visibility as the original repo.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
exist_ok (`bool`, *optional*, defaults to `False`):
If `True`, do not raise an error if repo already exists.
space_hardware (`SpaceHardware` or `str`, *optional*):
Choice of Hardware if repo_type is "space". Example: `"t4-medium"`. See
[`SpaceHardware`] for a complete list.
space_storage (`SpaceStorage` or `str`, *optional*):
<Deprecated, use `set_space_volumes` instead> Choice of persistent storage tier if repo_type is "space". Example:
`"small"`. See [`SpaceStorage`] for a complete list.
space_sleep_time (`int`, *optional*):
Number of seconds of inactivity to wait before a Space is put to sleep.
Set to `-1` if you don't want your Space to sleep (default behavior for
upgraded hardware). For free hardware, you can't configure the sleep time
(value is fixed to 48 hours of inactivity). Only applicable if repo_type is "space".
See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
space_secrets (`list[dict[str, str]]`, *optional*):
A list of secret keys to set in your Space. Each item is in the form
`{"key": ..., "value": ..., "description": ...}` where description is optional.
Only applicable if repo_type is "space".
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
space_variables (`list[dict[str, str]]`, *optional*):
A list of public environment variables to set in your Space. Each item is in
the form `{"key": ..., "value": ..., "description": ...}` where description
is optional. Only applicable if repo_type is "space".
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables.
space_volumes (`list[Volume]`, *optional*):
A list of [`Volume`] objects to mount in the Space at duplication time. Each volume has a `type`
(`"bucket"`, `"model"`, `"dataset"`, or `"space"`), a `source` (repo or bucket ID), a `mount_path`
(path inside the container), and optional `revision`, `read_only`, and `path` fields.
Only applicable if repo_type is "space".
Returns:
[`RepoUrl`]: URL to the newly created repo. Value is a subclass of `str` containing
attributes like `endpoint`, `repo_type` and `repo_id`.
Raises:
[`~utils.RepositoryNotFoundError`]:
If one of `from_id` or `to_id` cannot be found. This may be because it doesn't exist,
or because it is set to `private` and you do not have access.
[`HfHubHTTPError`]:
If the HuggingFace API returned an error
Example:
```python
>>> from huggingface_hub import duplicate_repo
# Duplicate a model to your account
>>> duplicate_repo("google/gemma-7b")
RepoUrl('https://huggingface.co/nateraw/gemma-7b',...)
# Duplicate a dataset with a custom name
>>> duplicate_repo("openai/gdpval", to_id="myorg/my-gdpval", repo_type="dataset")
RepoUrl('https://huggingface.co/datasets/myorg/my-gdpval',...)
# Duplicate a Space with custom hardware
>>> duplicate_repo("multimodalart/dreambooth-training", repo_type="space", space_hardware="t4-medium")
RepoUrl('https://huggingface.co/spaces/nateraw/dreambooth-training',...)
```
huggingface-hub.duplicate_space
Python Library Documentation: method duplicate_space in module huggingface_hub.hf_api
duplicate_space(from_id: 'str', to_id: 'str | None' = None, *, private: 'bool | None' = None, visibility: 'RepoVisibility_T | None' = None, token: 'bool | str | None' = None, exist_ok: 'bool' = False, hardware: 'SpaceHardware | None' = None, storage: 'SpaceStorage | None' = None, sleep_time: 'int | None' = None, secrets: 'list[dict[str, str]] | None' = None, variables: 'list[dict[str, str]] | None' = None) -> 'RepoUrl' method of huggingface_hub.hf_api.HfApi instance
Duplicate a Space.
Programmatically duplicate a Space. The new Space will be created in your account and will be in the same state
as the original Space (running or paused). You can duplicate a Space no matter the current state of a Space.
Args:
from_id (`str`):
ID of the Space to duplicate. Example: `"pharma/CLIP-Interrogator"`.
to_id (`str`, *optional*):
ID of the new Space. Example: `"dog/CLIP-Interrogator"`. If not provided, the new Space will have the same
name as the original Space, but in your account.
private (`bool`, *optional*):
Whether the new Space should be private or not. Defaults to the same privacy as the original Space. Cannot be passed together with `visibility`.
visibility (`Literal["public", "private", "protected"]`, *optional*):
Visibility of the new Space. Can be `"public"`, `"private"`, or `"protected"`. Defaults to the same
visibility as the original Space.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
exist_ok (`bool`, *optional*, defaults to `False`):
If `True`, do not raise an error if repo already exists.
hardware (`SpaceHardware` or `str`, *optional*):
Choice of Hardware. Example: `"t4-medium"`. See [`SpaceHardware`] for a complete list.
storage (`SpaceStorage` or `str`, *optional*):
Choice of persistent storage tier. Example: `"small"`. See [`SpaceStorage`] for a complete list.
sleep_time (`int`, *optional*):
Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure
the sleep time (value is fixed to 48 hours of inactivity).
See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
secrets (`list[dict[str, str]]`, *optional*):
A list of secret keys to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
variables (`list[dict[str, str]]`, *optional*):
A list of public environment variables to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables.
Returns:
[`RepoUrl`]: URL to the newly created repo. Value is a subclass of `str` containing
attributes like `endpoint`, `repo_type` and `repo_id`.
Raises:
[`~utils.RepositoryNotFoundError`]:
If one of `from_id` or `to_id` cannot be found. This may be because it doesn't exist,
or because it is set to `private` and you do not have access.
[`HfHubHTTPError`]:
If the HuggingFace API returned an error
Example:
```python
>>> from huggingface_hub import duplicate_space
# Duplicate a Space to your account
>>> duplicate_space("multimodalart/dreambooth-training")
RepoUrl('https://huggingface.co/spaces/nateraw/dreambooth-training',...)
# Can set custom destination id and visibility flag.
>>> duplicate_space("multimodalart/dreambooth-training", to_id="my-dreambooth", visibility="private")
RepoUrl('https://huggingface.co/spaces/nateraw/my-dreambooth',...)
```
> [!WARNING]
> `duplicate_space` is deprecated and will be removed in version 2.0. Use [`~HfApi.duplicate_repo`] instead.
huggingface-hub.edit_discussion_comment
Python Library Documentation: method edit_discussion_comment in module huggingface_hub.hf_api
edit_discussion_comment(repo_id: 'str', discussion_num: 'int', comment_id: 'str', new_content: 'str', *, token: 'bool | str | None' = None, repo_type: 'str | None' = None) -> 'DiscussionComment' method of huggingface_hub.hf_api.HfApi instance
Edits a comment on a Discussion / Pull Request.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
discussion_num (`int`):
The number of the Discussion or Pull Request . Must be a strictly positive integer.
comment_id (`str`):
The ID of the comment to edit.
new_content (`str`):
The new content of the comment. Comments support markdown formatting.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`DiscussionComment`]: the edited comment
> [!TIP]
> Raises the following errors:
>
> - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
> if the HuggingFace API returned an error
> - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
> if some parameter value is invalid
> - [`~utils.RepositoryNotFoundError`]
> If the repository to download from cannot be found. This may be because it doesn't exist,
> or because it is set to `private` and you do not have access.
huggingface-hub.enable_space_dev_mode
Python Library Documentation: method enable_space_dev_mode in module huggingface_hub.hf_api
enable_space_dev_mode(repo_id: 'str', *, token: 'bool | str | None' = None) -> 'SpaceRuntime' method of huggingface_hub.hf_api.HfApi instance
Enable dev mode on a Space.
Spaces Dev Mode eases the debugging of your application and makes iterating on Spaces faster by allowing you
to restart your application without stopping the Space container itself. This feature is available as part of
a PRO or Team & Enterprise plan. See https://huggingface.co/docs/hub/spaces-dev-mode for more details.
Args:
repo_id (`str`):
ID of the Space to enable dev mode. Example: `"Salesforce/BLIP2"`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`SpaceRuntime`]: Runtime information about your Space.
Raises:
[`~utils.RepositoryNotFoundError`]:
If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you
are not authenticated.
[`~utils.HfHubHTTPError`]:
403 Forbidden: only the owner of a Space can set dev mode. If you want to handle a Space that you don't
own, either ask the owner by opening a Discussion or duplicate the Space.
[`~utils.BadRequestError`]:
If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide
a static Space, you can set it to private.
huggingface-hub.enable_webhook
Python Library Documentation: method enable_webhook in module huggingface_hub.hf_api
enable_webhook(webhook_id: 'str', *, token: 'bool | str | None' = None) -> 'WebhookInfo' method of huggingface_hub.hf_api.HfApi instance
Enable a webhook (makes it "active").
Args:
webhook_id (`str`):
The unique identifier of the webhook to enable.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved token, which is the recommended
method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`WebhookInfo`]:
Info about the enabled webhook.
Example:
```python
>>> from huggingface_hub import enable_webhook
>>> enabled_webhook = enable_webhook("654bbbc16f2ec14d77f109cc")
>>> enabled_webhook
WebhookInfo(
id="654bbbc16f2ec14d77f109cc",
job=None,
url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
domains=["repo", "discussion"],
secret="my-secret",
disabled=False,
)
```
huggingface-hub.eval_result_entries_to_yaml
Python Library Documentation: function eval_result_entries_to_yaml in module huggingface_hub._eval_results
eval_result_entries_to_yaml(entries: list[huggingface_hub._eval_results.EvalResultEntry]) -> list[dict[str, typing.Any]]
Convert a list of [`EvalResultEntry`] objects to a YAML-serializable list of dicts.
This produces the format expected in `.eval_results/*.yaml` files.
Args:
entries (`list[EvalResultEntry]`):
List of evaluation result entries to serialize.
Returns:
`list[dict[str, Any]]`: A list of dictionaries ready to be dumped to YAML.
Example:
```python
>>> from huggingface_hub import EvalResultEntry, eval_result_entries_to_yaml
>>> entries = [
... EvalResultEntry(dataset_id="cais/hle", task_id="default", value=20.90),
... EvalResultEntry(dataset_id="Idavidrein/gpqa", task_id="gpqa_diamond", value=0.412),
... ]
>>> yaml_data = eval_result_entries_to_yaml(entries)
>>> yaml_data[0]
{'dataset': {'id': 'cais/hle', 'task_id': 'default'}, 'value': 20.9}
```
To upload eval results to the Hub:
```python
>>> import yaml
>>> from huggingface_hub import upload_file, EvalResultEntry, eval_result_entries_to_yaml
>>> entries = [
... EvalResultEntry(dataset_id="cais/hle", task_id="default", value=20.90),
... ]
>>> yaml_content = yaml.dump(eval_result_entries_to_yaml(entries))
>>> upload_file(
... path_or_fileobj=yaml_content.encode(),
... path_in_repo=".eval_results/hle.yaml",
... repo_id="your-username/your-model",
... )
```
huggingface-hub.export_entries_as_dduf
Python Library Documentation: function export_entries_as_dduf in module huggingface_hub.serialization._dduf
export_entries_as_dduf(dduf_path: str | os.PathLike, entries: collections.abc.Iterable[tuple[str, str | pathlib.Path | bytes]]) -> None
Write a DDUF file from an iterable of entries.
This is a lower-level helper than [`export_folder_as_dduf`] that allows more flexibility when serializing data.
In particular, you don't need to save the data on disk before exporting it in the DDUF file.
Args:
dduf_path (`str` or `os.PathLike`):
The path to the DDUF file to write.
entries (`Iterable[tuple[str, Union[str, Path, bytes]]]`):
An iterable of entries to write in the DDUF file. Each entry is a tuple with the filename and the content.
The filename should be the path to the file in the DDUF archive.
The content can be a string or a pathlib.Path representing a path to a file on the local disk or directly the content as bytes.
Raises:
- [`DDUFExportError`]: If anything goes wrong during the export (e.g. invalid entry name, missing 'model_index.json', etc.).
Example:
```python
# Export specific files from the local disk.
>>> from huggingface_hub import export_entries_as_dduf
>>> export_entries_as_dduf(
... dduf_path="stable-diffusion-v1-4-FP16.dduf",
... entries=[ # List entries to add to the DDUF file (here, only FP16 weights)
... ("model_index.json", "path/to/model_index.json"),
... ("vae/config.json", "path/to/vae/config.json"),
... ("vae/diffusion_pytorch_model.fp16.safetensors", "path/to/vae/diffusion_pytorch_model.fp16.safetensors"),
... ("text_encoder/config.json", "path/to/text_encoder/config.json"),
... ("text_encoder/model.fp16.safetensors", "path/to/text_encoder/model.fp16.safetensors"),
... # ... add more entries here
... ]
... )
```
```python
# Export state_dicts one by one from a loaded pipeline
>>> from diffusers import DiffusionPipeline
>>> from typing import Generator, Tuple
>>> import safetensors.torch
>>> from huggingface_hub import export_entries_as_dduf
>>> pipe = DiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4")
... # ... do some work with the pipeline
>>> def as_entries(pipe: DiffusionPipeline) -> Generator[tuple[str, bytes], None, None]:
... # Build a generator that yields the entries to add to the DDUF file.
... # The first element of the tuple is the filename in the DDUF archive (must use UNIX separator!). The second element is the content of the file.
... # Entries will be evaluated lazily when the DDUF file is created (only 1 entry is loaded in memory at a time)
... yield "vae/config.json", pipe.vae.to_json_string().encode()
... yield "vae/diffusion_pytorch_model.safetensors", safetensors.torch.save(pipe.vae.state_dict())
... yield "text_encoder/config.json", pipe.text_encoder.config.to_json_string().encode()
... yield "text_encoder/model.safetensors", safetensors.torch.save(pipe.text_encoder.state_dict())
... # ... add more entries here
>>> export_entries_as_dduf(dduf_path="stable-diffusion-v1-4.dduf", entries=as_entries(pipe))
```
huggingface-hub.export_folder_as_dduf
Python Library Documentation: function export_folder_as_dduf in module huggingface_hub.serialization._dduf
export_folder_as_dduf(dduf_path: str | os.PathLike, folder_path: str | os.PathLike) -> None
Export a folder as a DDUF file.
AUses [`export_entries_as_dduf`] under the hood.
Args:
dduf_path (`str` or `os.PathLike`):
The path to the DDUF file to write.
folder_path (`str` or `os.PathLike`):
The path to the folder containing the diffusion model.
Example:
```python
>>> from huggingface_hub import export_folder_as_dduf
>>> export_folder_as_dduf(dduf_path="FLUX.1-dev.dduf", folder_path="path/to/FLUX.1-dev")
```
huggingface-hub.fetch_job_logs
Python Library Documentation: method fetch_job_logs in module huggingface_hub.hf_api
fetch_job_logs(*, job_id: 'str', namespace: 'str | None' = None, follow: 'bool' = False, tail: 'int | None' = None, token: 'bool | str | None' = None) -> 'Iterable[str]' method of huggingface_hub.hf_api.HfApi instance
Fetch all the logs from a compute Job on Hugging Face infrastructure.
Args:
job_id (`str`):
ID of the Job.
namespace (`str`, *optional*):
The namespace where the Job is running. Defaults to the current user's namespace.
follow (`bool`, *optional*):
If `True`, stream logs in real-time until the job completes (blocking).
If `False` (default), fetch only the currently available logs and return immediately (non-blocking).
tail (`int`, *optional*):
Maximum number of lines to return from the logs. When combined with `follow=True`,
starts from the last N lines and continues streaming new logs. When `follow=False`,
returns only the last N lines from currently available logs.
token `(Union[bool, str, None]`, *optional*):
A valid user access token. If not provided, the locally saved token will be used, which is the
recommended authentication method. Set to `False` to disable authentication.
Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
Example:
```python
>>> from huggingface_hub import fetch_job_logs, run_job
>>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"])
>>> for log in fetch_job_logs(job_id=job.id):
... print(log)
Hello from HF compute!
>>> # Non-blocking: fetch only currently available logs
>>> for log in fetch_job_logs(job_id=job.id, follow=False):
... print(log)
>>> # Stream logs starting from the last 100 lines
>>> for log in fetch_job_logs(job_id=job.id, follow=True, tail=100):
... print(log)
```
huggingface-hub.fetch_job_metrics
Python Library Documentation: method fetch_job_metrics in module huggingface_hub.hf_api
fetch_job_metrics(*, job_id: 'str', namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'Iterable[dict[str, Any]]' method of huggingface_hub.hf_api.HfApi instance
Fetch all the live metrics from a compute Job on Hugging Face infrastructure.
Args:
job_id (`str`):
ID of the Job.
namespace (`str`, *optional*):
The namespace where the Job is running. Defaults to the current user's namespace.
token `(Union[bool, str, None]`, *optional*):
A valid user access token. If not provided, the locally saved token will be used, which is the
recommended authentication method. Set to `False` to disable authentication.
Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
Example:
```python
>>> from huggingface_hub import fetch_job_metrics, run_job
>>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"], flavor="a10g-small")
>>> for metrics in fetch_job_metrics(job_id=job.id):
... print(metrics)
{
"cpu_usage_pct": 0,
"cpu_millicores": 3500,
"memory_used_bytes": 1306624,
"memory_total_bytes": 15032385536,
"rx_bps": 0,
"tx_bps": 0,
"gpus": {
"882fa930": {
"utilization": 0,
"memory_used_bytes": 0,
"memory_total_bytes": 22836000000
}
},
"replica": "57vr7"
}
```
huggingface-hub.fetch_space_logs
Python Library Documentation: method fetch_space_logs in module huggingface_hub.hf_api
fetch_space_logs(repo_id: 'str', *, build: 'bool' = False, follow: 'bool' = False, token: 'bool | str | None' = None) -> 'Iterable[str]' method of huggingface_hub.hf_api.HfApi instance
Fetch the run or build logs of a Space on the Hub.
Useful for debugging a Space that is failing to build or crashing at runtime,
especially from a script or agentic workflow where reading logs in a browser
is not an option.
Args:
repo_id (`str`):
ID of the Space. Example: `"bigcode/in-the-stack"`.
build (`bool`, *optional*, defaults to `False`):
If `True`, fetch the container build logs (useful when a Space is stuck
in `BUILD_ERROR`). If `False` (default), fetch the run logs, i.e. the
stdout/stderr of the running application.
follow (`bool`, *optional*, defaults to `False`):
If `True`, stream logs in real-time (blocking) until the server closes
the stream or `KeyboardInterrupt` is raised. If `False` (default), fetch
only the currently buffered logs and return immediately (non-blocking,
like `docker logs`).
token (`bool` or `str`, *optional*):
A valid user access token. Defaults to the locally saved token, which is
the recommended authentication method. Set to `False` to disable
authentication. See
https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
Returns:
`Iterable[str]`: A generator yielding log lines as they become available.
Example:
```python
>>> from huggingface_hub import fetch_space_logs
>>> # Non-blocking: print currently available run logs and exit.
>>> for line in fetch_space_logs("username/my-space"):
... print(line, end="")
>>> # Debug a build failure:
>>> for line in fetch_space_logs("username/my-space", build=True):
... print(line, end="")
>>> # Stream run logs until the server closes the stream.
>>> for line in fetch_space_logs("username/my-space", follow=True):
... print(line, end="")
```
huggingface-hub.file_exists
Python Library Documentation: method file_exists in module huggingface_hub.hf_api
file_exists(repo_id: 'str', filename: 'str', *, repo_type: 'str | None' = None, revision: 'str | None' = None, token: 'str | bool | None' = None) -> 'bool' method of huggingface_hub.hf_api.HfApi instance
Checks if a file exists in a repository on the Hugging Face Hub.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
filename (`str`):
The name of the file to check, for example:
`"config.json"`
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
`None` or `"model"` if getting repository info from a model. Default is `None`.
revision (`str`, *optional*):
The revision of the repository from which to get the information. Defaults to `"main"` branch.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
True if the file exists, False otherwise.
Examples:
```py
>>> from huggingface_hub import file_exists
>>> file_exists("bigcode/starcoder", "config.json")
True
>>> file_exists("bigcode/starcoder", "not-a-file")
False
>>> file_exists("bigcode/not-a-repo", "config.json")
False
```
huggingface-hub.from_pretrained_fastai
Python Library Documentation: function from_pretrained_fastai in module huggingface_hub.fastai_utils
from_pretrained_fastai(repo_id: str, revision: str | None = None)
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.
huggingface-hub.get_async_session
Python Library Documentation: function get_async_session in module huggingface_hub.utils._http
get_async_session() -> httpx.AsyncClient
Return a `httpx.AsyncClient` object, using the transport factory from the user.
Use [`set_async_client_factory`] to customize the `httpx.AsyncClient`.
> [!WARNING]
> Contrary to the `httpx.Client` that is shared between all calls made by `huggingface_hub`, the `httpx.AsyncClient` is not shared.
> It is recommended to use an async context manager to ensure the client is properly closed when the context is exited.
huggingface-hub.get_bucket_file_metadata
Python Library Documentation: method get_bucket_file_metadata in module huggingface_hub.hf_api
get_bucket_file_metadata(bucket_id: 'str', remote_path: 'str', *, token: 'str | bool | None' = None) -> 'BucketFileMetadata' method of huggingface_hub.hf_api.HfApi instance
Fetch metadata of a file in a bucket.
Args:
bucket_id (`str`):
The ID of the bucket (e.g. `"username/my-bucket"`).
remote_path (`str`):
The path of the file in the bucket.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`BucketFileMetadata`]: The file metadata containing size and xet information.
Example:
```python
>>> from huggingface_hub import get_bucket_file_metadata
>>> metadata = get_bucket_file_metadata(
... bucket_id="username/my-bucket",
... remote_path="models/model.safetensors",
... )
>>> metadata.size
42000
```
huggingface-hub.get_bucket_paths_info
Python Library Documentation: method get_bucket_paths_info in module huggingface_hub.hf_api
get_bucket_paths_info(bucket_id: 'str', paths: 'Iterable[str]', *, token: 'str | bool | None' = None) -> 'Iterable[BucketFile]' method of huggingface_hub.hf_api.HfApi instance
Get information about a bucket's paths.
Calls are made in batches of 1000 paths. Results are yielded as they are received.
Args:
bucket_id (`str`):
The ID of the bucket (e.g. `"username/my-bucket"`).
paths (`Iterable[str]`):
The paths to get information about. If a path does not exist, it is ignored without raising an exception.
Only file paths are supported.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`Iterable[BucketFile]`:
The information about the paths, as an iterable of [`BucketFile`] objects.
Example:
```py
>>> from huggingface_hub import get_bucket_paths_info
>>> paths_info = get_bucket_paths_info("username/my-bucket", ["file.txt", "checkpoints/model.safetensors"])
>>> for info in paths_info:
... print(info)
BucketFile(type='file', path='file.txt', size=2379, xet_hash='96e637d9665bd35477b1908a23f2e254edfba0618dbd2d62f90a6baee7d139cf', mtime=datetime.datetime(2024, 9, 25, 15, 31, 2, 346000, tzinfo=datetime.timezone.utc))
BucketFile(type='file', path='checkpoints/model.safetensors', size=2408828, xet_hash='3ed0e9fefe788ddd61d1e26eba67057e9740a064b009256fbafadf6bb95785ca', mtime=datetime.datetime(2024, 9, 25, 15, 31, 2, 346000, tzinfo=datetime.timezone.utc))
```
huggingface-hub.get_cached_repo_tree
Python Library Documentation: function get_cached_repo_tree in module huggingface_hub._snapshot_download
get_cached_repo_tree(repo_id: str, *, repo_type: str | None = None, revision: str | None = None, cache_dir: str | pathlib.Path | None = None, local_dir: str | pathlib.Path | None = None) -> list[huggingface_hub.hf_api.RepoFile]
Return the cached tree listing of a repo at a given revision, without any network call.
The tree listing is the set of files (with their download metadata) of a repo at a commit. It is populated
on disk as a side effect of [`snapshot_download`] (see the `trees/<commit_hash>.json` cache files) and is
used to skip network calls on subsequent downloads. This function exposes that cache directly.
If you need the current tree listing of a repo on the Hub, use [`list_repo_tree`] instead.
Args:
repo_id (`str`):
A user or an organization name and a repo name separated by a `/`.
repo_type (`str`, *optional*):
Set to `"dataset"`, `"space"` or `"kernel"` if listing from a dataset, space or kernel repo,
`None` or `"model"` if listing from a model. Default is `None`.
revision (`str`, *optional*):
An optional Git revision id, which can be a branch name, a tag, or a commit hash. Defaults to the
default branch. Branch/tag names are resolved to a commit hash using the local cache (`refs/`).
cache_dir (`str`, `Path`, *optional*):
Path to the folder where cached files are stored. Defaults to the value of `HF_HUB_CACHE`.
local_dir (`str` or `Path`, *optional*):
If provided, read the tree listing cached by a `local_dir` download (from
`local_dir/.cache/huggingface/`) instead of the main cache. Branch/tag revisions are still resolved
to a commit hash using the main cache (`cache_dir`).
Returns:
`list[RepoFile]`: The list of [`RepoFile`] objects cached for this revision.
Raises:
[`~errors.CachedRepoTreeNotFoundError`]
If no tree listing is cached for the requested revision (e.g. the repo was never downloaded at this revision).
Example:
```py
>>> from huggingface_hub import get_cached_repo_tree
>>> files = get_cached_repo_tree("openai-community/gpt2")
>>> [f.path for f in files]
['.gitattributes', 'config.json', 'model.safetensors', ...]
```
huggingface-hub.get_collection
Python Library Documentation: method get_collection in module huggingface_hub.hf_api
get_collection(collection_slug: 'str', *, token: 'bool | str | None' = None) -> 'Collection' method of huggingface_hub.hf_api.HfApi instance
Gets information about a Collection on the Hub.
Args:
collection_slug (`str`):
Slug of the collection of the Hub. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns: [`Collection`]
Example:
```py
>>> from huggingface_hub import get_collection
>>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")
>>> collection.title
'Recent models'
>>> len(collection.items)
37
>>> collection.items[0]
CollectionItem(
item_object_id='651446103cd773a050bf64c2',
item_id='TheBloke/U-Amethyst-20B-AWQ',
item_type='model',
position=88,
note=None
)
```
huggingface-hub.get_dataset_leaderboard
Python Library Documentation: method get_dataset_leaderboard in module huggingface_hub.hf_api
get_dataset_leaderboard(repo_id: 'str', *, base_model_only: 'bool | None' = None, token: 'bool | str | None' = None, timeout: 'float | None' = None) -> 'list[DatasetLeaderboardEntry]' method of huggingface_hub.hf_api.HfApi instance
Get the leaderboard for a dataset on the Hub.
The leaderboard ranks models based on their evaluation scores on the given benchmark
dataset. Not all datasets have leaderboards — only benchmark datasets with evaluation
results submitted to them. This gives a dataset-centric view of scores; for a model-centric
view, use [`model_info`] with `expand=["evalResults"]`.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`. For example: `"allenai/olmOCR-bench"`.
base_model_only (`bool` or `None`, *optional*):
By default, the leaderboard only includes models that have no declared `base_model` relation
(i.e. canonical/root repos), matching the Hub's default leaderboard view. Fine-tuned or derivative
repos that declare a parent model are excluded. Pass `base_model_only=False` to disable this filter and
include every submitted result, regardless of whether the model declares a base model relation.
token (`bool` or `str`, *optional*):
A valid user access token. Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
timeout (`float`, *optional*):
Whether to set a timeout for the request to the Hub.
Returns:
`list[DatasetLeaderboardEntry]`: A list of [`DatasetLeaderboardEntry`] objects representing
the leaderboard entries, sorted by rank.
> [!TIP]
> Raises the following errors:
>
> - [`~utils.RepositoryNotFoundError`]
> If the repository cannot be found. This may be because it doesn't exist,
> or because it is set to `private` and you do not have access.
> - [`~utils.HfHubHTTPError`]
> If the dataset does not have a leaderboard.
Example:
```python
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> leaderboard = api.get_dataset_leaderboard("allenai/olmOCR-bench")
>>> leaderboard[0].model_id
'datalab-to/chandra-ocr-2'
>>> leaderboard[0].rank
1
# Include fine-tuned / derivative models too
>>> full_leaderboard = api.get_dataset_leaderboard("allenai/olmOCR-bench", base_model_only=False)
```
huggingface-hub.get_dataset_tags
Python Library Documentation: method get_dataset_tags in module huggingface_hub.hf_api
get_dataset_tags() -> 'dict' method of huggingface_hub.hf_api.HfApi instance
List all valid dataset tags as a nested namespace object.
huggingface-hub.get_discussion_details
Python Library Documentation: method get_discussion_details in module huggingface_hub.hf_api
get_discussion_details(repo_id: 'str', discussion_num: 'int', *, repo_type: 'str | None' = None, token: 'bool | str | None' = None) -> 'DiscussionWithDetails' method of huggingface_hub.hf_api.HfApi instance
Fetches a Discussion's / Pull Request 's details from the Hub.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
discussion_num (`int`):
The number of the Discussion or Pull Request . Must be a strictly positive integer.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns: [`DiscussionWithDetails`]
> [!TIP]
> Raises the following errors:
>
> - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
> if the HuggingFace API returned an error
> - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
> if some parameter value is invalid
> - [`~utils.RepositoryNotFoundError`]
> If the repository to download from cannot be found. This may be because it doesn't exist,
> or because it is set to `private` and you do not have access.
huggingface-hub.get_full_repo_name
Python Library Documentation: method get_full_repo_name in module huggingface_hub.hf_api
get_full_repo_name(model_id: 'str', *, organization: 'str | None' = None, token: 'bool | str | None' = None) method of huggingface_hub.hf_api.HfApi instance
Returns the repository name for a given model ID and optional
organization.
Args:
model_id (`str`):
The name of the model.
organization (`str`, *optional*):
If passed, the repository name will be in the organization
namespace instead of the user namespace.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`str`: The repository name in the user's namespace
({username}/{model_id}) if no organization is passed, and under the
organization namespace ({organization}/{model_id}) otherwise.
huggingface-hub.get_hf_file_metadata
Python Library Documentation: function get_hf_file_metadata in module huggingface_hub.file_download
get_hf_file_metadata(url: str, token: bool | str | None = None, timeout: float | None = 10, library_name: str | None = None, library_version: str | None = None, user_agent: dict | str | None = None, headers: dict[str, str] | None = None, endpoint: str | None = None, retry_on_errors: bool = False) -> huggingface_hub.file_download.HfFileMetadata
Fetch metadata of a file versioned on the Hub for a given url.
Args:
url (`str`):
File url, for example returned by [`hf_hub_url`].
token (`str` or `bool`, *optional*):
A token to be used for the download.
- If `True`, the token is read from the HuggingFace config
folder.
- If `False` or `None`, no token is provided.
- If a string, it's used as the authentication token.
timeout (`float`, *optional*, defaults to 10):
How many seconds to wait for the server to send metadata before giving up.
library_name (`str`, *optional*):
The name of the library to which the object corresponds.
library_version (`str`, *optional*):
The version of the library.
user_agent (`dict`, `str`, *optional*):
The user-agent info in the form of a dictionary or a string.
headers (`dict`, *optional*):
Additional headers to be sent with the request.
endpoint (`str`, *optional*):
Endpoint of the Hub. Defaults to <https://huggingface.co>.
retry_on_errors (`bool`, *optional*, defaults to `False`):
Whether to retry on errors (429, 5xx, timeout, network errors).
If False, no retry for fast fallback to local cache.
Returns:
A [`HfFileMetadata`] object containing metadata such as location, etag, size and
commit_hash.
huggingface-hub.get_inference_endpoint
Python Library Documentation: method get_inference_endpoint in module huggingface_hub.hf_api
get_inference_endpoint(name: 'str', *, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'InferenceEndpoint' method of huggingface_hub.hf_api.HfApi instance
Get information about an Inference Endpoint.
Args:
name (`str`):
The name of the Inference Endpoint to retrieve information about.
namespace (`str`, *optional*):
The namespace in which the Inference Endpoint is located. Defaults to the current user.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`InferenceEndpoint`]: information about the requested Inference Endpoint.
Example:
```python
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> endpoint = api.get_inference_endpoint("my-text-to-image")
>>> endpoint
InferenceEndpoint(name='my-text-to-image', ...)
# Get status
>>> endpoint.status
'running'
>>> endpoint.url
'https://my-text-to-image.region.vendor.endpoints.huggingface.cloud'
# Run inference
>>> endpoint.client.text_to_image(...)
```
huggingface-hub.get_local_safetensors_metadata
Python Library Documentation: function get_local_safetensors_metadata in module huggingface_hub.hf_api
get_local_safetensors_metadata(path: 'str | Path') -> 'SafetensorsRepoMetadata'
Parse metadata for a local safetensors file or folder.
Supports:
- Single safetensors file (e.g., `model.safetensors`)
- Directory with non-sharded model (contains `model.safetensors`)
- Directory with sharded model (contains `model.safetensors.index.json`)
For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.
Args:
path (`str` or `Path`):
Path to a safetensors file or directory containing safetensors files.
Returns:
[`SafetensorsRepoMetadata`]: information related to the safetensors repo.
Raises:
[`NotASafetensorsRepoError`]:
If the path is not a valid safetensors file or folder (i.e., doesn't have either a
`model.safetensors` or a `model.safetensors.index.json` file).
[`SafetensorsParsingError`]:
If a safetensors file header couldn't be parsed correctly.
`FileNotFoundError`:
If the path does not exist.
Example:
```py
# Parse single safetensors file
>>> metadata = get_local_safetensors_metadata("path/to/model.safetensors")
>>> metadata
SafetensorsRepoMetadata(metadata=None, sharded=False, weight_map={...}, files_metadata={...})
# Parse directory with sharded model
>>> metadata = get_local_safetensors_metadata("path/to/model_folder")
>>> metadata
SafetensorsRepoMetadata(metadata={'total_size': ...}, sharded=True, weight_map={...}, files_metadata={...})
>>> len(metadata.files_metadata)
3 # Number of safetensors shards
```
huggingface-hub.get_model_tags
Python Library Documentation: method get_model_tags in module huggingface_hub.hf_api
get_model_tags() -> 'dict' method of huggingface_hub.hf_api.HfApi instance
List all valid model tags as a nested namespace object
huggingface-hub.get_organization_overview
Python Library Documentation: method get_organization_overview in module huggingface_hub.hf_api
get_organization_overview(organization: 'str', token: 'bool | str | None' = None) -> 'Organization' method of huggingface_hub.hf_api.HfApi instance
Get an overview of an organization on the Hub.
Args:
organization (`str`):
Name of the organization to get an overview of.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved token, which is the recommended method
for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`Organization`: An [`Organization`] object with the organization's overview.
Raises:
[`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
HTTP 404 If the organization does not exist on the Hub.
huggingface-hub.get_paths_info
Python Library Documentation: method get_paths_info in module huggingface_hub.hf_api
get_paths_info(repo_id: 'str', paths: 'list[str] | str', *, expand: 'bool' = False, revision: 'str | None' = None, repo_type: 'str | None' = None, token: 'str | bool | None' = None) -> 'list[RepoFile | RepoFolder]' method of huggingface_hub.hf_api.HfApi instance
Get information about a repo's paths.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated by a `/`.
paths (`Union[list[str], str]`, *optional*):
The paths to get information about. If a path do not exist, it is ignored without raising
an exception.
expand (`bool`, *optional*, defaults to `False`):
Whether to fetch more information about the paths (e.g. last commit and files' security scan results). This
operation is more expensive for the server so only 50 results are returned per page (instead of 1000).
As pagination is implemented in `huggingface_hub`, this is transparent for you except for the time it
takes to get the results.
revision (`str`, *optional*):
The revision of the repository from which to get the information. Defaults to `"main"` branch.
repo_type (`str`, *optional*):
The type of the repository from which to get the information (`"model"`, `"dataset"` or `"space"`.
Defaults to `"model"`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`list[Union[RepoFile, RepoFolder]]`:
The information about the paths, as a list of [`RepoFile`] and [`RepoFolder`] objects.
Raises:
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
does not exist.
[`~utils.RevisionNotFoundError`]:
If revision is not found (error 404) on the repo.
Example:
```py
>>> from huggingface_hub import get_paths_info
>>> paths_info = get_paths_info("allenai/c4", ["README.md", "en"], repo_type="dataset")
>>> paths_info
[
RepoFile(path='README.md', size=2379, blob_id='f84cb4c97182890fc1dbdeaf1a6a468fd27b4fff', lfs=None, last_commit=None, security=None),
RepoFolder(path='en', tree_id='dc943c4c40f53d02b31ced1defa7e5f438d5862e', last_commit=None)
]
```
huggingface-hub.get_repo_discussions
Python Library Documentation: method get_repo_discussions in module huggingface_hub.hf_api
get_repo_discussions(repo_id: 'str', *, author: 'str | None' = None, discussion_type: 'constants.DiscussionTypeFilter | None' = None, discussion_status: 'constants.DiscussionStatusFilter | None' = None, repo_type: 'str | None' = None, token: 'bool | str | None' = None) -> 'Iterator[Discussion]' method of huggingface_hub.hf_api.HfApi instance
Fetches Discussions and Pull Requests for the given repo.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
author (`str`, *optional*):
Pass a value to filter by discussion author. `None` means no filter.
Default is `None`.
discussion_type (`str`, *optional*):
Set to `"pull_request"` to fetch only pull requests, `"discussion"`
to fetch only discussions. Set to `"all"` or `None` to fetch both.
Default is `None`.
discussion_status (`str`, *optional*):
Set to `"open"` (respectively `"closed"`) to fetch only open
(respectively closed) discussions. Set to `"all"` or `None`
to fetch both.
Default is `None`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if fetching from a dataset or
space, `None` or `"model"` if fetching from a model. Default is
`None`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`Iterator[Discussion]`: An iterator of [`Discussion`] objects.
Example:
Collecting all discussions of a repo in a list:
```python
>>> from huggingface_hub import get_repo_discussions
>>> discussions_list = list(get_repo_discussions(repo_id="bert-base-uncased"))
```
Iterating over discussions of a repo:
```python
>>> from huggingface_hub import get_repo_discussions
>>> for discussion in get_repo_discussions(repo_id="bert-base-uncased"):
... print(discussion.num, discussion.title)
```
huggingface-hub.get_safetensors_metadata
Python Library Documentation: method get_safetensors_metadata in module huggingface_hub.hf_api
get_safetensors_metadata(repo_id: 'str', *, repo_type: 'str | None' = None, revision: 'str | None' = None, token: 'bool | str | None' = None, timeout: 'float | None' = 10) -> 'SafetensorsRepoMetadata' method of huggingface_hub.hf_api.HfApi instance
Parse metadata for a safetensors repo on the Hub.
We first check if the repo has a single safetensors file or a sharded safetensors repo. If it's a single
safetensors file, we parse the metadata from this file. If it's a sharded safetensors repo, we parse the
metadata from the index file and then parse the metadata from each shard.
To parse metadata from a single safetensors file, use [`parse_safetensors_file_metadata`].
For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.
Args:
repo_id (`str`):
A user or an organization name and a repo name separated by a `/`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if the file is in a dataset or space, `None` or `"model"` if in a
model. Default is `None`.
revision (`str`, *optional*):
The git revision to fetch the file from. Can be a branch name, a tag, or a commit hash. Defaults to the
head of the `"main"` branch.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
timeout (`float`, *optional*, defaults to 10):
How many seconds to wait for the server to send data before giving up, passed to each request that
fetches a safetensors file header. Set to `None` to disable the timeout (not recommended, as a stalled
connection can hang the call indefinitely).
Returns:
[`SafetensorsRepoMetadata`]: information related to safetensors repo.
Raises:
[`NotASafetensorsRepoError`]
If the repo is not a safetensors repo i.e. doesn't have either a
`model.safetensors` or a `model.safetensors.index.json` file.
[`SafetensorsParsingError`]
If a safetensors file header couldn't be parsed correctly.
Example:
```py
# Parse repo with single weights file
>>> metadata = get_safetensors_metadata("bigscience/bloomz-560m")
>>> metadata
SafetensorsRepoMetadata(
metadata=None,
sharded=False,
weight_map={'h.0.input_layernorm.bias': 'model.safetensors', ...},
files_metadata={'model.safetensors': SafetensorsFileMetadata(...)}
)
>>> metadata.files_metadata["model.safetensors"].metadata
{'format': 'pt'}
# Parse repo with sharded model
>>> metadata = get_safetensors_metadata("bigscience/bloom")
Parse safetensors files: 100%|██████████████████████████████████████████| 72/72 [00:12<00:00, 5.78it/s]
>>> metadata
SafetensorsRepoMetadata(metadata={'total_size': 352494542848}, sharded=True, weight_map={...}, files_metadata={...})
>>> len(metadata.files_metadata)
72 # All safetensors files have been fetched
# Parse repo with sharded model
>>> get_safetensors_metadata("runwayml/stable-diffusion-v1-5")
NotASafetensorsRepoError: 'runwayml/stable-diffusion-v1-5' is not a safetensors repo. Couldn't find 'model.safetensors.index.json' or 'model.safetensors' files.
```
huggingface-hub.get_session
Python Library Documentation: function get_session in module huggingface_hub.utils._http
get_session() -> httpx.Client
Get a `httpx.Client` object, using the transport factory from the user.
This client is shared between all calls made by `huggingface_hub`. Therefore you should not close it manually.
Use [`set_client_factory`] to customize the `httpx.Client`.
huggingface-hub.get_space_runtime
Python Library Documentation: method get_space_runtime in module huggingface_hub.hf_api
get_space_runtime(repo_id: 'str', *, token: 'bool | str | None' = None) -> 'SpaceRuntime' method of huggingface_hub.hf_api.HfApi instance
Gets runtime information about a Space.
Args:
repo_id (`str`):
ID of the repo to update. Example: `"bigcode/in-the-stack"`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
huggingface-hub.get_space_secrets
Python Library Documentation: method get_space_secrets in module huggingface_hub.hf_api
get_space_secrets(repo_id: 'str', *, token: 'bool | str | None' = None) -> 'dict[str, SpaceSecret]' method of huggingface_hub.hf_api.HfApi instance
Gets all secrets from a Space.
Secret values are write-only and cannot be read back. Only the key, description, and last update time
are returned.
Secrets allow to set secret keys or tokens to a Space without hardcoding them.
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
Args:
repo_id (`str`):
ID of the repo to query. Example: `"bigcode/in-the-stack"`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`dict[str, SpaceSecret]`: Dictionary of [`SpaceSecret`] objects keyed by secret name.
Example:
```python
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> api.get_space_secrets("username/my-space")
{'HF_TOKEN': SpaceSecret(key='HF_TOKEN', description='...', updated_at=datetime.datetime(...))}
```
huggingface-hub.get_space_variables
Python Library Documentation: method get_space_variables in module huggingface_hub.hf_api
get_space_variables(repo_id: 'str', *, token: 'bool | str | None' = None) -> 'dict[str, SpaceVariable]' method of huggingface_hub.hf_api.HfApi instance
Gets all variables from a Space.
Variables allow to set environment variables to a Space without hardcoding them.
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables
Args:
repo_id (`str`):
ID of the repo to query. Example: `"bigcode/in-the-stack"`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
huggingface-hub.get_token
Python Library Documentation: function get_token in module huggingface_hub.utils._auth
get_token() -> str | None
Get token if user is logged in.
Note: in most cases, you should use [`huggingface_hub.utils.build_hf_headers`] instead. This method is only useful
if you want to retrieve the token for other purposes than sending an HTTP request.
If `HF_OIDC_RESOURCE` is set (Trusted Publishers, typically in CI), a short-lived token obtained via OIDC token
exchange takes precedence. Otherwise the token is retrieved from the `HF_TOKEN` environment variable, then from the
token file in the Hugging Face home folder. Returns None if user is not logged in. To log in, use [`login`] or
`hf auth login`.
OAuth tokens obtained with the browser-based login come with a refresh token: when such a token is close to
expiry, it is transparently refreshed and persisted before being returned.
Note: if `HF_OIDC_RESOURCE` is set but the OIDC token exchange fails, this raises instead of returning `None`,
opting into OIDC is explicit, so a failure surfaces as a clear error rather than a silent fallback.
Returns:
`str` or `None`: The token, `None` if it doesn't exist.
huggingface-hub.get_torch_storage_id
Python Library Documentation: function get_torch_storage_id in module huggingface_hub.serialization._torch
get_torch_storage_id(tensor: 'torch.Tensor') -> tuple['torch.device', int | tuple[typing.Any, ...], int] | None
Return unique identifier to a tensor storage.
Multiple different tensors can share the same underlying storage. This identifier is
guaranteed to be unique and constant for this tensor's storage during its lifetime. Two tensor storages with
non-overlapping lifetimes may have the same id.
In the case of meta tensors, we return None since we can't tell if they share the same storage.
Taken from https://github.com/huggingface/transformers/blob/1ecf5f7c982d761b4daaa96719d162c324187c64/src/transformers/pytorch_utils.py#L278.
huggingface-hub.get_torch_storage_size
Python Library Documentation: function get_torch_storage_size in module huggingface_hub.serialization._torch
get_torch_storage_size(tensor: 'torch.Tensor') -> int
Taken from https://github.com/huggingface/safetensors/blob/08db34094e9e59e2f9218f2df133b7b4aaff5a99/bindings/python/py_src/safetensors/torch.py#L31C1-L41C59
huggingface-hub.get_user_overview
Python Library Documentation: method get_user_overview in module huggingface_hub.hf_api
get_user_overview(username: 'str', token: 'bool | str | None' = None) -> 'User' method of huggingface_hub.hf_api.HfApi instance
Get an overview of a user on the Hub.
Args:
username (`str`):
Username of the user to get an overview of.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`User`: A [`User`] object with the user's overview.
Raises:
[`HfHubHTTPError`]:
HTTP 404 If the user does not exist on the Hub.
huggingface-hub.get_webhook
Python Library Documentation: method get_webhook in module huggingface_hub.hf_api
get_webhook(webhook_id: 'str', *, token: 'bool | str | None' = None) -> 'WebhookInfo' method of huggingface_hub.hf_api.HfApi instance
Get a webhook by its id.
Args:
webhook_id (`str`):
The unique identifier of the webhook to get.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved token, which is the recommended
method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`WebhookInfo`]:
Info about the webhook.
Example:
```python
>>> from huggingface_hub import get_webhook
>>> webhook = get_webhook("654bbbc16f2ec14d77f109cc")
>>> print(webhook)
WebhookInfo(
id="654bbbc16f2ec14d77f109cc",
job=None,
watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
secret="my-secret",
domains=["repo", "discussion"],
disabled=False,
)
```
huggingface-hub.grant_access
Python Library Documentation: method grant_access in module huggingface_hub.hf_api
grant_access(repo_id: 'str', user: 'str', *, repo_type: 'str | None' = None, token: 'bool | str | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Grant access to a user for a given gated repo.
Granting access don't require for the user to send an access request by themselves. The user is automatically
added to the accepted list meaning they can download the files You can revoke the granted access at any time
using [`cancel_access_request`] or [`reject_access_request`].
For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
Args:
repo_id (`str`):
The id of the repo to grant access to.
user (`str`):
The username of the user to grant access.
repo_type (`str`, *optional*):
The type of the repo to grant access to. Must be one of `model`, `dataset` or `space`.
Defaults to `model`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Raises:
[`HfHubHTTPError`]:
HTTP 400 if the repo is not gated.
[`HfHubHTTPError`]:
HTTP 400 if the user already has access to the repo.
[`HfHubHTTPError`]:
HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
or `admin` role in the organization the repo belongs to or if you passed a `read` token.
[`HfHubHTTPError`]:
HTTP 404 if the user does not exist on the Hub.
huggingface-hub.hf_hub_download
Python Library Documentation: function hf_hub_download in module huggingface_hub.file_download
hf_hub_download(repo_id: str, filename: str, *, subfolder: str | None = None, repo_type: str | None = None, revision: str | None = None, library_name: str | None = None, library_version: str | None = None, cache_dir: str | pathlib.Path | None = None, local_dir: str | pathlib.Path | None = None, user_agent: dict | str | None = None, force_download: bool = False, etag_timeout: float = 10, token: bool | str | None = None, local_files_only: bool = False, headers: dict[str, str] | None = None, endpoint: str | None = None, tqdm_class: type[tqdm.asyncio.tqdm_asyncio] | None = None, dry_run: bool = False) -> str | huggingface_hub.file_download.DryRunFileInfo
Download a given file if it's not already present in the local cache.
The new cache file layout looks like this:
- The cache directory contains one subfolder per repo_id (namespaced by repo type)
- inside each repo folder:
- refs is a list of the latest known revision => commit_hash pairs
- blobs contains the actual file blobs (identified by their git-sha or sha256, depending on
whether they're LFS files or not)
- snapshots contains one subfolder per commit, each "commit" contains the subset of the files
that have been resolved at that particular commit. Each filename is a symlink to the blob
at that particular commit.
```
[ 96] .
└── [ 160] models--julien-c--EsperBERTo-small
├── [ 160] blobs
│ ├── [321M] 403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
│ ├── [ 398] 7cb18dc9bafbfcf74629a4b760af1b160957a83e
│ └── [1.4K] d7edf6bd2a681fb0175f7735299831ee1b22b812
├── [ 96] refs
│ └── [ 40] main
└── [ 128] snapshots
├── [ 128] 2439f60ef33a0d46d85da5001d52aeda5b00ce9f
│ ├── [ 52] README.md -> ../../blobs/d7edf6bd2a681fb0175f7735299831ee1b22b812
│ └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
└── [ 128] bbc77c8132af1cc5cf678da3f1ddf2de43606d48
├── [ 52] README.md -> ../../blobs/7cb18dc9bafbfcf74629a4b760af1b160957a83e
└── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
```
If `local_dir` is provided, the file structure from the repo will be replicated in this location. When using this
option, the `cache_dir` will not be used and a `.cache/huggingface/` folder will be created at the root of `local_dir`
to store some metadata related to the downloaded files. While this mechanism is not as robust as the main
cache-system, it's optimized for regularly pulling the latest version of a repository.
Args:
repo_id (`str`):
A user or an organization name and a repo name separated by a `/`.
filename (`str`):
The name of the file in the repo.
subfolder (`str`, *optional*):
An optional value corresponding to a folder inside the model repo.
repo_type (`str`, *optional*):
Set to `"dataset"`, `"space"` or `"kernel"` if downloading from a dataset, space or kernel repo,
`None` or `"model"` if downloading from a model. Default is `None`.
revision (`str`, *optional*):
An optional Git revision id which can be a branch name, a tag, or a
commit hash.
library_name (`str`, *optional*):
The name of the library to which the object corresponds.
library_version (`str`, *optional*):
The version of the library.
cache_dir (`str`, `Path`, *optional*):
Path to the folder where cached files are stored.
local_dir (`str` or `Path`, *optional*):
If provided, the downloaded file will be placed under this directory.
user_agent (`dict`, `str`, *optional*):
The user-agent info in the form of a dictionary or a string.
force_download (`bool`, *optional*, defaults to `False`):
Whether the file should be downloaded even if it already exists in
the local cache.
etag_timeout (`float`, *optional*, defaults to `10`):
When fetching ETag, how many seconds to wait for the server to send
data before giving up, which is passed to `httpx.request`.
token (`str`, `bool`, *optional*):
A token to be used for the download.
- If `True`, the token is read from the HuggingFace config
folder.
- If a string, it's used as the authentication token.
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.
headers (`dict`, *optional*):
Additional headers to be sent with the request.
endpoint (`str`, *optional*):
The Hub endpoint to send the request to. Defaults to the value of `HF_ENDPOINT`.
tqdm_class (`tqdm`, *optional*):
If provided, overwrites the default behavior for the progress bar. Passed
argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior.
Defaults to the custom HF progress bar that can be disabled by setting
`HF_HUB_DISABLE_PROGRESS_BARS` environment variable.
dry_run (`bool`, *optional*, defaults to `False`):
If `True`, perform a dry run without actually downloading the file. Returns a
[`DryRunFileInfo`] object containing information about what would be downloaded.
Returns:
`str` or [`DryRunFileInfo`]:
- If `dry_run=False`: Local path of file or if networking is off, last version of file cached on disk.
- If `dry_run=True`: A [`DryRunFileInfo`] object containing download information.
Raises:
[`~utils.RepositoryNotFoundError`]
If the repository to download from cannot be found. This may be because it doesn't exist,
or because it is set to `private` and you do not have access.
[`~utils.RevisionNotFoundError`]
If the revision to download from cannot be found.
[`~utils.RemoteEntryNotFoundError`]
If the file to download cannot be found.
[`~utils.LocalEntryNotFoundError`]
If network is disabled or unavailable and file is not found in cache.
[`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
If `token=True` but the token cannot be found.
[`OSError`](https://docs.python.org/3/library/exceptions.html#OSError)
If ETag cannot be determined.
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If some parameter value is invalid.
huggingface-hub.hf_hub_url
Python Library Documentation: function hf_hub_url in module huggingface_hub.file_download
hf_hub_url(repo_id: str, filename: str, *, subfolder: str | None = None, repo_type: str | None = None, revision: str | None = None, endpoint: str | None = None) -> str
Construct the URL of a file from the given information.
The resolved address can either be a huggingface.co-hosted url, or a link to
Cloudfront (a Content Delivery Network, or CDN) for large files which are
more than a few MBs.
Args:
repo_id (`str`):
A namespace (user or an organization) name and a repo name separated
by a `/`.
filename (`str`):
The name of the file in the repo.
subfolder (`str`, *optional*):
An optional value corresponding to a folder inside the repo.
repo_type (`str`, *optional*):
Set to `"dataset"`, `"space"` or `"kernel"` if downloading from a dataset, space or kernel repo,
`None` or `"model"` if downloading from a model. Default is `None`.
revision (`str`, *optional*):
An optional Git revision id which can be a branch name, a tag, or a
commit hash.
endpoint (`str`, *optional*):
The Hub endpoint to send the request to. Defaults to the value of `HF_ENDPOINT`.
Example:
```python
>>> from huggingface_hub import hf_hub_url
>>> hf_hub_url(
... repo_id="julien-c/EsperBERTo-small", filename="pytorch_model.bin"
... )
'https://huggingface.co/julien-c/EsperBERTo-small/resolve/main/pytorch_model.bin'
```
> [!TIP]
> Notes:
>
> Cloudfront is replicated over the globe so downloads are way faster for
> the end user (and it also lowers our bandwidth costs).
>
> Cloudfront aggressively caches files by default (default TTL is 24
> hours), however this is not an issue here because we implement a
> git-based versioning system on huggingface.co, which means that we store
> the files on S3/Cloudfront in a content-addressable way (i.e., the file
> name is its hash). Using content-addressable filenames means cache can't
> ever be stale.
>
> In terms of client-side caching from this library, we base our caching
> on the objects' entity tag (`ETag`), which is an identifier of a
> specific version of a resource [1]_. An object's ETag is: its git-sha1
> if stored in git, or its sha256 if stored in git-lfs.
References:
- [1] https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag
huggingface-hub.hf_raise_for_status
Python Library Documentation: function hf_raise_for_status in module huggingface_hub.utils._http
hf_raise_for_status(response: httpx.Response, endpoint_name: str | None = None) -> None
Internal version of `response.raise_for_status()` that will refine a potential HTTPError.
Raised exception will be an instance of [`~errors.HfHubHTTPError`].
This helper is meant to be the unique method to raise_for_status when making a call to the Hugging Face Hub.
Args:
response (`Response`):
Response from the server.
endpoint_name (`str`, *optional*):
Name of the endpoint that has been called. If provided, the error message will be more complete.
> [!WARNING]
> Raises when the request has failed:
>
> - [`~utils.RepositoryNotFoundError`]
> If the repository to download from cannot be found. This may be because it
> doesn't exist, because `repo_type` is not set correctly, or because the repo
> is `private` and you do not have access.
> - [`~utils.GatedRepoError`]
> If the repository exists but is gated and the user is not on the authorized
> list.
> - [`~utils.RevisionNotFoundError`]
> If the repository exists but the revision couldn't be found.
> - [`~utils.EntryNotFoundError`]
> If the repository exists but the entry (e.g. the requested file) couldn't be
> find.
> - [`~utils.BadRequestError`]
> If request failed with a HTTP 400 BadRequest error.
> - [`~utils.HfHubHTTPError`]
> If request failed for a reason not listed above.
huggingface-hub.hffs
Python Library Documentation: HfFileSystem in module huggingface_hub.hf_file_system object
class HfFileSystem(fsspec.spec.AbstractFileSystem)
| HfFileSystem(*args, **kwargs)
|
| Access a remote Hugging Face Hub repository as if were a local file system.
|
| > [!WARNING]
| > [`HfFileSystem`] provides fsspec compatibility, which is useful for libraries that require it (e.g., reading
| > Hugging Face datasets directly with `pandas`). However, it introduces additional overhead due to this compatibility
| > layer. For better performance and reliability, it's recommended to use `HfApi` methods when possible.
|
| The file system supports paths for the `hf://` protocol, which follows those URL schemes:
|
| * Models, Datasets and Spaces repositories:
|
| ```
| hf://<repo-id>[@<revision>]/<path/in/repo>
| hf://datasets/<repo-id>[@<revision>]/<path/in/repo>
| hf://spaces/<repo-id>[@<revision>]/<path/in/repo>
| ```
|
| * Buckets (generic storage):
|
| ```
| hf://buckets/<bucket-id>/<path/in/bucket>
| ```
|
| Note: when using the [`HfFileSystem`] directly, passing the `hf://` protocol prefix is optional in paths.
|
| Args:
| endpoint (`str`, *optional*):
| Endpoint of the Hub. Defaults to <https://huggingface.co>.
| token (`bool` or `str`, *optional*):
| A valid user access token (string). Defaults to the locally saved
| token, which is the recommended method for authentication (see
| https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
| To disable authentication, pass `False`.
| block_size (`int`, *optional*):
| Block size for reading and writing files.
| expand_info (`bool`, *optional*):
| Whether to expand the information of the files.
| **storage_options (`dict`, *optional*):
| Additional options for the filesystem. See [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.__init__).
|
| Usage:
|
| ```python
| >>> from huggingface_hub import hffs
|
| >>> # List files
| >>> hffs.glob("my-username/my-model/*.bin")
| ['my-username/my-model/pytorch_model.bin']
| >>> hffs.ls("datasets/my-username/my-dataset", detail=False)
| ['datasets/my-username/my-dataset/.gitattributes', 'datasets/my-username/my-dataset/README.md', 'datasets/my-username/my-dataset/data.json']
|
| >>> # Read/write files
| >>> with hffs.open("my-username/my-model/pytorch_model.bin") as f:
| ... data = f.read()
| >>> with hffs.open("my-username/my-model/pytorch_model.bin", "wb") as f:
| ... f.write(data)
| ```
|
| Specify a token for authentication:
| ```python
| >>> from huggingface_hub import HfFileSystem
| >>> hffs = HfFileSystem(token=token)
| ```
|
| Method resolution order:
| HfFileSystem
| fsspec.spec.AbstractFileSystem
| builtins.object
|
| Methods defined here:
|
| __init__(self, *args, endpoint: str | None = None, token: bool | str | None = None, block_size: int | None = None, expand_info: bool | None = None, **storage_options)
| Create and configure file-system instance
|
| Instances may be cachable, so if similar enough arguments are seen
| a new instance is not required. The token attribute exists to allow
| implementations to cache instances if they wish.
|
| A reasonable default should be provided if there are no arguments.
|
| Subclasses should call this method.
|
| Parameters
| ----------
| use_listings_cache, listings_expiry_time, max_paths:
| passed to ``DirCache``, if the implementation supports
| directory listing caching. Pass use_listings_cache=False
| to disable such caching.
| skip_instance_cache: bool
| If this is a cachable implementation, pass True here to force
| creating a new instance even if a matching instance exists, and prevent
| storing this instance.
| asynchronous: bool
| loop: asyncio-compatible IOLoop or None
|
| __reduce__(self)
| Helper for pickle.
|
| cp_file(self, path1: str, path2: str, revision: str | None = None, **kwargs) -> None
| Copy a file within or between repositories.
|
| > [!WARNING]
| > Note: When possible, use `HfApi.upload_file()` for better performance.
|
| Args:
| path1 (`str`):
| Source path to copy from.
| path2 (`str`):
| Destination path to copy to.
| revision (`str`, *optional*):
| The git revision to copy from.
|
| exists(self, path, **kwargs)
| Check if a file exists.
|
| For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.exists).
|
| > [!WARNING]
| > Note: When possible, use `HfApi.file_exists()` for better performance.
|
| Args:
| path (`str`):
| Path to check.
|
| Returns:
| `bool`: True if file exists, False otherwise.
|
| find(self, path: str, maxdepth: int | None = None, withdirs: bool = False, detail: bool = False, refresh: bool = False, revision: str | None = None, **kwargs) -> list[str] | dict[str, dict[str, typing.Any]]
| List all files below path.
|
| For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.find).
|
| Args:
| path (`str`):
| Root path to list files from.
| maxdepth (`int`, *optional*):
| Maximum depth to descend into subdirectories.
| withdirs (`bool`, *optional*):
| Include directory paths in the output. Defaults to False.
| detail (`bool`, *optional*):
| If True, returns a dict mapping paths to file information. Defaults to False.
| refresh (`bool`, *optional*):
| If True, bypass the cache and fetch the latest data. Defaults to False.
| revision (`str`, *optional*):
| The git revision to list from.
|
| Returns:
| `Union[list[str], dict[str, dict[str, Any]]]`: List of paths or dict of file information.
|
| get_file(self, rpath, lpath, callback=<fsspec.callbacks.NoOpCallback object at 0x000001F176839970>, outfile=None, **kwargs) -> None
| Copy single remote file to local.
|
| > [!WARNING]
| > Note: When possible, use `HfApi.hf_hub_download()` or `HfApi.download_bucket_files` for better performance.
|
| Args:
| rpath (`str`):
| Remote path to download from.
| lpath (`str`):
| Local path to download to.
| callback (`Callback`, *optional*):
| Optional callback to track download progress. Defaults to no callback.
| outfile (`IO`, *optional*):
| Optional file-like object to write to. If provided, `lpath` is ignored.
|
| glob(self, path: str, maxdepth: int | None = None, **kwargs) -> list[str]
| Find files by glob-matching.
|
| For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.glob).
|
| Args:
| path (`str`):
| Path pattern to match.
| maxdepth (`int`, *optional*):
| Maximum depth to descend into directories. By default, no limit.
|
| Returns:
| `list[str]`: List of paths matching the pattern.
|
| info(self, path: str, refresh: bool = False, revision: str | None = None, **kwargs) -> dict[str, typing.Any]
| Get information about a file or directory.
|
| For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.info).
|
| > [!WARNING]
| > Note: When possible, use `HfApi.get_paths_info()` or `HfApi.repo_info()` for better performance
| > (or `HfApi.get_bucket_paths_info()` or `HfApi.bucket_info()` for buckets)
|
| Args:
| path (`str`):
| Path to get info for.
| refresh (`bool`, *optional*):
| If True, bypass the cache and fetch the latest data. Defaults to False.
| revision (`str`, *optional*):
| The git revision to get info from.
|
| Returns:
| `dict[str, Any]`: Dictionary containing file information (type, size, commit info, etc.).
|
| invalidate_cache(self, path: str | None = None) -> None
| Clear the cache for a given path.
|
| For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.invalidate_cache).
|
| Args:
| path (`str`, *optional*):
| Path to clear from cache. If not provided, clear the entire cache.
|
| isdir(self, path)
| Check if a path is a directory.
|
| For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.isdir).
|
| Args:
| path (`str`):
| Path to check.
|
| Returns:
| `bool`: True if path is a directory, False otherwise.
|
| isfile(self, path)
| Check if a path is a file.
|
| For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.isfile).
|
| Args:
| path (`str`):
| Path to check.
|
| Returns:
| `bool`: True if path is a file, False otherwise.
|
| ls(self, path: str, detail: bool = True, refresh: bool = False, revision: str | None = None, **kwargs) -> list[str | dict[str, typing.Any]]
| List the contents of a directory.
|
| For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.ls).
|
| > [!WARNING]
| > Note: When possible, use `HfApi.list_repo_tree()` for better performance.
|
| Args:
| path (`str`):
| Path to the directory.
| detail (`bool`, *optional*):
| If True, returns a list of dictionaries containing file information. If False,
| returns a list of file paths. Defaults to True.
| refresh (`bool`, *optional*):
| If True, bypass the cache and fetch the latest data. Defaults to False.
| revision (`str`, *optional*):
| The git revision to list from.
|
| Returns:
| `list[Union[str, dict[str, Any]]]`: List of file paths (if detail=False) or list of file information
| dictionaries (if detail=True).
|
| modified(self, path: str, **kwargs) -> datetime.datetime
| Get the last modified time of a file.
|
| For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.modified).
|
| Args:
| path (`str`):
| Path to the file.
|
| Returns:
| `datetime`: Last modified time of the file.
|
| resolve_path(self, path: str, revision: str | None = None) -> huggingface_hub.hf_file_system.HfFileSystemResolvedRepositoryPath | huggingface_hub.hf_file_system.HfFileSystemResolvedBucketPath
| Resolve a Hugging Face file system path into its components.
|
| Args:
| path (`str`):
| Path to resolve.
| revision (`str`, *optional*):
| The revision of the repo to resolve. Defaults to the revision specified in the path.
|
| Returns:
| [`HfFileSystemResolvedPath`]: Resolved path information containing `repo_type`, `repo_id`, `revision` and `path_in_repo`.
|
| Raises:
| `ValueError`:
| If path contains conflicting revision information.
| `NotImplementedError`:
| If trying to list repositories.
|
| rm(self, path: str, recursive: bool = False, maxdepth: int | None = None, revision: str | None = None, **kwargs) -> None
| Delete files from a repository.
|
| For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.rm).
|
| > [!WARNING]
| > Note: When possible, use `HfApi.delete_file()` for better performance.
|
| Args:
| path (`str`):
| Path to delete.
| recursive (`bool`, *optional*):
| If True, delete directory and all its contents. Defaults to False.
| maxdepth (`int`, *optional*):
| Maximum number of subdirectories to visit when deleting recursively.
| revision (`str`, *optional*):
| The git revision to delete from.
|
| start_transaction(self)
| Begin write transaction for deferring files, non-context version
|
| url(self, path: str) -> str
| Get the HTTP URL of the given path.
|
| Args:
| path (`str`):
| Path to get URL for.
|
| Returns:
| `str`: HTTP URL to access the file or directory on the Hub.
|
| walk(self, path: str, *args, **kwargs) -> collections.abc.Iterator[tuple[str, list[str], list[str]]]
| Return all files below the given path.
|
| For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.walk).
|
| Args:
| path (`str`):
| Root path to list files from.
|
| Returns:
| `Iterator[tuple[str, list[str], list[str]]]`: An iterator of (path, list of directory names, list of file names) tuples.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| transaction
| A context within which files are committed together upon exit
|
| Requires the file class to implement `.commit()` and `.discard()`
| for the normal and exception cases.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| protocol = 'hf'
|
| root_marker = ''
|
| ----------------------------------------------------------------------
| Methods inherited from fsspec.spec.AbstractFileSystem:
|
| __dask_tokenize__(self)
|
| __eq__(self, other)
| Return self==value.
|
| __hash__(self)
| Return hash(self).
|
| cat(self, path, recursive=False, on_error='raise', **kwargs)
| Fetch (potentially multiple) paths' contents
|
| Parameters
| ----------
| recursive: bool
| If True, assume the path(s) are directories, and get all the
| contained files
| on_error : "raise", "omit", "return"
| If raise, an underlying exception will be raised (converted to KeyError
| if the type is in self.missing_exceptions); if omit, keys with exception
| will simply not be included in the output; if "return", all keys are
| included in the output, but the value will be bytes or an exception
| instance.
| kwargs: passed to cat_file
|
| Returns
| -------
| dict of {path: contents} if there are multiple paths
| or the path has been otherwise expanded
|
| cat_file(self, path, start=None, end=None, **kwargs)
| Get the content of a file
|
| Parameters
| ----------
| path: URL of file on this filesystems
| start, end: int
| Bytes limits of the read. If negative, backwards from end,
| like usual python slices. Either can be None for start or
| end of file, respectively
| kwargs: passed to ``open()``.
|
| cat_ranges(self, paths, starts, ends, max_gap=None, on_error='return', **kwargs)
| Get the contents of byte ranges from one or more files
|
| Parameters
| ----------
| paths: list
| A list of of filepaths on this filesystems
| starts, ends: int or list
| Bytes limits of the read. If using a single int, the same value will be
| used to read all the specified files.
|
| checksum(self, path)
| Unique value for current version of file
|
| If the checksum is the same from one moment to another, the contents
| are guaranteed to be the same. If the checksum changes, the contents
| *might* have changed.
|
| This should normally be overridden; default will probably capture
| creation/modification timestamp (which would be good) or maybe
| access timestamp (which would be bad)
|
| copy(self, path1, path2, recursive=False, maxdepth=None, on_error=None, **kwargs)
| Copy within two locations in the filesystem
|
| on_error : "raise", "ignore"
| If raise, any not-found exceptions will be raised; if ignore any
| not-found exceptions will cause the path to be skipped; defaults to
| raise unless recursive is true, where the default is ignore
|
| cp(self, path1, path2, **kwargs)
| Alias of `AbstractFileSystem.copy`.
|
| created(self, path)
| Return the created timestamp of a file as a datetime.datetime
|
| delete(self, path, recursive=False, maxdepth=None)
| Alias of `AbstractFileSystem.rm`.
|
| disk_usage(self, path, total=True, maxdepth=None, **kwargs)
| Alias of `AbstractFileSystem.du`.
|
| download(self, rpath, lpath, recursive=False, **kwargs)
| Alias of `AbstractFileSystem.get`.
|
| du(self, path, total=True, maxdepth=None, withdirs=False, **kwargs)
| Space used by files and optionally directories within a path
|
| Directory size does not include the size of its contents.
|
| Parameters
| ----------
| path: str
| total: bool
| Whether to sum all the file sizes
| maxdepth: int or None
| Maximum number of directory levels to descend, None for unlimited.
| withdirs: bool
| Whether to include directory paths in the output.
| kwargs: passed to ``find``
|
| Returns
| -------
| Dict of {path: size} if total=False, or int otherwise, where numbers
| refer to bytes used.
|
| end_transaction(self)
| Finish write transaction, non-context version
|
| expand_path(self, path, recursive=False, maxdepth=None, assume_literal=False, **kwargs)
| Turn one or more globs or directories into a list of all matching paths
| to files or directories.
|
| kwargs are passed to ``glob`` or ``find``, which may in turn call ``ls``
|
| get(self, rpath, lpath, recursive=False, callback=<fsspec.callbacks.NoOpCallback object at 0x000001F176839970>, maxdepth=None, **kwargs)
| Copy file(s) to local.
|
| Copies a specific file or tree of files (if recursive=True). If lpath
| ends with a "/", it will be assumed to be a directory, and target files
| will go within. Can submit a list of paths, which may be glob-patterns
| and will be expanded.
|
| Calls get_file for each source.
|
| get_mapper(self, root='', check=False, create=False, missing_exceptions=None)
| Create key/value store based on this file-system
|
| Makes a MutableMapping interface to the FS at the given root path.
| See ``fsspec.mapping.FSMap`` for further details.
|
| head(self, path, size=1024)
| Get the first ``size`` bytes from file
|
| lexists(self, path, **kwargs)
| If there is a file at the given path (including
| broken links)
|
| listdir(self, path, detail=True, **kwargs)
| Alias of `AbstractFileSystem.ls`.
|
| makedir(self, path, create_parents=True, **kwargs)
| Alias of `AbstractFileSystem.mkdir`.
|
| makedirs(self, path, exist_ok=False)
| Recursively make directories
|
| Creates directory at path and any intervening required directories.
| Raises exception if, for instance, the path already exists but is a
| file.
|
| Parameters
| ----------
| path: str
| leaf directory name
| exist_ok: bool (False)
| If False, will error if the target already exists
|
| mkdir(self, path, create_parents=True, **kwargs)
| Create directory entry at path
|
| For systems that don't have true directories, may create an for
| this instance only and not touch the real filesystem
|
| Parameters
| ----------
| path: str
| location
| create_parents: bool
| if True, this is equivalent to ``makedirs``
| kwargs:
| may be permissions, etc.
|
| mkdirs(self, path, exist_ok=False)
| Alias of `AbstractFileSystem.makedirs`.
|
| move(self, path1, path2, **kwargs)
| Alias of `AbstractFileSystem.mv`.
|
| mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs)
| Move file(s) from one location to another
|
| open(self, path, mode='rb', block_size=None, cache_options=None, compression=None, **kwargs)
| Return a file-like object from the filesystem
|
| The resultant instance must function correctly in a context ``with``
| block.
|
| Parameters
| ----------
| path: str
| Target file
| mode: str like 'rb', 'w'
| See builtin ``open()``
| Mode "x" (exclusive write) may be implemented by the backend. Even if
| it is, whether it is checked up front or on commit, and whether it is
| atomic is implementation-dependent.
| block_size: int
| Some indication of buffering - this is a value in bytes
| cache_options : dict, optional
| Extra arguments to pass through to the cache.
| compression: string or None
| If given, open file using compression codec. Can either be a compression
| name (a key in ``fsspec.compression.compr``) or "infer" to guess the
| compression from the filename suffix.
| encoding, errors, newline: passed on to TextIOWrapper for text mode
|
| pipe(self, path, value=None, **kwargs)
| Put value into path
|
| (counterpart to ``cat``)
|
| Parameters
| ----------
| path: string or dict(str, bytes)
| If a string, a single remote location to put ``value`` bytes; if a dict,
| a mapping of {path: bytesvalue}.
| value: bytes, optional
| If using a single path, these are the bytes to put there. Ignored if
| ``path`` is a dict
|
| pipe_file(self, path, value, mode='overwrite', **kwargs)
| Set the bytes of given file
|
| put(self, lpath, rpath, recursive=False, callback=<fsspec.callbacks.NoOpCallback object at 0x000001F176839970>, maxdepth=None, **kwargs)
| Copy file(s) from local.
|
| Copies a specific file or tree of files (if recursive=True). If rpath
| ends with a "/", it will be assumed to be a directory, and target files
| will go within.
|
| Calls put_file for each source.
|
| put_file(self, lpath, rpath, callback=<fsspec.callbacks.NoOpCallback object at 0x000001F176839970>, mode='overwrite', **kwargs)
| Copy single file to remote
|
| read_block(self, fn, offset, length, delimiter=None)
| Read a block of bytes from
|
| Starting at ``offset`` of the file, read ``length`` bytes. If
| ``delimiter`` is set then we ensure that the read starts and stops at
| delimiter boundaries that follow the locations ``offset`` and ``offset
| + length``. If ``offset`` is zero then we start at zero. The
| bytestring returned WILL include the end delimiter string.
|
| If offset+length is beyond the eof, reads to eof.
|
| Parameters
| ----------
| fn: string
| Path to filename
| offset: int
| Byte offset to start read
| length: int
| Number of bytes to read. If None, read to end.
| delimiter: bytes (optional)
| Ensure reading starts and stops at delimiter bytestring
|
| Examples
| --------
| >>> fs.read_block('data/file.csv', 0, 13) # doctest: +SKIP
| b'Alice, 100\nBo'
| >>> fs.read_block('data/file.csv', 0, 13, delimiter=b'\n') # doctest: +SKIP
| b'Alice, 100\nBob, 200\n'
|
| Use ``length=None`` to read to the end of the file.
| >>> fs.read_block('data/file.csv', 0, None, delimiter=b'\n') # doctest: +SKIP
| b'Alice, 100\nBob, 200\nCharlie, 300'
|
| See Also
| --------
| :func:`fsspec.utils.read_block`
|
| read_bytes(self, path, start=None, end=None, **kwargs)
| Alias of `AbstractFileSystem.cat_file`.
|
| read_text(self, path, encoding=None, errors=None, newline=None, **kwargs)
| Get the contents of the file as a string.
|
| Parameters
| ----------
| path: str
| URL of file on this filesystems
| encoding, errors, newline: same as `open`.
|
| rename(self, path1, path2, **kwargs)
| Alias of `AbstractFileSystem.mv`.
|
| rm_file(self, path)
| Delete a file
|
| rmdir(self, path)
| Remove a directory, if empty
|
| sign(self, path, expiration=100, **kwargs)
| Create a signed URL representing the given path
|
| Some implementations allow temporary URLs to be generated, as a
| way of delegating credentials.
|
| Parameters
| ----------
| path : str
| The path on the filesystem
| expiration : int
| Number of seconds to enable the URL for (if supported)
|
| Returns
| -------
| URL : str
| The signed URL
|
| Raises
| ------
| NotImplementedError : if method is not implemented for a filesystem
|
| size(self, path)
| Size in bytes of file
|
| sizes(self, paths)
| Size in bytes of each file in a list of paths
|
| stat(self, path, **kwargs)
| Alias of `AbstractFileSystem.info`.
|
| tail(self, path, size=1024)
| Get the last ``size`` bytes from file
|
| to_dict(self, *, include_password: 'bool' = True) -> 'dict[str, Any]'
| JSON-serializable dictionary representation of this filesystem instance.
|
| Parameters
| ----------
| include_password: bool, default True
| Whether to include the password (if any) in the output.
|
| Returns
| -------
| Dictionary with keys ``cls`` (the python location of this class),
| protocol (text name of this class's protocol, first one in case of
| multiple), ``args`` (positional args, usually empty), and all other
| keyword arguments as their own keys.
|
| Warnings
| --------
| Serialized filesystems may contain sensitive information which have been
| passed to the constructor, such as passwords and tokens. Make sure you
| store and send them in a secure environment!
|
| to_json(self, *, include_password: 'bool' = True) -> 'str'
| JSON representation of this filesystem instance.
|
| Parameters
| ----------
| include_password: bool, default True
| Whether to include the password (if any) in the output.
|
| Returns
| -------
| JSON string with keys ``cls`` (the python location of this class),
| protocol (text name of this class's protocol, first one in case of
| multiple), ``args`` (positional args, usually empty), and all other
| keyword arguments as their own keys.
|
| Warnings
| --------
| Serialized filesystems may contain sensitive information which have been
| passed to the constructor, such as passwords and tokens. Make sure you
| store and send them in a secure environment!
|
| touch(self, path, truncate=True, **kwargs)
| Create empty file, or update timestamp
|
| Parameters
| ----------
| path: str
| file location
| truncate: bool
| If True, always set file size to 0; if False, update timestamp and
| leave file unchanged, if backend allows this
|
| tree(self, path: 'str' = '/', recursion_limit: 'int' = 2, max_display: 'int' = 25, display_size: 'bool' = False, prefix: 'str' = '', is_last: 'bool' = True, first: 'bool' = True, indent_size: 'int' = 4) -> 'str'
| Return a tree-like structure of the filesystem starting from the given path as a string.
|
| Parameters
| ----------
| path: Root path to start traversal from
| recursion_limit: Maximum depth of directory traversal
| max_display: Maximum number of items to display per directory
| display_size: Whether to display file sizes
| prefix: Current line prefix for visual tree structure
| is_last: Whether current item is last in its level
| first: Whether this is the first call (displays root path)
| indent_size: Number of spaces by indent
|
| Returns
| -------
| str: A string representing the tree structure.
|
| Example
| -------
| >>> from fsspec import filesystem
|
| >>> fs = filesystem('ftp', host='test.rebex.net', user='demo', password='password')
| >>> tree = fs.tree(display_size=True, recursion_limit=3, indent_size=8, max_display=10)
| >>> print(tree)
|
| ukey(self, path)
| Hash of file properties, to tell if it has changed
|
| unstrip_protocol(self, name: 'str') -> 'str'
| Format FS-specific path to generic, including protocol
|
| upload(self, lpath, rpath, recursive=False, **kwargs)
| Alias of `AbstractFileSystem.put`.
|
| write_bytes(self, path, value, **kwargs)
| Alias of `AbstractFileSystem.pipe_file`.
|
| write_text(self, path, value, encoding=None, errors=None, newline=None, **kwargs)
| Write the text to the given file.
|
| An existing file will be overwritten.
|
| Parameters
| ----------
| path: str
| URL of file on this filesystems
| value: str
| Text to write.
| encoding, errors, newline: same as `open`.
|
| ----------------------------------------------------------------------
| Class methods inherited from fsspec.spec.AbstractFileSystem:
|
| clear_instance_cache()
| Clear the cache of filesystem instances.
|
| Notes
| -----
| Unless overridden by setting the ``cachable`` class attribute to False,
| the filesystem class stores a reference to newly created instances. This
| prevents Python's normal rules around garbage collection from working,
| since the instances refcount will not drop to zero until
| ``clear_instance_cache`` is called.
|
| current()
| Return the most recently instantiated FileSystem
|
| If no instance has been created, then create one with defaults
|
| ----------------------------------------------------------------------
| Static methods inherited from fsspec.spec.AbstractFileSystem:
|
| from_dict(dct: 'dict[str, Any]') -> 'AbstractFileSystem'
| Recreate a filesystem instance from dictionary representation.
|
| See ``.to_dict()`` for the expected structure of the input.
|
| Parameters
| ----------
| dct: Dict[str, Any]
|
| Returns
| -------
| file system instance, not necessarily of this particular class.
|
| Warnings
| --------
| This can import arbitrary modules (as determined by the ``cls`` key).
| Make sure you haven't installed any modules that may execute malicious code
| at import time.
|
| from_json(blob: 'str') -> 'AbstractFileSystem'
| Recreate a filesystem instance from JSON representation.
|
| See ``.to_json()`` for the expected structure of the input.
|
| Parameters
| ----------
| blob: str
|
| Returns
| -------
| file system instance, not necessarily of this particular class.
|
| Warnings
| --------
| This can import arbitrary modules (as determined by the ``cls`` key).
| Make sure you haven't installed any modules that may execute malicious code
| at import time.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from fsspec.spec.AbstractFileSystem:
|
| fsid
| Persistent filesystem id that can be used to compare filesystems
| across sessions.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from fsspec.spec.AbstractFileSystem:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from fsspec.spec.AbstractFileSystem:
|
| async_impl = False
|
| blocksize = 4194304
|
| cachable = True
|
| mirror_sync_methods = False
|
| sep = '/'
|
| transaction_type = <class 'fsspec.transaction.Transaction'>
| Filesystem transaction write context
|
| Gathers files for deferred commit or discard, so that several write
| operations can be finalized semi-atomically. This works by having this
| instance as the ``.transaction`` attribute of the given filesystem
huggingface-hub.inspect_job
Python Library Documentation: method inspect_job in module huggingface_hub.hf_api
inspect_job(*, job_id: 'str', namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'JobInfo' method of huggingface_hub.hf_api.HfApi instance
Inspect a compute Job on Hugging Face infrastructure.
Args:
job_id (`str`):
ID of the Job.
namespace (`str`, *optional*):
The namespace where the Job is running. Defaults to the current user's namespace.
token `(Union[bool, str, None]`, *optional*):
A valid user access token. If not provided, the locally saved token will be used, which is the
recommended authentication method. Set to `False` to disable authentication.
Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
Example:
```python
>>> from huggingface_hub import inspect_job, run_job
>>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"])
>>> inspect_job(job.id)
JobInfo(
id='68780d00bbe36d38803f645f',
created_at=datetime.datetime(2025, 7, 16, 20, 35, 12, 808000, tzinfo=datetime.timezone.utc),
docker_image='python:3.12',
space_id=None,
command=['python', '-c', "print('Hello from HF compute!')"],
arguments=[],
environment={},
secrets={},
flavor='cpu-basic',
status=JobStatus(stage='RUNNING', message=None)
)
```
huggingface-hub.inspect_scheduled_job
Python Library Documentation: method inspect_scheduled_job in module huggingface_hub.hf_api
inspect_scheduled_job(*, scheduled_job_id: 'str', namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'ScheduledJobInfo' method of huggingface_hub.hf_api.HfApi instance
Inspect a scheduled compute Job on Hugging Face infrastructure.
Args:
scheduled_job_id (`str`):
ID of the scheduled Job.
namespace (`str`, *optional*):
The namespace where the scheduled Job is. Defaults to the current user's namespace.
token `(Union[bool, str, None]`, *optional*):
A valid user access token. If not provided, the locally saved token will be used, which is the
recommended authentication method. Set to `False` to disable authentication.
Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
Example:
```python
>>> from huggingface_hub import inspect_job, create_scheduled_job
>>> scheduled_job = create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"], schedule="@hourly")
>>> inspect_scheduled_job(scheduled_job.id)
```
huggingface-hub.interpreter_login
Python Library Documentation: function interpreter_login in module huggingface_hub._login
interpreter_login(*, skip_if_logged_in: bool = True) -> None
Displays a prompt to log in to the HF website and store the token.
This is equivalent to [`login`] without passing a token when not run in a notebook.
[`interpreter_login`] is useful if you want to force the use of the terminal prompt
instead of a notebook flow.
For more details, see [`login`].
Args:
skip_if_logged_in (`bool`, defaults to `True`):
If `True`, do not prompt for token if user is already logged in.
Set to `False` to force re-login. In CLI, use `--force` instead.
huggingface-hub.is_offline_mode
Python Library Documentation: function is_offline_mode in module huggingface_hub.constants
is_offline_mode() -> bool
Returns whether we are in offline mode for the Hub.
When offline mode is enabled, all HTTP requests made with `get_session` will raise an `OfflineModeIsEnabled` exception.
Example:
```py
from huggingface_hub import is_offline_mode
def list_files(repo_id: str):
if is_offline_mode():
... # list files from local cache (degraded experience but still functional)
else:
... # list files from Hub (complete experience)
```
huggingface-hub.kernel_info
Python Library Documentation: method kernel_info in module huggingface_hub.hf_api
kernel_info(repo_id: 'str', *, revision: 'str | None' = None, timeout: 'float | None' = None, token: 'bool | str | None' = None) -> 'KernelInfo' method of huggingface_hub.hf_api.HfApi instance
Get info on one specific kernel on huggingface.co.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated by a `/`.
revision (`str`, *optional*):
The revision of the kernel repository from which to get the
information.
timeout (`float`, *optional*):
Whether to set a timeout for the request to the Hub.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`~hf_api.ModelInfo`]: The kernel repository information.
huggingface-hub.list_accepted_access_requests
Python Library Documentation: method list_accepted_access_requests in module huggingface_hub.hf_api
list_accepted_access_requests(repo_id: 'str', *, repo_type: 'str | None' = None, token: 'bool | str | None' = None) -> 'Iterable[AccessRequest]' method of huggingface_hub.hf_api.HfApi instance
Get accepted access requests for a given gated repo.
An accepted request means the user has requested access to the repo and the request has been accepted. The user
can download any file of the repo. If the approval mode is automatic, this list should contains by default all
requests. Accepted requests can be cancelled or rejected at any time using [`cancel_access_request`] and
[`reject_access_request`]. A cancelled request will go back to the pending list while a rejected request will
go to the rejected list. In both cases, the user will lose access to the repo.
For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
Args:
repo_id (`str`):
The id of the repo to get access requests for.
repo_type (`str`, *optional*):
The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`.
Defaults to `model`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`Iterable[AccessRequest]`: An iterable of [`AccessRequest`] objects. Each time contains a `username`, `email`,
`status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will
be populated with user's answers.
Raises:
[`HfHubHTTPError`]:
HTTP 400 if the repo is not gated.
[`HfHubHTTPError`]:
HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
or `admin` role in the organization the repo belongs to or if you passed a `read` token.
Example:
```py
>>> from huggingface_hub import list_accepted_access_requests
>>> requests = list(list_accepted_access_requests("meta-llama/Llama-2-7b"))
>>> len(requests)
411
>>> requests[0]
[
AccessRequest(
username='clem',
fullname='Clem 🤗',
email='***',
timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
status='accepted',
fields=None,
),
...
]
```
huggingface-hub.list_bucket_tree
Python Library Documentation: method list_bucket_tree in module huggingface_hub.hf_api
list_bucket_tree(bucket_id: 'str', prefix: 'str | None' = None, *, recursive: 'bool | None' = None, token: 'str | bool | None' = None) -> 'Iterable[BucketFile | BucketFolder]' method of huggingface_hub.hf_api.HfApi instance
List files in a bucket.
Args:
bucket_id (`str`):
The ID of the bucket (e.g. `"username/my-bucket"`).
prefix (`str`, *optional*):
Filter results to files whose path starts with this prefix.
recursive (`bool`, *optional*):
If `True`, list files recursively. If `False` (default), list files and directories only at root.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`Iterable[Union[BucketFile, BucketFolder]]`: An iterable of [`BucketFile`] and [`BucketFolder`] objects
containing file and directory information (path, etc.).
Example:
```python
>>> from huggingface_hub import list_bucket_tree
>>> for file_info in list_bucket_tree(bucket_id="username/my-bucket"):
... print(file_info.path)
>>> # Filter by prefix
>>> for file_info in list_bucket_tree(bucket_id="username/my-bucket", prefix="models/"):
... print(file_info.path)
```
huggingface-hub.list_buckets
Python Library Documentation: method list_buckets in module huggingface_hub.hf_api
list_buckets(namespace: 'str | None' = None, *, search: 'str | None' = None, token: 'bool | str | None' = None) -> 'Iterable[BucketInfo]' method of huggingface_hub.hf_api.HfApi instance
List buckets on the Hub under a certain namespace.
Args:
namespace (`str`, *optional*):
List buckets under this namespace (user or organization). Defaults to listing user's buckets.
search (`str`, *optional*):
A search string to filter bucket names.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`Iterable[BucketInfo]`: An iterable of [`BucketInfo`] objects.
Example:
```python
>>> from huggingface_hub import list_buckets
>>> for bucket in list_buckets(): # lists buckets in the user's namespace
... print(bucket)
>>> for bucket in list_buckets(namespace="huggingface"): # lists buckets in the "huggingface" organization
... print(bucket)
>>> for bucket in list_buckets(search="my-prefix"): # filter buckets by name
... print(bucket)
```
huggingface-hub.list_collections
Python Library Documentation: method list_collections in module huggingface_hub.hf_api
list_collections(*, owner: 'list[str] | str | None' = None, item: 'list[str] | str | None' = None, sort: 'CollectionSort_T | None' = None, limit: 'int | None' = None, token: 'bool | str | None' = None) -> 'Iterable[Collection]' method of huggingface_hub.hf_api.HfApi instance
List collections on the Huggingface Hub, given some filters.
> [!WARNING]
> When listing collections, the item list per collection is truncated to 4 items maximum. To retrieve all items
> from a collection, you must use [`get_collection`].
Args:
owner (`list[str]` or `str`, *optional*):
Filter by owner's username.
item (`list[str]` or `str`, *optional*):
Filter collections containing a particular items. Example: `"models/teknium/OpenHermes-2.5-Mistral-7B"`, `"datasets/squad"` or `"papers/2311.12983"`.
sort (`Literal["lastModified", "trending", "upvotes"]`, *optional*):
Sort collections by last modified, trending or upvotes.
limit (`int`, *optional*):
Maximum number of collections to be returned.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`Iterable[Collection]`: an iterable of [`Collection`] objects.
huggingface-hub.list_daily_papers
Python Library Documentation: method list_daily_papers in module huggingface_hub.hf_api
list_daily_papers(*, date: 'str | None' = None, token: 'bool | str | None' = None, week: 'str | None' = None, month: 'str | None' = None, submitter: 'str | None' = None, sort: 'DailyPapersSort_T | None' = None, p: 'int | None' = None, limit: 'int | None' = None) -> 'Iterable[PaperInfo]' method of huggingface_hub.hf_api.HfApi instance
List the daily papers published on a given date on the Hugging Face Hub.
Args:
date (`str`, *optional*):
Date in ISO format (YYYY-MM-DD) for which to fetch daily papers.
Defaults to most recent ones.
token (Union[bool, str, None], *optional*):
A valid user access token (string). Defaults to the locally saved
token. To disable authentication, pass `False`.
week (`str`, *optional*):
Week in ISO format (YYYY-Www) for which to fetch daily papers. Example, `2025-W09`.
month (`str`, *optional*):
Month in ISO format (YYYY-MM) for which to fetch daily papers. Example, `2025-02`.
submitter (`str`, *optional*):
Username of the submitter to filter daily papers.
sort (`Literal["publishedAt", "trending"]`, *optional*):
Sort order for the daily papers. Can be either by `publishedAt` or by `trending`.
Defaults to `"publishedAt"`
p (`int`, *optional*):
Page number for pagination. Defaults to 0.
limit (`int`, *optional*):
Limit of papers to fetch. Defaults to 50.
Returns:
`Iterable[PaperInfo]`: an iterable of [`huggingface_hub.hf_api.PaperInfo`] objects.
Example:
```python
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> list(api.list_daily_papers(date="2025-10-29"))
```
huggingface-hub.list_dataset_parquet_files
Python Library Documentation: method list_dataset_parquet_files in module huggingface_hub.hf_api
list_dataset_parquet_files(repo_id: 'str', *, config: 'str | None' = None, token: 'bool | str | None' = None) -> 'list[DatasetParquetEntry]' method of huggingface_hub.hf_api.HfApi instance
List parquet files available for a dataset on the Hub.
All datasets hosted on the Hub are auto-converted to Parquet by the
[Dataset Viewer](https://huggingface.co/docs/dataset-viewer/parquet).
This method returns the list of parquet files with their URLs, configs,
splits and sizes.
Args:
repo_id (`str`):
The dataset repository ID (e.g. `"username/dataset-name"`).
config (`str`, *optional*):
Filter by a specific config/subset name. When provided, only
parquet files for that config are returned.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`list[DatasetParquetEntry]`: a list of [`DatasetParquetEntry`] objects
containing config, split, url and size for each parquet file.
Example:
```python
>>> from huggingface_hub import list_dataset_parquet_files
>>> list_dataset_parquet_files("lhoestq/demo1")
>>> entries[0]
DatasetParquetEntry(config='default', split='train', url='https://huggingface.co/...', size=5038)
```
huggingface-hub.list_datasets
Python Library Documentation: method list_datasets in module huggingface_hub.hf_api
list_datasets(*, filter: 'str | Iterable[str] | None' = None, author: 'str | None' = None, benchmark: "Literal[True] | Literal['official'] | str | None" = None, dataset_name: 'str | None' = None, gated: 'bool | None' = None, language_creators: 'str | list[str] | None' = None, language: 'str | list[str] | None' = None, multilinguality: 'str | list[str] | None' = None, size_categories: 'str | list[str] | None' = None, task_categories: 'str | list[str] | None' = None, task_ids: 'str | list[str] | None' = None, search: 'str | None' = None, sort: 'DatasetSort_T | None' = None, limit: 'int | None' = None, expand: 'list[ExpandDatasetProperty_T] | None' = None, full: 'bool | None' = None, token: 'bool | str | None' = None) -> 'Iterable[DatasetInfo]' method of huggingface_hub.hf_api.HfApi instance
List datasets hosted on the Huggingface Hub, given some filters.
Args:
filter (`str` or `Iterable[str]`, *optional*):
A string or list of string to filter datasets on the hub.
author (`str`, *optional*):
A string which identify the author of the returned datasets.
benchmark (`True`, `"official"`, `str`, *optional*):
Filter datasets by benchmark. Can be `True` or `"official"` to return official benchmark datasets.
For future-compatibility, can also be a string representing the benchmark name (currently only "official" is supported).
dataset_name (`str`, *optional*):
A string or list of strings that can be used to identify datasets on
the Hub by its name, such as `SQAC` or `wikineural`
gated (`bool`, *optional*):
A boolean to filter datasets on the Hub that are gated or not. By default, all datasets are returned.
If `gated=True` is passed, only gated datasets are returned.
If `gated=False` is passed, only non-gated datasets are returned.
language_creators (`str` or `List`, *optional*):
A string or list of strings that can be used to identify datasets on
the Hub with how the data was curated, such as `crowdsourced` or
`machine_generated`.
language (`str` or `List`, *optional*):
A string or list of strings representing a two-character language to
filter datasets by on the Hub.
multilinguality (`str` or `List`, *optional*):
A string or list of strings representing a filter for datasets that
contain multiple languages.
size_categories (`str` or `List`, *optional*):
A string or list of strings that can be used to identify datasets on
the Hub by the size of the dataset such as `100K<n<1M` or
`1M<n<10M`.
tags (`str` or `List`, *optional*):
Deprecated. Pass tags in `filter` to filter datasets by tags.
task_categories (`str` or `List`, *optional*):
A string or list of strings that can be used to identify datasets on
the Hub by the designed task, such as `audio_classification` or
`named_entity_recognition`.
task_ids (`str` or `List`, *optional*):
A string or list of strings that can be used to identify datasets on
the Hub by the specific task such as `speech_emotion_recognition` or
`paraphrase`.
search (`str`, *optional*):
A string that will be contained in the returned datasets.
sort (`DatasetSort_T`, *optional*):
The key with which to sort the resulting datasets. Possible values are "created_at", "downloads",
"last_modified", "likes" and "trending_score".
limit (`int`, *optional*):
The limit on the number of datasets fetched. Leaving this option
to `None` fetches all datasets.
expand (`list[ExpandDatasetProperty_T]`, *optional*):
List properties to return in the response. When used, only the properties in the list will be returned.
This parameter cannot be used if `full` is passed.
Possible values are `"author"`, `"cardData"`, `"citation"`, `"createdAt"`, `"disabled"`, `"description"`, `"downloads"`, `"downloadsAllTime"`, `"gated"`, `"lastModified"`, `"likes"`, `"mainSize"`, `"paperswithcode_id"`, `"private"`, `"siblings"`, `"sha"`, `"tags"`, `"trendingScore"`, `"usedStorage"`, and `"resourceGroup"`.
full (`bool`, *optional*):
Whether to fetch all dataset data, including the `last_modified`,
the `card_data` and the files. Can contain useful information such as the
PapersWithCode ID.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`Iterable[DatasetInfo]`: an iterable of [`huggingface_hub.hf_api.DatasetInfo`] objects.
Example usage with the `filter` argument:
```python
>>> from huggingface_hub import HfApi
>>> api = HfApi()
# List all datasets
>>> api.list_datasets()
# List only the text classification datasets
>>> api.list_datasets(filter="task_categories:text-classification")
# List only the datasets in russian for language modeling
>>> api.list_datasets(
... filter=("language:ru", "task_ids:language-modeling")
... )
# List FiftyOne datasets (identified by the tag "fiftyone" in dataset card)
>>> api.list_datasets(tags="fiftyone")
```
Example usage with the `search` argument:
```python
>>> from huggingface_hub import HfApi
>>> api = HfApi()
# List all datasets with "text" in their name
>>> api.list_datasets(search="text")
# List all datasets with "text" in their name made by google
>>> api.list_datasets(search="text", author="google")
```
huggingface-hub.list_inference_catalog
Python Library Documentation: method list_inference_catalog in module huggingface_hub.hf_api
list_inference_catalog(*, token: 'bool | str | None' = None) -> 'list[str]' method of huggingface_hub.hf_api.HfApi instance
List models available in the Hugging Face Inference Catalog.
The goal of the Inference Catalog is to provide a curated list of models that are optimized for inference
and for which default configurations have been tested. See https://endpoints.huggingface.co/catalog for a list
of available models in the catalog.
Use [`create_inference_endpoint_from_catalog`] to deploy a model from the catalog.
Args:
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
Returns:
List[`str`]: A list of model IDs available in the catalog.
> [!WARNING]
> `list_inference_catalog` is experimental. Its API is subject to change in the future. Please provide feedback
> if you have any suggestions or requests.
huggingface-hub.list_inference_endpoints
Python Library Documentation: method list_inference_endpoints in module huggingface_hub.hf_api
list_inference_endpoints(namespace: 'str | None' = None, *, token: 'bool | str | None' = None) -> 'list[InferenceEndpoint]' method of huggingface_hub.hf_api.HfApi instance
Lists all inference endpoints for the given namespace.
Args:
namespace (`str`, *optional*):
The namespace to list endpoints for. Defaults to the current user. Set to `"*"` to list all endpoints
from all namespaces (i.e. personal namespace and all orgs the user belongs to).
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
list[`InferenceEndpoint`]: A list of all inference endpoints for the given namespace.
Example:
```python
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> api.list_inference_endpoints()
[InferenceEndpoint(name='my-endpoint', ...), ...]
```
huggingface-hub.list_jobs
Python Library Documentation: method list_jobs in module huggingface_hub.hf_api
list_jobs(*, status: 'list[JobStage | str] | JobStage | str | None' = None, labels: 'dict[str, str] | None' = None, timeout: 'int | None' = None, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'Iterable[JobInfo]' method of huggingface_hub.hf_api.HfApi instance
List compute Jobs on Hugging Face infrastructure.
Args:
status (`JobStage`, `str` or `list`, *optional*):
Only return Jobs with the given status(es), e.g. `"RUNNING"` or `[JobStage.RUNNING, JobStage.SCHEDULING]`.
See [`JobStage`] for possible values.
labels (`dict[str, str]`, *optional*):
Only return Jobs that have all the given `key=value` labels, e.g. `{"env": "prod", "team": "ml"}`.
timeout (`float`, *optional*):
Whether to set a timeout for the request to the Hub.
namespace (`str`, *optional*):
The namespace from where it lists the jobs. Defaults to the current user's namespace.
token `(Union[bool, str, None]`, *optional*):
A valid user access token. If not provided, the locally saved token will be used, which is the
recommended authentication method. Set to `False` to disable authentication.
Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
Returns:
`Iterable[JobInfo]`: an iterable of [`JobInfo`] objects.
huggingface-hub.list_jobs_hardware
Python Library Documentation: method list_jobs_hardware in module huggingface_hub.hf_api
list_jobs_hardware(token: 'bool | str | None' = None) -> 'list[JobHardwareInfo]' method of huggingface_hub.hf_api.HfApi instance
List available hardware options for Jobs on Hugging Face infrastructure.
Returns:
`list[JobHardwareInfo]`: A list of available hardware configurations.
Example:
```python
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> hardware_list = api.list_jobs_hardware()
>>> hardware_list[0]
JobHardwareInfo(name='cpu-basic', pretty_name='CPU Basic', cpu='2 vCPU', ram='16 GB', ephemeral_storage='20 GB', accelerator=None, unit_cost_micro_usd=167, unit_cost_usd=0.000167, unit_label='minute')
>>> hardware_list[0].name
'cpu-basic'
# Filter GPU options
>>> gpu_hardware = [hw for hw in hardware_list if hw.accelerator is not None]
>>> gpu_hardware[0].accelerator.model
'T4'
```
huggingface-hub.list_lfs_files
Python Library Documentation: method list_lfs_files in module huggingface_hub.hf_api
list_lfs_files(repo_id: 'str', *, repo_type: 'str | None' = None, token: 'bool | str | None' = None) -> 'Iterable[LFSFileInfo]' method of huggingface_hub.hf_api.HfApi instance
List all LFS files in a repo on the Hub.
This is primarily useful to count how much storage a repo is using and to eventually clean up large files
with [`permanently_delete_lfs_files`]. Note that this would be a permanent action that will affect all commits
referencing this deleted files and that cannot be undone.
Args:
repo_id (`str`):
The repository for which you are listing LFS files.
repo_type (`str`, *optional*):
Type of repository. Set to `"dataset"` or `"space"` if listing from a dataset or space, `None` or
`"model"` if listing from a model. Default is `None`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`Iterable[LFSFileInfo]`: An iterator of [`LFSFileInfo`] objects.
Example:
```py
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> lfs_files = api.list_lfs_files("username/my-cool-repo")
# Filter files files to delete based on a combination of `filename`, `pushed_at`, `ref` or `size`.
# e.g. select only LFS files in the "checkpoints" folder
>>> lfs_files_to_delete = (lfs_file for lfs_file in lfs_files if lfs_file.filename.startswith("checkpoints/"))
# Permanently delete LFS files
>>> api.permanently_delete_lfs_files("username/my-cool-repo", lfs_files_to_delete)
```
huggingface-hub.list_liked_repos
Python Library Documentation: method list_liked_repos in module huggingface_hub.hf_api
list_liked_repos(user: 'str | None' = None, *, token: 'bool | str | None' = None) -> 'UserLikes' method of huggingface_hub.hf_api.HfApi instance
List all public repos liked by a user on huggingface.co.
This list is public so token is optional. If `user` is not passed, it defaults to
the logged in user.
See also [`unlike`].
Args:
user (`str`, *optional*):
Name of the user for which you want to fetch the likes.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`UserLikes`]: object containing the user name and 3 lists of repo ids (1 for
models, 1 for datasets and 1 for Spaces).
Raises:
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If `user` is not passed and no token found (either from argument or from machine).
Example:
```python
>>> from huggingface_hub import list_liked_repos
>>> likes = list_liked_repos("julien-c")
>>> likes.user
"julien-c"
>>> likes.models
["osanseviero/streamlit_1.15", "Xhaheen/ChatGPT_HF", ...]
```
huggingface-hub.list_models
Python Library Documentation: method list_models in module huggingface_hub.hf_api
list_models(*, filter: 'str | Iterable[str] | None' = None, author: 'str | None' = None, apps: 'str | list[str] | None' = None, gated: 'bool | None' = None, inference: "Literal['warm'] | None" = None, inference_provider: "Literal['all'] | PROVIDER_T | list[PROVIDER_T] | None" = None, model_name: 'str | None' = None, trained_dataset: 'str | list[str] | None' = None, search: 'str | None' = None, pipeline_tag: 'str | None' = None, num_parameters: 'str | None' = None, emissions_thresholds: 'tuple[float, float] | None' = None, sort: 'ModelSort_T | None' = None, limit: 'int | None' = None, expand: 'list[ExpandModelProperty_T] | None' = None, full: 'bool | None' = None, cardData: 'bool' = False, fetch_config: 'bool' = False, token: 'bool | str | None' = None) -> 'Iterable[ModelInfo]' method of huggingface_hub.hf_api.HfApi instance
List models hosted on the Huggingface Hub, given some filters.
Args:
filter (`str` or `Iterable[str]`, *optional*):
A string or list of string to filter models on the Hub.
Models can be filtered by library, language, task, tags, and more.
author (`str`, *optional*):
A string which identify the author (user or organization) of the
returned models.
apps (`str` or `List`, *optional*):
A string or list of strings to filter models on the Hub that
support the specified apps. Example values include `"ollama"` or `["ollama", "vllm"]`.
gated (`bool`, *optional*):
A boolean to filter models on the Hub that are gated or not. By default, all models are returned.
If `gated=True` is passed, only gated models are returned.
If `gated=False` is passed, only non-gated models are returned.
inference (`Literal["warm"]`, *optional*):
If "warm", filter models on the Hub currently served by at least one provider.
inference_provider (`Literal["all"]` or `str`, *optional*):
A string to filter models on the Hub that are served by a specific provider.
Pass `"all"` to get all models served by at least one provider.
trained_dataset (`str` or `List`, *optional*):
A string tag or a list of string tags of the trained dataset for a
model on the Hub.
search (`str`, *optional*):
A string that will be contained in the returned model ids.
pipeline_tag (`str`, *optional*):
A string pipeline tag to filter models on the Hub by, such as `summarization`.
num_parameters (`str`, *optional*):
Filter models by parameter count. Accepts the same range syntax as the Hub UI and API, for example
`"min:6B,max:128B"`, `"min:6B"` or `"max:128B"`.
emissions_thresholds (`Tuple`, *optional*):
A tuple of two ints or floats representing a minimum and maximum
carbon footprint to filter the resulting models with in grams.
sort (`ModelSort_T`, *optional*):
The key with which to sort the resulting models. Possible values are "created_at", "downloads",
"last_modified", "likes" and "trending_score".
limit (`int`, *optional*):
The limit on the number of models fetched. Leaving this option
to `None` fetches all models.
expand (`list[ExpandModelProperty_T]`, *optional*):
List properties to return in the response. When used, only the properties in the list will be returned.
This parameter cannot be used if `full`, `cardData` or `fetch_config` are passed.
Possible values are `"author"`, `"cardData"`, `"config"`, `"createdAt"`, `"disabled"`, `"downloads"`, `"downloadsAllTime"`, `"evalResults"`, `"gated"`, `"gguf"`, `"inference"`, `"inferenceProviderMapping"`, `"lastModified"`, `"library_name"`, `"likes"`, `"mask_token"`, `"model-index"`, `"pipeline_tag"`, `"private"`, `"safetensors"`, `"sha"`, `"siblings"`, `"spaces"`, `"tags"`, `"transformersInfo"`, `"trendingScore"`, `"widgetData"`, and `"resourceGroup"`.
full (`bool`, *optional*):
Whether to fetch all model data, including the `last_modified`,
the `sha`, the files and the `tags`. This is set to `True` by
default when using a filter.
cardData (`bool`, *optional*):
Whether to grab the metadata for the model as well. Can contain
useful information such as carbon emissions, metrics, and
datasets trained on.
fetch_config (`bool`, *optional*):
Whether to fetch the model configs as well. This is not included
in `full` due to its size.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
model_name (`str`, *optional*):
(deprecated). Use `search` instead.
Returns:
`Iterable[ModelInfo]`: an iterable of [`huggingface_hub.hf_api.ModelInfo`] objects.
Example:
```python
>>> from huggingface_hub import HfApi
>>> api = HfApi()
# List all models
>>> api.list_models()
# List text classification models
>>> api.list_models(filter="text-classification")
# List models from the KerasHub library
>>> api.list_models(filter="keras-hub")
# List models served by Cohere
>>> api.list_models(inference_provider="cohere")
# List models with "bert" in their name
>>> api.list_models(search="bert")
# List models with "bert" in their name and pushed by google
>>> api.list_models(search="bert", author="google")
# List models with 6B to 128B parameters
>>> api.list_models(num_parameters="min:6B,max:128B", sort="likes")
```
huggingface-hub.list_organization_followers
Python Library Documentation: method list_organization_followers in module huggingface_hub.hf_api
list_organization_followers(organization: 'str', token: 'bool | str | None' = None) -> 'Iterable[User]' method of huggingface_hub.hf_api.HfApi instance
List followers of an organization on the Hub.
Args:
organization (`str`):
Name of the organization to get the followers of.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`Iterable[User]`: A list of [`User`] objects with the followers of the organization.
Raises:
[`HfHubHTTPError`]:
HTTP 404 If the organization does not exist on the Hub.
huggingface-hub.list_organization_members
Python Library Documentation: method list_organization_members in module huggingface_hub.hf_api
list_organization_members(organization: 'str', token: 'bool | str | None' = None) -> 'Iterable[User]' method of huggingface_hub.hf_api.HfApi instance
List of members of an organization on the Hub.
Args:
organization (`str`):
Name of the organization to get the members of.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`Iterable[User]`: A list of [`User`] objects with the members of the organization.
Raises:
[`HfHubHTTPError`]:
HTTP 404 If the organization does not exist on the Hub.
huggingface-hub.list_papers
Python Library Documentation: method list_papers in module huggingface_hub.hf_api
list_papers(*, query: 'str | None' = None, limit: 'int | None' = None, token: 'bool | str | None' = None) -> 'Iterable[PaperInfo]' method of huggingface_hub.hf_api.HfApi instance
List daily papers on the Hugging Face Hub given a search query.
Args:
query (`str`, *optional*):
A search query string to find papers.
If provided, returns papers that match the query.
limit (`int`, *optional*):
The maximum number of papers to return.
token (Union[bool, str, None], *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`Iterable[PaperInfo]`: an iterable of [`huggingface_hub.hf_api.PaperInfo`] objects.
Example:
```python
>>> from huggingface_hub import HfApi
>>> api = HfApi()
# List all papers with "attention" in their title
>>> api.list_papers(query="attention")
```
huggingface-hub.list_pending_access_requests
Python Library Documentation: method list_pending_access_requests in module huggingface_hub.hf_api
list_pending_access_requests(repo_id: 'str', *, repo_type: 'str | None' = None, token: 'bool | str | None' = None) -> 'Iterable[AccessRequest]' method of huggingface_hub.hf_api.HfApi instance
Get pending access requests for a given gated repo.
A pending request means the user has requested access to the repo but the request has not been processed yet.
If the approval mode is automatic, this list should be empty. Pending requests can be accepted or rejected
using [`accept_access_request`] and [`reject_access_request`].
For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
Args:
repo_id (`str`):
The id of the repo to get access requests for.
repo_type (`str`, *optional*):
The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`.
Defaults to `model`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`Iterable[AccessRequest]`: An iterable of [`AccessRequest`] objects. Each time contains a `username`, `email`,
`status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will
be populated with user's answers.
Raises:
[`HfHubHTTPError`]:
HTTP 400 if the repo is not gated.
[`HfHubHTTPError`]:
HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
or `admin` role in the organization the repo belongs to or if you passed a `read` token.
Example:
```py
>>> from huggingface_hub import list_pending_access_requests, accept_access_request
# List pending requests
>>> requests = list(list_pending_access_requests("meta-llama/Llama-2-7b"))
>>> len(requests)
411
>>> requests[0]
[
AccessRequest(
username='clem',
fullname='Clem 🤗',
email='***',
timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
status='pending',
fields=None,
),
...
]
# Accept Clem's request
>>> accept_access_request("meta-llama/Llama-2-7b", "clem")
```
huggingface-hub.list_rejected_access_requests
Python Library Documentation: method list_rejected_access_requests in module huggingface_hub.hf_api
list_rejected_access_requests(repo_id: 'str', *, repo_type: 'str | None' = None, token: 'bool | str | None' = None) -> 'Iterable[AccessRequest]' method of huggingface_hub.hf_api.HfApi instance
Get rejected access requests for a given gated repo.
A rejected request means the user has requested access to the repo and the request has been explicitly rejected
by a repo owner (either you or another user from your organization). The user cannot download any file of the
repo. Rejected requests can be accepted or cancelled at any time using [`accept_access_request`] and
[`cancel_access_request`]. A cancelled request will go back to the pending list while an accepted request will
go to the accepted list.
For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
Args:
repo_id (`str`):
The id of the repo to get access requests for.
repo_type (`str`, *optional*):
The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`.
Defaults to `model`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`Iterable[AccessRequest]`: An iterable of [`AccessRequest`] objects. Each time contains a `username`, `email`,
`status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will
be populated with user's answers.
Raises:
[`HfHubHTTPError`]:
HTTP 400 if the repo is not gated.
[`HfHubHTTPError`]:
HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
or `admin` role in the organization the repo belongs to or if you passed a `read` token.
Example:
```py
>>> from huggingface_hub import list_rejected_access_requests
>>> requests = list(list_rejected_access_requests("meta-llama/Llama-2-7b"))
>>> len(requests)
411
>>> requests[0]
[
AccessRequest(
username='clem',
fullname='Clem 🤗',
email='***',
timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
status='rejected',
fields=None,
),
...
]
```
huggingface-hub.list_repo_commits
Python Library Documentation: method list_repo_commits in module huggingface_hub.hf_api
list_repo_commits(repo_id: 'str', *, repo_type: 'str | None' = None, token: 'bool | str | None' = None, revision: 'str | None' = None, formatted: 'bool' = False) -> 'list[GitCommitInfo]' method of huggingface_hub.hf_api.HfApi instance
Get the list of commits of a given revision for a repo on the Hub.
Commits are sorted by date (last commit first).
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated by a `/`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if listing commits from a dataset or a Space, `None` or `"model"` if
listing from a model. Default is `None`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
revision (`str`, *optional*):
The git revision to commit from. Defaults to the head of the `"main"` branch.
formatted (`bool`):
Whether to return the HTML-formatted title and description of the commits. Defaults to False.
Example:
```py
>>> from huggingface_hub import HfApi
>>> api = HfApi()
# Commits are sorted by date (last commit first)
>>> initial_commit = api.list_repo_commits("gpt2")[-1]
# Initial commit is always a system commit containing the `.gitattributes` file.
>>> initial_commit
GitCommitInfo(
commit_id='9b865efde13a30c13e0a33e536cf3e4a5a9d71d8',
authors=['system'],
created_at=datetime.datetime(2019, 2, 18, 10, 36, 15, tzinfo=datetime.timezone.utc),
title='initial commit',
message='',
formatted_title=None,
formatted_message=None
)
# Create an empty branch by deriving from initial commit
>>> api.create_branch("gpt2", "new_empty_branch", revision=initial_commit.commit_id)
```
Returns:
list[[`GitCommitInfo`]]: list of objects containing information about the commits for a repo on the Hub.
Raises:
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
does not exist.
[`~utils.RevisionNotFoundError`]:
If revision is not found (error 404) on the repo.
huggingface-hub.list_repo_files
Python Library Documentation: method list_repo_files in module huggingface_hub.hf_api
list_repo_files(repo_id: 'str', *, revision: 'str | None' = None, repo_type: 'str | None' = None, token: 'str | bool | None' = None) -> 'list[str]' method of huggingface_hub.hf_api.HfApi instance
Get the list of files in a given repo.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated by a `/`.
revision (`str`, *optional*):
The revision of the repository from which to get the information.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or space, `None` or `"model"` if uploading to
a model. Default is `None`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`list[str]`: the list of files in a given repository.
huggingface-hub.list_repo_likers
Python Library Documentation: method list_repo_likers in module huggingface_hub.hf_api
list_repo_likers(repo_id: 'str', *, repo_type: 'str | None' = None, token: 'bool | str | None' = None) -> 'Iterable[User]' method of huggingface_hub.hf_api.HfApi instance
List all users who liked a given repo on the hugging Face Hub.
See also [`list_liked_repos`].
Args:
repo_id (`str`):
The repository to retrieve . Example: `"user/my-cool-model"`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
Returns:
`Iterable[User]`: an iterable of [`huggingface_hub.hf_api.User`] objects.
huggingface-hub.list_repo_refs
Python Library Documentation: method list_repo_refs in module huggingface_hub.hf_api
list_repo_refs(repo_id: 'str', *, repo_type: 'str | None' = None, include_pull_requests: 'bool' = False, token: 'str | bool | None' = None) -> 'GitRefs' method of huggingface_hub.hf_api.HfApi instance
Get the list of refs of a given repo (both tags and branches).
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
repo_type (`str`, *optional*):
Set to `"dataset"`, `"space"` or `"kernel"` if listing refs from a dataset, a Space or a Kernel,
`None` or `"model"` if listing from a model. Default is `None`.
include_pull_requests (`bool`, *optional*):
Whether to include refs from pull requests in the list. Defaults to `False`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Example:
```py
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> api.list_repo_refs("gpt2")
GitRefs(branches=[GitRefInfo(name='main', ref='refs/heads/main', target_commit='e7da7f221d5bf496a48136c0cd264e630fe9fcc8')], converts=[], tags=[])
>>> api.list_repo_refs("bigcode/the-stack", repo_type='dataset')
GitRefs(
branches=[
GitRefInfo(name='main', ref='refs/heads/main', target_commit='18edc1591d9ce72aa82f56c4431b3c969b210ae3'),
GitRefInfo(name='v1.1.a1', ref='refs/heads/v1.1.a1', target_commit='f9826b862d1567f3822d3d25649b0d6d22ace714')
],
converts=[],
tags=[
GitRefInfo(name='v1.0', ref='refs/tags/v1.0', target_commit='c37a8cd1e382064d8aced5e05543c5f7753834da')
]
)
```
Returns:
[`GitRefs`]: object containing all information about branches and tags for a
repo on the Hub.
huggingface-hub.list_repo_tree
Python Library Documentation: method list_repo_tree in module huggingface_hub.hf_api
list_repo_tree(repo_id: 'str', path_in_repo: 'str | None' = None, *, recursive: 'bool' = False, expand: 'bool' = False, revision: 'str | None' = None, repo_type: 'str | None' = None, token: 'str | bool | None' = None) -> 'Iterable[RepoFile | RepoFolder]' method of huggingface_hub.hf_api.HfApi instance
List a repo tree's files and folders and get information about them.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated by a `/`.
path_in_repo (`str`, *optional*):
Relative path of the tree (folder) in the repo, for example:
`"checkpoints/1fec34a/results"`. Will default to the root tree (folder) of the repository.
recursive (`bool`, *optional*, defaults to `False`):
Whether to list tree's files and folders recursively.
expand (`bool`, *optional*, defaults to `False`):
Whether to fetch more information about the tree's files and folders (e.g. last commit and files' security scan results). This
operation is more expensive for the server so only 50 results are returned per page (instead of 1000).
As pagination is implemented in `huggingface_hub`, this is transparent for you except for the time it
takes to get the results.
revision (`str`, *optional*):
The revision of the repository from which to get the tree. Defaults to `"main"` branch.
repo_type (`str`, *optional*):
The type of the repository from which to get the tree (`"model"`, `"dataset"`, `"space"` or `"kernel"`).
Defaults to `"model"`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`Iterable[Union[RepoFile, RepoFolder]]`:
The information about the tree's files and folders, as an iterable of [`RepoFile`] and [`RepoFolder`] objects. The order of the files and folders is
not guaranteed.
Raises:
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
does not exist.
[`~utils.RevisionNotFoundError`]:
If revision is not found (error 404) on the repo.
[`~utils.RemoteEntryNotFoundError`]:
If the tree (folder) does not exist (error 404) on the repo.
Examples:
Get information about a repo's tree.
```py
>>> from huggingface_hub import list_repo_tree
>>> repo_tree = list_repo_tree("lysandre/arxiv-nlp")
>>> repo_tree
<generator object HfApi.list_repo_tree at 0x7fa4088e1ac0>
>>> list(repo_tree)
[
RepoFile(path='.gitattributes', size=391, blob_id='ae8c63daedbd4206d7d40126955d4e6ab1c80f8f', lfs=None, last_commit=None, security=None),
RepoFile(path='README.md', size=391, blob_id='43bd404b159de6fba7c2f4d3264347668d43af25', lfs=None, last_commit=None, security=None),
RepoFile(path='config.json', size=554, blob_id='2f9618c3a19b9a61add74f70bfb121335aeef666', lfs=None, last_commit=None, security=None),
RepoFile(
path='flax_model.msgpack', size=497764107, blob_id='8095a62ccb4d806da7666fcda07467e2d150218e',
lfs={'size': 497764107, 'sha256': 'd88b0d6a6ff9c3f8151f9d3228f57092aaea997f09af009eefd7373a77b5abb9', 'pointer_size': 134}, last_commit=None, security=None
),
RepoFile(path='merges.txt', size=456318, blob_id='226b0752cac7789c48f0cb3ec53eda48b7be36cc', lfs=None, last_commit=None, security=None),
RepoFile(
path='pytorch_model.bin', size=548123560, blob_id='64eaa9c526867e404b68f2c5d66fd78e27026523',
lfs={'size': 548123560, 'sha256': '9be78edb5b928eba33aa88f431551348f7466ba9f5ef3daf1d552398722a5436', 'pointer_size': 134}, last_commit=None, security=None
),
RepoFile(path='vocab.json', size=898669, blob_id='b00361fece0387ca34b4b8b8539ed830d644dbeb', lfs=None, last_commit=None, security=None)]
]
```
Get even more information about a repo's tree (last commit and files' security scan results)
```py
>>> from huggingface_hub import list_repo_tree
>>> repo_tree = list_repo_tree("prompthero/openjourney-v4", expand=True)
>>> list(repo_tree)
[
RepoFolder(
path='feature_extractor',
tree_id='aa536c4ea18073388b5b0bc791057a7296a00398',
last_commit={
'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190',
'title': 'Upload diffusers weights (#48)',
'date': datetime.datetime(2023, 3, 21, 9, 5, 27, tzinfo=datetime.timezone.utc)
}
),
RepoFolder(
path='safety_checker',
tree_id='65aef9d787e5557373fdf714d6c34d4fcdd70440',
last_commit={
'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190',
'title': 'Upload diffusers weights (#48)',
'date': datetime.datetime(2023, 3, 21, 9, 5, 27, tzinfo=datetime.timezone.utc)
}
),
RepoFile(
path='model_index.json',
size=582,
blob_id='d3d7c1e8c3e78eeb1640b8e2041ee256e24c9ee1',
lfs=None,
last_commit={
'oid': 'b195ed2d503f3eb29637050a886d77bd81d35f0e',
'title': 'Fix deprecation warning by changing `CLIPFeatureExtractor` to `CLIPImageProcessor`. (#54)',
'date': datetime.datetime(2023, 5, 15, 21, 41, 59, tzinfo=datetime.timezone.utc)
},
security={
'safe': True,
'av_scan': {'virusFound': False, 'virusNames': None},
'pickle_import_scan': None
}
)
...
]
```
huggingface-hub.list_space_templates
Python Library Documentation: method list_space_templates in module huggingface_hub.hf_api
list_space_templates(*, token: 'str | bool | None' = None) -> 'list[SpaceTemplate]' method of huggingface_hub.hf_api.HfApi instance
List the official Space templates available on the Hub.
The `repo_id` of a returned template (or its short `name`) can be passed as `space_template`
to [`HfApi.create_repo`] to seed a new Space from that template.
Args:
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`list[SpaceTemplate]`: The list of available Space templates.
Example:
```py
>>> from huggingface_hub import list_space_templates
>>> templates = list_space_templates()
>>> templates[0]
SpaceTemplate(name='Streamlit', repo_id='streamlit/streamlit-template-space', sdk='docker', preferred_private=False)
```
huggingface-hub.list_spaces
Python Library Documentation: method list_spaces in module huggingface_hub.hf_api
list_spaces(*, filter: 'str | Iterable[str] | None' = None, author: 'str | None' = None, search: 'str | None' = None, datasets: 'str | Iterable[str] | None' = None, models: 'str | Iterable[str] | None' = None, linked: 'bool' = False, sort: 'SpaceSort_T | None' = None, limit: 'int | None' = None, expand: 'list[ExpandSpaceProperty_T] | None' = None, full: 'bool | None' = None, token: 'bool | str | None' = None) -> 'Iterable[SpaceInfo]' method of huggingface_hub.hf_api.HfApi instance
List spaces hosted on the Huggingface Hub, given some filters.
Args:
filter (`str` or `Iterable`, *optional*):
A string tag or list of tags that can be used to identify Spaces on the Hub.
author (`str`, *optional*):
A string which identify the author of the returned Spaces.
search (`str`, *optional*):
A string that will be contained in the returned Spaces.
datasets (`str` or `Iterable`, *optional*):
Whether to return Spaces that make use of a dataset.
The name of a specific dataset can be passed as a string.
models (`str` or `Iterable`, *optional*):
Whether to return Spaces that make use of a model.
The name of a specific model can be passed as a string.
linked (`bool`, *optional*):
Whether to return Spaces that make use of either a model or a dataset.
sort (`SpaceSort_T`, *optional*):
The key with which to sort the resulting spaces. Possible values are "created_at", "last_modified",
"likes" and "trending_score".
limit (`int`, *optional*):
The limit on the number of Spaces fetched. Leaving this option
to `None` fetches all Spaces.
expand (`list[ExpandSpaceProperty_T]`, *optional*):
List properties to return in the response. When used, only the properties in the list will be returned.
This parameter cannot be used if `full` is passed.
Possible values are `"author"`, `"cardData"`, `"datasets"`, `"disabled"`, `"lastModified"`, `"createdAt"`, `"likes"`, `"models"`, `"private"`, `"runtime"`, `"sdk"`, `"siblings"`, `"sha"`, `"subdomain"`, `"tags"`, `"trendingScore"`, `"usedStorage"`, and `"resourceGroup"`.
full (`bool`, *optional*):
Whether to fetch all Spaces data, including the `last_modified`, `siblings`
and `card_data` fields.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`Iterable[SpaceInfo]`: an iterable of [`huggingface_hub.hf_api.SpaceInfo`] objects.
huggingface-hub.list_spaces_hardware
Python Library Documentation: method list_spaces_hardware in module huggingface_hub.hf_api
list_spaces_hardware(token: 'bool | str | None' = None) -> 'list[JobHardwareInfo]' method of huggingface_hub.hf_api.HfApi instance
List available hardware options for Spaces.
Returns:
`list[JobHardwareInfo]`: A list of available hardware configurations.
Example:
```python
>>> from huggingface_hub import list_spaces_hardware
>>> hardware_list = list_spaces_hardware()
>>> hardware_list[0]
JobHardwareInfo(name='cpu-basic', pretty_name='CPU Basic', cpu='2 vCPU', ram='16 GB', ...)
>>> hardware_list[0].name
'cpu-basic'
```
huggingface-hub.list_user_followers
Python Library Documentation: method list_user_followers in module huggingface_hub.hf_api
list_user_followers(username: 'str', token: 'bool | str | None' = None) -> 'Iterable[User]' method of huggingface_hub.hf_api.HfApi instance
Get the list of followers of a user on the Hub.
Args:
username (`str`):
Username of the user to get the followers of.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`Iterable[User]`: A list of [`User`] objects with the followers of the user.
Raises:
[`HfHubHTTPError`]:
HTTP 404 If the user does not exist on the Hub.
huggingface-hub.list_user_following
Python Library Documentation: method list_user_following in module huggingface_hub.hf_api
list_user_following(username: 'str', token: 'bool | str | None' = None) -> 'Iterable[User]' method of huggingface_hub.hf_api.HfApi instance
Get the list of users followed by a user on the Hub.
Args:
username (`str`):
Username of the user to get the users followed by.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`Iterable[User]`: A list of [`User`] objects with the users followed by the user.
Raises:
[`HfHubHTTPError`]:
HTTP 404 If the user does not exist on the Hub.
huggingface-hub.list_user_repos
Python Library Documentation: method list_user_repos in module huggingface_hub.hf_api
list_user_repos(namespace: 'str | None' = None, *, token: 'bool | str | None' = None) -> 'Iterable[RepoStorageInfo]' method of huggingface_hub.hf_api.HfApi instance
List all repositories (models, datasets, spaces, buckets) for a user or organization with storage info.
Uses the `/api/settings/repositories` endpoint for the authenticated user or
`/api/organizations/{namespace}/settings/repositories` for an organization.
Args:
namespace (`str`, *optional*):
Organization name. If not provided, lists repos for the authenticated user.
token (`bool` or `str`, *optional*):
A valid user access token. Defaults to the locally saved token.
Returns:
`Iterable[RepoStorageInfo]`: An iterable of [`RepoStorageInfo`] objects.
Example:
```python
>>> from huggingface_hub import list_user_repos
>>> repos = list(list_user_repos())
>>> repos[0]
RepoStorageInfo(id='username/my-model', type='model', ...)
>>> # List repos from an organization
>>> repos = list(list_user_repos(namespace="my-org"))
```
huggingface-hub.list_webhooks
Python Library Documentation: method list_webhooks in module huggingface_hub.hf_api
list_webhooks(*, token: 'bool | str | None' = None) -> 'list[WebhookInfo]' method of huggingface_hub.hf_api.HfApi instance
List all configured webhooks.
Args:
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved token, which is the recommended
method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`list[WebhookInfo]`:
List of webhook info objects.
Example:
```python
>>> from huggingface_hub import list_webhooks
>>> webhooks = list_webhooks()
>>> len(webhooks)
2
>>> webhooks[0]
WebhookInfo(
id="654bbbc16f2ec14d77f109cc",
watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
secret="my-secret",
domains=["repo", "discussion"],
disabled=False,
)
```
huggingface-hub.load_state_dict_from_file
Python Library Documentation: function load_state_dict_from_file in module huggingface_hub.serialization._torch
load_state_dict_from_file(checkpoint_file: str | os.PathLike, map_location: Union[str, ForwardRef('torch.device'), NoneType] = None, weights_only: bool = False, mmap: bool = False) -> dict[str, 'torch.Tensor'] | typing.Any
Loads a checkpoint file, handling both safetensors and pickle checkpoint formats.
Args:
checkpoint_file (`str` or `os.PathLike`):
Path to the checkpoint file to load. Can be either a safetensors or pickle (`.bin`) checkpoint.
map_location (`str` or `torch.device`, *optional*):
A `torch.device` object, string or a dict specifying how to remap storage locations. It
indicates the location where all tensors should be loaded.
weights_only (`bool`, *optional*, defaults to `False`):
If True, only loads the model weights without optimizer states and other metadata.
Only supported for pickle (`.bin`) checkpoints with PyTorch >= 1.13. Has no effect when
loading safetensors files.
mmap (`bool`, *optional*, defaults to `False`):
Whether to use memory-mapped file loading. Memory mapping can improve loading performance
for large models in PyTorch >= 2.1.0 with zipfile-based checkpoints. Has no effect when
loading safetensors files, as the `safetensors` library uses memory mapping by default.
Returns:
`Union[dict[str, "torch.Tensor"], Any]`: The loaded checkpoint.
- For safetensors files: always returns a dictionary mapping parameter names to tensors.
- For pickle files: returns any Python object that was pickled (commonly a state dict, but could be
an entire model, optimizer state, or any other Python object).
Raises:
[`FileNotFoundError`](https://docs.python.org/3/library/exceptions.html#FileNotFoundError)
If the checkpoint file does not exist.
[`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
If safetensors or torch is not installed when trying to load a .safetensors file or a PyTorch checkpoint respectively.
[`OSError`](https://docs.python.org/3/library/exceptions.html#OSError)
If the checkpoint file format is invalid or if git-lfs files are not properly downloaded.
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If the checkpoint file path is empty or invalid.
Example:
```python
>>> from huggingface_hub import load_state_dict_from_file
# Load a PyTorch checkpoint
>>> state_dict = load_state_dict_from_file("path/to/model.bin", map_location="cpu")
>>> model.load_state_dict(state_dict)
# Load a safetensors checkpoint
>>> state_dict = load_state_dict_from_file("path/to/model.safetensors")
>>> model.load_state_dict(state_dict)
```
huggingface-hub.load_torch_model
Python Library Documentation: function load_torch_model in module huggingface_hub.serialization._torch
load_torch_model(model: 'torch.nn.Module', checkpoint_path: str | os.PathLike, *, strict: bool = False, safe: bool = True, weights_only: bool = False, map_location: Union[str, ForwardRef('torch.device'), NoneType] = None, mmap: bool = False, filename_pattern: str | None = None) -> <function NamedTuple at 0x000001F163829760>
Load a checkpoint into a model, handling both sharded and non-sharded checkpoints.
Args:
model (`torch.nn.Module`):
The model in which to load the checkpoint.
checkpoint_path (`str` or `os.PathLike`):
Path to either the checkpoint file or directory containing the checkpoint(s).
strict (`bool`, *optional*, defaults to `False`):
Whether to strictly enforce that the keys in the model state dict match the keys in the checkpoint.
safe (`bool`, *optional*, defaults to `True`):
If `safe` is True, the safetensors files will be loaded. If `safe` is False, the function
will first attempt to load safetensors files if they are available, otherwise it will fall back to loading
pickle files. `filename_pattern` parameter takes precedence over `safe` parameter.
weights_only (`bool`, *optional*, defaults to `False`):
If True, only loads the model weights without optimizer states and other metadata.
Only supported in PyTorch >= 1.13.
map_location (`str` or `torch.device`, *optional*):
A `torch.device` object, string or a dict specifying how to remap storage locations. It
indicates the location where all tensors should be loaded.
mmap (`bool`, *optional*, defaults to `False`):
Whether to use memory-mapped file loading. Memory mapping can improve loading performance
for large models in PyTorch >= 2.1.0 with zipfile-based checkpoints.
filename_pattern (`str`, *optional*):
The pattern to look for the index file. Pattern must be a string that
can be formatted with `filename_pattern.format(suffix=...)` and must contain the keyword `suffix`
Defaults to `"model{suffix}.safetensors"`.
Returns:
`NamedTuple`: A named tuple with `missing_keys` and `unexpected_keys` fields.
- `missing_keys` is a list of str containing the missing keys, i.e. keys that are in the model but not in the checkpoint.
- `unexpected_keys` is a list of str containing the unexpected keys, i.e. keys that are in the checkpoint but not in the model.
Raises:
[`FileNotFoundError`](https://docs.python.org/3/library/exceptions.html#FileNotFoundError)
If the checkpoint file or directory does not exist.
[`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
If safetensors or torch is not installed when trying to load a .safetensors file or a PyTorch checkpoint respectively.
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If the checkpoint path is invalid or if the checkpoint format cannot be determined.
Example:
```python
>>> from huggingface_hub import load_torch_model
>>> model = ... # A PyTorch model
>>> load_torch_model(model, "path/to/checkpoint")
```
huggingface-hub.logging
Python Library Documentation: module huggingface_hub.utils.logging in huggingface_hub.utils
NAME
huggingface_hub.utils.logging - Logging utilities.
FUNCTIONS
disable_propagation() -> None
Disable propagation of the library log outputs. Note that log propagation is
disabled by default.
enable_propagation() -> None
Enable propagation of the library log outputs. Please disable the
HuggingFace Hub's default handler to prevent double logging if the root
logger has been configured.
get_logger(name: str | None = None) -> logging.Logger
Returns a logger with the specified name. This function is not supposed
to be directly accessed by library users.
Args:
name (`str`, *optional*):
The name of the logger to get, usually the filename
Example:
```python
>>> from huggingface_hub import get_logger
>>> logger = get_logger(__file__)
>>> logger.set_verbosity_info()
```
get_verbosity() -> int
Return the current level for the HuggingFace Hub's root logger.
Returns:
Logging level, e.g., `huggingface_hub.logging.DEBUG` and
`huggingface_hub.logging.INFO`.
> [!TIP]
> HuggingFace Hub has following logging levels:
>
> - `huggingface_hub.logging.CRITICAL`, `huggingface_hub.logging.FATAL`
> - `huggingface_hub.logging.ERROR`
> - `huggingface_hub.logging.WARNING`, `huggingface_hub.logging.WARN`
> - `huggingface_hub.logging.INFO`
> - `huggingface_hub.logging.DEBUG`
set_verbosity(verbosity: int) -> None
Sets the level for the HuggingFace Hub's root logger.
Args:
verbosity (`int`):
Logging level, e.g., `huggingface_hub.logging.DEBUG` and
`huggingface_hub.logging.INFO`.
set_verbosity_debug()
Sets the verbosity to `logging.DEBUG`.
set_verbosity_error()
Sets the verbosity to `logging.ERROR`.
set_verbosity_info()
Sets the verbosity to `logging.INFO`.
set_verbosity_warning()
Sets the verbosity to `logging.WARNING`.
DATA
CRITICAL = 50
DEBUG = 10
ERROR = 40
FATAL = 50
INFO = 20
NOTSET = 0
WARN = 30
WARNING = 30
log_levels = {'critical': 50, 'debug': 10, 'error': 40, 'info': 20, 'w...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\huggingface_hub\utils\logging.py
huggingface-hub.login
Python Library Documentation: function login in module huggingface_hub._login
login(token: str | None = None, *, add_to_git_credential: bool = False, skip_if_logged_in: bool = True) -> None
Login the machine to access the Hub.
The `token` is persisted in cache and set as a git credential. Once done, the machine
is logged in and the access token will be available across all `huggingface_hub`
components. If `token` is not provided, a browser-based OAuth flow is used to
authenticate: open a URL, enter a short code, and the token is retrieved and saved.
In a terminal, you can also choose to paste an existing access token instead.
To log in from outside of a script, one can also use `hf auth login` which is
a cli command that wraps [`login`].
> [!TIP]
> When the token is not passed, [`login`] will automatically detect if the script runs
> in a notebook or not. However, this detection might not be accurate due to the
> variety of notebooks that exists nowadays. If that is the case, you can always force
> the UI by using [`notebook_login`] or [`interpreter_login`].
Args:
token (`str`, *optional*):
User access token to generate from https://huggingface.co/settings/token.
add_to_git_credential (`bool`, defaults to `False`):
If `True`, token will be set as git credential. If no git credential helper
is configured, a warning will be displayed to the user. Only used when `token`
is provided; ignored by the browser-based flow.
skip_if_logged_in (`bool`, defaults to `True`):
If `True`, do not prompt for token if user is already logged in.
Set to `False` to force re-login. In CLI, use `--force` instead.
Raises:
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If an organization token is passed. Only personal account tokens are valid
to log in.
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If token is invalid.
[`DeviceCodeError`]
If the browser-based login fails (authorization denied, code expired, ...).
huggingface-hub.logout
Python Library Documentation: function logout in module huggingface_hub._login
logout(token_name: str | None = None) -> None
Logout the machine from the Hub.
Token is deleted from the machine and removed from git credential.
Args:
token_name (`str`, *optional*):
Name of the access token to logout from. If `None`, will log out from all saved access tokens.
Raises:
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError):
If the access token name is not found.
huggingface-hub.merge_pull_request
Python Library Documentation: method merge_pull_request in module huggingface_hub.hf_api
merge_pull_request(repo_id: 'str', discussion_num: 'int', *, token: 'bool | str | None' = None, comment: 'str | None' = None, repo_type: 'str | None' = None) method of huggingface_hub.hf_api.HfApi instance
Merges a Pull Request.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
discussion_num (`int`):
The number of the Discussion or Pull Request . Must be a strictly positive integer.
comment (`str`, *optional*):
An optional comment to post with the status change.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`DiscussionStatusChange`]: the status change event
> [!TIP]
> Raises the following errors:
>
> - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
> if the HuggingFace API returned an error
> - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
> if some parameter value is invalid
> - [`~utils.RepositoryNotFoundError`]
> If the repository to download from cannot be found. This may be because it doesn't exist,
> or because it is set to `private` and you do not have access.
huggingface-hub.metadata_eval_result
Python Library Documentation: function metadata_eval_result in module huggingface_hub.repocard
metadata_eval_result(*, model_pretty_name: str, task_pretty_name: str, task_id: str, metrics_pretty_name: str, metrics_id: str, metrics_value: Any, dataset_pretty_name: str, dataset_id: str, metrics_config: str | None = None, metrics_verified: bool = False, dataset_config: str | None = None, dataset_split: str | None = None, dataset_revision: str | None = None, metrics_verification_token: str | None = None) -> dict
Creates a metadata dict with the result from a model evaluated on a dataset.
Args:
model_pretty_name (`str`):
The name of the model in natural language.
task_pretty_name (`str`):
The name of a task in natural language.
task_id (`str`):
Example: automatic-speech-recognition. A task id.
metrics_pretty_name (`str`):
A name for the metric in natural language. Example: Test WER.
metrics_id (`str`):
Example: wer. A metric id from https://hf.co/metrics.
metrics_value (`Any`):
The value from the metric. Example: 20.0 or "20.0 ± 1.2".
dataset_pretty_name (`str`):
The name of the dataset in natural language.
dataset_id (`str`):
Example: common_voice. A dataset id from https://hf.co/datasets.
metrics_config (`str`, *optional*):
The name of the metric configuration used in `load_metric()`.
Example: bleurt-large-512 in `load_metric("bleurt", "bleurt-large-512")`.
metrics_verified (`bool`, *optional*, defaults to `False`):
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.
dataset_config (`str`, *optional*):
Example: fr. The name of the dataset configuration used in `load_dataset()`.
dataset_split (`str`, *optional*):
Example: test. The name of the dataset split used in `load_dataset()`.
dataset_revision (`str`, *optional*):
Example: 5503434ddd753f426f4b38109466949a1217c2bb. The name of the dataset dataset revision
used in `load_dataset()`.
metrics_verification_token (`bool`, *optional*):
A JSON Web Token that is used to verify whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not.
Returns:
`dict`: a metadata dict with the result from a model evaluated on a dataset.
Example:
```python
>>> from huggingface_hub import metadata_eval_result
>>> results = metadata_eval_result(
... model_pretty_name="RoBERTa fine-tuned on ReactionGIF",
... task_pretty_name="Text Classification",
... task_id="text-classification",
... metrics_pretty_name="Accuracy",
... metrics_id="accuracy",
... metrics_value=0.2662102282047272,
... dataset_pretty_name="ReactionJPEG",
... dataset_id="julien-c/reactionjpeg",
... dataset_config="default",
... dataset_split="test",
... )
>>> results == {
... 'model-index': [
... {
... 'name': 'RoBERTa fine-tuned on ReactionGIF',
... 'results': [
... {
... 'task': {
... 'type': 'text-classification',
... 'name': 'Text Classification'
... },
... 'dataset': {
... 'name': 'ReactionJPEG',
... 'type': 'julien-c/reactionjpeg',
... 'config': 'default',
... 'split': 'test'
... },
... 'metrics': [
... {
... 'type': 'accuracy',
... 'value': 0.2662102282047272,
... 'name': 'Accuracy',
... 'verified': False
... }
... ]
... }
... ]
... }
... ]
... }
True
```
huggingface-hub.metadata_load
Python Library Documentation: function metadata_load in module huggingface_hub.repocard metadata_load(local_path: str | pathlib.Path) -> dict | None
huggingface-hub.metadata_save
Python Library Documentation: function metadata_save in module huggingface_hub.repocard
metadata_save(local_path: str | pathlib.Path, data: dict) -> None
Save the metadata dict in the upper YAML part Trying to preserve newlines as
in the existing file. Docs about open() with newline="" parameter:
https://docs.python.org/3/library/functions.html?highlight=open#open Does
not work with "^M" linebreaks, which are replaced by
huggingface-hub.metadata_update
Python Library Documentation: function metadata_update in module huggingface_hub.repocard
metadata_update(repo_id: str, metadata: dict, *, repo_type: str | None = None, overwrite: bool = False, token: str | None = None, commit_message: str | None = None, commit_description: str | None = None, revision: str | None = None, create_pr: bool = False, parent_commit: str | None = None) -> str
Updates the metadata in the README.md of a repository on the Hugging Face Hub.
If the README.md file doesn't exist yet, a new one is created with metadata and
the default ModelCard or DatasetCard template. For `space` repo, an error is thrown
as a Space cannot exist without a `README.md` file.
Args:
repo_id (`str`):
The name of the repository.
metadata (`dict`):
A dictionary containing the metadata to be updated.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if updating to a dataset or space,
`None` or `"model"` if updating to a model. Default is `None`.
overwrite (`bool`, *optional*, defaults to `False`):
If set to `True` an existing field can be overwritten, otherwise
attempting to overwrite an existing field will cause an error.
token (`str`, *optional*):
The Hugging Face authentication token.
commit_message (`str`, *optional*):
The summary / title / first line of the generated commit. Defaults to
`f"Update metadata with huggingface_hub"`
commit_description (`str` *optional*)
The description of the generated commit
revision (`str`, *optional*):
The git revision to commit from. Defaults to the head of the
`"main"` branch.
create_pr (`boolean`, *optional*):
Whether or not to create a Pull Request from `revision` with that commit.
Defaults to `False`.
parent_commit (`str`, *optional*):
The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
especially useful if the repo is updated / committed too concurrently.
Returns:
`str`: URL of the commit which updated the card metadata.
Example:
```python
>>> from huggingface_hub import metadata_update
>>> metadata = {'model-index': [{'name': 'RoBERTa fine-tuned on ReactionGIF',
... 'results': [{'dataset': {'name': 'ReactionGIF',
... 'type': 'julien-c/reactiongif'},
... 'metrics': [{'name': 'Recall',
... 'type': 'recall',
... 'value': 0.7762102282047272}],
... 'task': {'name': 'Text Classification',
... 'type': 'text-classification'}}]}]}
>>> url = metadata_update("hf-internal-testing/reactiongif-roberta-card", metadata)
```
huggingface-hub.model_info
Python Library Documentation: method model_info in module huggingface_hub.hf_api
model_info(repo_id: 'str', *, revision: 'str | None' = None, timeout: 'float | None' = None, securityStatus: 'bool | None' = None, files_metadata: 'bool' = False, expand: 'list[ExpandModelProperty_T] | None' = None, token: 'bool | str | None' = None) -> 'ModelInfo' method of huggingface_hub.hf_api.HfApi instance
Get info on one specific model on huggingface.co
Model can be private if you pass an acceptable token or are logged in.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
revision (`str`, *optional*):
The revision of the model repository from which to get the
information.
timeout (`float`, *optional*):
Whether to set a timeout for the request to the Hub.
securityStatus (`bool`, *optional*):
Whether to retrieve the security status from the model
repository as well. The security status will be returned in the `security_repo_status` field.
files_metadata (`bool`, *optional*):
Whether or not to retrieve metadata for files in the repository
(size, LFS metadata, etc). Defaults to `False`.
expand (`list[ExpandModelProperty_T]`, *optional*):
List properties to return in the response. When used, only the properties in the list will be returned.
This parameter cannot be used if `securityStatus` or `files_metadata` are passed.
Possible values are `"author"`, `"baseModels"`, `"cardData"`, `"childrenModelCount"`, `"config"`, `"createdAt"`, `"disabled"`, `"downloads"`, `"downloadsAllTime"`, `"evalResults"`, `"gated"`, `"gguf"`, `"inference"`, `"inferenceProviderMapping"`, `"lastModified"`, `"library_name"`, `"likes"`, `"mask_token"`, `"model-index"`, `"pipeline_tag"`, `"private"`, `"safetensors"`, `"sha"`, `"siblings"`, `"spaces"`, `"tags"`, `"transformersInfo"`, `"trendingScore"`, `"widgetData"`, `"usedStorage"`, and `"resourceGroup"`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`huggingface_hub.hf_api.ModelInfo`]: The model repository information.
> [!TIP]
> Raises the following errors:
>
> - [`~utils.RepositoryNotFoundError`]
> If the repository to download from cannot be found. This may be because it doesn't exist,
> or because it is set to `private` and you do not have access.
> - [`~utils.RevisionNotFoundError`]
> If the revision to download from cannot be found.
huggingface-hub.move_bucket
Python Library Documentation: method move_bucket in module huggingface_hub.hf_api
move_bucket(from_id: 'str', to_id: 'str', *, token: 'bool | str | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Move a bucket from "namespace1/repo_name1" to "namespace2/repo_name2"
Note there are certain limitations. For more information about moving
repositories, please see
https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo.
Args:
from_id (`str`):
A namespace (user or an organization) and a bucket name separated
by a `/`. Original bucket identifier (e.g. `"username/my-bucket"`).
to_id (`str`):
A namespace (user or an organization) and a bucket name separated
by a `/`. Final bucket identifier (e.g. `"username/new-bucket-name"`
or `"organization/my-bucket"`).
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Raises:
[`~errors.BucketNotFoundError`]:
If the source bucket cannot be found. This may be because it doesn't exist,
or because it is set to `private` and you do not have access.
Example:
```python
>>> from huggingface_hub import move_bucket
>>> # Rename a bucket within the same namespace
>>> move_bucket(from_id="username/old-name", to_id="username/new-name")
>>> # Transfer a bucket to an organization
>>> move_bucket(from_id="username/my-bucket", to_id="my-org/my-bucket")
```
huggingface-hub.move_repo
Python Library Documentation: method move_repo in module huggingface_hub.hf_api
move_repo(from_id: 'str', to_id: 'str', *, repo_type: 'str | None' = None, token: 'str | bool | None' = None) method of huggingface_hub.hf_api.HfApi instance
Moving a repository from namespace1/repo_name1 to namespace2/repo_name2
Note there are certain limitations. For more information about moving
repositories, please see
https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo.
Args:
from_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`. Original repository identifier.
to_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`. Final repository identifier.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
> [!TIP]
> Raises the following errors:
>
> - [`~utils.RepositoryNotFoundError`]
> If the repository to download from cannot be found. This may be because it doesn't exist,
> or because it is set to `private` and you do not have access.
huggingface-hub.notebook_login
Python Library Documentation: function notebook_login in module huggingface_hub._login
notebook_login(*, skip_if_logged_in: bool = True) -> None
Displays a prompt to log in to the HF website and store the token.
This is equivalent to [`login`] without passing a token when run in a notebook.
[`notebook_login`] is useful if you want to force the use of the notebook flow
instead of a prompt in the terminal.
For more details, see [`login`].
Args:
skip_if_logged_in (`bool`, defaults to `True`):
If `True`, do not prompt for token if user is already logged in.
Set to `False` to force re-login. In CLI, use `--force` instead.
huggingface-hub.paper_info
Python Library Documentation: method paper_info in module huggingface_hub.hf_api
paper_info(id: 'str') -> 'PaperInfo' method of huggingface_hub.hf_api.HfApi instance
Get information for a paper on the Hub.
Args:
id (`str`, **optional**):
ArXiv id of the paper.
Returns:
`PaperInfo`: A `PaperInfo` object.
Raises:
[`HfHubHTTPError`]:
HTTP 404 If the paper does not exist on the Hub.
huggingface-hub.parse_eval_result_entries
Python Library Documentation: function parse_eval_result_entries in module huggingface_hub._eval_results
parse_eval_result_entries(data: list[dict[str, typing.Any]]) -> list[huggingface_hub._eval_results.EvalResultEntry]
Parse a list of dicts into [`EvalResultEntry`] objects.
This parses the `.eval_results/*.yaml` format. For the legacy `model-index` format,
use [`model_index_to_eval_results`] instead.
Args:
data (`list[dict[str, Any]]`):
A list of dictionaries (e.g., parsed from YAML or API response).
Returns:
`list[EvalResultEntry]`: A list of evaluation result entry objects.
Example:
```python
>>> from huggingface_hub import parse_eval_result_entries
>>> data = [
... {"dataset": {"id": "cais/hle", "task_id": "default"}, "value": 20.90},
... {"dataset": {"id": "Idavidrein/gpqa", "task_id": "gpqa_diamond"}, "value": 0.412},
... ]
>>> entries = parse_eval_result_entries(data)
>>> entries[0].dataset_id
'cais/hle'
>>> entries[0].value
20.9
```
huggingface-hub.parse_hf_uri
Python Library Documentation: _lru_cache_wrapper in module huggingface_hub.utils._hf_uris
parse_hf_uri(uri: str, endpoint: str | None = None) -> huggingface_hub.utils._hf_uris.HfUri
Parse a Hugging Face Hub URI ('hf://...') or a Hugging Face web URL.
A HF URI is a URI-like string identifying a location on the Hugging Face Hub. The full grammar is:
```
hf://[<TYPE>/]<ID>[@<REVISION>][/<PATH>]
```
For convenience, Hugging Face **web URLs** (the ones you copy-paste from the website) are also
accepted and normalized to the canonical 'hf://' form, e.g.
'https://huggingface.co/datasets/my-org/my-dataset/blob/main/train.csv'. Only unambiguous URLs
(repository / bucket pages and file/folder viewer routes) are accepted; any other route is rejected.
See 'docs/source/en/package_reference/hf_uris.md' for the full specification.
Args:
uri (`str`):
The URI to parse. Must start with 'hf://', or be a Hugging Face URL (e.g. 'https://huggingface.co/...').
endpoint (`str`, *optional*):
A custom Hub endpoint (e.g. a self-hosted or proxied Hub like 'https://hub.my-company.com' or
'http://localhost:8080/hf'). When provided, web URLs on that endpoint are recognized in addition to
the default Hugging Face hosts. Has no effect on 'hf://' URIs.
Returns:
[`HfUri`]: the parsed URI.
Raises:
[`HfUriError`]:
If the URI is malformed (missing prefix, invalid type, missing id, unsupported URL route, etc.).
Examples:
```py
>>> from huggingface_hub.utils import parse_hf_uri
>>> parse_hf_uri("hf://my-org/my-model")
HfUri(type='model', id='my-org/my-model', revision=None, path_in_repo='')
>>> parse_hf_uri("hf://datasets/my-org/my-dataset@refs/pr/3/train.json")
HfUri(type='dataset', id='my-org/my-dataset', revision='refs/pr/3', path_in_repo='train.json')
>>> parse_hf_uri("https://huggingface.co/datasets/my-org/my-dataset/blob/main/train.csv")
HfUri(type='dataset', id='my-org/my-dataset', revision='main', path_in_repo='train.csv')
```
huggingface-hub.parse_huggingface_oauth
Python Library Documentation: function parse_huggingface_oauth in module huggingface_hub._oauth
parse_huggingface_oauth(request: 'fastapi.Request') -> huggingface_hub._oauth.OAuthInfo | None
Returns the information from a logged-in user as a [`OAuthInfo`] object.
For flexibility and future-proofing, this method is very lax in its parsing and does not raise errors.
Missing fields are set to `None` without a warning.
Return `None`, if the user is not logged in (no info in session cookie).
See [`attach_huggingface_oauth`] for an example on how to use this method.
huggingface-hub.parse_local_safetensors_file_metadata
Python Library Documentation: function parse_local_safetensors_file_metadata in module huggingface_hub.hf_api
parse_local_safetensors_file_metadata(path: 'str | Path') -> 'SafetensorsFileMetadata'
Parse metadata from a local safetensors file.
For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.
Args:
path (`str` or `Path`):
Path to the safetensors file.
Returns:
[`SafetensorsFileMetadata`]: information related to the safetensors file.
Raises:
[`SafetensorsParsingError`]:
If the safetensors file header couldn't be parsed correctly.
`FileNotFoundError`:
If the file does not exist.
Example:
```py
>>> metadata = parse_local_safetensors_file_metadata("path/to/model.safetensors")
>>> metadata
SafetensorsFileMetadata(
metadata={'format': 'pt'},
tensors={'layer.weight': TensorInfo(dtype='F32', shape=[512, 512], ...}, ...}
)
>>> metadata.parameter_count
{'F32': 262144}
```
huggingface-hub.parse_safetensors_file_metadata
Python Library Documentation: method parse_safetensors_file_metadata in module huggingface_hub.hf_api
parse_safetensors_file_metadata(repo_id: 'str', filename: 'str', *, repo_type: 'str | None' = None, revision: 'str | None' = None, token: 'bool | str | None' = None, timeout: 'float | None' = 10) -> 'SafetensorsFileMetadata' method of huggingface_hub.hf_api.HfApi instance
Parse metadata from a safetensors file on the Hub.
To parse metadata from all safetensors files in a repo at once, use [`get_safetensors_metadata`].
For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.
Args:
repo_id (`str`):
A user or an organization name and a repo name separated by a `/`.
filename (`str`):
The name of the file in the repo.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if the file is in a dataset or space, `None` or `"model"` if in a
model. Default is `None`.
revision (`str`, *optional*):
The git revision to fetch the file from. Can be a branch name, a tag, or a commit hash. Defaults to the
head of the `"main"` branch.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
timeout (`float`, *optional*, defaults to 10):
How many seconds to wait for the server to send data before giving up. Set to `None` to disable the
timeout (not recommended, as a stalled connection can hang the call indefinitely).
Returns:
[`SafetensorsFileMetadata`]: information related to a safetensors file.
Raises:
[`NotASafetensorsRepoError`]:
If the repo is not a safetensors repo i.e. doesn't have either a
`model.safetensors` or a `model.safetensors.index.json` file.
[`SafetensorsParsingError`]:
If a safetensors file header couldn't be parsed correctly.
huggingface-hub.pause_inference_endpoint
Python Library Documentation: method pause_inference_endpoint in module huggingface_hub.hf_api
pause_inference_endpoint(name: 'str', *, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'InferenceEndpoint' method of huggingface_hub.hf_api.HfApi instance
Pause an Inference Endpoint.
A paused Inference Endpoint will not be charged. It can be resumed at any time using [`resume_inference_endpoint`].
This is different than scaling the Inference Endpoint to zero with [`scale_to_zero_inference_endpoint`], which
would be automatically restarted when a request is made to it.
For convenience, you can also pause an Inference Endpoint using [`pause_inference_endpoint`].
Args:
name (`str`):
The name of the Inference Endpoint to pause.
namespace (`str`, *optional*):
The namespace in which the Inference Endpoint is located. Defaults to the current user.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`InferenceEndpoint`]: information about the paused Inference Endpoint.
huggingface-hub.pause_space
Python Library Documentation: method pause_space in module huggingface_hub.hf_api
pause_space(repo_id: 'str', *, token: 'bool | str | None' = None) -> 'SpaceRuntime' method of huggingface_hub.hf_api.HfApi instance
Pause your Space.
A paused Space stops executing until manually restarted by its owner. This is different from the sleeping
state in which free Spaces go after 48h of inactivity. Paused time is not billed to your account, no matter the
hardware you've selected. To restart your Space, use [`restart_space`] and go to your Space settings page.
For more details, please visit [the docs](https://huggingface.co/docs/hub/spaces-gpus#pause).
Args:
repo_id (`str`):
ID of the Space to pause. Example: `"Salesforce/BLIP2"`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`SpaceRuntime`]: Runtime information about your Space including `stage=PAUSED` and requested hardware.
Raises:
[`~utils.RepositoryNotFoundError`]:
If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you
are not authenticated.
[`~utils.HfHubHTTPError`]:
403 Forbidden: only the owner of a Space can pause it. If you want to manage a Space that you don't
own, either ask the owner by opening a Discussion or duplicate the Space.
[`~utils.BadRequestError`]:
If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide
a static Space, you can set it to private.
huggingface-hub.permanently_delete_lfs_files
Python Library Documentation: method permanently_delete_lfs_files in module huggingface_hub.hf_api
permanently_delete_lfs_files(repo_id: 'str', lfs_files: 'Iterable[LFSFileInfo]', *, rewrite_history: 'bool' = True, repo_type: 'str | None' = None, token: 'bool | str | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Permanently delete LFS files from a repo on the Hub.
> [!WARNING]
> This is a permanent action that will affect all commits referencing the deleted files and might corrupt your
> repository. This is a non-revertible operation. Use it only if you know what you are doing.
Args:
repo_id (`str`):
The repository for which you are listing LFS files.
lfs_files (`Iterable[LFSFileInfo]`):
An iterable of [`LFSFileInfo`] items to permanently delete from the repo. Use [`list_lfs_files`] to list
all LFS files from a repo.
rewrite_history (`bool`, *optional*, default to `True`):
Whether to rewrite repository history to remove file pointers referencing the deleted LFS files (recommended).
repo_type (`str`, *optional*):
Type of repository. Set to `"dataset"` or `"space"` if listing from a dataset or space, `None` or
`"model"` if listing from a model. Default is `None`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Example:
```py
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> lfs_files = api.list_lfs_files("username/my-cool-repo")
# Filter files files to delete based on a combination of `filename`, `pushed_at`, `ref` or `size`.
# e.g. select only LFS files in the "checkpoints" folder
>>> lfs_files_to_delete = (lfs_file for lfs_file in lfs_files if lfs_file.filename.startswith("checkpoints/"))
# Permanently delete LFS files
>>> api.permanently_delete_lfs_files("username/my-cool-repo", lfs_files_to_delete)
```
huggingface-hub.preupload_lfs_files
Python Library Documentation: method preupload_lfs_files in module huggingface_hub.hf_api
preupload_lfs_files(repo_id: 'str', additions: 'Iterable[CommitOperationAdd]', *, token: 'str | bool | None' = None, repo_type: 'str | None' = None, revision: 'str | None' = None, create_pr: 'bool | None' = None, num_threads: 'int' = 5, free_memory: 'bool' = True, gitignore_content: 'str | None' = None) method of huggingface_hub.hf_api.HfApi instance
Pre-upload LFS files to S3 in preparation on a future commit.
This method is useful if you are generating the files to upload on-the-fly and you don't want to store them
in memory before uploading them all at once.
> [!WARNING]
> This is a power-user method. You shouldn't need to call it directly to make a normal commit.
> Use [`create_commit`] directly instead.
> [!WARNING]
> Commit operations will be mutated during the process. In particular, the attached `path_or_fileobj` will be
> removed after the upload to save memory (and replaced by an empty `bytes` object). Do not reuse the same
> objects except to pass them to [`create_commit`]. If you don't want to remove the attached content from the
> commit operation object, pass `free_memory=False`.
Args:
repo_id (`str`):
The repository in which you will commit the files, for example: `"username/custom_transformers"`.
additions (`Iterable` of [`CommitOperationAdd`]):
The list of files to upload. Warning: the objects in this list will be mutated to include information
relative to the upload. Do not reuse the same objects for multiple commits.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
repo_type (`str`, *optional*):
The type of repository to upload to (e.g. `"model"` -default-, `"dataset"` or `"space"`).
revision (`str`, *optional*):
The git revision to commit from. Defaults to the head of the `"main"` branch.
create_pr (`boolean`, *optional*):
Whether or not you plan to create a Pull Request with that commit. Defaults to `False`.
num_threads (`int`, *optional*):
Number of concurrent threads for uploading files. Defaults to 5.
Setting it to 2 means at most 2 files will be uploaded concurrently.
free_memory (`bool`, *optional*, defaults to `True`):
If `True`, the `path_or_fileobj` attribute of each `CommitOperationAdd` is replaced by an empty
`bytes` object after upload to save memory. Set to `False` if you need to reuse the operation
objects outside of a subsequent [`create_commit`] call.
gitignore_content (`str`, *optional*):
The content of the `.gitignore` file to know which files should be ignored. The order of priority
is to first check if `gitignore_content` is passed, then check if the `.gitignore` file is present
in the list of files to commit and finally default to the `.gitignore` file already hosted on the Hub
(if any).
Example:
```py
>>> from huggingface_hub import CommitOperationAdd, preupload_lfs_files, create_commit, create_repo
>>> repo_id = create_repo("test_preupload").repo_id
# Generate and preupload LFS files one by one
>>> operations = [] # List of all `CommitOperationAdd` objects that will be generated
>>> for i in range(5):
... content = ... # generate binary content
... addition = CommitOperationAdd(path_in_repo=f"shard_{i}_of_5.bin", path_or_fileobj=content)
... preupload_lfs_files(repo_id, additions=[addition]) # upload + free memory
... operations.append(addition)
# Create commit
>>> create_commit(repo_id, operations=operations, commit_message="Commit all shards")
```
huggingface-hub.push_to_hub_fastai
Python Library Documentation: function push_to_hub_fastai in module huggingface_hub.fastai_utils
push_to_hub_fastai(learner, *, repo_id: str, commit_message: str = 'Push FastAI model using huggingface_hub.', private: bool | None = None, token: str | None = None, config: dict | None = None, branch: str | None = None, create_pr: bool | None = None, allow_patterns: list[str] | str | None = None, ignore_patterns: list[str] | str | None = None, delete_patterns: list[str] | str | None = None, api_endpoint: str | None = None)
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.
huggingface-hub.read_dduf_file
Python Library Documentation: function read_dduf_file in module huggingface_hub.serialization._dduf
read_dduf_file(dduf_path: os.PathLike | str) -> dict[str, huggingface_hub.serialization._dduf.DDUFEntry]
Read a DDUF file and return a dictionary of entries.
Only the metadata is read, the data is not loaded in memory.
Args:
dduf_path (`str` or `os.PathLike`):
The path to the DDUF file to read.
Returns:
`dict[str, DDUFEntry]`:
A dictionary of [`DDUFEntry`] indexed by filename.
Raises:
- [`DDUFCorruptedFileError`]: If the DDUF file is corrupted (i.e. doesn't follow the DDUF format).
Example:
```python
>>> import json
>>> import safetensors.torch
>>> from huggingface_hub import read_dduf_file
# Read DDUF metadata
>>> dduf_entries = read_dduf_file("FLUX.1-dev.dduf")
# Returns a mapping filename <> DDUFEntry
>>> dduf_entries["model_index.json"]
DDUFEntry(filename='model_index.json', offset=66, length=587)
# Load model index as JSON
>>> json.loads(dduf_entries["model_index.json"].read_text())
{'_class_name': 'FluxPipeline', '_diffusers_version': '0.32.0.dev0', '_name_or_path': 'black-forest-labs/FLUX.1-dev', ...
# Load VAE weights using safetensors
>>> with dduf_entries["vae/diffusion_pytorch_model.safetensors"].as_mmap() as mm:
... state_dict = safetensors.torch.load(mm)
```
huggingface-hub.read_paper
Python Library Documentation: method read_paper in module huggingface_hub.hf_api
read_paper(id: 'str') -> 'str' method of huggingface_hub.hf_api.HfApi instance
Get the markdown content of a paper page on the Hub.
Args:
id (`str`):
ArXiv id of the paper.
Returns:
`str`: The paper page content as markdown.
Raises:
[`HfHubHTTPError`]:
HTTP 404 If the paper does not exist on the Hub.
huggingface-hub.reject_access_request
Python Library Documentation: method reject_access_request in module huggingface_hub.hf_api
reject_access_request(repo_id: 'str', user: 'str', *, repo_type: 'str | None' = None, rejection_reason: 'str | None', token: 'bool | str | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Reject an access request from a user for a given gated repo.
A rejected request will go to the rejected list. The user cannot download any file of the repo. Rejected
requests can be accepted or cancelled at any time using [`accept_access_request`] and [`cancel_access_request`].
A cancelled request will go back to the pending list while an accepted request will go to the accepted list.
For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
Args:
repo_id (`str`):
The id of the repo to reject access request for.
user (`str`):
The username of the user which access request should be rejected.
repo_type (`str`, *optional*):
The type of the repo to reject access request for. Must be one of `model`, `dataset` or `space`.
Defaults to `model`.
rejection_reason (`str`, *optional*):
Optional rejection reason that will be visible to the user (max 200 characters).
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Raises:
[`HfHubHTTPError`]:
HTTP 400 if the repo is not gated.
[`HfHubHTTPError`]:
HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
or `admin` role in the organization the repo belongs to or if you passed a `read` token.
[`HfHubHTTPError`]:
HTTP 404 if the user does not exist on the Hub.
[`HfHubHTTPError`]:
HTTP 404 if the user access request cannot be found.
[`HfHubHTTPError`]:
HTTP 404 if the user access request is already in the rejected list.
huggingface-hub.rename_discussion
Python Library Documentation: method rename_discussion in module huggingface_hub.hf_api
rename_discussion(repo_id: 'str', discussion_num: 'int', new_title: 'str', *, token: 'bool | str | None' = None, repo_type: 'str | None' = None) -> 'DiscussionTitleChange' method of huggingface_hub.hf_api.HfApi instance
Renames a Discussion.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
discussion_num (`int`):
The number of the Discussion or Pull Request . Must be a strictly positive integer.
new_title (`str`):
The new title for the discussion
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`DiscussionTitleChange`]: the title change event
Examples:
```python
>>> new_title = "New title, fixing a typo"
>>> HfApi().rename_discussion(
... repo_id="username/repo_name",
... discussion_num=34
... new_title=new_title
... )
# DiscussionTitleChange(id='deadbeef0000000', type='title-change', ...)
```
> [!TIP]
> Raises the following errors:
>
> - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
> if the HuggingFace API returned an error
> - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
> if some parameter value is invalid
> - [`~utils.RepositoryNotFoundError`]
> If the repository to download from cannot be found. This may be because it doesn't exist,
> or because it is set to `private` and you do not have access.
huggingface-hub.repo_exists
Python Library Documentation: method repo_exists in module huggingface_hub.hf_api
repo_exists(repo_id: 'str', *, repo_type: 'str | None' = None, token: 'str | bool | None' = None) -> 'bool' method of huggingface_hub.hf_api.HfApi instance
Checks if a repository exists on the Hugging Face Hub.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
`None` or `"model"` if getting repository info from a model. Default is `None`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
True if the repository exists, False otherwise.
Examples:
```py
>>> from huggingface_hub import repo_exists
>>> repo_exists("google/gemma-7b")
True
>>> repo_exists("google/not-a-repo")
False
```
huggingface-hub.repo_info
Python Library Documentation: method repo_info in module huggingface_hub.hf_api
repo_info(repo_id: 'str', *, revision: 'str | None' = None, repo_type: 'str | None' = None, timeout: 'float | None' = None, files_metadata: 'bool' = False, expand: 'ExpandModelProperty_T | ExpandDatasetProperty_T | ExpandSpaceProperty_T | None' = None, token: 'bool | str | None' = None) -> 'ModelInfo | DatasetInfo | SpaceInfo | KernelInfo' method of huggingface_hub.hf_api.HfApi instance
Get the info object for a given repo of a given type.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
revision (`str`, *optional*):
The revision of the repository from which to get the
information.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
`None` or `"model"` if getting repository info from a model. Default is `None`.
timeout (`float`, *optional*):
Whether to set a timeout for the request to the Hub.
expand (`ExpandModelProperty_T` or `ExpandDatasetProperty_T` or `ExpandSpaceProperty_T`, *optional*):
List properties to return in the response. When used, only the properties in the list will be returned.
This parameter cannot be used if `files_metadata` is passed.
For an exhaustive list of available properties, check out [`model_info`], [`dataset_info`] or [`space_info`].
files_metadata (`bool`, *optional*):
Whether or not to retrieve metadata for files in the repository
(size, LFS metadata, etc). Defaults to `False`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`Union[SpaceInfo, DatasetInfo, ModelInfo]`: The repository information, as a
[`huggingface_hub.hf_api.DatasetInfo`], [`huggingface_hub.hf_api.ModelInfo`]
or [`huggingface_hub.hf_api.SpaceInfo`] object.
> [!TIP]
> Raises the following errors:
>
> - [`~utils.RepositoryNotFoundError`]
> If the repository to download from cannot be found. This may be because it doesn't exist,
> or because it is set to `private` and you do not have access.
> - [`~utils.RevisionNotFoundError`]
> If the revision to download from cannot be found.
huggingface-hub.repo_type_and_id_from_hf_id
Python Library Documentation: function repo_type_and_id_from_hf_id in module huggingface_hub.hf_api
repo_type_and_id_from_hf_id(hf_id: 'str', hub_url: 'str | None' = None) -> 'tuple[str | None, str | None, str]'
Returns the repo type and ID from a huggingface.co URL linking to a
repository
> [!WARNING]
> Deprecated: prefer [`parse_hf_uri`], which parses both `hf://` URIs and Hugging Face web URLs into a structured [`HfUri`].
> See https://huggingface.co/docs/huggingface_hub/package_reference/hf_uris for more details.
Args:
hf_id (`str`):
An URL or ID of a repository on the HF hub. Accepted values are:
- https://huggingface.co/<repo_type>/<namespace>/<repo_id>
- https://huggingface.co/<namespace>/<repo_id>
- hf://<repo_type>/<namespace>/<repo_id>
- hf://<namespace>/<repo_id>
- <repo_type>/<namespace>/<repo_id>
- <namespace>/<repo_id>
- <repo_id>
hub_url (`str`, *optional*):
The URL of the HuggingFace Hub, defaults to https://huggingface.co
Returns:
A tuple with three items: repo_type (`str` or `None`), namespace (`str` or
`None`) and repo_id (`str`).
Raises:
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If URL cannot be parsed.
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If `repo_type` is unknown.
huggingface-hub.request_space_hardware
Python Library Documentation: method request_space_hardware in module huggingface_hub.hf_api
request_space_hardware(repo_id: 'str', hardware: 'SpaceHardware', *, token: 'bool | str | None' = None, sleep_time: 'int | None' = None) -> 'SpaceRuntime' method of huggingface_hub.hf_api.HfApi instance
Request new hardware for a Space.
Args:
repo_id (`str`):
ID of the repo to update. Example: `"bigcode/in-the-stack"`.
hardware (`str` or [`SpaceHardware`]):
Hardware on which to run the Space. Example: `"t4-medium"`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
sleep_time (`int`, *optional*):
Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure
the sleep time (value is fixed to 48 hours of inactivity).
See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
Returns:
[`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
> [!TIP]
> It is also possible to request hardware directly when creating the Space repo! See [`create_repo`] for details.
huggingface-hub.request_space_storage
Python Library Documentation: method request_space_storage in module huggingface_hub.hf_api
request_space_storage(repo_id: 'str', storage: 'SpaceStorage', *, token: 'bool | str | None' = None) -> 'SpaceRuntime' method of huggingface_hub.hf_api.HfApi instance
Request persistent storage for a Space.
> [!WARNING]
> `request_space_storage` is deprecated and will be removed in version 2.0. Use [`set_space_volumes`] instead.
Args:
repo_id (`str`):
ID of the Space to update. Example: `"open-llm-leaderboard/open_llm_leaderboard"`.
storage (`str` or [`SpaceStorage`]):
Storage tier. Either 'small', 'medium', or 'large'.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
huggingface-hub.resolve_revision
Python Library Documentation: method resolve_revision in module huggingface_hub.hf_api
resolve_revision(repo_id: 'str', *, repo_type: 'str | None' = None, revision: 'str | None' = None, cache_dir: 'str | Path | None' = None, local_files_only: 'bool' = False, token: 'bool | str | None' = None) -> 'ResolvedRevision' method of huggingface_hub.hf_api.HfApi instance
Resolve a revision (branch, tag, PR ref) to a commit hash.
This is meant for libraries that download and load several components of a repo separately (config,
weights, tokenizer, ...). Resolving the revision once and passing the returned [`ResolvedRevision`] around
guarantees that every subsequent call targets the exact same commit, even if the repo is updated in the
meantime. It also saves HTTP calls, as downloads made with a commit hash can be served from the local
cache without contacting the Hub.
The `revision` -> `commit hash` mapping is cached on disk (in the `refs/` folder of the cache), on a
best-effort basis. If the Hub cannot be reached later on (offline mode, connection error, timeout, Hub
downtime, ...), the cached value is used as a fallback.
> [!TIP]
> If you only need to download a full repo snapshot, a single [`snapshot_download`] call is enough and
> already does the right thing. `resolve_revision` is only useful when downloading files separately.
Args:
repo_id (`str`):
A user or an organization name and a repo name separated by a `/`.
repo_type (`str`, *optional*):
Set to `"dataset"`, `"space"` or `"kernel"` if the repo is a dataset, space or kernel repo,
`None` or `"model"` if it is a model. Default is `None`.
revision (`str`, *optional*):
The revision to resolve. Can be a branch name, a tag, a PR ref or a commit hash. Defaults to the
default branch. If a [`ResolvedRevision`] is passed, it is returned as is.
cache_dir (`str`, `Path`, *optional*):
Path to the folder where cached files are stored. Defaults to the value of `HF_HUB_CACHE`.
local_files_only (`bool`, *optional*, defaults to `False`):
If `True`, resolve the revision from the local cache only, without contacting the Hub.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved token, which is the recommended
method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`ResolvedRevision`]: A `str` subclass holding both the requested revision and the commit hash it resolves to.
Raises:
[`~errors.RevisionResolutionError`]
If the revision cannot be resolved: the Hub could not be reached and nothing is cached locally.
[`~errors.RevisionNotFoundError`]
If the revision does not exist on the Hub.
[`~errors.RepositoryNotFoundError`]
If the repository cannot be found. This may be because it doesn't exist, or because it is set to
`private` and you do not have access.
Example:
```py
>>> from huggingface_hub import hf_hub_download, resolve_revision
>>> revision = resolve_revision("openai-community/gpt2")
>>> revision
ResolvedRevision(initial=None, resolved='607a30d783dfa663caf39e06633721c8d4cfcd7e')
# Pass it around: every download is pinned to the same commit
>>> config = hf_hub_download("openai-community/gpt2", "config.json", revision=revision)
>>> weights = hf_hub_download("openai-community/gpt2", "model.safetensors", revision=revision)
```
huggingface-hub.restart_space
Python Library Documentation: method restart_space in module huggingface_hub.hf_api
restart_space(repo_id: 'str', *, token: 'bool | str | None' = None, factory_reboot: 'bool' = False) -> 'SpaceRuntime' method of huggingface_hub.hf_api.HfApi instance
Restart your Space.
This is the only way to programmatically restart a Space if you've put it on Pause (see [`pause_space`]). You
must be the owner of the Space to restart it. If you are using an upgraded hardware, your account will be
billed as soon as the Space is restarted. You can trigger a restart no matter the current state of a Space.
For more details, please visit [the docs](https://huggingface.co/docs/hub/spaces-gpus#pause).
Args:
repo_id (`str`):
ID of the Space to restart. Example: `"Salesforce/BLIP2"`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
factory_reboot (`bool`, *optional*):
If `True`, the Space will be rebuilt from scratch without caching any requirements.
Returns:
[`SpaceRuntime`]: Runtime information about your Space.
Raises:
[`~utils.RepositoryNotFoundError`]:
If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you
are not authenticated.
[`~utils.HfHubHTTPError`]:
403 Forbidden: only the owner of a Space can restart it. If you want to restart a Space that you don't
own, either ask the owner by opening a Discussion or duplicate the Space.
[`~utils.BadRequestError`]:
If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide
a static Space, you can set it to private.
huggingface-hub.resume_inference_endpoint
Python Library Documentation: method resume_inference_endpoint in module huggingface_hub.hf_api
resume_inference_endpoint(name: 'str', *, namespace: 'str | None' = None, running_ok: 'bool' = True, token: 'bool | str | None' = None) -> 'InferenceEndpoint' method of huggingface_hub.hf_api.HfApi instance
Resume an Inference Endpoint.
For convenience, you can also resume an Inference Endpoint using [`InferenceEndpoint.resume`].
Args:
name (`str`):
The name of the Inference Endpoint to resume.
namespace (`str`, *optional*):
The namespace in which the Inference Endpoint is located. Defaults to the current user.
running_ok (`bool`, *optional*):
If `True`, the method will not raise an error if the Inference Endpoint is already running. Defaults to
`True`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`InferenceEndpoint`]: information about the resumed Inference Endpoint.
huggingface-hub.resume_scheduled_job
Python Library Documentation: method resume_scheduled_job in module huggingface_hub.hf_api
resume_scheduled_job(*, scheduled_job_id: 'str', namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Resume (unpause) a scheduled compute Job on Hugging Face infrastructure.
Args:
scheduled_job_id (`str`):
ID of the scheduled Job.
namespace (`str`, *optional*):
The namespace where the scheduled Job is. Defaults to the current user's namespace.
token `(Union[bool, str, None]`, *optional*):
A valid user access token. If not provided, the locally saved token will be used, which is the
recommended authentication method. Set to `False` to disable authentication.
Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
huggingface-hub.revision_exists
Python Library Documentation: method revision_exists in module huggingface_hub.hf_api
revision_exists(repo_id: 'str', revision: 'str', *, repo_type: 'str | None' = None, token: 'str | bool | None' = None) -> 'bool' method of huggingface_hub.hf_api.HfApi instance
Checks if a specific revision exists on a repo on the Hugging Face Hub.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
revision (`str`):
The revision of the repository to check.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
`None` or `"model"` if getting repository info from a model. Default is `None`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
True if the repository and the revision exists, False otherwise.
Examples:
```py
>>> from huggingface_hub import revision_exists
>>> revision_exists("google/gemma-7b", "float16")
True
>>> revision_exists("google/gemma-7b", "not-a-revision")
False
```
huggingface-hub.run_as_future
Python Library Documentation: method run_as_future in module huggingface_hub.hf_api
run_as_future(fn: 'Callable[..., R]', *args, **kwargs) -> 'Future[R]' method of huggingface_hub.hf_api.HfApi instance
Run a method in the background and return a Future instance.
The main goal is to run methods without blocking the main thread (e.g. to push data during a training).
Background jobs are queued to preserve order but are not ran in parallel. If you need to speed-up your scripts
by parallelizing lots of call to the API, you must setup and use your own [ThreadPoolExecutor](https://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor).
Note: Most-used methods like [`upload_file`], [`upload_folder`] and [`create_commit`] have a `run_as_future: bool`
argument to directly call them in the background. This is equivalent to calling `api.run_as_future(...)` on them
but less verbose.
Args:
fn (`Callable`):
The method to run in the background.
*args, **kwargs:
Arguments with which the method will be called.
Return:
`Future`: a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects) instance to
get the result of the task.
Example:
```py
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> future = api.run_as_future(api.whoami) # instant
>>> future.done()
False
>>> future.result() # wait until complete and return result
(...)
>>> future.done()
True
```
huggingface-hub.run_job
Python Library Documentation: method run_job in module huggingface_hub.hf_api
run_job(*, image: 'str', command: 'list[str]', env: 'dict[str, Any] | None' = None, secrets: 'dict[str, Any] | None' = None, flavor: 'JobHardware | str | None' = None, timeout: 'int | float | str | None' = None, name: 'str | None' = None, labels: 'dict[str, str] | None' = None, volumes: 'list[Volume] | None' = None, expose: 'list[int] | None' = None, ssh: 'bool' = False, resource_group_id: 'str | None' = None, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'JobInfo' method of huggingface_hub.hf_api.HfApi instance
Run compute Jobs on Hugging Face infrastructure.
Args:
image (`str`):
The Docker image to use.
Examples: `"ubuntu"`, `"python:3.12"`, `"pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"`.
Example with an image from a Space: `"hf.co/spaces/lhoestq/duckdb"`.
command (`list[str]`):
The command to run. Example: `["echo", "hello"]`.
env (`dict[str, Any]`, *optional*):
Defines the environment variables for the Job.
secrets (`dict[str, Any]`, *optional*):
Defines the secret environment variables for the Job.
flavor (`str`, *optional*):
Flavor for the hardware. See [`JobHardware`] for possible values.
Defaults to `"cpu-basic"`.
timeout (`Union[int, float, str]`, *optional*):
Max duration for the Job: int with s (seconds, default), m (minutes), h (hours) or d (days).
Example: `300` or `"5m"` for 5 minutes.
name (`str`, *optional*):
A name for the Job. Stored as the `name` label. Cannot be passed together with a `name` key in
`labels`. Names do not have to be unique. Defaults to a name derived from image and command (with a short hash suffix).
labels (`dict[str, str]`, *optional*):
Labels to attach to the job (key-value pairs).
volumes (`list[Volume]`, *optional*):
Hugging Face Buckets or Repos to mount as volumes in the job container.
Each volume is a [`Volume`] with `type` (`"bucket"`, `"model"`, `"dataset"`, or `"space"`),
`source` (e.g. `"username/my-bucket"`), and `mount_path` (e.g. `"/data"`).
expose (`list[int]`, *optional*):
Container ports to expose through the jobs proxy. Each listed port is reachable
on the public jobs domain (e.g. `https://<job_id>--8000.hf.jobs`). Access always
requires an HF token with read access to the job's namespace.
ssh (`bool`, *optional*):
If True, the job's container is reachable over SSH at the URL given by `job.status.ssh_url`
(e.g. `ssh <job_id>@ssh.hf.jobs`, or `hf jobs ssh <job_id>` from the CLI). Connecting requires
write access to the job's namespace and an SSH public key registered on the Hub
(https://huggingface.co/settings/keys). Defaults to False.
resource_group_id (`str`, *optional*):
The ID of the resource group to create the Job in. Used to control access to resources within an
organization and for cost attribution/spending-limit features. If not provided, the Job is created
outside of any resource group.
namespace (`str`, *optional*):
The namespace where the Job will be created. Defaults to the current user's namespace.
token `(Union[bool, str, None]`, *optional*):
A valid user access token. If not provided, the locally saved token will be used, which is the
recommended authentication method. Set to `False` to disable authentication.
Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
Example:
Run your first Job:
```python
>>> from huggingface_hub import run_job
>>> run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"])
```
Run a GPU Job:
```python
>>> from huggingface_hub import run_job
>>> image = "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"
>>> command = ["python", "-c", "import torch; print(f"This code ran with the following GPU: {torch.cuda.get_device_name()}")"]
>>> run_job(image=image, command=command, flavor="a10g-small")
```
Run a Job with volumes:
```python
>>> from huggingface_hub import Volume, run_job
>>> dataset_volume = Volume(type="dataset", source="HuggingFaceFW/fineweb", mount_path="/data")
>>> output_bucket_volume = Volume(type="bucket", source="username/my-bucket", mount_path="/output")
>>> image = "duckdb/duckdb"
>>> command = ["duckdb", "-c", "COPY (SELECT * FROM '/data/**/*.parquet' LIMIT 5) TO '/output/first-rows.parquet'"]
>>> run_job(image=image, command=command, volumes=[dataset_volume, output_bucket_volume])
```
huggingface-hub.run_uv_job
Python Library Documentation: method run_uv_job in module huggingface_hub.hf_api
run_uv_job(script: 'str', *, script_args: 'list[str] | None' = None, dependencies: 'list[str] | None' = None, python: 'str | None' = None, image: 'str | None' = None, env: 'dict[str, Any] | None' = None, secrets: 'dict[str, Any] | None' = None, flavor: 'JobHardware | str | None' = None, timeout: 'int | float | str | None' = None, name: 'str | None' = None, labels: 'dict[str, str] | None' = None, volumes: 'list[Volume] | None' = None, expose: 'list[int] | None' = None, ssh: 'bool' = False, resource_group_id: 'str | None' = None, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'JobInfo' method of huggingface_hub.hf_api.HfApi instance
Run a UV script Job on Hugging Face infrastructure.
Args:
script (`str`):
Path or URL of the UV script, or a command.
script_args (`list[str]`, *optional*)
Arguments to pass to the script or command.
dependencies (`list[str]`, *optional*)
Dependencies to use to run the UV script.
python (`str`, *optional*)
Use a specific Python version. Default is 3.12.
image (`str`, *optional*, defaults to "ghcr.io/astral-sh/uv:python3.12-bookworm"):
Use a custom Docker image with `uv` installed.
env (`dict[str, Any]`, *optional*):
Defines the environment variables for the Job.
secrets (`dict[str, Any]`, *optional*):
Defines the secret environment variables for the Job.
flavor (`str`, *optional*):
Flavor for the hardware. See [`JobHardware`] for possible values.
Defaults to `"cpu-basic"`.
timeout (`Union[int, float, str]`, *optional*):
Max duration for the Job: int with s (seconds, default), m (minutes), h (hours) or d (days).
Example: `300` or `"5m"` for 5 minutes.
name (`str`, *optional*):
A name for the Job. Stored as the `name` label. Cannot be passed together with a `name` key in
`labels`. Names do not have to be unique. Defaults to a name derived from script and its arguments (with a short hash suffix).
labels (`dict[str, str]`, *optional*):
Labels to attach to the job (key-value pairs).
volumes (`list[Volume]`, *optional*):
Hugging Face Buckets or Repos to mount as volumes in the job container.
Each volume is a [`Volume`] with `type` (`"bucket"`, `"model"`, `"dataset"`, or `"space"`),
`source` (e.g. `"username/my-bucket"`), and `mount_path` (e.g. `"/data"`).
expose (`list[int]`, *optional*):
Container ports to expose through the jobs proxy. Each listed port is reachable
on the public jobs domain (e.g. `https://<job_id>--8000.hf.jobs`). Access always
requires an HF token with read access to the job's namespace.
ssh (`bool`, *optional*):
If True, the job's container is reachable over SSH at the URL given by `job.status.ssh_url`
(e.g. `ssh <job_id>@ssh.hf.jobs`, or `hf jobs ssh <job_id>` from the CLI). Connecting requires
write access to the job's namespace and an SSH public key registered on the Hub
(https://huggingface.co/settings/keys). Defaults to False.
resource_group_id (`str`, *optional*):
The ID of the resource group to create the Job in. Used to control access to resources within an
organization and for cost attribution/spending-limit features. If not provided, the Job is created
outside of any resource group.
namespace (`str`, *optional*):
The namespace where the Job will be created. Defaults to the current user's namespace.
token `(Union[bool, str, None]`, *optional*):
A valid user access token. If not provided, the locally saved token will be used, which is the
recommended authentication method. Set to `False` to disable authentication.
Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
Example:
Run a script from a URL:
```python
>>> from huggingface_hub import run_uv_job
>>> script = "https://raw.githubusercontent.com/huggingface/trl/refs/heads/main/trl/scripts/sft.py"
>>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
>>> run_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small")
```
Run a local script:
```python
>>> from huggingface_hub import run_uv_job
>>> script = "my_sft.py"
>>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
>>> run_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small")
```
Run a command:
```python
>>> from huggingface_hub import run_uv_job
>>> script = "lighteval"
>>> script_args= ["endpoint", "inference-providers", "model_name=openai/gpt-oss-20b,provider=auto", "lighteval|gsm8k|0|0"]
>>> run_uv_job(script, script_args=script_args, dependencies=["lighteval"], flavor="a10g-small")
```
Mount volumes, e.g. to save model checkpoints during training:
```python
>>> from huggingface_hub import Volume, run_uv_job
>>> script = "my_sft.py"
>>> script_args = ["--output_dir", "/training-outputs/training-v3-final", ...]
>>> checkpoints_bucket = Volume(type="bucket", source="username/my-bucket", mount_path="/training-outputs")
>>> run_uv_job(script, script_args=script_args, volumes=[checkpoints_bucket])
```
huggingface-hub.save_torch_model
Python Library Documentation: function save_torch_model in module huggingface_hub.serialization._torch
save_torch_model(model: 'torch.nn.Module', save_directory: str | pathlib.Path, *, filename_pattern: str | None = None, force_contiguous: bool = True, max_shard_size: int | str = '5GB', metadata: dict[str, str] | None = None, safe_serialization: bool = True, is_main_process: bool = True, shared_tensors_to_discard: list[str] | None = None)
Saves a given torch model to disk, handling sharding and shared tensors issues.
See also [`save_torch_state_dict`] to save a state dict with more flexibility.
For more information about tensor sharing, check out [this guide](https://huggingface.co/docs/safetensors/torch_shared_tensors).
The model state dictionary is split into shards so that each shard is smaller than a given size. The shards are
saved in the `save_directory` with the given `filename_pattern`. If the model is too big to fit in a single shard,
an index file is saved in the `save_directory` to indicate where each tensor is saved. This helper uses
[`split_torch_state_dict_into_shards`] under the hood. If `safe_serialization` is `True`, the shards are saved as
safetensors (the default). Otherwise, the shards are saved as pickle.
Before saving the model, the `save_directory` is cleaned from any previous shard files.
> [!WARNING]
> If one of the model's tensor is bigger than `max_shard_size`, it will end up in its own shard which will have a
> size greater than `max_shard_size`.
> [!WARNING]
> If your model is a `transformers.PreTrainedModel`, you should pass `model._tied_weights_keys` as `shared_tensors_to_discard` to properly handle shared tensors saving. This ensures the correct duplicate tensors are discarded during saving.
Args:
model (`torch.nn.Module`):
The model to save on disk.
save_directory (`str` or `Path`):
The directory in which the model will be saved.
filename_pattern (`str`, *optional*):
The pattern to generate the files names in which the model will be saved. Pattern must be a string that
can be formatted with `filename_pattern.format(suffix=...)` and must contain the keyword `suffix`
Defaults to `"model{suffix}.safetensors"` or `pytorch_model{suffix}.bin` depending on `safe_serialization`
parameter.
force_contiguous (`boolean`, *optional*):
Forcing the state_dict to be saved as contiguous tensors. This has no effect on the correctness of the
model, but it could potentially change performance if the layout of the tensor was chosen specifically for
that reason. Defaults to `True`.
max_shard_size (`int` or `str`, *optional*):
The maximum size of each shard, in bytes. Defaults to 5GB.
metadata (`dict[str, str]`, *optional*):
Extra information to save along with the model. Some metadata will be added for each dropped tensors.
This information will not be enough to recover the entire shared structure but might help understanding
things.
safe_serialization (`bool`, *optional*):
Whether to save as safetensors, which is the default behavior. If `False`, the shards are saved as pickle.
Safe serialization is recommended for security reasons. Saving as pickle is deprecated and will be removed
in a future version.
is_main_process (`bool`, *optional*):
Whether the process calling this is the main process or not. Useful when in distributed training like
TPUs and need to call this function from all processes. In this case, set `is_main_process=True` only on
the main process to avoid race conditions. Defaults to True.
shared_tensors_to_discard (`list[str]`, *optional*):
List of tensor names to drop when saving shared tensors. If not provided and shared tensors are
detected, it will drop the first name alphabetically.
Example:
```py
>>> from huggingface_hub import save_torch_model
>>> model = ... # A PyTorch model
# Save state dict to "path/to/folder". The model will be split into shards of 5GB each and saved as safetensors.
>>> save_torch_model(model, "path/to/folder")
# Load model back
>>> from huggingface_hub import load_torch_model # TODO
>>> load_torch_model(model, "path/to/folder")
>>>
```
huggingface-hub.save_torch_state_dict
Python Library Documentation: function save_torch_state_dict in module huggingface_hub.serialization._torch
save_torch_state_dict(state_dict: dict[str, 'torch.Tensor'], save_directory: str | pathlib.Path, *, filename_pattern: str | None = None, force_contiguous: bool = True, max_shard_size: int | str = '5GB', metadata: dict[str, str] | None = None, safe_serialization: bool = True, is_main_process: bool = True, shared_tensors_to_discard: list[str] | None = None) -> None
Save a model state dictionary to the disk, handling sharding and shared tensors issues.
See also [`save_torch_model`] to directly save a PyTorch model.
For more information about tensor sharing, check out [this guide](https://huggingface.co/docs/safetensors/torch_shared_tensors).
The model state dictionary is split into shards so that each shard is smaller than a given size. The shards are
saved in the `save_directory` with the given `filename_pattern`. If the model is too big to fit in a single shard,
an index file is saved in the `save_directory` to indicate where each tensor is saved. This helper uses
[`split_torch_state_dict_into_shards`] under the hood. If `safe_serialization` is `True`, the shards are saved as
safetensors (the default). Otherwise, the shards are saved as pickle.
Before saving the model, the `save_directory` is cleaned from any previous shard files.
> [!WARNING]
> If one of the model's tensor is bigger than `max_shard_size`, it will end up in its own shard which will have a
> size greater than `max_shard_size`.
> [!WARNING]
> If your model is a `transformers.PreTrainedModel`, you should pass `model._tied_weights_keys` as `shared_tensors_to_discard` to properly handle shared tensors saving. This ensures the correct duplicate tensors are discarded during saving.
Args:
state_dict (`dict[str, torch.Tensor]`):
The state dictionary to save.
save_directory (`str` or `Path`):
The directory in which the model will be saved.
filename_pattern (`str`, *optional*):
The pattern to generate the files names in which the model will be saved. Pattern must be a string that
can be formatted with `filename_pattern.format(suffix=...)` and must contain the keyword `suffix`
Defaults to `"model{suffix}.safetensors"` or `pytorch_model{suffix}.bin` depending on `safe_serialization`
parameter.
force_contiguous (`boolean`, *optional*):
Forcing the state_dict to be saved as contiguous tensors. This has no effect on the correctness of the
model, but it could potentially change performance if the layout of the tensor was chosen specifically for
that reason. Defaults to `True`.
max_shard_size (`int` or `str`, *optional*):
The maximum size of each shard, in bytes. Defaults to 5GB.
metadata (`dict[str, str]`, *optional*):
Extra information to save along with the model. Some metadata will be added for each dropped tensors.
This information will not be enough to recover the entire shared structure but might help understanding
things.
safe_serialization (`bool`, *optional*):
Whether to save as safetensors, which is the default behavior. If `False`, the shards are saved as pickle.
Safe serialization is recommended for security reasons. Saving as pickle is deprecated and will be removed
in a future version.
is_main_process (`bool`, *optional*):
Whether the process calling this is the main process or not. Useful when in distributed training like
TPUs and need to call this function from all processes. In this case, set `is_main_process=True` only on
the main process to avoid race conditions. Defaults to True.
shared_tensors_to_discard (`list[str]`, *optional*):
List of tensor names to drop when saving shared tensors. If not provided and shared tensors are
detected, it will drop the first name alphabetically.
Example:
```py
>>> from huggingface_hub import save_torch_state_dict
>>> model = ... # A PyTorch model
# Save state dict to "path/to/folder". The model will be split into shards of 5GB each and saved as safetensors.
>>> state_dict = model_to_save.state_dict()
>>> save_torch_state_dict(state_dict, "path/to/folder")
```
huggingface-hub.scale_to_zero_inference_endpoint
Python Library Documentation: method scale_to_zero_inference_endpoint in module huggingface_hub.hf_api
scale_to_zero_inference_endpoint(name: 'str', *, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'InferenceEndpoint' method of huggingface_hub.hf_api.HfApi instance
Scale Inference Endpoint to zero.
An Inference Endpoint scaled to zero will not be charged. It will be resume on the next request to it, with a
cold start delay. This is different than pausing the Inference Endpoint with [`pause_inference_endpoint`], which
would require a manual resume with [`resume_inference_endpoint`].
For convenience, you can also scale an Inference Endpoint to zero using [`InferenceEndpoint.scale_to_zero`].
Args:
name (`str`):
The name of the Inference Endpoint to scale to zero.
namespace (`str`, *optional*):
The namespace in which the Inference Endpoint is located. Defaults to the current user.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`InferenceEndpoint`]: information about the scaled-to-zero Inference Endpoint.
huggingface-hub.scan_cache_dir
Python Library Documentation: function scan_cache_dir in module huggingface_hub.utils._cache_manager
scan_cache_dir(cache_dir: str | pathlib.Path | None = None) -> huggingface_hub.utils._cache_manager.HFCacheInfo
Scan the entire HF cache-system and return a [`~HFCacheInfo`] structure.
Use `scan_cache_dir` in order to programmatically scan your cache-system. The cache
will be scanned repo by repo. If a repo is corrupted, a [`~CorruptedCacheException`]
will be thrown internally but captured and returned in the [`~HFCacheInfo`]
structure. Only valid repos get a proper report.
```py
>>> from huggingface_hub import scan_cache_dir
>>> hf_cache_info = scan_cache_dir()
HFCacheInfo(
size_on_disk=3398085269,
repos=frozenset({
CachedRepoInfo(
repo_id='t5-small',
repo_type='model',
repo_path=PosixPath(...),
size_on_disk=970726914,
nb_files=11,
revisions=frozenset({
CachedRevisionInfo(
commit_hash='d78aea13fa7ecd06c29e3e46195d6341255065d5',
size_on_disk=970726339,
snapshot_path=PosixPath(...),
files=frozenset({
CachedFileInfo(
file_name='config.json',
size_on_disk=1197
file_path=PosixPath(...),
blob_path=PosixPath(...),
),
CachedFileInfo(...),
...
}),
),
CachedRevisionInfo(...),
...
}),
),
CachedRepoInfo(...),
...
}),
warnings=[
CorruptedCacheException("Snapshots dir doesn't exist in cached repo: ..."),
CorruptedCacheException(...),
...
],
)
```
You can also print a detailed report directly from the `hf` command line using:
```text
> hf cache ls
ID SIZE LAST_ACCESSED LAST_MODIFIED REFS
--------------------------- -------- ------------- ------------- -----------
dataset/nyu-mll/glue 157.4M 2 days ago 2 days ago main script
model/LiquidAI/LFM2-VL-1.6B 3.2G 4 days ago 4 days ago main
model/microsoft/UserLM-8b 32.1G 4 days ago 4 days ago main
Done in 0.0s. Scanned 6 repo(s) for a total of 3.4G.
Got 1 warning(s) while scanning. Use -vvv to print details.
```
Args:
cache_dir (`str` or `Path`, `optional`):
Cache directory to cache. Defaults to the default HF cache directory.
> [!WARNING]
> Raises:
>
> `CacheNotFound`
> If the cache directory does not exist.
>
> [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
> If the cache directory is a file, instead of a directory.
Returns: a [`~HFCacheInfo`] object.
huggingface-hub.search_spaces
Python Library Documentation: method search_spaces in module huggingface_hub.hf_api
search_spaces(query: 'str', *, filter: 'str | Iterable[str] | None' = None, sdk: 'str | list[str] | None' = None, include_non_running: 'bool' = False, token: 'bool | str | None' = None) -> 'Iterable[SpaceSearchResult]' method of huggingface_hub.hf_api.HfApi instance
Search Spaces on the Hub using semantic search.
This endpoint uses semantic search (embedding-based) for multi-word queries
and full-text search for single-word queries.
Args:
query (`str`):
The search query string.
filter (`str` or `Iterable[str]`, *optional*):
A string tag or list of tags to filter by.
sdk (`str` or `list[str]`, *optional*):
Filter by SDK (e.g. `"gradio"`, `"docker"`, `"static"`).
include_non_running (`bool`, *optional*):
Whether to include non-running Spaces in results. Defaults to `False`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
`Iterable[SpaceSearchResult]`: an iterable of [`SpaceSearchResult`] objects.
Example:
```python
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> results = list(api.search_spaces("generate image"))
>>> results[0].id
'mrfakename/Z-Image-Turbo'
>>> results[0].ai_category
'Image Generation'
```
huggingface-hub.set_async_client_factory
Python Library Documentation: function set_async_client_factory in module huggingface_hub.utils._http
set_async_client_factory(async_client_factory: collections.abc.Callable[[], httpx.AsyncClient]) -> None
Set the HTTP async client factory to be used by `huggingface_hub`.
The async client factory is a method that returns a `httpx.AsyncClient` object.
This can be useful if you are running your scripts in a specific environment requiring custom configuration (e.g. custom proxy or certifications).
Use [`get_async_client`] to get a correctly configured `httpx.AsyncClient`.
> [!WARNING]
> Contrary to the `httpx.Client` that is shared between all calls made by `huggingface_hub`, the `httpx.AsyncClient` is not shared.
> It is recommended to use an async context manager to ensure the client is properly closed when the context is exited.
huggingface-hub.set_client_factory
Python Library Documentation: function set_client_factory in module huggingface_hub.utils._http
set_client_factory(client_factory: collections.abc.Callable[[], httpx.Client]) -> None
Set the HTTP client factory to be used by `huggingface_hub`.
The client factory is a method that returns a `httpx.Client` object. On the first call to [`get_session`] the client factory
will be used to create a new `httpx.Client` object that will be shared between all calls made by `huggingface_hub`.
This can be useful if you are running your scripts in a specific environment requiring custom configuration (e.g. custom proxy or certifications).
Use [`get_session`] to get a correctly configured `httpx.Client`.
huggingface-hub.set_space_sleep_time
Python Library Documentation: method set_space_sleep_time in module huggingface_hub.hf_api
set_space_sleep_time(repo_id: 'str', sleep_time: 'int', *, token: 'bool | str | None' = None) -> 'SpaceRuntime' method of huggingface_hub.hf_api.HfApi instance
Set a custom sleep time for a Space running on upgraded hardware..
Your Space will go to sleep after X seconds of inactivity. You are not billed when your Space is in "sleep"
mode. If a new visitor lands on your Space, it will "wake it up". Only upgraded hardware can have a
configurable sleep time. To know more about the sleep stage, please refer to
https://huggingface.co/docs/hub/spaces-gpus#sleep-time.
Args:
repo_id (`str`):
ID of the repo to update. Example: `"bigcode/in-the-stack"`.
sleep_time (`int`, *optional*):
Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
your Space to pause (default behavior for upgraded hardware). For free hardware, you can't configure
the sleep time (value is fixed to 48 hours of inactivity).
See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
> [!TIP]
> It is also possible to set a custom sleep time when requesting hardware with [`request_space_hardware`].
huggingface-hub.set_space_volumes
Python Library Documentation: method set_space_volumes in module huggingface_hub.hf_api
set_space_volumes(repo_id: 'str', volumes: 'list[Volume]', *, token: 'bool | str | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Set volumes for a Space.
Sets (or replaces) the list of volumes mounted in the Space. Each volume gives the Space's container access
to a Hub resource (model, dataset, or storage bucket).
Args:
repo_id (`str`):
ID of the Space to update. Example: `"username/my-space"`.
volumes (`list[Volume]`):
List of [`Volume`] objects to mount. Each volume has a `type` (`"bucket"`, `"model"`, `"dataset"`, or
`"space"`), a `source` (repo or bucket ID), a `mount_path` (path inside the container), and optional
`revision`, `read_only`, and `path` fields.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Raises:
[`BadRequestError`]:
If the Space is a static Space (volumes are not supported on static Spaces).
Example:
```python
>>> from huggingface_hub import HfApi, Volume
>>> api = HfApi()
>>> api.set_space_volumes(
... "username/my-space",
... volumes=[
... Volume(type="model", source="username/my-model", mount_path="/models", read_only=True),
... Volume(type="bucket", source="username/my-bucket", mount_path="/data"),
... ],
... )
```
huggingface-hub.snapshot_download
Python Library Documentation: function snapshot_download in module huggingface_hub._snapshot_download
snapshot_download(repo_id: str, *, repo_type: str | None = None, revision: str | None = None, cache_dir: str | pathlib.Path | None = None, local_dir: str | pathlib.Path | None = None, library_name: str | None = None, library_version: str | None = None, user_agent: dict | str | None = None, etag_timeout: float = 10, force_download: bool = False, token: bool | str | None = None, local_files_only: bool = False, allow_patterns: list[str] | str | None = None, ignore_patterns: list[str] | str | None = None, max_workers: int = 8, tqdm_class: type[tqdm.asyncio.tqdm_asyncio] | None = None, headers: dict[str, str] | None = None, endpoint: str | None = None, dry_run: bool = False) -> str | list[huggingface_hub.file_download.DryRunFileInfo]
Download repo files.
Download a whole snapshot of a repo's files at the specified revision. This is useful when you want all files from
a repo because you don't know which ones you will need _a priori_. All files are nested in a folder to keep their
path and filename relative to that folder. You can also filter which files to download by using `allow_patterns`
and `ignore_patterns`.
If `local_dir` is provided, the file structure from the repo will be replicated in this location. When using this
option, the `cache_dir` will not be used, and a `.cache/huggingface/` folder will be created at the root of `local_dir`
to store some metadata related to the downloaded files. While this mechanism is not as robust as the main
cache system, it's optimized for regularly pulling the latest version of a repository.
An alternative would be to clone the repo, but this requires git and git-lfs to be installed and properly
configured. It is also not possible to filter which files to download when cloning a repository using git.
Args:
repo_id (`str`):
A user or an organization name and a repo name separated by a `/`.
repo_type (`str`, *optional*):
Set to `"dataset"`, `"space"` or `"kernel"` if downloading from a dataset, space or kernel repo,
`None` or `"model"` if downloading from a model. Default is `None`.
revision (`str`, *optional*):
An optional Git revision id, which can be a branch name, a tag, or a
commit hash.
cache_dir (`str`, `Path`, *optional*):
Path to the folder where cached files are stored.
local_dir (`str` or `Path`, *optional*):
If provided, the downloaded files will be placed under this directory.
library_name (`str`, *optional*):
The name of the library to which the object corresponds.
library_version (`str`, *optional*):
The version of the library.
user_agent (`str`, `dict`, *optional*):
The user-agent info in the form of a dictionary or a string.
etag_timeout (`float`, *optional*, defaults to `10`):
When fetching ETag, how many seconds to wait for the server to send
data before giving up, which is passed to `httpx.request`.
force_download (`bool`, *optional*, defaults to `False`):
Whether the file should be downloaded even if it already exists in the local cache.
token (`str`, `bool`, *optional*):
A token to be used for the download.
- If `True`, the token is read from the HuggingFace config
folder.
- If a string, it's used as the authentication token.
headers (`dict`, *optional*):
Additional headers to include in the request. Those headers take precedence over the others.
endpoint (`str`, *optional*):
The Hub endpoint to send the request to. Defaults to the value of `HF_ENDPOINT`.
local_files_only (`bool`, *optional*, defaults to `False`):
If `True`, do not download any files even if they are not in `cache_dir` or `local_dir`.
allow_patterns (`list[str]` or `str`, *optional*):
If provided, only files matching at least one pattern are downloaded.
ignore_patterns (`list[str]` or `str`, *optional*):
If provided, files matching any of the patterns are not downloaded.
max_workers (`int`, *optional*):
Number of concurrent threads to download files (1 thread = 1 file download).
Defaults to 8.
tqdm_class (`tqdm`, *optional*):
If provided, overwrites the default behavior for the progress bar. Passed
argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior.
Note that the `tqdm_class` is not passed to each individual download.
Defaults to the custom HF progress bar that can be disabled by setting
`HF_HUB_DISABLE_PROGRESS_BARS` environment variable.
dry_run (`bool`, *optional*, defaults to `False`):
If `True`, perform a dry run without actually downloading the files. Returns a list of
[`DryRunFileInfo`] objects containing information about what would be downloaded.
Returns:
`str` or list of [`DryRunFileInfo`]:
- If `dry_run=False`: Local snapshot path.
- If `dry_run=True`: A list of [`DryRunFileInfo`] objects containing download information.
Raises:
[`~utils.RepositoryNotFoundError`]
If the repository to download from cannot be found. This may be because it doesn't exist
or because it is set to `private` and you do not have access.
[`~utils.RevisionNotFoundError`]
If the revision to download from cannot be found.
[`~errors.IncompleteSnapshotError`]
If the Hub cannot be reached (offline, connection issue, or `local_files_only=True`) and the
cached snapshot is missing some of the requested files.
[`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
If `token=True` and the token cannot be found.
[`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) if
ETag cannot be determined.
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If some parameter value is invalid.
huggingface-hub.space_info
Python Library Documentation: method space_info in module huggingface_hub.hf_api
space_info(repo_id: 'str', *, revision: 'str | None' = None, timeout: 'float | None' = None, files_metadata: 'bool' = False, expand: 'list[ExpandSpaceProperty_T] | None' = None, token: 'bool | str | None' = None) -> 'SpaceInfo' method of huggingface_hub.hf_api.HfApi instance
Get info on one specific Space on huggingface.co.
Space can be private if you pass an acceptable token.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
revision (`str`, *optional*):
The revision of the space repository from which to get the
information.
timeout (`float`, *optional*):
Whether to set a timeout for the request to the Hub.
files_metadata (`bool`, *optional*):
Whether or not to retrieve metadata for files in the repository
(size, LFS metadata, etc). Defaults to `False`.
expand (`list[ExpandSpaceProperty_T]`, *optional*):
List properties to return in the response. When used, only the properties in the list will be returned.
This parameter cannot be used if `full` is passed.
Possible values are `"author"`, `"cardData"`, `"createdAt"`, `"datasets"`, `"disabled"`, `"lastModified"`, `"likes"`, `"models"`, `"private"`, `"runtime"`, `"sdk"`, `"siblings"`, `"sha"`, `"subdomain"`, `"tags"`, `"trendingScore"`, `"usedStorage"`, and `"resourceGroup"`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`~hf_api.SpaceInfo`]: The space repository information.
> [!TIP]
> Raises the following errors:
>
> - [`~utils.RepositoryNotFoundError`]
> If the repository to download from cannot be found. This may be because it doesn't exist,
> or because it is set to `private` and you do not have access.
> - [`~utils.RevisionNotFoundError`]
> If the revision to download from cannot be found.
huggingface-hub.split_state_dict_into_shards_factory
Python Library Documentation: function split_state_dict_into_shards_factory in module huggingface_hub.serialization._base
split_state_dict_into_shards_factory(state_dict: dict[str, ~TensorT], *, get_storage_size: collections.abc.Callable[[~TensorT], int], filename_pattern: str, get_storage_id: collections.abc.Callable[[~TensorT], typing.Any | None] = <function <lambda> at 0x000001F166C7E020>, max_shard_size: int | str = '5GB') -> huggingface_hub.serialization._base.StateDictSplit
Split a model state dictionary in shards so that each shard is smaller than a given size.
The shards are determined by iterating through the `state_dict` in the order of its keys. There is no optimization
made to make each shard as close as possible to the maximum size passed. For example, if the limit is 10GB and we
have tensors of sizes [6GB, 6GB, 2GB, 6GB, 2GB, 2GB] they will get sharded as [6GB], [6+2GB], [6+2+2GB] and not
[6+2+2GB], [6+2GB], [6GB].
> [!WARNING]
> If one of the model's tensor is bigger than `max_shard_size`, it will end up in its own shard which will have a
> size greater than `max_shard_size`.
Args:
state_dict (`dict[str, Tensor]`):
The state dictionary to save.
get_storage_size (`Callable[[Tensor], int]`):
A function that returns the size of a tensor when saved on disk in bytes.
get_storage_id (`Callable[[Tensor], Optional[Any]]`, *optional*):
A function that returns a unique identifier to a tensor storage. Multiple different tensors can share the
same underlying storage. This identifier is guaranteed to be unique and constant for this tensor's storage
during its lifetime. Two tensor storages with non-overlapping lifetimes may have the same id.
filename_pattern (`str`, *optional*):
The pattern to generate the files names in which the model will be saved. Pattern must be a string that
can be formatted with `filename_pattern.format(suffix=...)` and must contain the keyword `suffix`
max_shard_size (`int` or `str`, *optional*):
The maximum size of each shard, in bytes. Defaults to 5GB.
Returns:
[`StateDictSplit`]: A `StateDictSplit` object containing the shards and the index to retrieve them.
huggingface-hub.split_torch_state_dict_into_shards
Python Library Documentation: function split_torch_state_dict_into_shards in module huggingface_hub.serialization._torch
split_torch_state_dict_into_shards(state_dict: dict[str, 'torch.Tensor'], *, filename_pattern: str = 'model{suffix}.safetensors', max_shard_size: int | str = '5GB') -> huggingface_hub.serialization._base.StateDictSplit
Split a model state dictionary in shards so that each shard is smaller than a given size.
The shards are determined by iterating through the `state_dict` in the order of its keys. There is no optimization
made to make each shard as close as possible to the maximum size passed. For example, if the limit is 10GB and we
have tensors of sizes [6GB, 6GB, 2GB, 6GB, 2GB, 2GB] they will get sharded as [6GB], [6+2GB], [6+2+2GB] and not
[6+2+2GB], [6+2GB], [6GB].
> [!TIP]
> To save a model state dictionary to the disk, see [`save_torch_state_dict`]. This helper uses
> `split_torch_state_dict_into_shards` under the hood.
> [!WARNING]
> If one of the model's tensor is bigger than `max_shard_size`, it will end up in its own shard which will have a
> size greater than `max_shard_size`.
Args:
state_dict (`dict[str, torch.Tensor]`):
The state dictionary to save.
filename_pattern (`str`, *optional*):
The pattern to generate the files names in which the model will be saved. Pattern must be a string that
can be formatted with `filename_pattern.format(suffix=...)` and must contain the keyword `suffix`
Defaults to `"model{suffix}.safetensors"`.
max_shard_size (`int` or `str`, *optional*):
The maximum size of each shard, in bytes. Defaults to 5GB.
Returns:
[`StateDictSplit`]: A `StateDictSplit` object containing the shards and the index to retrieve them.
Example:
```py
>>> import json
>>> import os
>>> from safetensors.torch import save_file as safe_save_file
>>> from huggingface_hub import split_torch_state_dict_into_shards
>>> def save_state_dict(state_dict: dict[str, torch.Tensor], save_directory: str):
... state_dict_split = split_torch_state_dict_into_shards(state_dict)
... for filename, tensors in state_dict_split.filename_to_tensors.items():
... shard = {tensor: state_dict[tensor] for tensor in tensors}
... safe_save_file(
... shard,
... os.path.join(save_directory, filename),
... metadata={"format": "pt"},
... )
... if state_dict_split.is_sharded:
... index = {
... "metadata": state_dict_split.metadata,
... "weight_map": state_dict_split.tensor_to_filename,
... }
... with open(os.path.join(save_directory, "model.safetensors.index.json"), "w") as f:
... f.write(json.dumps(index, indent=2))
```
huggingface-hub.super_squash_history
Python Library Documentation: method super_squash_history in module huggingface_hub.hf_api
super_squash_history(repo_id: 'str', *, branch: 'str | None' = None, commit_message: 'str | None' = None, repo_type: 'str | None' = None, token: 'str | bool | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Squash commit history on a branch for a repo on the Hub.
Squashing the repo history is useful when you know you'll make hundreds of commits and you don't want to
clutter the history. Squashing commits can only be performed from the head of a branch.
> [!WARNING]
> Once squashed, the commit history cannot be retrieved. This is a non-revertible operation.
> [!WARNING]
> Once the history of a branch has been squashed, it is not possible to merge it back into another branch since
> their history will have diverged.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated by a `/`.
branch (`str`, *optional*):
The branch to squash. Defaults to the head of the `"main"` branch.
commit_message (`str`, *optional*):
The commit message to use for the squashed commit.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if listing commits from a dataset or a Space, `None` or `"model"` if
listing from a model. Default is `None`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Raises:
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
does not exist.
[`~utils.RevisionNotFoundError`]:
If the branch to squash cannot be found.
[`~utils.BadRequestError`]:
If invalid reference for a branch. You cannot squash history on tags.
Example:
```py
>>> from huggingface_hub import HfApi
>>> api = HfApi()
# Create repo
>>> repo_id = api.create_repo("test-squash").repo_id
# Make a lot of commits.
>>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"content")
>>> api.upload_file(repo_id=repo_id, path_in_repo="lfs.bin", path_or_fileobj=b"content")
>>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"another_content")
# Squash history
>>> api.super_squash_history(repo_id=repo_id)
```
huggingface-hub.suspend_scheduled_job
Python Library Documentation: method suspend_scheduled_job in module huggingface_hub.hf_api
suspend_scheduled_job(*, scheduled_job_id: 'str', namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Suspend (pause) a scheduled compute Job on Hugging Face infrastructure.
Args:
scheduled_job_id (`str`):
ID of the scheduled Job.
namespace (`str`, *optional*):
The namespace where the scheduled Job is. Defaults to the current user's namespace.
token `(Union[bool, str, None]`, *optional*):
A valid user access token. If not provided, the locally saved token will be used, which is the
recommended authentication method. Set to `False` to disable authentication.
Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
huggingface-hub.sync_bucket
Python Library Documentation: method sync_bucket in module huggingface_hub.hf_api
sync_bucket(source: 'str | None' = None, dest: 'str | None' = None, *, delete: 'bool' = False, ignore_times: 'bool' = False, ignore_sizes: 'bool' = False, existing: 'bool' = False, ignore_existing: 'bool' = False, include: 'list[str] | None' = None, exclude: 'list[str] | None' = None, filter_from: 'str | None' = None, plan: 'str | None' = None, apply: 'str | None' = None, dry_run: 'bool' = False, verbose: 'bool' = False, quiet: 'bool' = False, token: 'bool | str | None' = None) -> 'SyncPlan' method of huggingface_hub.hf_api.HfApi instance
Sync files between a local directory and a bucket.
This is equivalent to the ``hf buckets sync`` CLI command. One of ``source`` or ``dest`` must be a bucket path
(``hf://buckets/...``) and the other must be a local directory path.
Args:
source (`str`, *optional*):
Source path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``.
Required unless using ``apply``.
dest (`str`, *optional*):
Destination path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``.
Required unless using ``apply``.
delete (`bool`, *optional*, defaults to `False`):
Delete destination files not present in source.
ignore_times (`bool`, *optional*, defaults to `False`):
Skip files only based on size, ignoring modification times.
ignore_sizes (`bool`, *optional*, defaults to `False`):
Skip files only based on modification times, ignoring sizes.
existing (`bool`, *optional*, defaults to `False`):
Skip creating new files on receiver (only update existing files).
ignore_existing (`bool`, *optional*, defaults to `False`):
Skip updating files that exist on receiver (only create new files).
include (`list[str]`, *optional*):
Include files matching patterns (fnmatch-style).
exclude (`list[str]`, *optional*):
Exclude files matching patterns (fnmatch-style).
filter_from (`str`, *optional*):
Path to a filter file with include/exclude rules.
plan (`str`, *optional*):
Save sync plan to this JSONL file instead of executing.
apply (`str`, *optional*):
Apply a previously saved plan file. When set, ``source`` and ``dest`` are not needed.
dry_run (`bool`, *optional*, defaults to `False`):
Print sync plan to stdout as JSONL without executing.
verbose (`bool`, *optional*, defaults to `False`):
Show detailed per-file operations.
quiet (`bool`, *optional*, defaults to `False`):
Suppress all output and progress bars.
token (Union[bool, str, None], optional):
A valid user access token. If not provided, the locally saved token will be used.
Returns:
[`SyncPlan`]: The computed (or loaded) sync plan.
Example:
```python
>>> from huggingface_hub import HfApi
>>> api = HfApi()
# Upload local directory to bucket
>>> api.sync_bucket("./data", "hf://buckets/username/my-bucket")
# Download bucket to local directory
>>> api.sync_bucket("hf://buckets/username/my-bucket", "./data")
# Sync with delete and filtering
>>> api.sync_bucket(
... "./data",
... "hf://buckets/username/my-bucket",
... delete=True,
... include=["*.safetensors"],
... )
# Dry run: preview what would be synced
>>> plan = api.sync_bucket("./data", "hf://buckets/username/my-bucket", dry_run=True)
>>> plan.summary()
{'uploads': 3, 'downloads': 0, 'deletes': 0, 'skips': 1, 'total_size': 4096}
# Save plan for review, then apply
>>> api.sync_bucket("./data", "hf://buckets/username/my-bucket", plan="sync-plan.jsonl")
>>> api.sync_bucket(apply="sync-plan.jsonl")
```
huggingface-hub.sync_job_volume
Python Library Documentation: method sync_job_volume in module huggingface_hub.hf_api
sync_job_volume(source: 'str | Path', mount_path: 'str', *, remote_name: 'str | None' = None, read_only: 'bool' = True, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'Volume' method of huggingface_hub.hf_api.HfApi instance
Sync a local directory to a bucket and return a [`Volume`] ready to mount in a Job.
Files are uploaded to a subfolder of the `{namespace}/jobs-artifacts` bucket (auto-created as
private; a warning is emitted if it already exists and is public) using the same sync logic
as [`sync_bucket`]: re-syncing the same directory only
uploads new or modified files. By default the subfolder name is derived from the directory
path and the machine's hostname, so repeated calls from the same directory reuse the same
remote folder. Pass `remote_name` to use a fixed name instead.
Note that the data is *copied* to the bucket, not mounted live: changes made locally after
the sync are not visible to the Job (re-run `sync_job_volume` to update), and the volume is
mounted read-only by default. To retrieve data written by a Job to a read-write volume, sync
the bucket folder back with [`sync_bucket`]. If the source directory is empty (e.g. an output
directory), a placeholder `.keep` file is uploaded so the volume can still be mounted.
Args:
source (`str` or `Path`):
Path to a local directory to sync.
mount_path (`str`):
Mount path inside the Job container, e.g. `"/inputs"`. Must start with `/`.
remote_name (`str`, *optional*):
Name of the bucket subfolder to sync to. Defaults to a `{dirname}-{hash}` name derived
from the source path and the machine's hostname.
read_only (`bool`, *optional*, defaults to `True`):
Mount the volume read-only in the Job. Pass `False` to let the Job write back to the
bucket folder (e.g. to retrieve outputs with [`sync_bucket`] afterwards).
namespace (`str`, *optional*):
The namespace owning the `jobs-artifacts` bucket. Defaults to the current user's
namespace. Use the same namespace as the Job that will mount the volume.
token (`Union[bool, str, None]`, *optional*):
A valid user access token. If not provided, the locally saved token will be used, which is the
recommended authentication method. Set to `False` to disable authentication.
Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
Returns:
[`Volume`]: A bucket volume scoped to the synced subfolder, to pass in the `volumes` list
of [`run_job`], [`run_uv_job`], [`create_scheduled_job`] or [`create_scheduled_uv_job`].
Example:
```python
>>> from huggingface_hub import run_uv_job, sync_job_volume
# Upload ./training-data once, then run multiple jobs against it
>>> volume = sync_job_volume("./training-data", "/data")
>>> run_uv_job("train.py", script_args=["--learning-rate", "0.01"], volumes=[volume])
>>> run_uv_job("train.py", script_args=["--learning-rate", "0.05"], volumes=[volume])
# Read-write volume to retrieve outputs after the job completes
>>> volume = sync_job_volume("./outputs", "/outputs", read_only=False)
>>> job = run_uv_job("process.py", volumes=[volume])
```
huggingface-hub.trigger_scheduled_job
Python Library Documentation: method trigger_scheduled_job in module huggingface_hub.hf_api
trigger_scheduled_job(*, scheduled_job_id: 'str', namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'JobInfo' method of huggingface_hub.hf_api.HfApi instance
Trigger a scheduled Job to run immediately.
This triggers one immediate run of the scheduled job's spec. It does **not** modify the schedule
and does **not** affect the next scheduled run. If an instance is already running and the scheduled
job does not allow concurrent runs, the request is rejected (HTTP 409).
Args:
scheduled_job_id (`str`):
ID of the scheduled Job.
namespace (`str`, *optional*):
The namespace where the scheduled Job is. Defaults to the current user's namespace.
token `(Union[bool, str, None]`, *optional*):
A valid user access token. If not provided, the locally saved token will be used, which is the
recommended authentication method. Set to `False` to disable authentication.
Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
Returns:
[`JobInfo`]: Info about the triggered run.
Raises:
[`~utils.HfHubHTTPError`]:
HTTP 409 if another instance is already running and `concurrency` is disabled on the scheduled job.
huggingface-hub.try_to_load_from_cache
Python Library Documentation: function try_to_load_from_cache in module huggingface_hub.file_download
try_to_load_from_cache(repo_id: str, filename: str, cache_dir: str | pathlib.Path | None = None, revision: str | None = None, repo_type: str | None = None) -> str | typing.Any | None
Explores the cache to return the latest cached file for a given revision if found.
This function will not raise any exception if the file in not cached.
Args:
cache_dir (`str` or `os.PathLike`):
The folder where the cached files lie.
repo_id (`str`):
The ID of the repo on huggingface.co.
filename (`str`):
The filename to look for inside `repo_id`.
revision (`str`, *optional*):
The specific model version to use. Will default to `"main"` if it's not provided and no `commit_hash` is
provided either.
repo_type (`str`, *optional*):
The type of the repository. Will default to `"model"`.
Returns:
`Optional[str]` or `_CACHED_NO_EXIST`:
Will return `None` if the file was not cached. Otherwise:
- The exact path to the cached file if it's found in the cache
- A special value `_CACHED_NO_EXIST` if the file does not exist at the given commit hash and this fact was
cached.
Example:
```python
from huggingface_hub import try_to_load_from_cache, _CACHED_NO_EXIST
filepath = try_to_load_from_cache()
if isinstance(filepath, str):
# file exists and is cached
...
elif filepath is _CACHED_NO_EXIST:
# non-existence of file is cached
...
else:
# file is not cached
...
```
huggingface-hub.typer_factory
Python Library Documentation: function typer_factory in module huggingface_hub.cli._cli_utils
typer_factory(help: str, epilog: str | None = None, cls: type[huggingface_hub.cli._cli_utils.HFCliTyperGroup] | None = None) -> 'HFCliTyperGroup'
Create a CLI command group with consistent settings.
The returned group is the app: register commands with ``@group.command(...)``,
subgroups with ``group.add_group(sub, name=...)``, and a group-level callback
with ``@group.callback(...)``.
Args:
help: Help text for the group.
epilog: Optional epilog text (use `generate_epilog` to create one).
cls: Optional group class to use (defaults to `HFCliTyperGroup`).
Returns:
A configured `HFCliTyperGroup` instance.
huggingface-hub.unlike
Python Library Documentation: method unlike in module huggingface_hub.hf_api
unlike(repo_id: 'str', *, token: 'bool | str | None' = None, repo_type: 'str | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Unlike a given repo on the Hub (e.g. remove from favorite list).
To prevent spam usage, it is not possible to `like` a repository from a script.
See also [`list_liked_repos`].
Args:
repo_id (`str`):
The repository to unlike. Example: `"user/my-cool-model"`.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if unliking a dataset or space, `None` or
`"model"` if unliking a model. Default is `None`.
Raises:
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private
but not authenticated or repo does not exist.
Example:
```python
>>> from huggingface_hub import list_liked_repos, unlike
>>> "gpt2" in list_liked_repos().models # we assume you have already liked gpt2
True
>>> unlike("gpt2")
>>> "gpt2" in list_liked_repos().models
False
```
huggingface-hub.update_collection_item
Python Library Documentation: method update_collection_item in module huggingface_hub.hf_api
update_collection_item(collection_slug: 'str', item_object_id: 'str', *, note: 'str | None' = None, position: 'int | None' = None, token: 'bool | str | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Update an item in a collection.
Args:
collection_slug (`str`):
Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
item_object_id (`str`):
ID of the item in the collection. This is not the id of the item on the Hub (repo_id or paper id).
It must be retrieved from a [`CollectionItem`] object. Example: `collection.items[0].item_object_id`.
note (`str`, *optional*):
A note to attach to the item in the collection. The maximum size for a note is 500 characters.
position (`int`, *optional*):
New position of the item in the collection.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Example:
```py
>>> from huggingface_hub import get_collection, update_collection_item
# Get collection first
>>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")
# Update item based on its ID (add note + update position)
>>> update_collection_item(
... collection_slug="TheBloke/recent-models-64f9a55bb3115b4f513ec026",
... item_object_id=collection.items[-1].item_object_id,
... note="Newly updated model!"
... position=0,
... )
```
huggingface-hub.update_collection_metadata
Python Library Documentation: method update_collection_metadata in module huggingface_hub.hf_api
update_collection_metadata(collection_slug: 'str', *, title: 'str | None' = None, description: 'str | None' = None, position: 'int | None' = None, private: 'bool | None' = None, theme: 'str | None' = None, token: 'bool | str | None' = None) -> 'Collection' method of huggingface_hub.hf_api.HfApi instance
Update metadata of a collection on the Hub.
All arguments are optional. Only provided metadata will be updated.
Args:
collection_slug (`str`):
Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
title (`str`):
Title of the collection to update.
description (`str`, *optional*):
Description of the collection to update. The maximum size for a description is 150 characters.
position (`int`, *optional*):
New position of the collection in the list of collections of the user.
private (`bool`, *optional*):
Whether the collection should be private or not.
theme (`str`, *optional*):
Theme of the collection on the Hub.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns: [`Collection`]
Example:
```py
>>> from huggingface_hub import update_collection_metadata
>>> collection = update_collection_metadata(
... collection_slug="username/iccv-2023-64f9a55bb3115b4f513ec026",
... title="ICCV Oct. 2023"
... description="Portfolio of models, datasets, papers and demos I presented at ICCV Oct. 2023",
... private=False,
... theme="pink",
... )
>>> collection.slug
"username/iccv-oct-2023-64f9a55bb3115b4f513ec026"
# ^collection slug got updated but not the trailing ID
```
huggingface-hub.update_collection_resource_group
Python Library Documentation: method update_collection_resource_group in module huggingface_hub.hf_api
update_collection_resource_group(collection_slug: 'str', resource_group_id: 'str | None', *, token: 'bool | str | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Assign a collection to a resource group, or remove it from any resource group.
Only valid for organization-owned collections.
Args:
collection_slug (`str`):
Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
resource_group_id (`str` or `None`):
The resource group to assign the collection to, as a 24-character hexadecimal string. If `None`,
the collection is removed from any resource group.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Example:
```py
>>> from huggingface_hub import update_collection_resource_group
>>> update_collection_resource_group(
... collection_slug="my-org/iccv-2023-64f9a55bb3115b4f513ec026",
... resource_group_id="66980ecfc1e12a49c8f0e42d",
... )
```
huggingface-hub.update_inference_endpoint
Python Library Documentation: method update_inference_endpoint in module huggingface_hub.hf_api
update_inference_endpoint(name: 'str', *, accelerator: 'str | None' = None, instance_size: 'str | None' = None, instance_type: 'str | None' = None, min_replica: 'int | None' = None, max_replica: 'int | None' = None, scale_to_zero_timeout: 'int | None' = None, scaling_metric: 'InferenceEndpointScalingMetric | None' = None, scaling_threshold: 'float | None' = None, repository: 'str | None' = None, framework: 'str | None' = None, revision: 'str | None' = None, task: 'str | None' = None, custom_image: 'dict | None' = None, env: 'dict[str, str] | None' = None, secrets: 'dict[str, str] | None' = None, domain: 'str | None' = None, path: 'str | None' = None, cache_http_responses: 'bool | None' = None, tags: 'list[str] | None' = None, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'InferenceEndpoint' method of huggingface_hub.hf_api.HfApi instance
Update an Inference Endpoint.
This method allows the update of either the compute configuration, the deployed model, the route, or any combination.
All arguments are optional but at least one must be provided.
For convenience, you can also update an Inference Endpoint using [`InferenceEndpoint.update`].
Args:
name (`str`):
The name of the Inference Endpoint to update.
accelerator (`str`, *optional*):
The hardware accelerator to be used for inference (e.g. `"cpu"`).
instance_size (`str`, *optional*):
The size or type of the instance to be used for hosting the model (e.g. `"x4"`).
instance_type (`str`, *optional*):
The cloud instance type where the Inference Endpoint will be deployed (e.g. `"intel-icl"`).
min_replica (`int`, *optional*):
The minimum number of replicas (instances) to keep running for the Inference Endpoint.
max_replica (`int`, *optional*):
The maximum number of replicas (instances) to scale to for the Inference Endpoint.
scale_to_zero_timeout (`int`, *optional*):
The duration in minutes before an inactive endpoint is scaled to zero.
scaling_metric (`str` or [`InferenceEndpointScalingMetric `], *optional*):
The metric reference for scaling. Either "pendingRequests" or "hardwareUsage" when provided.
Defaults to None.
scaling_threshold (`float`, *optional*):
The scaling metric threshold used to trigger a scale up. Ignored when scaling metric is not provided.
Defaults to None.
repository (`str`, *optional*):
The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`).
framework (`str`, *optional*):
The machine learning framework used for the model (e.g. `"custom"`).
revision (`str`, *optional*):
The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`).
task (`str`, *optional*):
The task on which to deploy the model (e.g. `"text-classification"`).
custom_image (`dict`, *optional*):
A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an
Inference Endpoint running on the `text-generation-inference` (TGI) framework (see examples).
env (`dict[str, str]`, *optional*):
Non-secret environment variables to inject in the container environment
secrets (`dict[str, str]`, *optional*):
Secret values to inject in the container environment.
domain (`str`, *optional*):
The custom domain for the Inference Endpoint deployment, if setup the inference endpoint will be available at this domain (e.g. `"my-new-domain.cool-website.woof"`).
path (`str`, *optional*):
The custom path to the deployed model, should start with a `/` (e.g. `"/models/google-bert/bert-base-uncased"`).
cache_http_responses (`bool`, *optional*):
Whether to cache HTTP responses from the Inference Endpoint.
tags (`list[str]`, *optional*):
A list of tags to associate with the Inference Endpoint.
namespace (`str`, *optional*):
The namespace where the Inference Endpoint will be updated. Defaults to the current user's namespace.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`InferenceEndpoint`]: information about the updated Inference Endpoint.
huggingface-hub.update_job_labels
Python Library Documentation: method update_job_labels in module huggingface_hub.hf_api
update_job_labels(*, job_id: 'str', labels: 'dict[str, str]', namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'JobInfo' method of huggingface_hub.hf_api.HfApi instance
Update labels of an existing Job.
Replaces all existing user-provided labels with the new labels.
Args:
job_id (`str`):
ID of the Job.
labels (`dict[str, str]`):
New labels to set on the job. Replaces all existing labels.
Both keys and values must be max 100 characters and contain only
alphanumeric characters, dots, dashes, and underscores.
namespace (`str`, *optional*):
The namespace where the Job is running. Defaults to the current user's namespace.
token `(Union[bool, str, None]`, *optional*):
A valid user access token. If not provided, the locally saved token will be used, which is the
recommended authentication method. Set to `False` to disable authentication.
Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
Returns:
[`JobInfo`]: The updated Job info.
huggingface-hub.update_repo_settings
Python Library Documentation: method update_repo_settings in module huggingface_hub.hf_api
update_repo_settings(repo_id: 'str', *, gated: "Literal['auto', 'manual', False] | None" = None, private: 'bool | None' = None, visibility: 'RepoVisibility_T | None' = None, token: 'str | bool | None' = None, repo_type: 'str | None' = None) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Update the settings of a repository, including gated access and visibility.
To give more control over how repos are used, the Hub allows repo authors to enable
access requests for their repos, and also to change the visibility of the repo.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated by a /.
gated (`Literal["auto", "manual", False]`, *optional*):
The gated status for the repository. If set to `None` (default), the `gated` setting of the repository won't be updated.
* "auto": The repository is gated, and access requests are automatically approved or denied based on predefined criteria.
* "manual": The repository is gated, and access requests require manual approval.
* False : The repository is not gated, and anyone can access it.
private (`bool`, *optional*):
Whether the repository should be private. Cannot be passed together with `visibility`.
visibility (`Literal["public", "private", "protected"]`, *optional*):
Visibility of the repository. Can be `"public"` or `"private"`, or `"protected"` for Spaces.
token (`Union[str, bool, None]`, *optional*):
A valid user access token (string). Defaults to the locally saved token,
which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass False.
repo_type (`str`, *optional*):
The type of the repository to update settings from (`"model"`, `"dataset"` or `"space"`).
Defaults to `"model"`.
Raises:
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If gated is not one of "auto", "manual", or False.
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If repo_type is not one of the values in constants.REPO_TYPES.
[`~utils.HfHubHTTPError`]:
If the request to the Hugging Face Hub API fails.
[`~utils.RepositoryNotFoundError`]
If the repository to download from cannot be found. This may be because it doesn't exist,
or because it is set to `private` and you do not have access.
huggingface-hub.update_scheduled_job_labels
Python Library Documentation: method update_scheduled_job_labels in module huggingface_hub.hf_api
update_scheduled_job_labels(*, scheduled_job_id: 'str', labels: 'dict[str, str]', namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'ScheduledJobInfo' method of huggingface_hub.hf_api.HfApi instance
Update labels of an existing scheduled Job.
Replaces all existing user-provided labels with the new labels.
Args:
scheduled_job_id (`str`):
ID of the scheduled Job.
labels (`dict[str, str]`):
New labels to set on the scheduled job. Replaces all existing labels.
Both keys and values must be max 100 characters and contain only
alphanumeric characters, dots, dashes, and underscores.
namespace (`str`, *optional*):
The namespace where the scheduled Job is. Defaults to the current user's namespace.
token `(Union[bool, str, None]`, *optional*):
A valid user access token. If not provided, the locally saved token will be used, which is the
recommended authentication method. Set to `False` to disable authentication.
Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
Returns:
[`ScheduledJobInfo`]: The updated scheduled Job info.
huggingface-hub.update_webhook
Python Library Documentation: method update_webhook in module huggingface_hub.hf_api
update_webhook(webhook_id: 'str', *, url: 'str | None' = None, watched: 'list[dict | WebhookWatchedItem] | None' = None, domains: 'list[constants.WEBHOOK_DOMAIN_T] | None' = None, secret: 'str | None' = None, token: 'bool | str | None' = None) -> 'WebhookInfo' method of huggingface_hub.hf_api.HfApi instance
Update an existing webhook.
Args:
webhook_id (`str`):
The unique identifier of the webhook to be updated.
url (`str`, optional):
The URL to which the payload will be sent.
watched (`list[WebhookWatchedItem]`, optional):
List of items to watch. It can be users, orgs, models, datasets, or spaces.
Refer to [`WebhookWatchedItem`] for more details. Watched items can also be provided as plain dictionaries.
domains (`list[Literal["repo", "discussion"]]`, optional):
The domains to watch. This can include "repo", "discussion", or both.
secret (`str`, optional):
A secret to sign the payload with, providing an additional layer of security.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved token, which is the recommended
method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`WebhookInfo`]:
Info about the updated webhook.
Example:
```python
>>> from huggingface_hub import update_webhook
>>> updated_payload = update_webhook(
... webhook_id="654bbbc16f2ec14d77f109cc",
... url="https://new.webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
... watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}],
... domains=["repo"],
... secret="my-secret",
... )
>>> print(updated_payload)
WebhookInfo(
id="654bbbc16f2ec14d77f109cc",
job=None,
url="https://new.webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
domains=["repo"],
secret="my-secret",
disabled=False,
```
huggingface-hub.upload_file
Python Library Documentation: method upload_file in module huggingface_hub.hf_api
upload_file(*, path_or_fileobj: 'str | Path | bytes | BinaryIO', path_in_repo: 'str', repo_id: 'str', token: 'str | bool | None' = None, repo_type: 'str | None' = None, revision: 'str | None' = None, commit_message: 'str | None' = None, commit_description: 'str | None' = None, create_pr: 'bool | None' = None, parent_commit: 'str | None' = None, run_as_future: 'bool' = False, _hot_reload: 'bool | None' = None) -> 'CommitInfo | Future[CommitInfo]' method of huggingface_hub.hf_api.HfApi instance
Upload a local file (up to 50 GB) to the given repo. The upload is done
through a HTTP post request, and doesn't require git or git-lfs to be
installed.
Args:
path_or_fileobj (`str`, `Path`, `bytes`, or `IO`):
Path to a file on the local machine or binary data stream /
fileobj / buffer.
path_in_repo (`str`):
Relative filepath in the repo, for example:
`"checkpoints/1fec34a/weights.bin"`
repo_id (`str`):
The repository to which the file will be uploaded, for example:
`"username/custom_transformers"`
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
revision (`str`, *optional*):
The git revision to commit from. Defaults to the head of the `"main"` branch.
commit_message (`str`, *optional*):
The summary / title / first line of the generated commit
commit_description (`str` *optional*)
The description of the generated commit
create_pr (`boolean`, *optional*):
Whether or not to create a Pull Request with that commit. Defaults to `False`.
If `revision` is not set, PR is opened against the `"main"` branch. If
`revision` is set and is a branch, PR is opened against this branch. If
`revision` is set and is not a branch name (example: a commit oid), an
`RevisionNotFoundError` is returned by the server.
parent_commit (`str`, *optional*):
The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
especially useful if the repo is updated / committed to concurrently.
run_as_future (`bool`, *optional*):
Whether or not to run this method in the background. Background jobs are run sequentially without
blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects)
object. Defaults to `False`.
Returns:
[`CommitInfo`] or `Future`:
Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit
url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will
contain the result when executed.
> [!TIP]
> Raises the following errors:
>
> - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
> if the HuggingFace API returned an error
> - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
> if some parameter value is invalid
> - [`~utils.RepositoryNotFoundError`]
> If the repository to download from cannot be found. This may be because it doesn't exist,
> or because it is set to `private` and you do not have access.
> - [`~utils.RevisionNotFoundError`]
> If the revision to download from cannot be found.
> [!WARNING]
> `upload_file` assumes that the repo already exists on the Hub. If you get a
> Client error 404, please make sure you are authenticated, that your token has the required permissions,
> and that `repo_id` and `repo_type` are set correctly. If repo does not exist,
> create it first using [`~hf_api.create_repo`].
Example:
```python
>>> from huggingface_hub import upload_file
>>> with open("./local/filepath", "rb") as fobj:
... upload_file(
... path_or_fileobj=fileobj,
... path_in_repo="remote/file/path.h5",
... repo_id="username/my-dataset",
... repo_type="dataset",
... token="my_token",
... )
>>> upload_file(
... path_or_fileobj=".\\local\\file\\path",
... path_in_repo="remote/file/path.h5",
... repo_id="username/my-model",
... token="my_token",
... )
>>> upload_file(
... path_or_fileobj=".\\local\\file\\path",
... path_in_repo="remote/file/path.h5",
... repo_id="username/my-model",
... token="my_token",
... create_pr=True,
... )
```
huggingface-hub.upload_folder
Python Library Documentation: method upload_folder in module huggingface_hub.hf_api
upload_folder(*, repo_id: 'str', folder_path: 'str | Path', path_in_repo: 'str | None' = None, commit_message: 'str | None' = None, commit_description: 'str | None' = None, token: 'str | bool | None' = None, repo_type: 'str | None' = None, revision: 'str | None' = None, create_pr: 'bool | None' = None, parent_commit: 'str | None' = None, allow_patterns: 'list[str] | str | None' = None, ignore_patterns: 'list[str] | str | None' = None, delete_patterns: 'list[str] | str | None' = None, run_as_future: 'bool' = False) -> 'CommitInfo | Future[CommitInfo]' method of huggingface_hub.hf_api.HfApi instance
Upload a local folder to the given repo. The upload is done through a HTTP requests, and doesn't require git or
git-lfs to be installed.
The structure of the folder will be preserved. Files with the same name already present in the repository will
be overwritten. Others will be left untouched.
Use the `allow_patterns` and `ignore_patterns` arguments to specify which files to upload. These parameters
accept either a single pattern or a list of patterns. Patterns are Standard Wildcards (globbing patterns) as
documented [here](https://tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm). If both `allow_patterns` and
`ignore_patterns` are provided, both constraints apply. By default, all files from the folder are uploaded.
Use the `delete_patterns` argument to specify remote files you want to delete. Input type is the same as for
`allow_patterns` (see above). If `path_in_repo` is also provided, the patterns are matched against paths
relative to this folder. For example, `upload_folder(..., path_in_repo="experiment", delete_patterns="logs/*")`
will delete any remote file under `./experiment/logs/`. Note that the `.gitattributes` file will not be deleted
even if it matches the patterns.
Any `.git/` folder present in any subdirectory will be ignored. However, please be aware that the `.gitignore`
file is not taken into account.
When `hf_xet` is installed (the default), files are uploaded through a streamed pipeline: uploads start while
the folder is still being checked against the Hub, files are hashed while being chunked for upload (single
read pass), and large folders are automatically committed in several batches to stay below server limits
(follow-up commits get a ` (part N)` suffix on the commit message). If the upload is interrupted, re-running
the same call resumes it: already-committed files are skipped and already-uploaded data is deduplicated. When
`hf_xet` is not installed, falls back to a single commit created with [`create_commit`].
Args:
repo_id (`str`):
The repository to which the file will be uploaded, for example:
`"username/custom_transformers"`
folder_path (`str` or `Path`):
Path to the folder to upload on the local file system
path_in_repo (`str`, *optional*):
Relative path of the directory in the repo, for example:
`"checkpoints/1fec34a/results"`. Will default to the root folder of the repository.
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
revision (`str`, *optional*):
The git revision to commit from. Defaults to the head of the `"main"` branch.
commit_message (`str`, *optional*):
The summary / title / first line of the generated commit. Defaults to:
`f"Upload {path_in_repo} with huggingface_hub"`
commit_description (`str` *optional*):
The description of the generated commit
create_pr (`boolean`, *optional*):
Whether or not to create a Pull Request with that commit. Defaults to `False`. The PR is always
opened against the default branch: setting both `create_pr=True` and `revision` raises a
`ValueError`. Note that each call with `create_pr=True` opens a new pull request: to resume an
interrupted upload into the existing PR, re-run with `revision="refs/pr/N"` instead.
parent_commit (`str`, *optional*):
The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
especially useful if the repo is updated / committed to concurrently. If the upload is split into
several commits (large folders), `parent_commit` only applies to the first one.
allow_patterns (`list[str]` or `str`, *optional*):
If provided, only files matching at least one pattern are uploaded.
ignore_patterns (`list[str]` or `str`, *optional*):
If provided, files matching any of the patterns are not uploaded.
delete_patterns (`list[str]` or `str`, *optional*):
If provided, remote files matching any of the patterns will be deleted from the repo while committing
new files. This is useful if you don't know which files have already been uploaded.
Note: to avoid discrepancies the `.gitattributes` file is not deleted even if it matches the pattern.
run_as_future (`bool`, *optional*):
Whether or not to run this method in the background. Background jobs are run sequentially without
blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects)
object. Defaults to `False`.
Returns:
[`CommitInfo`] or `Future`:
Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit
url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will
contain the result when executed.
> [!TIP]
> Raises the following errors:
>
> - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
> if the HuggingFace API returned an error
> - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
> if some parameter value is invalid
> [!WARNING]
> `upload_folder` assumes that the repo already exists on the Hub. If you get a Client error 404, please make
> sure you are authenticated, that your token has the required permissions, and that `repo_id` and `repo_type`
> are set correctly. If repo does not exist, create it first using [`~hf_api.create_repo`].
Example:
```python
# Upload checkpoints folder except the log files
>>> upload_folder(
... folder_path="local/checkpoints",
... path_in_repo="remote/experiment/checkpoints",
... repo_id="username/my-dataset",
... repo_type="datasets",
... token="my_token",
... ignore_patterns="**/logs/*.txt",
... )
# Upload checkpoints folder including logs while deleting existing logs from the repo
# Useful if you don't know exactly which log files have already being pushed
>>> upload_folder(
... folder_path="local/checkpoints",
... path_in_repo="remote/experiment/checkpoints",
... repo_id="username/my-dataset",
... repo_type="datasets",
... token="my_token",
... delete_patterns="**/logs/*.txt",
... )
# Upload checkpoints folder while creating a PR
>>> upload_folder(
... folder_path="local/checkpoints",
... path_in_repo="remote/experiment/checkpoints",
... repo_id="username/my-dataset",
... repo_type="datasets",
... token="my_token",
... create_pr=True,
... )
```
huggingface-hub.upload_large_folder
Python Library Documentation: method upload_large_folder in module huggingface_hub.hf_api
upload_large_folder(repo_id: 'str', folder_path: 'str | Path', *, repo_type: 'str', revision: 'str | None' = None, private: 'bool | None' = None, allow_patterns: 'list[str] | str | None' = None, ignore_patterns: 'list[str] | str | None' = None, num_workers: 'int | None' = None, print_report: 'bool' = True, print_report_every: 'int' = 60) -> 'None' method of huggingface_hub.hf_api.HfApi instance
Upload a large folder to the Hub in the most resilient way possible.
> [!WARNING]
> `upload_large_folder` is deprecated and will be removed in a future release. [`upload_folder`] is now multi-commits
> by default and resilient to interruptions so it is the recommended way to upload large folders.
Several workers are started to upload files in an optimized way. Before being committed to a repo, files must be
hashed and be pre-uploaded if they are LFS files. Workers will perform these tasks for each file in the folder.
At each step, some metadata information about the upload process is saved in the folder under `.cache/.huggingface/`
to be able to resume the process if interrupted. The whole process might result in several commits.
Args:
repo_id (`str`):
The repository to which the file will be uploaded.
E.g. `"HuggingFaceTB/smollm-corpus"`.
folder_path (`str` or `Path`):
Path to the folder to upload on the local file system.
repo_type (`str`):
Type of the repository. Must be one of `"model"`, `"dataset"` or `"space"`.
Unlike in all other `HfApi` methods, `repo_type` is explicitly required here. This is to avoid
any mistake when uploading a large folder to the Hub, and therefore prevent from having to re-upload
everything.
revision (`str`, `optional`):
The branch to commit to. If not provided, the `main` branch will be used.
private (`bool`, `optional`):
Whether the repository should be private.
If `None` (default), the repo will be public unless the organization's default is private.
allow_patterns (`list[str]` or `str`, *optional*):
If provided, only files matching at least one pattern are uploaded.
ignore_patterns (`list[str]` or `str`, *optional*):
If provided, files matching any of the patterns are not uploaded.
num_workers (`int`, *optional*):
Number of workers to start. Defaults to half of CPU cores (minimum 1).
A higher number of workers may speed up the process if your machine allows it. However, on machines with a
slower connection, it is recommended to keep the number of workers low to ensure better resumability.
Indeed, partially uploaded files will have to be completely re-uploaded if the process is interrupted.
print_report (`bool`, *optional*):
Whether to print a report of the upload progress. Defaults to True.
Report is printed to `sys.stdout` every X seconds (60 by defaults) and overwrites the previous report.
print_report_every (`int`, *optional*):
Frequency at which the report is printed. Defaults to 60 seconds.
> [!TIP]
> A few things to keep in mind:
> - Repository limits still apply: https://huggingface.co/docs/hub/repositories-recommendations
> - Do not start several processes in parallel.
> - You can interrupt and resume the process at any time.
> - Do not upload the same folder to several repositories. If you need to do so, you must delete the local `.cache/.huggingface/` folder first.
> [!WARNING]
> While being much more robust to upload large folders, `upload_large_folder` is more limited than [`upload_folder`] feature-wise. In practice:
> - you cannot set a custom `path_in_repo`. If you want to upload to a subfolder, you need to set the proper structure locally.
> - you cannot set a custom `commit_message` and `commit_description` since multiple commits are created.
> - you cannot delete from the repo while uploading. Please make a separate commit first.
> - you cannot create a PR directly. Please create a PR first (from the UI or using [`create_pull_request`]) and then commit to it by passing `revision`.
**Technical details:**
`upload_large_folder` process is as follow:
1. (Check parameters and setup.)
2. Create repo if missing.
3. List local files to upload.
4. Run validation checks and display warnings if repository limits might be exceeded:
- Warns if the total number of files exceeds 100k (recommended limit).
- Warns if any folder contains more than 10k files (recommended limit).
- Warns about files larger than 20GB (recommended) or 50GB (hard limit).
5. Start workers. Workers can perform the following tasks:
- Hash a file.
- Get upload mode (regular or LFS) for a list of files.
- Pre-upload an LFS file.
- Commit a bunch of files.
Once a worker finishes a task, it will move on to the next task based on the priority list (see below) until
all files are uploaded and committed.
6. While workers are up, regularly print a report to sys.stdout.
Order of priority:
1. Commit if more than 5 minutes since last commit attempt (and at least 1 file).
2. Commit if at least 150 files are ready to commit.
3. Get upload mode if at least 10 files have been hashed.
4. Pre-upload LFS file if at least 1 file and no worker is pre-uploading.
5. Hash file if at least 1 file and no worker is hashing.
6. Get upload mode if at least 1 file and no worker is getting upload mode.
7. Pre-upload LFS file if at least 1 file.
8. Hash file if at least 1 file to hash.
9. Get upload mode if at least 1 file to get upload mode.
10. Commit if at least 1 file to commit and at least 1 min since last commit attempt.
11. Commit if at least 1 file to commit and all other queues are empty.
Special rules:
- Only one worker can commit at a time.
- If no tasks are available, the worker waits for 10 seconds before checking again.
huggingface-hub.verify_repo_checksums
Python Library Documentation: method verify_repo_checksums in module huggingface_hub.hf_api
verify_repo_checksums(repo_id: 'str', *, repo_type: 'str | None' = None, revision: 'str | None' = None, local_dir: 'str | Path | None' = None, cache_dir: 'str | Path | None' = None, token: 'str | bool | None' = None) -> 'FolderVerification' method of huggingface_hub.hf_api.HfApi instance
Verify local files for a repo against Hub checksums.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated by a `/`.
repo_type (`str`, *optional*):
The type of the repository from which to get the tree (`"model"`, `"dataset"` or `"space"`.
Defaults to `"model"`.
revision (`str`, *optional*):
The revision of the repository from which to get the tree. Defaults to `"main"` branch.
local_dir (`str` or `Path`, *optional*):
The local directory to verify.
cache_dir (`str` or `Path`, *optional*):
The cache directory to verify.
token (Union[bool, str, None], optional):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
Returns:
[`FolderVerification`]: a structured result containing the verification details.
Raises:
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
does not exist.
[`~utils.RevisionNotFoundError`]:
If revision is not found (error 404) on the repo.
huggingface-hub.wait_for_job
Python Library Documentation: method wait_for_job in module huggingface_hub.hf_api
wait_for_job(job_id: 'str | list[str]', *, timeout: 'float | None' = None, poll_interval: 'float' = 1.0, stages: 'list[JobStage] | None' = None, namespace: 'str | None' = None, token: 'bool | str | None' = None) -> 'JobInfo | list[JobInfo]' method of huggingface_hub.hf_api.HfApi instance
Wait until one or more compute Jobs on Hugging Face infrastructure reach a given stage.
Each Job status is polled (with [`inspect_job`]) every `poll_interval` seconds until its stage is one
of `stages` (terminal stages by default: `"COMPLETED"`, `"CANCELED"`, `"ERROR"` or `"DELETED"`). The
final [`JobInfo`] is returned in all cases: a failed or canceled Job does **not** raise an exception —
check `job.status.stage` to act on the outcome.
Terminal stages always stop the wait, even when not listed in `stages`. This avoids waiting forever for
a stage the Job will never reach (e.g. waiting for `"RUNNING"` on a Job that fails during scheduling).
Args:
job_id (`str` or `list[str]`):
ID of the Job, or a list of Job IDs to wait for. If a list is passed, a list of [`JobInfo`]
is returned (in the same order).
timeout (`float`, *optional*):
The maximum time to wait for the Job(s) to finish, in seconds. If `None`, will wait
indefinitely.
poll_interval (`float`, *optional*):
The time to wait between each status check, in seconds. Defaults to 1s.
stages (`list[JobStage]`, *optional*):
The stages to wait for. Defaults to the terminal stages (`"COMPLETED"`, `"CANCELED"`,
`"ERROR"`, `"DELETED"`). Pass e.g. `[JobStage.RUNNING]` to wait for the Job to start running.
Terminal stages always stop the wait regardless of this value.
namespace (`str`, *optional*):
The namespace where the Job(s) are running. Defaults to the current user's namespace.
token `(Union[bool, str, None]`, *optional*):
A valid user access token. If not provided, the locally saved token will be used, which is the
recommended authentication method. Set to `False` to disable authentication.
Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
Returns:
[`JobInfo`] or `list[JobInfo]`: the final Job info(s).
Raises:
`TimeoutError`:
If at least one Job has not reached one of the target stages after `timeout` seconds.
Example:
```python
>>> from huggingface_hub import run_job, wait_for_job
>>> job = run_job(image="python:3.12", command=["python", "-c", "print('Hello from HF compute!')"])
>>> wait_for_job(job_id=job.id).status.stage
'COMPLETED'
```
huggingface-hub.wait_for_space
Python Library Documentation: method wait_for_space in module huggingface_hub.hf_api
wait_for_space(repo_id: 'str', *, timeout: 'float | None' = None, poll_interval: 'float' = 1.0, token: 'bool | str | None' = None) -> 'SpaceRuntime' method of huggingface_hub.hf_api.HfApi instance
Wait until a Space reaches a terminal stage (not building/starting).
Polls [`get_space_runtime`] every `poll_interval` seconds until the Space's stage
is no longer intermediate (`BUILDING`, `RUNNING_BUILDING`, `APP_STARTING`,
`RUNNING_APP_STARTING`). Returns the final [`SpaceRuntime`] in all cases — check
`runtime.stage` to act on the outcome (e.g. `RUNNING` vs `BUILD_ERROR`).
Args:
repo_id (`str`):
ID of the Space to wait for. Example: `"username/my-space"`.
timeout (`float`, *optional*):
Maximum time to wait in seconds. If `None`, waits indefinitely.
poll_interval (`float`, *optional*):
Seconds between status checks. Defaults to 1s.
token (`bool` or `str`, *optional*):
A valid user access token. Defaults to the locally saved token, which is the
recommended authentication method. Set to `False` to disable authentication.
See https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
Returns:
[`SpaceRuntime`]: The final runtime information once the Space reaches a terminal stage.
Raises:
`TimeoutError`:
If the Space has not reached a terminal stage after `timeout` seconds.
Example:
```python
>>> from huggingface_hub import restart_space, wait_for_space
>>> restart_space("username/my-space")
>>> runtime = wait_for_space("username/my-space")
>>> runtime.stage
'RUNNING'
```
huggingface-hub.webhook_endpoint
Python Library Documentation: function webhook_endpoint in module huggingface_hub._webhooks_server
webhook_endpoint(path: str | None = None) -> collections.abc.Callable
Decorator to start a [`WebhooksServer`] and register the decorated function as a webhook endpoint.
This is a helper to get started quickly. If you need more flexibility (custom landing page or webhook secret),
you can use [`WebhooksServer`] directly. You can register multiple webhook endpoints (to the same server) by using
this decorator multiple times.
Check out the [webhooks guide](../guides/webhooks_server) for a step-by-step tutorial on how to set up your
server and deploy it on a Space.
> [!WARNING]
> `webhook_endpoint` is experimental. Its API is subject to change in the future.
> [!WARNING]
> You must have `gradio` installed to use `webhook_endpoint` (`pip install --upgrade gradio`).
Args:
path (`str`, optional):
The URL path to register the webhook function. If not provided, the function name will be used as the path.
In any case, all webhooks are registered under `/webhooks`.
Examples:
The default usage is to register a function as a webhook endpoint. The function name will be used as the path.
The server will be started automatically at exit (i.e. at the end of the script).
```python
from huggingface_hub import webhook_endpoint, WebhookPayload
@webhook_endpoint
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
...
# Server is automatically started at the end of the script.
```
Advanced usage: register a function as a webhook endpoint and start the server manually. This is useful if you
are running it in a notebook.
```python
from huggingface_hub import webhook_endpoint, WebhookPayload
@webhook_endpoint
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
...
# Start the server manually
trigger_training.launch()
```
huggingface-hub.whoami
Python Library Documentation: method whoami in module huggingface_hub.hf_api
whoami(token: 'bool | str | None' = None, *, cache: 'bool' = False) -> 'dict' method of huggingface_hub.hf_api.HfApi instance
Call HF API to know "whoami".
If passing `cache=True`, the result will be cached for subsequent calls for the duration of the Python process. This is useful if you plan to call
`whoami` multiple times as this endpoint is heavily rate-limited for security reasons.
Args:
token (`bool` or `str`, *optional*):
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass `False`.
cache (`bool`, *optional*):
Whether to cache the result of the `whoami` call for subsequent calls.
If an error occurs during the first call, it won't be cached.
Defaults to `False`.