# Inferência

Inferência é o processo de usar um modelo treinado para fazer previsões em novos dados. Como esse processo pode ser intensivo em computação, executá-lo em um serviço dedicado ou externo pode ser uma opção interessante. A biblioteca `huggingface_hub` fornece uma interface unificada para executar inferência em vários serviços para modelos hospedados no Hugging Face Hub:

1.  [Provedores de Inferência](https://huggingface.co/docs/inference-providers/index): acesso simplificado e unificado a centenas de modelos de machine learning, impulsionado por nossos parceiros de inferência serverless. Essa nova abordagem se baseia na nossa anterior API de Inferência Serverless, oferecendo mais modelos, desempenho aprimorado e maior confiabilidade graças a provedores de classe mundial. Consulte a [documentação](https://huggingface.co/docs/inference-providers/index#partners) para obter a lista de provedores suportados.
2.  [Inference Endpoints](https://huggingface.co/docs/inference-endpoints/index): um produto para implantar modelos em produção com facilidade. A inferência é executada pela Hugging Face em uma infraestrutura dedicada e totalmente gerenciada em um provedor de nuvem de sua escolha.
3.  Endpoints locais: você também pode executar inferência com servidores de inferência locais, como [llama.cpp](https://github.com/ggerganov/llama.cpp), [Ollama](https://ollama.com/), [vLLM](https://github.com/vllm-project/vllm), [LiteLLM](https://docs.litellm.ai/docs/simple_proxy) ou [Text Generation Inference (TGI)](https://github.com/huggingface/text-generation-inference), conectando o cliente a esses endpoints locais.

Esses serviços podem ser chamados com o objeto [InferenceClient](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceClient). Consulte [este guia](../guides/inference) para mais informações sobre como usá-lo.

## Cliente de Inferência[[huggingface_hub.InferenceClient]]

#### huggingface_hub.InferenceClient[[huggingface_hub.InferenceClient]]

```python
huggingface_hub.InferenceClient(model: str | None = None, provider: typing.Union[typing.Literal['baseten', 'cerebras', 'cohere', 'deepinfra', 'fal-ai', 'featherless-ai', 'fireworks-ai', 'groq', 'hf-inference', 'novita', 'nscale', 'openai', 'ovhcloud', 'publicai', 'replicate', 'scaleway', 'together', 'wavespeed', 'zai-org'], typing.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)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L124)

**Parâmetros:**

model (`str`, `optional`) : O modelo para executar a inferência. Pode ser um id de modelo hospedado no Hugging Face Hub, por exemplo `meta-llama/Meta-Llama-3-8B-Instruct`, ou uma URL para um Inference Endpoint implantado. O padrão é None, caso em que um modelo recomendado é selecionado automaticamente para a tarefa. Observação: para melhor compatibilidade com o cliente da OpenAI, `model` foi aliasado como `base_url`. Esses 2 argumentos são mutuamente exclusivos. Se uma URL for passada como `model` ou `base_url` para chat completion, o sufixo de caminho `(/v1)/chat/completions` será anexado à URL.

provider (`str`, *opcional*) : Nome do provedor a ser usado para inferência. Pode ser `"baseten"`, `"cerebras"`, `"cohere"`, `"deepinfra"`, `"fal-ai"`, `"featherless-ai"`, `"fireworks-ai"`, `"groq"`, `"hf-inference"`, `"novita"`, `"nscale"`, `"openai"`, `"ovhcloud"`, `"publicai"`, `"replicate"`, `"scaleway"`, `"together"`, `"wavespeed"` ou `"zai-org"`. O padrão é "auto": roteamento automático, que por padrão usa o provedor "fastest"; você pode alternar para a ordem de provedores "cheapest" ou "preferred" em https://hf.co/settings/inference-providers. Se o modelo for uma URL ou `base_url` for passado, então `provider` não é usado.

token (`str`, *opcional*) : token do Hugging Face. Se não for fornecido, será usado o token salvo localmente. Observação: para melhor compatibilidade com o cliente da OpenAI, `token` foi aliasado como `api_key`. Esses 2 argumentos são mutuamente exclusivos e têm exatamente o mesmo comportamento.

timeout (`float`, `optional`) : O número máximo de segundos para aguardar uma resposta do servidor. O padrão é None, o que significa que o loop continuará até que o servidor esteja disponível.

headers (`dict[str, str]`, `optional`) : Cabeçalhos adicionais para enviar ao servidor. Por padrão, apenas os cabeçalhos de autorização e user-agent são enviados. Os valores neste dicionário substituirão os valores padrão.

bill_to (`str`, `optional`) : A conta de faturamento a ser usada para as solicitações. Por padrão, as solicitações são faturadas na conta do usuário. As solicitações só podem ser faturadas para uma organização da qual o usuário é membro e que tenha assinado o Enterprise Hub.

cookies (`dict[str, str]`, `optional`) : Cookies adicionais para enviar ao servidor.

base_url (`str`, `optional`) : URL base para executar inferência. Este é um argumento duplicado de `model` para fazer o [InferenceClient](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceClient) seguir o mesmo padrão do cliente `openai.OpenAI`. Não pode ser usado se `model` estiver definido. Padrão: None.

api_key (`str`, `optional`) : Token a ser usado para autenticação. Este é um argumento duplicado de `token` para fazer o [InferenceClient](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceClient) seguir o mesmo padrão do cliente `openai.OpenAI`. Não pode ser usado se `token` estiver definido. Padrão: None.

Inicialize um novo Inference Client.

O [InferenceClient](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceClient) visa fornecer uma experiência unificada para realizar inferência. O cliente pode ser usado de forma transparente com a API de Inferência (gratuita), Endpoints de Inferência auto-hospedados ou Provedores de Inferência de terceiros.

#### audio_classification[[huggingface_hub.InferenceClient.audio_classification]]

```python
audio_classification(audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None, top_k: int | None = None, function_to_apply: typing.Optional[ForwardRef('AudioClassificationOutputTransform')] = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L295)

**Parâmetros:**

audio (Union[str, Path, bytes, BinaryIO]) : O conteúdo de áudio a ser classificado. Pode ser bytes de áudio brutos, um arquivo de áudio local ou uma URL apontando para um arquivo de áudio.

model (`str`, *opcional*) : O modelo a ser usado para classificação de áudio. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo recomendado por padrão para classificação de áudio será utilizado.

top_k (`int`, *opcional*) : Quando especificado, limita a saída às K classes mais prováveis.

function_to_apply (`"AudioClassificationOutputTransform"`, *opcional*) : A função a ser aplicada às saídas do modelo para recuperar as pontuações.

**Retorna:** `list[AudioClassificationOutputElement]`

Lista de itens [AudioClassificationOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.AudioClassificationOutputElement) contendo os rótulos previstos e sua confiança.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Realize a classificação de áudio no conteúdo de áudio fornecido.

Exemplo:
```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[[huggingface_hub.InferenceClient.audio_to_audio]]

```python
audio_to_audio(audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L352)

**Parâmetros:**

audio (Union[str, Path, bytes, BinaryIO]) : O conteúdo de áudio para o modelo. Pode ser bytes de áudio brutos, um arquivo de áudio local ou uma URL apontando para um arquivo de áudio.

model (`str`, *opcional*) : O modelo pode ser qualquer modelo que receba um arquivo de áudio e retorne outro arquivo de áudio. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo recomendado por padrão para audio_to_audio será utilizado.

**Retorna:** `list[AudioToAudioOutputElement]`

Uma lista de itens [AudioToAudioOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.AudioToAudioOutputElement) contendo rótulo de áudio, tipo de conteúdo e conteúdo de áudio em blob.

**Exceções:** ``InferenceTimeoutError`` ou `HfHubHTTPError`

- ``InferenceTimeoutError`` -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Executa várias tarefas relacionadas a áudio-para-áudio, dependendo do modelo (por exemplo: aprimoramento de fala, separação de fontes).

Exemplo:
```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[[huggingface_hub.InferenceClient.automatic_speech_recognition]]

```python
automatic_speech_recognition(audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None, extra_body: dict | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L404)

**Parâmetros:**

audio (Union[str, Path, bytes, BinaryIO]) : O conteúdo a ser transcrito. Pode ser bytes de áudio brutos, um arquivo de áudio local ou uma URL para um arquivo de áudio.

model (`str`, *opcional*) : O modelo a ser usado para ASR. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo recomendado por padrão para ASR será utilizado.

extra_body (`dict`, *opcional*) : Parâmetros adicionais específicos do provedor para passar ao modelo. Consulte a documentação do provedor para os parâmetros suportados.

**Retorna:** [AutomaticSpeechRecognitionOutput](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.AutomaticSpeechRecognitionOutput)

Um item contendo o texto transcrito e, opcionalmente, os blocos de timestamp.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Execute o reconhecimento automático de fala (ASR ou áudio-para-texto) no conteúdo de áudio fornecido.

Exemplo:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.automatic_speech_recognition("hello_world.flac").text
"hello world"
```

#### chat_completion[[huggingface_hub.InferenceClient.chat_completion]]

```python
chat_completion(messages: list, 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: typing.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: typing.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)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L531)

**Parâmetros:**

messages (Lista de [ChatCompletionInputMessage](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ChatCompletionInputMessage)) : Histórico da conversa consistindo de pares de papéis e conteúdo.

model (`str`, *opcional*) : O modelo a ser usado para chat-completion. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo recomendado por padrão para geração de texto baseada em chat será utilizado. Veja https://huggingface.co/tasks/text-generation para mais detalhes. Se `model` for um ID de modelo, ele é passado ao servidor como o parâmetro `model`. Se você deseja definir uma URL personalizada enquanto configura `model` no payload da requisição, você deve definir `base_url` ao inicializar o [InferenceClient](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceClient).

frequency_penalty (`float`, *opcional*) : Penaliza novos tokens com base na sua frequência existente no texto até o momento. Intervalo: [-2,0, 2,0]. Padrão: 0,0.

logit_bias (`list[float]`, *opcional*) : Ajusta a probabilidade de tokens específicos aparecerem na saída gerada.

logprobs (`bool`, *opcional*) : Se deve retornar as probabilidades logarítmicas dos tokens de saída ou não. Se verdadeiro, retorna as probabilidades logarítmicas de cada token de saída retornado no conteúdo da mensagem.

max_tokens (`int`, *opcional*) : Número máximo de tokens permitidos na resposta. O valor padrão é 100.

n (`int`, *opcional*) : O número de complementações a serem geradas para cada prompt.

presence_penalty (`float`, *opcional*) : Número entre -2,0 e 2,0. Valores positivos penalizam novos tokens com base em sua ocorrência no texto até o momento, aumentando a probabilidade de o modelo abordar novos tópicos.

response_format (`ChatCompletionInputGrammarType()`, *opcional*) : Restrições de gramática. Pode ser um JSONSchema ou uma regex.

seed (Opcional`int`, *optional*) : Semente para fluxo de controle reproduzível. Padrão é None.

stop (`list[str]`, *opcional*) : Até quatro strings que acionam o fim da resposta. O padrão é None.

stream (`bool`, *opcional*) : Ativa o streaming em tempo real das respostas. O valor padrão é False.

stream_options ([ChatCompletionInputStreamOptions](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ChatCompletionInputStreamOptions), *opcional*) : Opções para streaming de completions.

temperature (`float`, *opcional*) : Controla a aleatoriedade das gerações. Valores menores garantem conclusões menos aleatórias. Intervalo: [0, 2]. Padrão: 1.0.

top_logprobs (`int`, *opcional*) : Um inteiro entre 0 e 5 que especifica o número de tokens mais prováveis a serem retornados em cada posição de token, cada um com uma probabilidade log associada. logprobs deve ser definido como true se este parâmetro for usado.

top_p (`float`, *opcional*) : Fração das próximas palavras mais prováveis a serem amostradas. Deve estar entre 0 e 1. O padrão é 1.0.

tool_choice ([ChatCompletionInputToolChoiceClass](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ChatCompletionInputToolChoiceClass) ou `ChatCompletionInputToolChoiceEnum()`, *opcional*) : A ferramenta a ser usada para a conclusão. O padrão é "auto".

tool_prompt (`str`, *opcional*) : Um prompt a ser adicionado antes das ferramentas.

tools (Lista de [ChatCompletionInputTool](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ChatCompletionInputTool), *opcional*) : Uma lista de ferramentas que o modelo pode chamar. Atualmente, apenas funções são suportadas como ferramenta. Use isso para fornecer uma lista de funções para as quais o modelo pode gerar entradas JSON.

extra_body (`dict`, *opcional*) : Parâmetros adicionais específicos do provedor para passar ao modelo. Consulte a documentação do provedor para os parâmetros suportados.

**Retorna:** [ChatCompletionOutput](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ChatCompletionOutput) ou um iterável de [ChatCompletionStreamOutput](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ChatCompletionStreamOutput)

Texto gerado retornado pelo servidor:
- se `stream=False`, o texto gerado é retornado como um [ChatCompletionOutput](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ChatCompletionOutput) (padrão).
- se `stream=True`, o texto gerado é retornado token por token como uma sequência de [ChatCompletionStreamOutput](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ChatCompletionStreamOutput).

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Um método para completar conversas usando um modelo de linguagem especificado.

> [!TIP]
> O método `client.chat_completion` é um alias de `client.chat.completions.create` para compatibilidade com o cliente da OpenAI. As entradas e saídas são estritamente as mesmas e o uso de qualquer uma das sintaxes produzirá os mesmos resultados. Consulte o [Guia de Inferência](https://huggingface.co/docs/huggingface_hub/guides/inference#openai-compatibility) para mais detalhes sobre a compatibilidade com a OpenAI.

> [!TIP]
> Você pode passar parâmetros específicos do provedor para o modelo usando o argumento `extra_body`.

Exemplo:

```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
    )
)
```

Exemplo usando 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)
```

Exemplo usando a sintaxe da OpenAI:
```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)
```

Exemplo de uso de um provedor de terceiros diretamente com parâmetros extras (específicos do provedor). O uso será cobrado na sua conta do Together AI.

```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"},
... )
```

Exemplo usando um provedor de terceiros por meio do Hugging Face Routing. O uso será cobrado na sua conta do Hugging Face.

```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?"}],
... )
```

Exemplo usando Imagem + Texto como entrada:
```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.
```

Exemplo usando ferramentas:
```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
)
```

Exemplo usando 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
'{

y": "bike ride",
": ["puppy", "cat", "raccoon"],
_seen": 3,
n": "park"}'
```

#### document_question_answering[[huggingface_hub.InferenceClient.document_question_answering]]

```python
document_question_answering(image: typing.Union[bytes, typing.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)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L933)

**Parâmetros:**

image (`Union[str, Path, bytes, BinaryIO]`) : A imagem de entrada para o contexto. Pode ser bytes brutos, um arquivo de imagem ou uma URL para uma imagem online.

question (`str`) : Pergunta a ser respondida.

model (`str`, *opcional*) : O modelo a ser usado para a tarefa de question answering de documentos. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de question answering de documentos recomendado por padrão será usado. Padrão: None.

doc_stride (`int`, *opcional*) : Se as palavras do documento forem longas demais para caber junto com a pergunta para o modelo, elas serão divididas em vários blocos com alguma sobreposição. Este argumento controla o tamanho dessa sobreposição.

handle_impossible_answer (`bool`, *opcional*) : Se aceitar "impossível" como resposta

lang (`str`, *opcional*) : Idioma a ser usado durante a execução do OCR. O padrão é inglês.

max_answer_len (`int`, *opcional*) : O comprimento máximo das respostas previstas (por exemplo, apenas respostas com comprimento menor são consideradas).

max_question_len (`int`, *opcional*) : O comprimento máximo da pergunta após a tokenização. Será truncado, se necessário.

max_seq_len (`int`, *opcional*) : O comprimento máximo da frase total (contexto + pergunta) em tokens de cada bloco passado ao modelo. O contexto será dividido em vários blocos (usando doc_stride como sobreposição), se necessário.

top_k (`int`, *opcional*) : O número de respostas a retornar (será escolhido pela ordem de probabilidade). Pode retornar menos respostas do que top_k se não houver opções suficientes disponíveis no contexto.

word_boxes (`list[Union[list[float], str`, *opcional*) : Uma lista de palavras e caixas delimitadoras (normalizadas de 0->1000). Se fornecida, a inferência ignorará a etapa de OCR e usará as caixas delimitadoras fornecidas.

**Retorna:** `list[DocumentQuestionAnsweringOutputElement]`

uma lista de itens [DocumentQuestionAnsweringOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.DocumentQuestionAnsweringOutputElement) contendo o rótulo previsto, a probabilidade associada, os ids das palavras e o número da página.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Responda perguntas sobre imagens de documentos.

Exemplo:
```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[[huggingface_hub.InferenceClient.feature_extraction]]

```python
feature_extraction(text: str | list[str], normalize: bool | None = None, prompt_name: str | None = None, truncate: bool | None = None, truncation_direction: typing.Optional[typing.Literal['left', 'right']] = None, dimensions: int | None = None, encoding_format: typing.Optional[typing.Literal['float', 'base64']] = None, model: str | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1020)

**Parâmetros:**

text (*str* ou *list[str]*) : O texto ou lista de textos para incorporar.

model (*str*, *opcional*) : O modelo a ser usado para a tarefa de extração de recursos. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de extração de recursos recomendado por padrão será usado. Padrão: None.

normalize (*bool*, *opcional*) : Se as embeddings devem ser normalizadas ou não. Disponível apenas em servidores alimentados por Text-Embedding-Inference.

prompt_name (*str*, *opcional*) : O nome do prompt que deve ser usado para a codificação. Se não for definido, nenhum prompt será aplicado. Deve ser uma chave no dicionário *prompts* da configuração do *Sentence Transformers*. Por exemplo, se `prompt_name` for "query" e o `prompts` for &amp;lcub;"query": "query: ",...}, então a frase "What is the capital of France?" será codificada como "query: What is the capital of France?" porque o texto do prompt será adicionado antes de qualquer texto a ser codificado.

truncate (*bool*, *opcional*) : Se as embeddings devem ser truncadas ou não. Disponível apenas em servidores alimentados por Text-Embedding-Inference.

truncation_direction (*Literal["left", "right"]*, *opcional*) : Qual lado da entrada deve ser truncado quando *truncate=True* é passado.

dimensions (*int*, *opcional*) : O número de dimensões que as embeddings de saída resultantes devem ter. Disponível apenas em endpoints de embedding compatíveis com a OpenAI.

encoding_format (*Literal["float", "base64"]*, *opcional*) : O formato dos embeddings de saída. Pode ser "float" ou "base64". Disponível apenas em endpoints de embedding compatíveis com a OpenAI.

**Retorna:** `*np.ndarray*`

O embedding que representa o(s) texto(s) de entrada como um array numpy float32.

**Exceções:** [*InferenceTimeoutError*] ou [*HfHubHTTPError*]

- [*InferenceTimeoutError*] -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- [*HfHubHTTPError*] -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Gere embeddings para um texto ou lote de textos específico.

Exemplo:
```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[[huggingface_hub.InferenceClient.fill_mask]]

```python
fill_mask(text: str, model: str | None = None, targets: list[str] | None = None, top_k: int | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1103)

**Parâmetros:**

text (`str`) : uma string para ser preenchida, deve conter o token [MASK] (verifique o cartão do modelo para o nome exato da máscara).

model (`str`, *opcional*) : O modelo a ser usado para a tarefa de preenchimento de máscara. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de preenchimento de máscara recomendado por padrão será usado.

targets (`list[str`, *optional*) : Quando fornecido, o modelo limitará as pontuações aos alvos passados, em vez de procurar em todo o vocabulário. Se os alvos fornecidos não estiverem no vocabulário do modelo, eles serão tokenizados e o primeiro token resultante será usado (com um aviso, e isso pode ser mais lento).

top_k (`int`, *opcional*) : Quando fornecido, substitui o número de previsões a serem retornadas.

**Retorna:** `list[FillMaskOutputElement]`

uma lista de itens [FillMaskOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.FillMaskOutputElement) contendo o rótulo previsto, a probabilidade associada, a referência do token e o texto completado.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Preencha um espaço com uma palavra ausente (mais precisamente, um token).

Exemplo:
```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[[huggingface_hub.InferenceClient.get_endpoint_info]]

```python
get_endpoint_info(model: str | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L3250)

**Parâmetros:**

model (`str`, *opcional*) : O modelo a ser usado para inferência. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Este parâmetro substitui o modelo definido no nível da instância. O valor padrão é None.

**Retorna:** `dict[str, Any]`

Informações sobre o endpoint.

Obtenha informações sobre o endpoint implantado.

Este endpoint está disponível apenas em endpoints alimentados por Text-Generation-Inference (TGI) ou Text-Embedding-Inference (TEI). Endpoints alimentados por `transformers` retornam um payload vazio.

Exemplo:
```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[[huggingface_hub.InferenceClient.health_check]]

```python
health_check(model: str | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L3308)

**Parâmetros:**

model (`str`, *opcional*) : URL do Inference Endpoint. Este parâmetro substitui o modelo definido no nível da instância. O valor padrão é None.

**Retorna:** `bool`

Verdadeiro se tudo estiver funcionando corretamente.

Verifique a saúde do endpoint implantado.

O Health check está disponível apenas com Inference Endpoints powered by Text-Generation-Inference (TGI) ou Text-Embedding-Inference (TEI).

Exemplo:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient("https://jzgu0buei5.us-east-1.aws.endpoints.huggingface.cloud")
>>> client.health_check()
True
```

#### image_classification[[huggingface_hub.InferenceClient.image_classification]]

```python
image_classification(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None, function_to_apply: typing.Optional[ForwardRef('ImageClassificationOutputTransform')] = None, top_k: int | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1159)

**Parâmetros:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : A imagem a ser classificada. Pode ser bytes brutos, um arquivo de imagem, uma URL para uma imagem online ou uma imagem PIL.

model (`str`, *opcional*) : O modelo a ser usado para classificação de imagens. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo recomendado por padrão para classificação de imagens será utilizado.

function_to_apply (`"ImageClassificationOutputTransform"`, *opcional*) : A função a ser aplicada às saídas do modelo para recuperar as pontuações.

top_k (`int`, *opcional*) : Quando especificado, limita a saída às K classes mais prováveis.

**Retorna:** `list[ImageClassificationOutputElement]`

uma lista de itens [ImageClassificationOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ImageClassificationOutputElement) contendo o rótulo previsto e a probabilidade associada.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Realize a classificação de imagem na imagem fornecida usando o modelo especificado.

Exemplo:
```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[[huggingface_hub.InferenceClient.image_segmentation]]

```python
image_segmentation(image: typing.Union[bytes, typing.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: typing.Optional[ForwardRef('ImageSegmentationSubtask')] = None, threshold: float | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1209)

**Parâmetros:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : A imagem a ser segmentada. Pode ser bytes brutos, um arquivo de imagem, uma URL para uma imagem online ou uma imagem PIL.

model (`str`, *opcional*) : O modelo a ser usado para segmentação de imagem. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo recomendado por padrão para segmentação de imagem será utilizado.

mask_threshold (`float`, *opcional*) : Limiar a ser usado ao converter as máscaras previstas em valores binários.

overlap_mask_area_threshold (`float`, *opcional*) : Limiar de sobreposição de máscara para eliminar segmentos pequenos e desconectados.

subtask (`"ImageSegmentationSubtask"`, *opcional*) : Tarefa de segmentação a ser executada, dependendo das capacidades do modelo.

threshold (`float`, *opcional*) : Limiar de probabilidade para filtrar máscaras previstas.

**Retorna:** `list[ImageSegmentationOutputElement]`

Uma lista de itens [ImageSegmentationOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ImageSegmentationOutputElement) contendo as máscaras segmentadas e os atributos associados.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Realize a segmentação de imagem na imagem fornecida usando o modelo especificado.

> [!WARNING]
> Você deve ter o `PIL` instalado se quiser trabalhar com imagens (`pip install Pillow`).

Exemplo:
```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[[huggingface_hub.InferenceClient.image_to_image]]

```python
image_to_image(image: typing.Union[bytes, typing.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)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1277)

**Parâmetros:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : A imagem de entrada para a tradução. Pode ser bytes brutos, um arquivo de imagem, uma URL para uma imagem online ou uma imagem PIL.

prompt (`str`, *opcional*) : O prompt de texto para orientar a geração da imagem.

negative_prompt (`str`, *opcional*) : Um prompt para orientar o que NÃO incluir na geração de imagem.

num_inference_steps (`int`, *opcional*) : Para modelos de difusão. O número de etapas de desruidamento. Mais etapas de desruidamento geralmente resultam em uma imagem de maior qualidade, às custas de uma inferência mais lenta.

guidance_scale (`float`, *opcional*) : Para modelos de difusão. Um valor de escala de orientação mais alto incentiva o modelo a gerar imagens fortemente ligadas ao prompt de texto, em detrimento de uma menor qualidade de imagem.

model (`str`, *opcional*) : O modelo a ser usado para inferência. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Este parâmetro substitui o modelo definido no nível da instância. O valor padrão é None.

target_size (`ImageToImageTargetSize`, *opcional*) : O tamanho em pixels da imagem de saída. Este parâmetro é suportado apenas por alguns provedores e para modelos específicos. Ele será ignorado quando não for suportado.

**Retorna:** `Image`

A imagem traduzida.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Realize a tradução de imagem para imagem usando um modelo especificado.

> [!WARNING]
> Você deve ter o `PIL` instalado se quiser trabalhar com imagens (`pip install Pillow`).

Exemplo:
```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[[huggingface_hub.InferenceClient.image_to_text]]

```python
image_to_text(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1432)

**Parâmetros:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : A imagem de entrada para a legenda. Pode ser bytes brutos, um arquivo de imagem, uma URL para uma imagem online ou uma imagem PIL.

model (`str`, *opcional*) : O modelo a ser usado para inferência. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Este parâmetro substitui o modelo definido no nível da instância. O valor padrão é None.

**Retorna:** [ImageToTextOutput](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ImageToTextOutput)

O texto gerado.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Recebe uma imagem de entrada e retorna texto.

Os modelos podem ter saídas muito diferentes dependendo do seu caso de uso (legendagem de imagens, reconhecimento óptico de caracteres (OCR), Pix2Struct, etc.). Consulte o cartão do modelo para saber mais sobre as especificidades de um modelo.

Exemplo:
```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[[huggingface_hub.InferenceClient.image_to_video]]

```python
image_to_video(image: typing.Union[bytes, typing.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)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1353)

**Parâmetros:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : A imagem de entrada para gerar um vídeo. Pode ser bytes brutos, um arquivo de imagem, uma URL para uma imagem online ou uma imagem PIL.

model (`str`, *opcional*) : O modelo a ser usado para inferência. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Este parâmetro substitui o modelo definido no nível da instância. O valor padrão é None.

prompt (`str`, *opcional*) : O prompt de texto para orientar a geração do vídeo.

negative_prompt (`str`, *opcional*) : Um prompt para orientar o que NÃO incluir na geração de vídeo.

num_frames (`float`, *opcional*) : O parâmetro num_frames determina quantos quadros de vídeo são gerados.

num_inference_steps (`int`, *opcional*) : Para modelos de difusão. O número de etapas de desruidamento. Mais etapas de desruidamento geralmente resultam em uma imagem de maior qualidade, às custas de uma inferência mais lenta.

guidance_scale (`float`, *opcional*) : Para modelos de difusão. Um valor de escala de orientação mais alto incentiva o modelo a gerar vídeos estreitamente ligados ao prompt de texto, em detrimento de uma menor qualidade de imagem.

seed (`int`, *opcional*) : A semente a ser usada para a geração do vídeo.

target_size (`ImageToVideoTargetSize`, *opcional*) : O tamanho, em pixels, dos quadros do vídeo de saída.

num_inference_steps (`int`, *opcional*) : O número de etapas de remoção de ruído. Mais etapas de remoção de ruído geralmente resultam em um vídeo de maior qualidade, em detrimento de uma inferência mais lenta.

seed (`int`, *opcional*) : Semente para o gerador de números aleatórios.

**Retorna:** `bytes`

O vídeo gerado.

Gere um vídeo a partir de uma imagem de entrada.

Exemplos:
```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[[huggingface_hub.InferenceClient.object_detection]]

```python
object_detection(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None, threshold: float | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1478)

**Parâmetros:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : A imagem na qual detectar objetos. Pode ser bytes brutos, um arquivo de imagem, uma URL para uma imagem online ou uma imagem PIL.

model (`str`, *opcional*) : O modelo a ser usado para detecção de objetos. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo recomendado por padrão para detecção de objetos (DETR) será utilizado.

threshold (`float`, *opcional*) : A probabilidade necessária para fazer uma previsão.

**Retorna:** `list[ObjectDetectionOutputElement]`

Uma lista de itens [ObjectDetectionOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ObjectDetectionOutputElement) contendo as caixas delimitadoras e os atributos associados.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError` ou ``ValueError``

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.
- ``ValueError`` -- Se a saída da solicitação não for uma List.

Realize a detecção de objetos na imagem fornecida usando o modelo especificado.

> [!WARNING]
> Você deve ter o `PIL` instalado se quiser trabalhar com imagens (`pip install Pillow`).

Exemplo:
```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[[huggingface_hub.InferenceClient.question_answering]]

```python
question_answering(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)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1526)

**Parâmetros:**

question (`str`) : Pergunta a ser respondida.

context (`str`) : O contexto da pergunta.

model (`str`) : O modelo a ser usado para a tarefa de resposta a perguntas. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado.

align_to_words (`bool`, *opcional*) : Tenta alinhar a resposta a palavras reais. Melhora a qualidade em idiomas separados por espaços. Pode prejudicar em idiomas não separados por espaços (como japonês ou chinês)

doc_stride (`int`, *opcional*) : Se o contexto for longo demais para caber junto com a pergunta para o modelo, ele será dividido em vários blocos com alguma sobreposição. Este argumento controla o tamanho dessa sobreposição.

handle_impossible_answer (`bool`, *opcional*) : Se deve aceitar "impossível" como resposta.

max_answer_len (`int`, *opcional*) : O comprimento máximo das respostas previstas (por exemplo, apenas respostas com comprimento menor são consideradas).

max_question_len (`int`, *opcional*) : O comprimento máximo da pergunta após a tokenização. Será truncado, se necessário.

max_seq_len (`int`, *opcional*) : O comprimento máximo da frase total (contexto + pergunta) em tokens de cada bloco passado ao modelo. O contexto será dividido em vários blocos (usando docStride como sobreposição), se necessário.

top_k (`int`, *opcional*) : O número de respostas a serem retornadas (serão escolhidas pela ordem de probabilidade). Observe que retornamos menos respostas do que topk se não houver opções suficientes disponíveis no contexto.

**Retorna:** Union[`QuestionAnsweringOutputElement`, list[QuestionAnsweringOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.QuestionAnsweringOutputElement)]

Quando `top_k` é 1 ou não é fornecido, retorna um único `QuestionAnsweringOutputElement`. Quando `top_k` é maior que 1, retorna uma lista de `QuestionAnsweringOutputElement`.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Obter a resposta para uma pergunta a partir de um texto fornecido.

Exemplo:
```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[[huggingface_hub.InferenceClient.sentence_similarity]]

```python
sentence_similarity(sentence: str, other_sentences: list, model: str | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1610)

**Parâmetros:**

sentence (`str`) : A frase principal para comparação com as outras.

other_sentences (`list[str]`) : A lista de frases para comparação.

model (`str`, *opcional*) : O modelo a ser usado para a tarefa de similaridade de sentenças. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de similaridade de sentenças recomendado por padrão será usado. Padrão: None.

**Retorna:** `list[float]`

O embedding que representa o texto de entrada.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Calcule a similaridade semântica entre uma frase e uma lista de outras frases comparando seus embeddings.

Exemplo:
```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]
```

#### sumarização[[huggingface_hub.InferenceClient.summarization]]

```python
summarization(text: str, model: str | None = None, clean_up_tokenization_spaces: bool | None = None, generate_parameters: dict[str, typing.Any] | None = None, truncation: typing.Optional[ForwardRef('SummarizationTruncationStrategy')] = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1663)

**Parâmetros:**

text (`str`) : O texto de entrada a ser resumido.

model (`str`, *opcional*) : O modelo a ser usado para inferência. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo recomendado por padrão para sumarização será utilizado.

clean_up_tokenization_spaces (`bool`, *opcional*) : Se deve limpar os espaços extras potenciais na saída de texto.

generate_parameters (`dict[str, Any]`, *opcional*) : Parametrização adicional do algoritmo de geração de texto.

truncation (`"SummarizationTruncationStrategy"`, *opcional*) : A estratégia de truncamento a ser utilizada.

**Retorna:** [SummarizationOutput](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.SummarizationOutput)

O texto do resumo gerado.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Gere um resumo de um texto específico usando um modelo designado.

Exemplo:
```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[[huggingface_hub.InferenceClient.table_question_answering]]

```python
table_question_answering(table: dict, query: str, model: str | None = None, padding: typing.Optional[ForwardRef('Padding')] = None, sequential: bool | None = None, truncation: bool | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1721)

**Parâmetros:**

table (`str`) : Uma tabela de dados representada como um dict de listas, em que as entradas são os cabeçalhos e as listas contêm todos os valores; todas as listas devem ter o mesmo tamanho.

query (`str`) : A consulta em texto simples que você deseja fazer à tabela.

model (`str`) : O modelo a ser usado para a tarefa de resposta a perguntas sobre tabelas. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado.

padding (`"Padding"`, *opcional*) : Ativa e controla o preenchimento.

sequential (`bool`, *opcional*) : Se a inferência deve ser feita sequencialmente ou em lote. O processamento em lote é mais rápido, mas modelos como SQA exigem que a inferência seja realizada sequencialmente para extrair relações dentro das sequências, dada sua natureza conversacional.

truncation (`bool`, *opcional*) : Ativa e controla a truncagem.

**Retorna:** [TableQuestionAnsweringOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.TableQuestionAnsweringOutputElement)

uma saída de question answering de tabela contendo a resposta, as coordenadas, as células e o agregador utilizado.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Obter a resposta para uma pergunta a partir de informações fornecidas em uma tabela.

Exemplo:
```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[[huggingface_hub.InferenceClient.tabular_classification]]

```python
tabular_classification(table: dict, model: str | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1783)

**Parâmetros:**

table (`dict[str, Any]`) : Conjunto de atributos a classificar.

model (`str`, *opcional*) : O modelo a ser usado para a tarefa de classificação tabular. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de classificação tabular recomendado por padrão será usado. Padrão: None.

**Retorna:** `List`

uma lista de rótulos, um para cada linha na tabela inicial.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Classificar uma categoria-alvo (um grupo) com base em um conjunto de atributos.

Exemplo:
```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[[huggingface_hub.InferenceClient.tabular_regression]]

```python
tabular_regression(table: dict, model: str | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1838)

**Parâmetros:**

table (`dict[str, Any]`) : Conjunto de atributos armazenados em uma tabela. Os atributos usados para prever o alvo podem ser numéricos e categóricos.

model (`str`, *opcional*) : O modelo a ser usado para a tarefa de regressão tabular. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de regressão tabular recomendado por padrão será usado. Padrão: None.

**Retorna:** `List`

uma lista de valores numéricos de alvo previstos.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Prever um valor numérico de destino dado um conjunto de atributos/recursos em uma tabela.

Exemplo:
```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[[huggingface_hub.InferenceClient.text_classification]]

```python
text_classification(text: str, model: str | None = None, top_k: int | None = None, function_to_apply: typing.Optional[ForwardRef('TextClassificationOutputTransform')] = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1888)

**Parâmetros:**

text (`str`) : Uma string a ser classificada.

model (`str`, *opcional*) : O modelo a ser usado para a tarefa de classificação de texto. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de classificação de texto recomendado por padrão será usado. Padrão: None.

top_k (`int`, *opcional*) : Quando especificado, limita a saída às K classes mais prováveis.

function_to_apply (`"TextClassificationOutputTransform"`, *opcional*) : A função a ser aplicada às saídas do modelo para recuperar as pontuações.

**Retorna:** `list[TextClassificationOutputElement]`

uma lista de itens [TextClassificationOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.TextClassificationOutputElement) contendo o rótulo previsto e a probabilidade associada.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Realize a classificação de texto (por exemplo, análise de sentimento) no texto fornecido.

Exemplo:
```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[[huggingface_hub.InferenceClient.text_generation]]

```python
text_generation(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, 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)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L2091)

**Parâmetros:**

prompt (`str`) : Texto de entrada.

details (`bool`, *opcional*) : Por padrão, text_generation retorna uma string. Passe `details=True` se você quiser uma saída detalhada (tokens, probabilidades, seed, motivo de término, etc.). Disponível apenas para modelos executados com o backend `text-generation-inference`.

stream (`bool`, *opcional*) : Por padrão, text_generation retorna o texto gerado completo. Passe `stream=True` se você quiser que um fluxo de tokens seja retornado. Disponível apenas para modelos executados com o backend `text-generation-inference`.

model (`str`, *opcional*) : O modelo a ser usado para inferência. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Este parâmetro substitui o modelo definido no nível da instância. O valor padrão é None.

adapter_id (`str`, *opcional*) : id do adaptador Lora.

best_of (`int`, *opcional*) : Gera sequências de best_of e retorna a que possui os logprobs de tokens mais altos.

decoder_input_details (`bool`, *opcional*) : Retorna os logprobs e os ids dos tokens de entrada do decodificador. Você deve definir `details=True` também para que seja considerado. O padrão é `False`.

do_sample (`bool`, *opcional*) : Ativar a amostragem de logits

frequency_penalty (`float`, *opcional*) : Número entre -2,0 e 2,0. Valores positivos penalizam novos tokens com base na sua frequência existente no texto até o momento, diminuindo a probabilidade do modelo de repetir a mesma linha literalmente.

grammar ([TextGenerationInputGrammarType](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.TextGenerationInputGrammarType), *opcional*) : Restrições de gramática. Pode ser um JSONSchema ou uma regex.

max_new_tokens (`int`, *opcional*) : Número máximo de tokens gerados. O valor padrão é 100.

repetition_penalty (`float`, *opcional*) : O parâmetro para a penalidade de repetição. 1.0 significa sem penalidade. Veja [este artigo](https://arxiv.org/pdf/1909.05858.pdf) para mais detalhes.

return_full_text (`bool`, *opcional*) : Se deve anteceder o prompt ao texto gerado

seed (`int`, *opcional*) : Semente para amostragem aleatória

stop (`list[str]`, *opcional*) : Pare de gerar tokens se um membro de `stop` for gerado.

temperature (`float`, *opcional*) : O valor usado para modular a distribuição de logits.

top_n_tokens (`int`, *opcional*) : Retorna informações sobre os `top_n_tokens` tokens mais prováveis em cada etapa de geração, em vez de apenas o token amostrado.

top_k (`int`, *opcional`) : O número de tokens de vocabulário com maior probabilidade a serem mantidos para a filtragem top-k.

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`, *opcional`) : Trunca os tokens de entrada para o tamanho especificado.

typical_p (`float`, *opcional`) : Massa típica de Decoding. Consulte [Decoding Típico para Geração de Linguagem Natural](https://arxiv.org/abs/2202.00666) para mais informações

watermark (`bool`, *opcional*) : Marca d'água com [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226)

**Retorna:** `Union[str, TextGenerationOutput, Iterable[str], Iterable[TextGenerationStreamOutput]]`

Texto gerado retornado pelo servidor:
- se `stream=False` e `details=False`, o texto gerado é retornado como `str` (padrão)
- se `stream=True` e `details=False`, o texto gerado é retornado token por token como um `Iterable[str]`
- se `stream=False` e `details=True`, o texto gerado é retornado com mais detalhes como um [TextGenerationOutput](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.TextGenerationOutput)
- se `details=True` e `stream=True`, o texto gerado é retornado token por token como um iterável de [TextGenerationStreamOutput](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.TextGenerationStreamOutput)

**Exceções:** ``ValidationError`` ou [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- ``ValidationError`` -- Se os valores de entrada não forem válidos. Nenhuma chamada HTTP é feita ao servidor.
- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Dado um prompt, gere o texto a seguir.

> [!TIP]
> Se você deseja gerar uma resposta a partir de mensagens de chat, deve usar o método [InferenceClient.chat_completion()](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceClient.chat_completion). Ele aceita uma lista de mensagens em vez de um único prompt de texto e trata o modelamento de chat para você.

Exemplo:
```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[[huggingface_hub.InferenceClient.text_to_image]]

```python
text_to_image(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)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L2418)

**Parâmetros:**

prompt (`str`) : O prompt para gerar uma imagem.

negative_prompt (`str`, *opcional*) : Um prompt para orientar o que NÃO incluir na geração de imagem.

height (`int`, *opcional*) : A altura em pixels da imagem de saída

width (`int`, *opcional*) : A largura em pixels da imagem de saída

num_inference_steps (`int`, *opcional*) : O número de etapas de desruido. Mais etapas de desruido geralmente resultam em uma imagem de maior qualidade, em detrimento de uma inferência mais lenta.

guidance_scale (`float`, *opcional*) : Um valor mais alto de escala de orientação incentiva o modelo a gerar imagens fortemente ligadas ao prompt de texto, mas valores muito altos podem causar saturação e outros artefatos.

model (`str`, *opcional*) : O modelo a ser usado para inferência. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de texto para imagem recomendado por padrão será usado. Padrão: None.

scheduler (`str`, *opcional*) : Substitui o agendador por um compatível.

seed (`int`, *opcional*) : Semente para o gerador de números aleatórios.

extra_body (`dict[str, Any]`, *opcional*) : Parâmetros adicionais específicos do provedor para passar ao modelo. Consulte a documentação do provedor para os parâmetros suportados.

**Retorna:** `Image`

A imagem gerada.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Gere uma imagem com base em um texto fornecido usando um modelo especificado.

> [!WARNING]
> Você deve ter o `PIL` instalado se quiser trabalhar com imagens (`pip install Pillow`).

> [!TIP]
> Você pode passar parâmetros específicos do provedor para o modelo usando o argumento `extra_body`.

Exemplo:
```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")
```

Exemplo usando um provedor de terceiros diretamente. O uso será cobrado na sua conta do fal.ai.

```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")
```

Exemplo usando um provedor de terceiros por meio do Hugging Face Routing. O uso será cobrado na sua conta do Hugging Face.

```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")
```

Exemplo usando o provedor Replicate com parâmetros extras

```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[[huggingface_hub.InferenceClient.text_to_speech]]

```python
text_to_speech(text: str, model: str | None = None, do_sample: bool | None = None, early_stopping: typing.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)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L2655)

**Parâmetros:**

text (`str`) : O texto a ser sintetizado.

model (`str`, *opcional*) : O modelo a ser usado para inferência. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de texto para fala recomendado por padrão será usado. Padrão: None.

do_sample (`bool`, *opcional*) : Se deve usar amostragem em vez de decodificação gulosa ao gerar novos tokens.

early_stopping (`Union[bool, "TextToSpeechEarlyStoppingEnum"]`, *opcional*) : Controla a condição de parada para métodos baseados em beam.

epsilon_cutoff (`float`, *opcional*) : Se definido como um float estritamente entre 0 e 1, apenas tokens com probabilidade condicional maior que epsilon_cutoff serão amostrados. No artigo, os valores sugeridos variam de 3e-4 a 9e-4, dependendo do tamanho do modelo. Consulte [Truncation Sampling as Language Model Desmoothing](https://hf.co/papers/2210.15191) para mais detalhes.

eta_cutoff (`float`, *opcional*) : A amostragem Eta é um híbrido da amostragem localmente típica e da amostragem epsilon. Se definido como um float estritamente entre 0 e 1, um token é considerado apenas se for maior que eta_cutoff ou sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits))). O segundo termo é, intuitivamente, a probabilidade esperada do próximo token, escalada por sqrt(eta_cutoff). No artigo, os valores sugeridos variam de 3e-4 a 2e-3, dependendo do tamanho do modelo. Consulte [Truncation Sampling as Language Model Desmoothing](https://hf.co/papers/2210.15191) para mais detalhes.

max_length (`int`, *opcional*) : O comprimento máximo (em tokens) do texto gerado, incluindo a entrada.

max_new_tokens (`int`, *opcional*) : O número máximo de tokens a serem gerados. Tem precedência sobre max_length.

min_length (`int`, *opcional*) : O comprimento mínimo (em tokens) do texto gerado, incluindo a entrada.

min_new_tokens (`int`, *opcional*) : O número mínimo de tokens a serem gerados. Tem precedência sobre min_length.

num_beam_groups (`int`, *opcional*) : Número de grupos para dividir num_beams, a fim de garantir diversidade entre diferentes grupos de feixes. Consulte [este artigo](https://hf.co/papers/1610.02424) para mais detalhes.

num_beams (`int`, *opcional*) : Número de feixes a serem usados para a busca por feixes.

penalty_alpha (`float`, *opcional*) : O valor equilibra a confiança do modelo e a penalidade de degeneração na decodificação de busca contrastiva.

temperature (`float`, *opcional*) : O valor usado para modular as probabilidades do próximo token.

top_k (`int`, *opcional*) : O número de tokens do vocabulário com maior probabilidade a serem mantidos para a filtragem top-k.

top_p (`float`, *opcional*) : Se definido como float < 1, apenas o menor conjunto de tokens mais prováveis, cujas probabilidades somadas sejam iguais ou superiores a top_p, é mantido para a geração.

typical_p (`float`, *opcional*) : A tipicidade local mede o quão semelhante é a probabilidade condicional de prever o próximo token alvo à probabilidade condicional esperada de prever um token aleatório a seguir, dado o texto parcial já gerado. Se definido como float < 1, o menor conjunto dos tokens mais localmente típicos, cujas probabilidades somem typical_p ou mais, é mantido para a geração. Veja [este artigo](https://hf.co/papers/2202.00666) para mais detalhes.

use_cache (`bool`, *opcional*) : Se o modelo deve usar as atenções de chaves/valores do passado para acelerar a decodificação

extra_body (`dict[str, Any]`, *opcional*) : Parâmetros adicionais específicos do provedor para passar ao modelo. Consulte a documentação do provedor para os parâmetros suportados.

**Retorna:** `bytes`

O áudio gerado.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Sintetize um áudio de uma voz pronunciando um texto dado.

> [!TIP]
> Você pode passar parâmetros específicos do provedor para o modelo usando o argumento `extra_body`.

Exemplo:
```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)
```

Exemplo usando um provedor de terceiros diretamente. O uso será cobrado na sua conta do Replicate.

```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)
```

Exemplo usando um provedor de terceiros por meio do Hugging Face Routing. O uso será cobrado na sua conta do Hugging Face.

```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)
```

Exemplo usando o provedor Replicate com parâmetros extras

```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)
```

Exemplo de geração de música usando "YuE-s1-7B-anneal-en-cot" no 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[[huggingface_hub.InferenceClient.text_to_video]]

```python
text_to_video(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)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L2558)

**Parâmetros:**

prompt (`str`) : O prompt para gerar um vídeo.

model (`str`, *opcional*) : O modelo a ser usado para inferência. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de texto para vídeo recomendado por padrão será usado. Padrão: None.

guidance_scale (`float`, *opcional*) : Um valor mais alto de escala de orientação incentiva o modelo a gerar vídeos estreitamente ligados ao prompt de texto, mas valores muito altos podem causar saturação e outros artefatos.

negative_prompt (`list[str]`, *opcional*) : Um ou vários prompts para orientar o que NÃO incluir na geração de vídeo.

num_frames (`float`, *opcional*) : O parâmetro num_frames determina quantos quadros de vídeo são gerados.

num_inference_steps (`int`, *opcional*) : O número de etapas de remoção de ruído. Mais etapas de remoção de ruído geralmente resultam em um vídeo de maior qualidade, em detrimento de uma inferência mais lenta.

seed (`int`, *opcional*) : Semente para o gerador de números aleatórios.

extra_body (`dict[str, Any]`, *opcional*) : Parâmetros adicionais específicos do provedor para passar ao modelo. Consulte a documentação do provedor para os parâmetros suportados.

**Retorna:** `bytes`

O vídeo gerado.

Gere um vídeo com base em um texto fornecido.

> [!TIP]
> Você pode passar parâmetros específicos do provedor para o modelo usando o argumento `extra_body`.

Exemplo:

Exemplo usando um provedor de terceiros diretamente. O uso será cobrado na sua conta do fal.ai.

```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)
```

Exemplo usando um provedor de terceiros por meio do Hugging Face Routing. O uso será cobrado na sua conta do Hugging Face.

```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[[huggingface_hub.InferenceClient.token_classification]]

```python
token_classification(text: str, model: str | None = None, aggregation_strategy: typing.Optional[ForwardRef('TokenClassificationAggregationStrategy')] = None, ignore_labels: list[str] | None = None, stride: int | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L2863)

**Parâmetros:**

text (`str`) : Uma string a ser classificada.

model (`str`, *opcional*) : O modelo a ser usado para a tarefa de classificação de tokens. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de classificação de tokens recomendado por padrão será usado. Padrão: None.

aggregation_strategy (`"TokenClassificationAggregationStrategy"`, *opcional*) : A estratégia usada para fundir tokens com base nas previsões do modelo

ignore_labels (`list[str`, *optional*) : Uma lista de rótulos para ignorar

stride (`int`, *opcional*) : O número de tokens sobrepostos entre os blocos ao dividir o texto de entrada.

**Retorna:** `list[TokenClassificationOutputElement]`

Lista de itens [TokenClassificationOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.TokenClassificationOutputElement) contendo o grupo de entidade, a pontuação de confiança, a palavra e os índices de início e fim.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Realize a classificação de tokens no texto fornecido. Geralmente usado para análise de sentenças, seja gramatical, seja Reconhecimento de Entidades Nomeadas (NER), para entender as palavras-chave contidas no texto.

Exemplo:
```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,
    )
]
```

#### tradução[[huggingface_hub.InferenceClient.translation]]

```python
translation(text: str, model: str | None = None, src_lang: str | None = None, tgt_lang: str | None = None, clean_up_tokenization_spaces: bool | None = None, truncation: typing.Optional[ForwardRef('TranslationTruncationStrategy')] = None, generate_parameters: dict[str, typing.Any] | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L2938)

**Parâmetros:**

text (`str`) : Uma string a ser traduzida.

model (`str`, *opcional*) : O modelo a ser usado para a tarefa de tradução. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de tradução recomendado por padrão será usado. Padrão: None.

src_lang (`str`, *opcional*) : O idioma de origem do texto. Obrigatório para modelos que podem traduzir de vários idiomas.

tgt_lang (`str`, *opcional*) : Idioma de destino para a tradução. Obrigatório para modelos que podem traduzir para vários idiomas.

clean_up_tokenization_spaces (`bool`, *opcional*) : Se deve limpar os espaços extras potenciais na saída de texto.

truncation (`"TranslationTruncationStrategy"`, *opcional*) : A estratégia de truncamento a ser utilizada.

generate_parameters (`dict[str, Any]`, *opcional*) : Parametrização adicional do algoritmo de geração de texto.

**Retorna:** [TranslationOutput](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.TranslationOutput)

O texto traduzido gerado.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError` ou ``ValueError``

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.
- ``ValueError`` -- Se apenas um dos argumentos `src_lang` e `tgt_lang` for fornecido.

Converta texto de um idioma para outro.

Confira https://huggingface.co/tasks/translation para mais informações sobre como escolher o melhor modelo para o seu caso de uso específico. Os idiomas de origem e de destino geralmente dependem do modelo. No entanto, é possível especificar os idiomas de origem e de destino para determinados modelos. Se você estiver trabalhando com um desses modelos, pode usar os argumentos `src_lang` e `tgt_lang` para passar as informações relevantes.

Exemplo:
```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.')
```

Especificando idiomas:
```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[[huggingface_hub.InferenceClient.visual_question_answering]]

```python
visual_question_answering(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], question: str, model: str | None = None, top_k: int | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L3027)

**Parâmetros:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : A imagem de entrada para o contexto. Pode ser bytes brutos, um arquivo de imagem, uma URL para uma imagem online ou uma imagem PIL.

question (`str`) : Pergunta a ser respondida.

model (`str`, *opcional*) : O modelo a ser usado para a tarefa de resposta a perguntas visuais. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de resposta a perguntas visuais recomendado por padrão será usado. Padrão: None.

top_k (`int`, *opcional*) : O número de respostas a serem retornadas (serão escolhidas pela ordem de probabilidade). Observe que retornamos menos respostas do que topk se não houver opções suficientes disponíveis no contexto.

**Retorna:** `list[VisualQuestionAnsweringOutputElement]`

uma lista de itens [VisualQuestionAnsweringOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.VisualQuestionAnsweringOutputElement) contendo o rótulo previsto e a probabilidade associada.

**Exceções:** ``InferenceTimeoutError`` ou `HfHubHTTPError`

- ``InferenceTimeoutError`` -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Responder a perguntas abertas com base em uma imagem.

Exemplo:
```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[[huggingface_hub.InferenceClient.zero_shot_classification]]

```python
zero_shot_classification(text: str, candidate_labels: list, multi_label: bool | None = False, hypothesis_template: str | None = None, model: str | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L3086)

**Parâmetros:**

text (`str`) : O texto de entrada a ser classificado.

candidate_labels (`list[str]`) : O conjunto de rótulos de classe possíveis para classificar o texto.

multi_label (`bool`, *opcional*) : Se múltiplos rótulos candidatos podem ser verdadeiros. Se for falso, as pontuações são normalizadas de modo que a soma das probabilidades dos rótulos para cada sequência seja 1. Se for verdadeiro, os rótulos são considerados independentes e as probabilidades são normalizadas para cada candidato.

hypothesis_template (`str`, *opcional*) : A frase usada em conjunto com `candidate_labels` para tentar a classificação de texto, substituindo o placeholder pelos rótulos candidatos.

model (`str`, *opcional*) : O modelo a ser usado para inferência. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Este parâmetro substitui o modelo definido no nível da instância. Se não for fornecido, o modelo de classificação zero-shot recomendado por padrão será usado.

**Retorna:** `list[ZeroShotClassificationOutputElement]`

Lista de itens [ZeroShotClassificationOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ZeroShotClassificationOutputElement) contendo os rótulos previstos e sua confiança.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Forneça como entrada um texto e um conjunto de rótulos candidatos para classificar o texto de entrada.

Exemplo com `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),
]
```

Exemplo com `multi_label=True` e um `hypothesis_template` personalizado:
```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.",
...    candidate_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[[huggingface_hub.InferenceClient.zero_shot_image_classification]]

```python
zero_shot_image_classification(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], candidate_labels: list, model: str | None = None, hypothesis_template: str | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L3187)

**Parâmetros:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : A imagem de entrada para a legenda. Pode ser bytes brutos, um arquivo de imagem, uma URL para uma imagem online ou uma imagem PIL.

candidate_labels (`list[str]`) : Os rótulos candidatos para esta imagem

model (`str`, *opcional*) : O modelo a ser usado para inferência. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Este parâmetro substitui o modelo definido no nível da instância. Se não for fornecido, o modelo de classificação de imagem zero-shot recomendado por padrão será usado.

hypothesis_template (`str`, *opcional*) : A frase usada em conjunto com `candidate_labels` para tentar a classificação de imagem substituindo o placeholder pelos rótulos candidatos.

**Retorna:** `list[ZeroShotImageClassificationOutputElement]`

Lista de itens [ZeroShotImageClassificationOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ZeroShotImageClassificationOutputElement) contendo os rótulos previstos e sua confiança.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Forneça uma imagem de entrada e rótulos de texto para prever os rótulos de texto da imagem.

Exemplo:
```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",
...     candidate_labels=["dog", "cat", "horse"],
... )
[ZeroShotImageClassificationOutputElement(label='dog', score=0.956),...]
```

## Cliente de Inferência Assíncrona[[huggingface_hub.AsyncInferenceClient]]

Também é fornecida uma versão assíncrona do cliente, baseada em `asyncio` e `httpx2`.

#### huggingface_hub.AsyncInferenceClient[[huggingface_hub.AsyncInferenceClient]]

```python
huggingface_hub.AsyncInferenceClient(model: str | None = None, provider: typing.Union[typing.Literal['baseten', 'cerebras', 'cohere', 'deepinfra', 'fal-ai', 'featherless-ai', 'fireworks-ai', 'groq', 'hf-inference', 'novita', 'nscale', 'openai', 'ovhcloud', 'publicai', 'replicate', 'scaleway', 'together', 'wavespeed', 'zai-org'], typing.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)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L112)

**Parâmetros:**

model (`str`, `optional`) : O modelo para executar a inferência. Pode ser um id de modelo hospedado no Hugging Face Hub, por exemplo `meta-llama/Meta-Llama-3-8B-Instruct`, ou uma URL para um Inference Endpoint implantado. O padrão é None, caso em que um modelo recomendado é selecionado automaticamente para a tarefa. Observação: para melhor compatibilidade com o cliente da OpenAI, `model` foi aliasado como `base_url`. Esses 2 argumentos são mutuamente exclusivos. Se uma URL for passada como `model` ou `base_url` para chat completion, o sufixo de caminho `(/v1)/chat/completions` será anexado à URL.

provider (`str`, *opcional*) : Nome do provedor a ser usado para inferência. Pode ser `"baseten"`, `"cerebras"`, `"cohere"`, `"deepinfra"`, `"fal-ai"`, `"featherless-ai"`, `"fireworks-ai"`, `"groq"`, `"hf-inference"`, `"novita"`, `"nscale"`, `"openai"`, `"ovhcloud"`, `"publicai"`, `"replicate"`, `"scaleway"`, `"together"`, `"wavespeed"` ou `"zai-org"`. O padrão é "auto": roteamento automático, que por padrão usa o provedor "fastest"; você pode alternar para a ordem de provedores "cheapest" ou "preferred" em https://hf.co/settings/inference-providers. Se o modelo for uma URL ou `base_url` for passado, então `provider` não é usado.

token (`str`, *opcional*) : token do Hugging Face. Se não for fornecido, será usado o token salvo localmente. Observação: para melhor compatibilidade com o cliente da OpenAI, `token` foi aliasado como `api_key`. Esses 2 argumentos são mutuamente exclusivos e têm exatamente o mesmo comportamento.

timeout (`float`, `optional`) : O número máximo de segundos para aguardar uma resposta do servidor. O padrão é None, o que significa que o loop continuará até que o servidor esteja disponível.

headers (`dict[str, str]`, `optional`) : Cabeçalhos adicionais para enviar ao servidor. Por padrão, apenas os cabeçalhos de autorização e user-agent são enviados. Os valores neste dicionário substituirão os valores padrão.

bill_to (`str`, `optional`) : A conta de faturamento a ser usada para as solicitações. Por padrão, as solicitações são faturadas na conta do usuário. As solicitações só podem ser faturadas para uma organização da qual o usuário é membro e que tenha assinado o Enterprise Hub.

cookies (`dict[str, str]`, `optional`) : Cookies adicionais para enviar ao servidor.

base_url (`str`, `optional`) : URL base para executar inferência. Este é um argumento duplicado de `model` para fazer o [InferenceClient](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceClient) seguir o mesmo padrão do cliente `openai.OpenAI`. Não pode ser usado se `model` estiver definido. Padrão: None.

api_key (`str`, `optional`) : Token a ser usado para autenticação. Este é um argumento duplicado de `token` para fazer o [InferenceClient](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceClient) seguir o mesmo padrão do cliente `openai.OpenAI`. Não pode ser usado se `token` estiver definido. Padrão: None.

Inicialize um novo Inference Client.

O [InferenceClient](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceClient) visa fornecer uma experiência unificada para realizar inferência. O cliente pode ser usado de forma transparente com a API de Inferência (gratuita), Endpoints de Inferência auto-hospedados ou Provedores de Inferência de terceiros.

#### audio_classification[[huggingface_hub.AsyncInferenceClient.audio_classification]]

```python
audio_classification(audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None, top_k: int | None = None, function_to_apply: typing.Optional[ForwardRef('AudioClassificationOutputTransform')] = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L313)

**Parâmetros:**

audio (Union[str, Path, bytes, BinaryIO]) : O conteúdo de áudio a ser classificado. Pode ser bytes de áudio brutos, um arquivo de áudio local ou uma URL apontando para um arquivo de áudio.

model (`str`, *opcional*) : O modelo a ser usado para classificação de áudio. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo recomendado por padrão para classificação de áudio será utilizado.

top_k (`int`, *opcional*) : Quando especificado, limita a saída às K classes mais prováveis.

function_to_apply (`"AudioClassificationOutputTransform"`, *opcional*) : A função a ser aplicada às saídas do modelo para recuperar as pontuações.

**Retorna:** `list[AudioClassificationOutputElement]`

Lista de itens [AudioClassificationOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.AudioClassificationOutputElement) contendo os rótulos previstos e sua confiança.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Realize a classificação de áudio no conteúdo de áudio fornecido.

Exemplo:
```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'),
    ...
]
```

#### audio_to_audio[[huggingface_hub.AsyncInferenceClient.audio_to_audio]]

```python
audio_to_audio(audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L371)

**Parâmetros:**

audio (Union[str, Path, bytes, BinaryIO]) : O conteúdo de áudio para o modelo. Pode ser bytes de áudio brutos, um arquivo de áudio local ou uma URL apontando para um arquivo de áudio.

model (`str`, *opcional*) : O modelo pode ser qualquer modelo que receba um arquivo de áudio e retorne outro arquivo de áudio. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo recomendado por padrão para audio_to_audio será utilizado.

**Retorna:** `list[AudioToAudioOutputElement]`

Uma lista de itens [AudioToAudioOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.AudioToAudioOutputElement) contendo rótulo de áudio, tipo de conteúdo e conteúdo de áudio em blob.

**Exceções:** ``InferenceTimeoutError`` ou `HfHubHTTPError`

- ``InferenceTimeoutError`` -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Executa várias tarefas relacionadas a áudio-para-áudio, dependendo do modelo (por exemplo: aprimoramento de fala, separação de fontes).

Exemplo:
```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)
```

#### automatic_speech_recognition[[huggingface_hub.AsyncInferenceClient.automatic_speech_recognition]]

```python
automatic_speech_recognition(audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None, extra_body: dict | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L424)

**Parâmetros:**

audio (Union[str, Path, bytes, BinaryIO]) : O conteúdo a ser transcrito. Pode ser bytes de áudio brutos, um arquivo de áudio local ou uma URL para um arquivo de áudio.

model (`str`, *opcional*) : O modelo a ser usado para ASR. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo recomendado por padrão para ASR será utilizado.

extra_body (`dict`, *opcional*) : Parâmetros adicionais específicos do provedor para passar ao modelo. Consulte a documentação do provedor para os parâmetros suportados.

**Retorna:** [AutomaticSpeechRecognitionOutput](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.AutomaticSpeechRecognitionOutput)

Um item contendo o texto transcrito e, opcionalmente, os blocos de timestamp.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Execute o reconhecimento automático de fala (ASR ou áudio-para-texto) no conteúdo de áudio fornecido.

Exemplo:
```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"
```

#### chat_completion[[huggingface_hub.AsyncInferenceClient.chat_completion]]

```python
chat_completion(messages: list, 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: typing.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: typing.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)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L552)

**Parâmetros:**

messages (Lista de [ChatCompletionInputMessage](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ChatCompletionInputMessage)) : Histórico da conversa consistindo de pares de papéis e conteúdo.

model (`str`, *opcional*) : O modelo a ser usado para chat-completion. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo recomendado por padrão para geração de texto baseada em chat será utilizado. Veja https://huggingface.co/tasks/text-generation para mais detalhes. Se `model` for um ID de modelo, ele é passado ao servidor como o parâmetro `model`. Se você deseja definir uma URL personalizada enquanto configura `model` no payload da requisição, você deve definir `base_url` ao inicializar o [InferenceClient](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceClient).

frequency_penalty (`float`, *opcional*) : Penaliza novos tokens com base na sua frequência existente no texto até o momento. Intervalo: [-2,0, 2,0]. Padrão: 0,0.

logit_bias (`list[float]`, *opcional*) : Ajusta a probabilidade de tokens específicos aparecerem na saída gerada.

logprobs (`bool`, *opcional*) : Se deve retornar as probabilidades logarítmicas dos tokens de saída ou não. Se verdadeiro, retorna as probabilidades logarítmicas de cada token de saída retornado no conteúdo da mensagem.

max_tokens (`int`, *opcional*) : Número máximo de tokens permitidos na resposta. O valor padrão é 100.

n (`int`, *opcional*) : O número de complementações a serem geradas para cada prompt.

presence_penalty (`float`, *opcional*) : Número entre -2,0 e 2,0. Valores positivos penalizam novos tokens com base em sua ocorrência no texto até o momento, aumentando a probabilidade de o modelo abordar novos tópicos.

response_format (`ChatCompletionInputGrammarType()`, *opcional*) : Restrições de gramática. Pode ser um JSONSchema ou uma regex.

seed (Opcional`int`, *optional*) : Semente para fluxo de controle reproduzível. Padrão é None.

stop (`list[str]`, *opcional*) : Até quatro strings que acionam o fim da resposta. O padrão é None.

stream (`bool`, *opcional*) : Ativa o streaming em tempo real das respostas. O valor padrão é False.

stream_options ([ChatCompletionInputStreamOptions](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ChatCompletionInputStreamOptions), *opcional*) : Opções para streaming de completions.

temperature (`float`, *opcional*) : Controla a aleatoriedade das gerações. Valores menores garantem conclusões menos aleatórias. Intervalo: [0, 2]. Padrão: 1.0.

top_logprobs (`int`, *opcional*) : Um inteiro entre 0 e 5 que especifica o número de tokens mais prováveis a serem retornados em cada posição de token, cada um com uma probabilidade log associada. logprobs deve ser definido como true se este parâmetro for usado.

top_p (`float`, *opcional*) : Fração das próximas palavras mais prováveis a serem amostradas. Deve estar entre 0 e 1. O padrão é 1.0.

tool_choice ([ChatCompletionInputToolChoiceClass](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ChatCompletionInputToolChoiceClass) ou `ChatCompletionInputToolChoiceEnum()`, *opcional*) : A ferramenta a ser usada para a conclusão. O padrão é "auto".

tool_prompt (`str`, *opcional*) : Um prompt a ser adicionado antes das ferramentas.

tools (Lista de [ChatCompletionInputTool](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ChatCompletionInputTool), *opcional*) : Uma lista de ferramentas que o modelo pode chamar. Atualmente, apenas funções são suportadas como ferramenta. Use isso para fornecer uma lista de funções para as quais o modelo pode gerar entradas JSON.

extra_body (`dict`, *opcional*) : Parâmetros adicionais específicos do provedor para passar ao modelo. Consulte a documentação do provedor para os parâmetros suportados.

**Retorna:** [ChatCompletionOutput](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ChatCompletionOutput) ou um iterável de [ChatCompletionStreamOutput](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ChatCompletionStreamOutput)

Texto gerado retornado pelo servidor:
- se `stream=False`, o texto gerado é retornado como um [ChatCompletionOutput](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ChatCompletionOutput) (padrão).
- se `stream=True`, o texto gerado é retornado token por token como uma sequência de [ChatCompletionStreamOutput](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ChatCompletionStreamOutput).

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Um método para completar conversas usando um modelo de linguagem especificado.

> [!TIP]
> O método `client.chat_completion` é um alias de `client.chat.completions.create` para compatibilidade com o cliente da OpenAI. As entradas e saídas são estritamente as mesmas e o uso de qualquer uma das sintaxes produzirá os mesmos resultados. Consulte o [Guia de Inferência](https://huggingface.co/docs/huggingface_hub/guides/inference#openai-compatibility) para mais detalhes sobre a compatibilidade com a OpenAI.

> [!TIP]
> Você pode passar parâmetros específicos do provedor para o modelo usando o argumento `extra_body`.

Exemplo:

```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
    )
)
```

Exemplo usando 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)
```

Exemplo usando a sintaxe da OpenAI:
```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)
```

Exemplo de uso de um provedor de terceiros diretamente com parâmetros extras (específicos do provedor). O uso será cobrado na sua conta do Together AI.

```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"},
... )
```

Exemplo usando um provedor de terceiros por meio do Hugging Face Routing. O uso será cobrado na sua conta do Hugging Face.

```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?"}],
... )
```

Exemplo usando Imagem + Texto como entrada:
```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.
```

Exemplo usando ferramentas:
```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
)
```

Exemplo usando 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
'{

y": "bike ride",
": ["puppy", "cat", "raccoon"],
_seen": 3,
n": "park"}'
```

#### fechar[[huggingface_hub.AsyncInferenceClient.close]]

```python
close()
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L226)

Feche o cliente.

Este método é chamado automaticamente ao usar o cliente como um gerenciador de contexto.

#### document_question_answering[[huggingface_hub.AsyncInferenceClient.document_question_answering]]

```python
document_question_answering(image: typing.Union[bytes, typing.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)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L960)

**Parâmetros:**

image (`Union[str, Path, bytes, BinaryIO]`) : A imagem de entrada para o contexto. Pode ser bytes brutos, um arquivo de imagem ou uma URL para uma imagem online.

question (`str`) : Pergunta a ser respondida.

model (`str`, *opcional*) : O modelo a ser usado para a tarefa de question answering de documentos. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de question answering de documentos recomendado por padrão será usado. Padrão: None.

doc_stride (`int`, *opcional*) : Se as palavras do documento forem longas demais para caber junto com a pergunta para o modelo, elas serão divididas em vários blocos com alguma sobreposição. Este argumento controla o tamanho dessa sobreposição.

handle_impossible_answer (`bool`, *opcional*) : Se aceitar "impossível" como resposta

lang (`str`, *opcional*) : Idioma a ser usado durante a execução do OCR. O padrão é inglês.

max_answer_len (`int`, *opcional*) : O comprimento máximo das respostas previstas (por exemplo, apenas respostas com comprimento menor são consideradas).

max_question_len (`int`, *opcional*) : O comprimento máximo da pergunta após a tokenização. Será truncado, se necessário.

max_seq_len (`int`, *opcional*) : O comprimento máximo da frase total (contexto + pergunta) em tokens de cada bloco passado ao modelo. O contexto será dividido em vários blocos (usando doc_stride como sobreposição), se necessário.

top_k (`int`, *opcional*) : O número de respostas a retornar (será escolhido pela ordem de probabilidade). Pode retornar menos respostas do que top_k se não houver opções suficientes disponíveis no contexto.

word_boxes (`list[Union[list[float], str`, *opcional*) : Uma lista de palavras e caixas delimitadoras (normalizadas de 0->1000). Se fornecida, a inferência ignorará a etapa de OCR e usará as caixas delimitadoras fornecidas.

**Retorna:** `list[DocumentQuestionAnsweringOutputElement]`

uma lista de itens [DocumentQuestionAnsweringOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.DocumentQuestionAnsweringOutputElement) contendo o rótulo previsto, a probabilidade associada, os ids das palavras e o número da página.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Responda perguntas sobre imagens de documentos.

Exemplo:
```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)]
```

#### feature_extraction[[huggingface_hub.AsyncInferenceClient.feature_extraction]]

```python
feature_extraction(text: str | list[str], normalize: bool | None = None, prompt_name: str | None = None, truncate: bool | None = None, truncation_direction: typing.Optional[typing.Literal['left', 'right']] = None, dimensions: int | None = None, encoding_format: typing.Optional[typing.Literal['float', 'base64']] = None, model: str | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1048)

**Parâmetros:**

text (*str* ou *list[str]*) : O texto ou lista de textos para incorporar.

model (*str*, *opcional*) : O modelo a ser usado para a tarefa de extração de recursos. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de extração de recursos recomendado por padrão será usado. Padrão: None.

normalize (*bool*, *opcional*) : Se as embeddings devem ser normalizadas ou não. Disponível apenas em servidores alimentados por Text-Embedding-Inference.

prompt_name (*str*, *opcional*) : O nome do prompt que deve ser usado para a codificação. Se não for definido, nenhum prompt será aplicado. Deve ser uma chave no dicionário *prompts* da configuração do *Sentence Transformers*. Por exemplo, se `prompt_name` for "query" e o `prompts` for &amp;lcub;"query": "query: ",...}, então a frase "What is the capital of France?" será codificada como "query: What is the capital of France?" porque o texto do prompt será adicionado antes de qualquer texto a ser codificado.

truncate (*bool*, *opcional*) : Se as embeddings devem ser truncadas ou não. Disponível apenas em servidores alimentados por Text-Embedding-Inference.

truncation_direction (*Literal["left", "right"]*, *opcional*) : Qual lado da entrada deve ser truncado quando *truncate=True* é passado.

dimensions (*int*, *opcional*) : O número de dimensões que as embeddings de saída resultantes devem ter. Disponível apenas em endpoints de embedding compatíveis com a OpenAI.

encoding_format (*Literal["float", "base64"]*, *opcional*) : O formato dos embeddings de saída. Pode ser "float" ou "base64". Disponível apenas em endpoints de embedding compatíveis com a OpenAI.

**Retorna:** `*np.ndarray*`

O embedding que representa o(s) texto(s) de entrada como um array numpy float32.

**Exceções:** [*InferenceTimeoutError*] ou [*HfHubHTTPError*]

- [*InferenceTimeoutError*] -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- [*HfHubHTTPError*] -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Gere embeddings para um texto ou lote de textos específico.

Exemplo:
```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)
```

#### fill_mask[[huggingface_hub.AsyncInferenceClient.fill_mask]]

```python
fill_mask(text: str, model: str | None = None, targets: list[str] | None = None, top_k: int | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1132)

**Parâmetros:**

text (`str`) : uma string para ser preenchida, deve conter o token [MASK] (verifique o cartão do modelo para o nome exato da máscara).

model (`str`, *opcional*) : O modelo a ser usado para a tarefa de preenchimento de máscara. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de preenchimento de máscara recomendado por padrão será usado.

targets (`list[str`, *optional*) : Quando fornecido, o modelo limitará as pontuações aos alvos passados, em vez de procurar em todo o vocabulário. Se os alvos fornecidos não estiverem no vocabulário do modelo, eles serão tokenizados e o primeiro token resultante será usado (com um aviso, e isso pode ser mais lento).

top_k (`int`, *opcional*) : Quando fornecido, substitui o número de previsões a serem retornadas.

**Retorna:** `list[FillMaskOutputElement]`

uma lista de itens [FillMaskOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.FillMaskOutputElement) contendo o rótulo previsto, a probabilidade associada, a referência do token e o texto completado.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Preencha um espaço com uma palavra ausente (mais precisamente, um token).

Exemplo:
```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.')
]
```

#### get_endpoint_info[[huggingface_hub.AsyncInferenceClient.get_endpoint_info]]

```python
get_endpoint_info(model: str | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L3302)

**Parâmetros:**

model (`str`, *opcional*) : O modelo a ser usado para inferência. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Este parâmetro substitui o modelo definido no nível da instância. O valor padrão é None.

**Retorna:** `dict[str, Any]`

Informações sobre o endpoint.

Obtenha informações sobre o endpoint implantado.

Este endpoint está disponível apenas em endpoints alimentados por Text-Generation-Inference (TGI) ou Text-Embedding-Inference (TEI). Endpoints alimentados por `transformers` retornam um payload vazio.

Exemplo:
```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'
}
```

#### health_check[[huggingface_hub.AsyncInferenceClient.health_check]]

```python
health_check(model: str | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L3362)

**Parâmetros:**

model (`str`, *opcional*) : URL do Inference Endpoint. Este parâmetro substitui o modelo definido no nível da instância. O valor padrão é None.

**Retorna:** `bool`

Verdadeiro se tudo estiver funcionando corretamente.

Verifique a saúde do endpoint implantado.

O Health check está disponível apenas com Inference Endpoints powered by Text-Generation-Inference (TGI) ou Text-Embedding-Inference (TEI).

Exemplo:
```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
```

#### image_classification[[huggingface_hub.AsyncInferenceClient.image_classification]]

```python
image_classification(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None, function_to_apply: typing.Optional[ForwardRef('ImageClassificationOutputTransform')] = None, top_k: int | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1189)

**Parâmetros:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : A imagem a ser classificada. Pode ser bytes brutos, um arquivo de imagem, uma URL para uma imagem online ou uma imagem PIL.

model (`str`, *opcional*) : O modelo a ser usado para classificação de imagens. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo recomendado por padrão para classificação de imagens será utilizado.

function_to_apply (`"ImageClassificationOutputTransform"`, *opcional*) : A função a ser aplicada às saídas do modelo para recuperar as pontuações.

top_k (`int`, *opcional*) : Quando especificado, limita a saída às K classes mais prováveis.

**Retorna:** `list[ImageClassificationOutputElement]`

uma lista de itens [ImageClassificationOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ImageClassificationOutputElement) contendo o rótulo previsto e a probabilidade associada.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Realize a classificação de imagem na imagem fornecida usando o modelo especificado.

Exemplo:
```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), ...]
```

#### image_segmentation[[huggingface_hub.AsyncInferenceClient.image_segmentation]]

```python
image_segmentation(image: typing.Union[bytes, typing.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: typing.Optional[ForwardRef('ImageSegmentationSubtask')] = None, threshold: float | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1240)

**Parâmetros:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : A imagem a ser segmentada. Pode ser bytes brutos, um arquivo de imagem, uma URL para uma imagem online ou uma imagem PIL.

model (`str`, *opcional*) : O modelo a ser usado para segmentação de imagem. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo recomendado por padrão para segmentação de imagem será utilizado.

mask_threshold (`float`, *opcional*) : Limiar a ser usado ao converter as máscaras previstas em valores binários.

overlap_mask_area_threshold (`float`, *opcional*) : Limiar de sobreposição de máscara para eliminar segmentos pequenos e desconectados.

subtask (`"ImageSegmentationSubtask"`, *opcional*) : Tarefa de segmentação a ser executada, dependendo das capacidades do modelo.

threshold (`float`, *opcional*) : Limiar de probabilidade para filtrar máscaras previstas.

**Retorna:** `list[ImageSegmentationOutputElement]`

Uma lista de itens [ImageSegmentationOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ImageSegmentationOutputElement) contendo as máscaras segmentadas e os atributos associados.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Realize a segmentação de imagem na imagem fornecida usando o modelo especificado.

> [!WARNING]
> Você deve ter o `PIL` instalado se quiser trabalhar com imagens (`pip install Pillow`).

Exemplo:
```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>), ...]
```

#### image_to_image[[huggingface_hub.AsyncInferenceClient.image_to_image]]

```python
image_to_image(image: typing.Union[bytes, typing.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)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1309)

**Parâmetros:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : A imagem de entrada para a tradução. Pode ser bytes brutos, um arquivo de imagem, uma URL para uma imagem online ou uma imagem PIL.

prompt (`str`, *opcional*) : O prompt de texto para orientar a geração da imagem.

negative_prompt (`str`, *opcional*) : Um prompt para orientar o que NÃO incluir na geração de imagem.

num_inference_steps (`int`, *opcional*) : Para modelos de difusão. O número de etapas de desruidamento. Mais etapas de desruidamento geralmente resultam em uma imagem de maior qualidade, às custas de uma inferência mais lenta.

guidance_scale (`float`, *opcional*) : Para modelos de difusão. Um valor de escala de orientação mais alto incentiva o modelo a gerar imagens fortemente ligadas ao prompt de texto, em detrimento de uma menor qualidade de imagem.

model (`str`, *opcional*) : O modelo a ser usado para inferência. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Este parâmetro substitui o modelo definido no nível da instância. O valor padrão é None.

target_size (`ImageToImageTargetSize`, *opcional*) : O tamanho em pixels da imagem de saída. Este parâmetro é suportado apenas por alguns provedores e para modelos específicos. Ele será ignorado quando não for suportado.

**Retorna:** `Image`

A imagem traduzida.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Realize a tradução de imagem para imagem usando um modelo especificado.

> [!WARNING]
> Você deve ter o `PIL` instalado se quiser trabalhar com imagens (`pip install Pillow`).

Exemplo:
```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")
```

#### image_to_text[[huggingface_hub.AsyncInferenceClient.image_to_text]]

```python
image_to_text(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1466)

**Parâmetros:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : A imagem de entrada para a legenda. Pode ser bytes brutos, um arquivo de imagem, uma URL para uma imagem online ou uma imagem PIL.

model (`str`, *opcional*) : O modelo a ser usado para inferência. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Este parâmetro substitui o modelo definido no nível da instância. O valor padrão é None.

**Retorna:** [ImageToTextOutput](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ImageToTextOutput)

O texto gerado.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Recebe uma imagem de entrada e retorna texto.

Os modelos podem ter saídas muito diferentes dependendo do seu caso de uso (legendagem de imagens, reconhecimento óptico de caracteres (OCR), Pix2Struct, etc.). Consulte o cartão do modelo para saber mais sobre as especificidades de um modelo.

Exemplo:
```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 '
```

#### image_to_video[[huggingface_hub.AsyncInferenceClient.image_to_video]]

```python
image_to_video(image: typing.Union[bytes, typing.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)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1386)

**Parâmetros:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : A imagem de entrada para gerar um vídeo. Pode ser bytes brutos, um arquivo de imagem, uma URL para uma imagem online ou uma imagem PIL.

model (`str`, *opcional*) : O modelo a ser usado para inferência. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Este parâmetro substitui o modelo definido no nível da instância. O valor padrão é None.

prompt (`str`, *opcional*) : O prompt de texto para orientar a geração do vídeo.

negative_prompt (`str`, *opcional*) : Um prompt para orientar o que NÃO incluir na geração de vídeo.

num_frames (`float`, *opcional*) : O parâmetro num_frames determina quantos quadros de vídeo são gerados.

num_inference_steps (`int`, *opcional*) : Para modelos de difusão. O número de etapas de desruidamento. Mais etapas de desruidamento geralmente resultam em uma imagem de maior qualidade, às custas de uma inferência mais lenta.

guidance_scale (`float`, *opcional*) : Para modelos de difusão. Um valor de escala de orientação mais alto incentiva o modelo a gerar vídeos estreitamente ligados ao prompt de texto, em detrimento de uma menor qualidade de imagem.

seed (`int`, *opcional*) : A semente a ser usada para a geração do vídeo.

target_size (`ImageToVideoTargetSize`, *opcional*) : O tamanho, em pixels, dos quadros do vídeo de saída.

num_inference_steps (`int`, *opcional*) : O número de etapas de remoção de ruído. Mais etapas de remoção de ruído geralmente resultam em um vídeo de maior qualidade, em detrimento de uma inferência mais lenta.

seed (`int`, *opcional*) : Semente para o gerador de números aleatórios.

**Retorna:** `bytes`

O vídeo gerado.

Gere um vídeo a partir de uma imagem de entrada.

Exemplos:
```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)
```

#### object_detection[[huggingface_hub.AsyncInferenceClient.object_detection]]

```python
object_detection(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None, threshold: float | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1513)

**Parâmetros:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : A imagem na qual detectar objetos. Pode ser bytes brutos, um arquivo de imagem, uma URL para uma imagem online ou uma imagem PIL.

model (`str`, *opcional*) : O modelo a ser usado para detecção de objetos. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo recomendado por padrão para detecção de objetos (DETR) será utilizado.

threshold (`float`, *opcional*) : A probabilidade necessária para fazer uma previsão.

**Retorna:** `list[ObjectDetectionOutputElement]`

Uma lista de itens [ObjectDetectionOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ObjectDetectionOutputElement) contendo as caixas delimitadoras e os atributos associados.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError` ou ``ValueError``

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.
- ``ValueError`` -- Se a saída da solicitação não for uma List.

Realize a detecção de objetos na imagem fornecida usando o modelo especificado.

> [!WARNING]
> Você deve ter o `PIL` instalado se quiser trabalhar com imagens (`pip install Pillow`).

Exemplo:
```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)), ...]
```

#### question_answering[[huggingface_hub.AsyncInferenceClient.question_answering]]

```python
question_answering(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)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1562)

**Parâmetros:**

question (`str`) : Pergunta a ser respondida.

context (`str`) : O contexto da pergunta.

model (`str`) : O modelo a ser usado para a tarefa de resposta a perguntas. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado.

align_to_words (`bool`, *opcional*) : Tenta alinhar a resposta a palavras reais. Melhora a qualidade em idiomas separados por espaços. Pode prejudicar em idiomas não separados por espaços (como japonês ou chinês)

doc_stride (`int`, *opcional*) : Se o contexto for longo demais para caber junto com a pergunta para o modelo, ele será dividido em vários blocos com alguma sobreposição. Este argumento controla o tamanho dessa sobreposição.

handle_impossible_answer (`bool`, *opcional*) : Se deve aceitar "impossível" como resposta.

max_answer_len (`int`, *opcional*) : O comprimento máximo das respostas previstas (por exemplo, apenas respostas com comprimento menor são consideradas).

max_question_len (`int`, *opcional*) : O comprimento máximo da pergunta após a tokenização. Será truncado, se necessário.

max_seq_len (`int`, *opcional*) : O comprimento máximo da frase total (contexto + pergunta) em tokens de cada bloco passado ao modelo. O contexto será dividido em vários blocos (usando docStride como sobreposição), se necessário.

top_k (`int`, *opcional*) : O número de respostas a serem retornadas (serão escolhidas pela ordem de probabilidade). Observe que retornamos menos respostas do que topk se não houver opções suficientes disponíveis no contexto.

**Retorna:** Union[`QuestionAnsweringOutputElement`, list[QuestionAnsweringOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.QuestionAnsweringOutputElement)]

Quando `top_k` é 1 ou não é fornecido, retorna um único `QuestionAnsweringOutputElement`. Quando `top_k` é maior que 1, retorna uma lista de `QuestionAnsweringOutputElement`.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Obter a resposta para uma pergunta a partir de um texto fornecido.

Exemplo:
```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)
```

#### sentence_similarity[[huggingface_hub.AsyncInferenceClient.sentence_similarity]]

```python
sentence_similarity(sentence: str, other_sentences: list, model: str | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1647)

**Parâmetros:**

sentence (`str`) : A frase principal para comparação com as outras.

other_sentences (`list[str]`) : A lista de frases para comparação.

model (`str`, *opcional*) : O modelo a ser usado para a tarefa de similaridade de sentenças. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de similaridade de sentenças recomendado por padrão será usado. Padrão: None.

**Retorna:** `list[float]`

O embedding que representa o texto de entrada.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Calcule a similaridade semântica entre uma frase e uma lista de outras frases comparando seus embeddings.

Exemplo:
```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]
```

#### sumarização[[huggingface_hub.AsyncInferenceClient.summarization]]

```python
summarization(text: str, model: str | None = None, clean_up_tokenization_spaces: bool | None = None, generate_parameters: dict[str, typing.Any] | None = None, truncation: typing.Optional[ForwardRef('SummarizationTruncationStrategy')] = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1701)

**Parâmetros:**

text (`str`) : O texto de entrada a ser resumido.

model (`str`, *opcional*) : O modelo a ser usado para inferência. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo recomendado por padrão para sumarização será utilizado.

clean_up_tokenization_spaces (`bool`, *opcional*) : Se deve limpar os espaços extras potenciais na saída de texto.

generate_parameters (`dict[str, Any]`, *opcional*) : Parametrização adicional do algoritmo de geração de texto.

truncation (`"SummarizationTruncationStrategy"`, *opcional*) : A estratégia de truncamento a ser utilizada.

**Retorna:** [SummarizationOutput](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.SummarizationOutput)

O texto do resumo gerado.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Gere um resumo de um texto específico usando um modelo designado.

Exemplo:
```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....")
```

#### table_question_answering[[huggingface_hub.AsyncInferenceClient.table_question_answering]]

```python
table_question_answering(table: dict, query: str, model: str | None = None, padding: typing.Optional[ForwardRef('Padding')] = None, sequential: bool | None = None, truncation: bool | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1760)

**Parâmetros:**

table (`str`) : Uma tabela de dados representada como um dict de listas, em que as entradas são os cabeçalhos e as listas contêm todos os valores; todas as listas devem ter o mesmo tamanho.

query (`str`) : A consulta em texto simples que você deseja fazer à tabela.

model (`str`) : O modelo a ser usado para a tarefa de resposta a perguntas sobre tabelas. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado.

padding (`"Padding"`, *opcional*) : Ativa e controla o preenchimento.

sequential (`bool`, *opcional*) : Se a inferência deve ser feita sequencialmente ou em lote. O processamento em lote é mais rápido, mas modelos como SQA exigem que a inferência seja realizada sequencialmente para extrair relações dentro das sequências, dada sua natureza conversacional.

truncation (`bool`, *opcional*) : Ativa e controla a truncagem.

**Retorna:** [TableQuestionAnsweringOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.TableQuestionAnsweringOutputElement)

uma saída de question answering de tabela contendo a resposta, as coordenadas, as células e o agregador utilizado.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Obter a resposta para uma pergunta a partir de informações fornecidas em uma tabela.

Exemplo:
```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')
```

#### tabular_classification[[huggingface_hub.AsyncInferenceClient.tabular_classification]]

```python
tabular_classification(table: dict, model: str | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1823)

**Parâmetros:**

table (`dict[str, Any]`) : Conjunto de atributos a classificar.

model (`str`, *opcional*) : O modelo a ser usado para a tarefa de classificação tabular. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de classificação tabular recomendado por padrão será usado. Padrão: None.

**Retorna:** `List`

uma lista de rótulos, um para cada linha na tabela inicial.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Classificar uma categoria-alvo (um grupo) com base em um conjunto de atributos.

Exemplo:
```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"]
```

#### tabular_regression[[huggingface_hub.AsyncInferenceClient.tabular_regression]]

```python
tabular_regression(table: dict, model: str | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1879)

**Parâmetros:**

table (`dict[str, Any]`) : Conjunto de atributos armazenados em uma tabela. Os atributos usados para prever o alvo podem ser numéricos e categóricos.

model (`str`, *opcional*) : O modelo a ser usado para a tarefa de regressão tabular. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de regressão tabular recomendado por padrão será usado. Padrão: None.

**Retorna:** `List`

uma lista de valores numéricos de alvo previstos.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Prever um valor numérico de destino dado um conjunto de atributos/recursos em uma tabela.

Exemplo:
```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]
```

#### text_classification[[huggingface_hub.AsyncInferenceClient.text_classification]]

```python
text_classification(text: str, model: str | None = None, top_k: int | None = None, function_to_apply: typing.Optional[ForwardRef('TextClassificationOutputTransform')] = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1930)

**Parâmetros:**

text (`str`) : Uma string a ser classificada.

model (`str`, *opcional*) : O modelo a ser usado para a tarefa de classificação de texto. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de classificação de texto recomendado por padrão será usado. Padrão: None.

top_k (`int`, *opcional*) : Quando especificado, limita a saída às K classes mais prováveis.

function_to_apply (`"TextClassificationOutputTransform"`, *opcional*) : A função a ser aplicada às saídas do modelo para recuperar as pontuações.

**Retorna:** `list[TextClassificationOutputElement]`

uma lista de itens [TextClassificationOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.TextClassificationOutputElement) contendo o rótulo previsto e a probabilidade associada.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Realize a classificação de texto (por exemplo, análise de sentimento) no texto fornecido.

Exemplo:
```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),
]
```

#### text_generation[[huggingface_hub.AsyncInferenceClient.text_generation]]

```python
text_generation(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, 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)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L2134)

**Parâmetros:**

prompt (`str`) : Texto de entrada.

details (`bool`, *opcional*) : Por padrão, text_generation retorna uma string. Passe `details=True` se você quiser uma saída detalhada (tokens, probabilidades, seed, motivo de término, etc.). Disponível apenas para modelos executados com o backend `text-generation-inference`.

stream (`bool`, *opcional*) : Por padrão, text_generation retorna o texto gerado completo. Passe `stream=True` se você quiser que um fluxo de tokens seja retornado. Disponível apenas para modelos executados com o backend `text-generation-inference`.

model (`str`, *opcional*) : O modelo a ser usado para inferência. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Este parâmetro substitui o modelo definido no nível da instância. O valor padrão é None.

adapter_id (`str`, *opcional*) : id do adaptador Lora.

best_of (`int`, *opcional*) : Gera sequências de best_of e retorna a que possui os logprobs de tokens mais altos.

decoder_input_details (`bool`, *opcional*) : Retorna os logprobs e os ids dos tokens de entrada do decodificador. Você deve definir `details=True` também para que seja considerado. O padrão é `False`.

do_sample (`bool`, *opcional*) : Ativar a amostragem de logits

frequency_penalty (`float`, *opcional*) : Número entre -2,0 e 2,0. Valores positivos penalizam novos tokens com base na sua frequência existente no texto até o momento, diminuindo a probabilidade do modelo de repetir a mesma linha literalmente.

grammar ([TextGenerationInputGrammarType](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.TextGenerationInputGrammarType), *opcional*) : Restrições de gramática. Pode ser um JSONSchema ou uma regex.

max_new_tokens (`int`, *opcional*) : Número máximo de tokens gerados. O valor padrão é 100.

repetition_penalty (`float`, *opcional*) : O parâmetro para a penalidade de repetição. 1.0 significa sem penalidade. Veja [este artigo](https://arxiv.org/pdf/1909.05858.pdf) para mais detalhes.

return_full_text (`bool`, *opcional*) : Se deve anteceder o prompt ao texto gerado

seed (`int`, *opcional*) : Semente para amostragem aleatória

stop (`list[str]`, *opcional*) : Pare de gerar tokens se um membro de `stop` for gerado.

temperature (`float`, *opcional*) : O valor usado para modular a distribuição de logits.

top_n_tokens (`int`, *opcional*) : Retorna informações sobre os `top_n_tokens` tokens mais prováveis em cada etapa de geração, em vez de apenas o token amostrado.

top_k (`int`, *opcional`) : O número de tokens de vocabulário com maior probabilidade a serem mantidos para a filtragem top-k.

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`, *opcional`) : Trunca os tokens de entrada para o tamanho especificado.

typical_p (`float`, *opcional`) : Massa típica de Decoding. Consulte [Decoding Típico para Geração de Linguagem Natural](https://arxiv.org/abs/2202.00666) para mais informações

watermark (`bool`, *opcional*) : Marca d'água com [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226)

**Retorna:** `Union[str, TextGenerationOutput, AsyncIterable[str], AsyncIterable[TextGenerationStreamOutput]]`

Texto gerado retornado pelo servidor:
- se `stream=False` e `details=False`, o texto gerado é retornado como `str` (padrão)
- se `stream=True` e `details=False`, o texto gerado é retornado token por token como um `AsyncIterable[str]`
- se `stream=False` e `details=True`, o texto gerado é retornado com mais detalhes como um [TextGenerationOutput](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.TextGenerationOutput)
- se `details=True` e `stream=True`, o texto gerado é retornado token por token como um iterável de [TextGenerationStreamOutput](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.TextGenerationStreamOutput)

**Exceções:** ``ValidationError`` ou [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- ``ValidationError`` -- Se os valores de entrada não forem válidos. Nenhuma chamada HTTP é feita ao servidor.
- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Dado um prompt, gere o texto a seguir.

> [!TIP]
> Se você deseja gerar uma resposta a partir de mensagens de chat, deve usar o método [InferenceClient.chat_completion()](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceClient.chat_completion). Ele aceita uma lista de mensagens em vez de um único prompt de texto e trata o modelamento de chat para você.

Exemplo:
```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"
}
```

#### text_to_image[[huggingface_hub.AsyncInferenceClient.text_to_image]]

```python
text_to_image(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)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L2462)

**Parâmetros:**

prompt (`str`) : O prompt para gerar uma imagem.

negative_prompt (`str`, *opcional*) : Um prompt para orientar o que NÃO incluir na geração de imagem.

height (`int`, *opcional*) : A altura em pixels da imagem de saída

width (`int`, *opcional*) : A largura em pixels da imagem de saída

num_inference_steps (`int`, *opcional*) : O número de etapas de desruido. Mais etapas de desruido geralmente resultam em uma imagem de maior qualidade, em detrimento de uma inferência mais lenta.

guidance_scale (`float`, *opcional*) : Um valor mais alto de escala de orientação incentiva o modelo a gerar imagens fortemente ligadas ao prompt de texto, mas valores muito altos podem causar saturação e outros artefatos.

model (`str`, *opcional*) : O modelo a ser usado para inferência. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de texto para imagem recomendado por padrão será usado. Padrão: None.

scheduler (`str`, *opcional*) : Substitui o agendador por um compatível.

seed (`int`, *opcional*) : Semente para o gerador de números aleatórios.

extra_body (`dict[str, Any]`, *opcional*) : Parâmetros adicionais específicos do provedor para passar ao modelo. Consulte a documentação do provedor para os parâmetros suportados.

**Retorna:** `Image`

A imagem gerada.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Gere uma imagem com base em um texto fornecido usando um modelo especificado.

> [!WARNING]
> Você deve ter o `PIL` instalado se quiser trabalhar com imagens (`pip install Pillow`).

> [!TIP]
> Você pode passar parâmetros específicos do provedor para o modelo usando o argumento `extra_body`.

Exemplo:
```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")
```

Exemplo usando um provedor de terceiros diretamente. O uso será cobrado na sua conta do fal.ai.

```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")
```

Exemplo usando um provedor de terceiros por meio do Hugging Face Routing. O uso será cobrado na sua conta do Hugging Face.

```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")
```

Exemplo usando o provedor Replicate com parâmetros extras

```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[[huggingface_hub.AsyncInferenceClient.text_to_speech]]

```python
text_to_speech(text: str, model: str | None = None, do_sample: bool | None = None, early_stopping: typing.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)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L2700)

**Parâmetros:**

text (`str`) : O texto a ser sintetizado.

model (`str`, *opcional*) : O modelo a ser usado para inferência. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de texto para fala recomendado por padrão será usado. Padrão: None.

do_sample (`bool`, *opcional*) : Se deve usar amostragem em vez de decodificação gulosa ao gerar novos tokens.

early_stopping (`Union[bool, "TextToSpeechEarlyStoppingEnum"]`, *opcional*) : Controla a condição de parada para métodos baseados em beam.

epsilon_cutoff (`float`, *opcional*) : Se definido como um float estritamente entre 0 e 1, apenas tokens com probabilidade condicional maior que epsilon_cutoff serão amostrados. No artigo, os valores sugeridos variam de 3e-4 a 9e-4, dependendo do tamanho do modelo. Consulte [Truncation Sampling as Language Model Desmoothing](https://hf.co/papers/2210.15191) para mais detalhes.

eta_cutoff (`float`, *opcional*) : A amostragem Eta é um híbrido da amostragem localmente típica e da amostragem epsilon. Se definido como um float estritamente entre 0 e 1, um token é considerado apenas se for maior que eta_cutoff ou sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits))). O segundo termo é, intuitivamente, a probabilidade esperada do próximo token, escalada por sqrt(eta_cutoff). No artigo, os valores sugeridos variam de 3e-4 a 2e-3, dependendo do tamanho do modelo. Consulte [Truncation Sampling as Language Model Desmoothing](https://hf.co/papers/2210.15191) para mais detalhes.

max_length (`int`, *opcional*) : O comprimento máximo (em tokens) do texto gerado, incluindo a entrada.

max_new_tokens (`int`, *opcional*) : O número máximo de tokens a serem gerados. Tem precedência sobre max_length.

min_length (`int`, *opcional*) : O comprimento mínimo (em tokens) do texto gerado, incluindo a entrada.

min_new_tokens (`int`, *opcional*) : O número mínimo de tokens a serem gerados. Tem precedência sobre min_length.

num_beam_groups (`int`, *opcional*) : Número de grupos para dividir num_beams, a fim de garantir diversidade entre diferentes grupos de feixes. Consulte [este artigo](https://hf.co/papers/1610.02424) para mais detalhes.

num_beams (`int`, *opcional*) : Número de feixes a serem usados para a busca por feixes.

penalty_alpha (`float`, *opcional*) : O valor equilibra a confiança do modelo e a penalidade de degeneração na decodificação de busca contrastiva.

temperature (`float`, *opcional*) : O valor usado para modular as probabilidades do próximo token.

top_k (`int`, *opcional*) : O número de tokens do vocabulário com maior probabilidade a serem mantidos para a filtragem top-k.

top_p (`float`, *opcional*) : Se definido como float < 1, apenas o menor conjunto de tokens mais prováveis, cujas probabilidades somadas sejam iguais ou superiores a top_p, é mantido para a geração.

typical_p (`float`, *opcional*) : A tipicidade local mede o quão semelhante é a probabilidade condicional de prever o próximo token alvo à probabilidade condicional esperada de prever um token aleatório a seguir, dado o texto parcial já gerado. Se definido como float < 1, o menor conjunto dos tokens mais localmente típicos, cujas probabilidades somem typical_p ou mais, é mantido para a geração. Veja [este artigo](https://hf.co/papers/2202.00666) para mais detalhes.

use_cache (`bool`, *opcional*) : Se o modelo deve usar as atenções de chaves/valores do passado para acelerar a decodificação

extra_body (`dict[str, Any]`, *opcional*) : Parâmetros adicionais específicos do provedor para passar ao modelo. Consulte a documentação do provedor para os parâmetros suportados.

**Retorna:** `bytes`

O áudio gerado.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Sintetize um áudio de uma voz pronunciando um texto dado.

> [!TIP]
> Você pode passar parâmetros específicos do provedor para o modelo usando o argumento `extra_body`.

Exemplo:
```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)
```

Exemplo usando um provedor de terceiros diretamente. O uso será cobrado na sua conta do Replicate.

```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)
```

Exemplo usando um provedor de terceiros por meio do Hugging Face Routing. O uso será cobrado na sua conta do Hugging Face.

```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)
```

Exemplo usando o provedor Replicate com parâmetros extras

```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)
```

Exemplo de geração de música usando "YuE-s1-7B-anneal-en-cot" no 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[[huggingface_hub.AsyncInferenceClient.text_to_video]]

```python
text_to_video(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)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L2603)

**Parâmetros:**

prompt (`str`) : O prompt para gerar um vídeo.

model (`str`, *opcional*) : O modelo a ser usado para inferência. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de texto para vídeo recomendado por padrão será usado. Padrão: None.

guidance_scale (`float`, *opcional*) : Um valor mais alto de escala de orientação incentiva o modelo a gerar vídeos estreitamente ligados ao prompt de texto, mas valores muito altos podem causar saturação e outros artefatos.

negative_prompt (`list[str]`, *opcional*) : Um ou vários prompts para orientar o que NÃO incluir na geração de vídeo.

num_frames (`float`, *opcional*) : O parâmetro num_frames determina quantos quadros de vídeo são gerados.

num_inference_steps (`int`, *opcional*) : O número de etapas de remoção de ruído. Mais etapas de remoção de ruído geralmente resultam em um vídeo de maior qualidade, em detrimento de uma inferência mais lenta.

seed (`int`, *opcional*) : Semente para o gerador de números aleatórios.

extra_body (`dict[str, Any]`, *opcional*) : Parâmetros adicionais específicos do provedor para passar ao modelo. Consulte a documentação do provedor para os parâmetros suportados.

**Retorna:** `bytes`

O vídeo gerado.

Gere um vídeo com base em um texto fornecido.

> [!TIP]
> Você pode passar parâmetros específicos do provedor para o modelo usando o argumento `extra_body`.

Exemplo:

Exemplo usando um provedor de terceiros diretamente. O uso será cobrado na sua conta do fal.ai.

```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)
```

Exemplo usando um provedor de terceiros por meio do Hugging Face Routing. O uso será cobrado na sua conta do Hugging Face.

```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[[huggingface_hub.AsyncInferenceClient.token_classification]]

```python
token_classification(text: str, model: str | None = None, aggregation_strategy: typing.Optional[ForwardRef('TokenClassificationAggregationStrategy')] = None, ignore_labels: list[str] | None = None, stride: int | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L2909)

**Parâmetros:**

text (`str`) : Uma string a ser classificada.

model (`str`, *opcional*) : O modelo a ser usado para a tarefa de classificação de tokens. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de classificação de tokens recomendado por padrão será usado. Padrão: None.

aggregation_strategy (`"TokenClassificationAggregationStrategy"`, *opcional*) : A estratégia usada para fundir tokens com base nas previsões do modelo

ignore_labels (`list[str`, *optional*) : Uma lista de rótulos para ignorar

stride (`int`, *opcional*) : O número de tokens sobrepostos entre os blocos ao dividir o texto de entrada.

**Retorna:** `list[TokenClassificationOutputElement]`

Lista de itens [TokenClassificationOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.TokenClassificationOutputElement) contendo o grupo de entidade, a pontuação de confiança, a palavra e os índices de início e fim.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Realize a classificação de tokens no texto fornecido. Geralmente usado para análise de sentenças, seja gramatical, seja Reconhecimento de Entidades Nomeadas (NER), para entender as palavras-chave contidas no texto.

Exemplo:
```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,
    )
]
```

#### tradução[[huggingface_hub.AsyncInferenceClient.translation]]

```python
translation(text: str, model: str | None = None, src_lang: str | None = None, tgt_lang: str | None = None, clean_up_tokenization_spaces: bool | None = None, truncation: typing.Optional[ForwardRef('TranslationTruncationStrategy')] = None, generate_parameters: dict[str, typing.Any] | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L2985)

**Parâmetros:**

text (`str`) : Uma string a ser traduzida.

model (`str`, *opcional*) : O modelo a ser usado para a tarefa de tradução. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de tradução recomendado por padrão será usado. Padrão: None.

src_lang (`str`, *opcional*) : O idioma de origem do texto. Obrigatório para modelos que podem traduzir de vários idiomas.

tgt_lang (`str`, *opcional*) : Idioma de destino para a tradução. Obrigatório para modelos que podem traduzir para vários idiomas.

clean_up_tokenization_spaces (`bool`, *opcional*) : Se deve limpar os espaços extras potenciais na saída de texto.

truncation (`"TranslationTruncationStrategy"`, *opcional*) : A estratégia de truncamento a ser utilizada.

generate_parameters (`dict[str, Any]`, *opcional*) : Parametrização adicional do algoritmo de geração de texto.

**Retorna:** [TranslationOutput](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.TranslationOutput)

O texto traduzido gerado.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError` ou ``ValueError``

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.
- ``ValueError`` -- Se apenas um dos argumentos `src_lang` e `tgt_lang` for fornecido.

Converta texto de um idioma para outro.

Confira https://huggingface.co/tasks/translation para mais informações sobre como escolher o melhor modelo para o seu caso de uso específico. Os idiomas de origem e de destino geralmente dependem do modelo. No entanto, é possível especificar os idiomas de origem e de destino para determinados modelos. Se você estiver trabalhando com um desses modelos, pode usar os argumentos `src_lang` e `tgt_lang` para passar as informações relevantes.

Exemplo:
```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.')
```

Especificando idiomas:
```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[[huggingface_hub.AsyncInferenceClient.visual_question_answering]]

```python
visual_question_answering(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], question: str, model: str | None = None, top_k: int | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L3075)

**Parâmetros:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : A imagem de entrada para o contexto. Pode ser bytes brutos, um arquivo de imagem, uma URL para uma imagem online ou uma imagem PIL.

question (`str`) : Pergunta a ser respondida.

model (`str`, *opcional*) : O modelo a ser usado para a tarefa de resposta a perguntas visuais. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Se não for fornecido, o modelo de resposta a perguntas visuais recomendado por padrão será usado. Padrão: None.

top_k (`int`, *opcional*) : O número de respostas a serem retornadas (serão escolhidas pela ordem de probabilidade). Observe que retornamos menos respostas do que topk se não houver opções suficientes disponíveis no contexto.

**Retorna:** `list[VisualQuestionAnsweringOutputElement]`

uma lista de itens [VisualQuestionAnsweringOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.VisualQuestionAnsweringOutputElement) contendo o rótulo previsto e a probabilidade associada.

**Exceções:** ``InferenceTimeoutError`` ou `HfHubHTTPError`

- ``InferenceTimeoutError`` -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Responder a perguntas abertas com base em uma imagem.

Exemplo:
```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'),
]
```

#### zero_shot_classification[[huggingface_hub.AsyncInferenceClient.zero_shot_classification]]

```python
zero_shot_classification(text: str, candidate_labels: list, multi_label: bool | None = False, hypothesis_template: str | None = None, model: str | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L3135)

**Parâmetros:**

text (`str`) : O texto de entrada a ser classificado.

candidate_labels (`list[str]`) : O conjunto de rótulos de classe possíveis para classificar o texto.

multi_label (`bool`, *opcional*) : Se múltiplos rótulos candidatos podem ser verdadeiros. Se for falso, as pontuações são normalizadas de modo que a soma das probabilidades dos rótulos para cada sequência seja 1. Se for verdadeiro, os rótulos são considerados independentes e as probabilidades são normalizadas para cada candidato.

hypothesis_template (`str`, *opcional*) : A frase usada em conjunto com `candidate_labels` para tentar a classificação de texto, substituindo o placeholder pelos rótulos candidatos.

model (`str`, *opcional*) : O modelo a ser usado para inferência. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Este parâmetro substitui o modelo definido no nível da instância. Se não for fornecido, o modelo de classificação zero-shot recomendado por padrão será usado.

**Retorna:** `list[ZeroShotClassificationOutputElement]`

Lista de itens [ZeroShotClassificationOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ZeroShotClassificationOutputElement) contendo os rótulos previstos e sua confiança.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Forneça como entrada um texto e um conjunto de rótulos candidatos para classificar o texto de entrada.

Exemplo com `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),
]
```

Exemplo com `multi_label=True` e um `hypothesis_template` personalizado:
```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.",
...    candidate_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[[huggingface_hub.AsyncInferenceClient.zero_shot_image_classification]]

```python
zero_shot_image_classification(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], candidate_labels: list, model: str | None = None, hypothesis_template: str | None = None)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L3238)

**Parâmetros:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : A imagem de entrada para a legenda. Pode ser bytes brutos, um arquivo de imagem, uma URL para uma imagem online ou uma imagem PIL.

candidate_labels (`list[str]`) : Os rótulos candidatos para esta imagem

model (`str`, *opcional*) : O modelo a ser usado para inferência. Pode ser um ID de modelo hospedado no Hugging Face Hub ou uma URL para um Inference Endpoint implantado. Este parâmetro substitui o modelo definido no nível da instância. Se não for fornecido, o modelo de classificação de imagem zero-shot recomendado por padrão será usado.

hypothesis_template (`str`, *opcional*) : A frase usada em conjunto com `candidate_labels` para tentar a classificação de imagem substituindo o placeholder pelos rótulos candidatos.

**Retorna:** `list[ZeroShotImageClassificationOutputElement]`

Lista de itens [ZeroShotImageClassificationOutputElement](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_types#huggingface_hub.ZeroShotImageClassificationOutputElement) contendo os rótulos previstos e sua confiança.

**Exceções:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) ou `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/pt/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- Se o modelo estiver indisponível ou a solicitação exceder o tempo limite.
- `HfHubHTTPError` -- Se a solicitação falhar com um código de status de erro HTTP diferente de HTTP 503.

Forneça uma imagem de entrada e rótulos de texto para prever os rótulos de texto da imagem.

Exemplo:
```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",
...     candidate_labels=["dog", "cat", "horse"],
... )
[ZeroShotImageClassificationOutputElement(label='dog', score=0.956),...]
```

## InferenceTimeoutError[[huggingface_hub.InferenceTimeoutError]]

#### huggingface_hub.InferenceTimeoutError[[huggingface_hub.InferenceTimeoutError]]

```python
huggingface_hub.InferenceTimeoutError(message: str)
```

[Fonte](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/errors.py#L155)

Erro lançado quando um modelo está indisponível ou a solicitação expira.

