Hub Python Library documentation

推論

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

推論

推論とは、学習済みのモデルを使用して新しいデータに対して予測を行うプロセスです。このプロセスは計算負荷が高くなる可能性があるため、専用サービスまたは外部サービス上で実行することは魅力的な選択肢となり得ます。 huggingface_hubライブラリは、Hugging Face Hubにホストされているモデルに対して、複数のサービスで推論を実行するための統一されたインターフェースを提供します:

  1. Inference Providers: サーバーレス推論パートナーが提供する、数百の機械学習モデルへの統一かつ簡素化されたアクセスです。この新しいアプローチは、従来の Serverless Inference API を基盤として構築されており、世界クラスのプロバイダーのおかげで、より多くのモデル、パフォーマンスの向上、そして高い信頼性を提供します。サポートされているプロバイダーの一覧については、ドキュメントを参照してください。
  2. Inference Endpoints: モデルを本番環境に簡単にデプロイするためのプロダクトです。推論は、Hugging Face が選択したクラウドプロバイダー上で、専用かつフルマネージドのインフラストラクチャで実行されます。
  3. ローカルエンドポイント: llama.cpp、Ollama、vLLM、LiteLLM、Text Generation Inference (TGI)などのローカル推論サーバーにクライアントを接続することで、これらを使用して推論を実行することもできます。

これらのサービスは、InferenceClientオブジェクトを介して呼び出すことができます。使用方法の詳細については、このガイドを参照してください。

推論クライアント

クラス huggingface_hub.InferenceClient

< >

( model: str | None = Noneprovider: 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] = Nonetoken: str | None = Nonetimeout: float | None = Noneheaders: dict[str, str] | None = Nonecookies: dict[str, str] | None = Nonebill_to: str | None = Nonebase_url: str | None = Noneapi_key: str | None = None )

パラメータ

  • model (str, optional) — 推論を実行するモデルです。Hugging Face Hub にホストされているモデル ID (例: meta-llama/Meta-Llama-3-8B-Instruct) または、デプロイされた Inference Endpoint への URL を指定できます。デフォルトは None で、この場合、タスクに適した推奨モデルが自動的に選択されます。 注: OpenAI のクライアントとの互換性を高めるため、model は base_url としてエイリアス化されています。これら 2 つの引数は排他的です。チャット補完のために model または base_url として URL が渡された場合、その URL に (/v1)/chat/completions サフィックスパスが追加されます。
  • provider (str, 省略可) — 推論に使用するプロバイダーの名前。"baseten"、"cerebras"、"cohere"、"deepinfra"、"fal-ai"、"featherless-ai"、"fireworks-ai"、"groq"、"hf-inference"、"novita"、"nscale"、"openai"、"ovhcloud"、"publicai"、"replicate"、"scaleway"、"together"、"wavespeed"、または"zai-org"を指定できます。 デフォルトは“auto”です。自動ルーティングを行い、デフォルトでは“fastest”プロバイダーが選択されます。https://hf.co/settings/inference-providers で、“cheapest”または“preferred”のプロバイダー順序に切り替えることができます。 モデルが URL の場合、またはbase_url が渡された場合、provider は使用されません。
  • token (str, 省略可能) — Hugging Face トークン。指定しない場合、ローカルに保存されているトークンがデフォルトで使用されます。 注: OpenAI のクライアントとの互換性を高めるため、token は api_key としてエイリアス化されています。これら 2 つの引数は排他的であり、動作は完全に同一です。
  • timeout (float, optional) — サーバーからの応答を待機する最大秒数です。デフォルトは None で、サーバーが利用可能になるまでループし続けます。
  • headers (dict[str, str]、optional) — サーバーに送信する追加のヘッダーです。デフォルトでは、authorization ヘッダーと user-agent ヘッダーのみが送信されます。この辞書の値は、デフォルトの値を上書きします。
  • bill_to (str, optional) — リクエストに使用する請求先アカウントです。デフォルトでは、リクエストはユーザーのアカウントに請求されます。リクエストは、ユーザーがメンバーであり、かつ Enterprise Hub に加入している組織にのみ請求できます。
  • cookies (dict[str, str]、optional) — サーバーに送信する追加のクッキー。
  • base_url (str, optional) — 推論を実行するためのベースURLです。modelからの重複引数であり、InferenceClientがopenai.OpenAIクライアントと同じパターンに従うようにするためのものです。modelが設定されている場合は使用できません。デフォルトはNoneです。
  • api_key (str, optional) — 認証に使用するトークン。tokenからの重複引数であり、InferenceClientがopenai.OpenAIクライアントと同じパターンに従うようにするためのものです。tokenが設定されている場合は使用できません。デフォルトはNoneです。

新しいInference Clientを初期化します。

InferenceClientは、推論の実行に統一された体験を提供することを目的としています。このクライアントは、(無料の)Inference API、セルフホストされたInference Endpoints、またはサードパーティのInference Providersのいずれともシームレスに使用できます。

音声分類

< >

( audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]model: str | None = Nonetop_k: int | None = Nonefunction_to_apply: typing.Optional[ForwardRef('AudioClassificationOutputTransform')] = None ) → list[AudioClassificationOutputElement]

パラメータ

  • audio (Union[str, Path, bytes, BinaryIO]) — 分類対象のオーディオコンテンツです。生のオーディオバイト、ローカルのオーディオファイル、またはオーディオファイルへのURLを指定できます。
  • model (str, 省略可) — 音声分類に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、音声分類用のデフォルトの推奨モデルが使用されます。
  • top_k (int, 省略可) — 指定すると、出力が最も確率の高い上位 K 個のクラスに制限されます。
  • function_to_apply ("AudioClassificationOutputTransform", 省略可能) — スコアを取得するためにモデルの出力に適用する関数。

戻り値

list[AudioClassificationOutputElement]

予測ラベルとその信頼度を含むAudioClassificationOutputElementの項目のリスト。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

提供された音声コンテンツに対して音声分類を実行します。

例:

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

< >

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

パラメータ

  • audio (Union[str, Path, bytes, BinaryIO]) — モデル用のオーディオコンテンツです。生のオーディオバイト、ローカルのオーディオファイル、またはオーディオファイルへのURLを指定できます。
  • model (str, 任意) — モデルは、音声ファイルを受け取り、別の音声ファイルを返す任意のモデルです。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、audio_to_audio のデフォルトで推奨されるモデルが使用されます。

戻り値

list[AudioToAudioOutputElement]

オーディオのラベル、コンテンツタイプ、およびブロブ形式のオーディオコンテンツを含むAudioToAudioOutputElementの項目のリスト。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

モデルに応じて、音声から音声への変換に関連する複数のタスクを実行します(例:音声の品質向上、ソース分離)。

例:

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

自動音声認識

< >

( audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]model: str | None = Noneextra_body: dict | None = None ) → AutomaticSpeechRecognitionOutput

パラメータ

  • audio (Union[str, Path, bytes, BinaryIO]) — 書き起こす対象の内容です。生のオーディオバイト、ローカルのオーディオファイル、またはオーディオファイルへのURLを指定できます。
  • model (str, 任意) — ASR に使用するモデルです。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、ASR 用のデフォルトの推奨モデルが使用されます。
  • extra_body (dict, 任意) — モデルに渡すプロバイダー固有の追加パラメータです。サポートされているパラメータについては、プロバイダーのドキュメントを参照してください。

転写テキストと、任意のタイムスタンプチャンクを含むアイテム。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

与えられた音声コンテンツに対して、自動音声認識(ASRまたは音声からテキストへの変換)を実行します。

例:

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

chat_completion

< >

( messages: listmodel: str | None = Nonestream: bool = Falsefrequency_penalty: float | None = Nonelogit_bias: list[float] | None = Nonelogprobs: bool | None = Nonemax_tokens: int | None = Nonen: int | None = Nonepresence_penalty: float | None = Noneresponse_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] = Noneseed: int | None = Nonestop: list[str] | None = Nonestream_options: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputStreamOptions | None = Nonetemperature: float | None = Nonetool_choice: typing.Union[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputToolChoiceClass, ForwardRef('ChatCompletionInputToolChoiceEnum'), NoneType] = Nonetool_prompt: str | None = Nonetools: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputTool] | None = Nonetop_logprobs: int | None = Nonetop_p: float | None = Noneextra_body: dict | None = None ) → ChatCompletionOutput or Iterable of ChatCompletionStreamOutput

パラメータ

  • messages (ChatCompletionInputMessage のリスト) — ロールとコンテンツのペアで構成される会話履歴。
  • model (str, 省略可) — チャット補完に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、チャットベースのテキスト生成用のデフォルト推奨モデルが使用されます。詳細は https://huggingface.co/tasks/text-generation を参照してください。 model がモデル ID の場合、サーバーに model パラメータとして渡されます。リクエストペイロードで model を設定しながらカスタム URL を定義したい場合は、InferenceClient を初期化する際に base_url を設定する必要があります。
  • frequency_penalty (float, 任意) — これまでのテキストにおけるトークンの出現頻度に基づいて、新しいトークンにペナルティを課します。範囲: [-2.0, 2.0]。デフォルト値は 0.0 です。
  • logit_bias (list[float]、任意) — 生成出力に特定のトークンが出現する可能性を調整します。
  • logprobs (bool, 任意) — 出力トークンの対数確率を返すかどうかを指定します。true の場合、メッセージの content に返される各出力トークンの対数確率が返されます。
  • max_tokens (int, 省略可) — 応答で許可されるトークンの最大数です。デフォルト値は 100 です。
  • n (int, 省略可能) — 各プロンプトに対して生成する補完の数を指定します。
  • presence_penalty (float, 任意) — -2.0 から 2.0 までの数値。正の値を指定すると、それまでのテキストにトークンが出現しているかどうかに基づいて新しいトークンにペナルティを課し、モデルが新しい話題について述べる可能性を高めます。
  • response_format (ChatCompletionInputGrammarType()、省略可) — 文法制約です。JSONSchema または正規表現のいずれかを指定できます。
  • seed (任意int, optional) — 再現可能な制御フローのためのシード。デフォルトは None です。
  • stop (list[str]、任意) — レスポンスの終了をトリガーする、最大4つの文字列。 デフォルトはNoneです。
  • stream (bool, 省略可) — レスポンスのリアルタイムストリーミングを有効にします。デフォルトは False です。
  • stream_options (ChatCompletionInputStreamOptions、任意) — ストリーミング補完のオプション。
  • temperature (float, 任意) — 生成のランダム性を制御します。値が低いほど、より予測可能な補完になります。範囲: [0, 2]。デフォルト値は 1.0 です。
  • top_logprobs (int, 任意) — 各トークン位置で返す最も確率の高いトークンの数を指定する 0 から 5 までの整数です。各トークンには対応する対数確率が付与されます。このパラメータを使用する場合は、logprobs を true に設定する必要があります。
  • top_p (float, 任意) — サンプリング対象とする、最も確率の高い次の単語の割合。 0 以上 1 以下である必要があります。デフォルト値は 1.0 です。
  • tool_choice (ChatCompletionInputToolChoiceClass または ChatCompletionInputToolChoiceEnum()、任意) — 補完に使用するツールです。デフォルト値は “auto” です。
  • tool_prompt (str, 省略可) — ツールに付加するプロンプト。
  • tools (ChatCompletionInputTool のリスト、任意) — モデルが呼び出すことのできるツールのリストです。現在、ツールとしてサポートされているのは関数のみです。モデルが JSON 入力を生成できる関数のリストを指定するために使用します。
  • extra_body (dict, 任意) — モデルに渡すプロバイダー固有の追加パラメータです。サポートされているパラメータについては、プロバイダーのドキュメントを参照してください。

戻り値

ChatCompletionOutput または ChatCompletionStreamOutput のイテラブル

サーバーから返された生成テキスト:

  • stream=Falseの場合、生成されたテキストはChatCompletionOutputとして返されます(デフォルト)。
  • stream=Trueの場合、生成されたテキストはChatCompletionStreamOutputのシーケンスとして、トークンごとに返されます。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定された言語モデルを使用して会話を補完するためのメソッド。

client.chat_completion メソッドは、OpenAI のクライアントとの互換性のために client.chat.completions.create としてエイリアス化されています。 入力と出力は完全に同一であり、どちらの構文を使用しても同じ結果が得られます。 OpenAI の互換性に関する詳細については、推論ガイドを参照してください。

extra_body 引数を使用して、プロバイダー固有のパラメータをモデルに渡すことができます。

例:

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

ストリーミングを使用した例:

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

OpenAIの構文を使用した例:

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

サードパーティプロバイダーを直接使用し、追加の(プロバイダー固有の)パラメータを指定する例。利用料はTogether AIアカウントに請求されます。

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

Hugging Face Routing を介したサードパーティプロバイダーを使用する例。利用料は Hugging Face アカウントに請求されます。

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

画像とテキストを入力として使用する例:

>>> 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.

ツールを使用した例:

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

response_format を使用した例:

>>> 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"}'

文書質問応答

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]question: strmodel: str | None = Nonedoc_stride: int | None = Nonehandle_impossible_answer: bool | None = Nonelang: str | None = Nonemax_answer_len: int | None = Nonemax_question_len: int | None = Nonemax_seq_len: int | None = Nonetop_k: int | None = Noneword_boxes: list[list[float] | str] | None = None ) → list[DocumentQuestionAnsweringOutputElement]

パラメータ

  • image (Union[str, Path, bytes, BinaryIO]) — コンテキスト用の入力画像です。生のバイト列、画像ファイル、またはオンライン画像へのURLを指定できます。
  • question (str) — 回答する質問。
  • model (str, 任意) — ドキュメント質問応答タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨されるドキュメント質問応答モデルが使用されます。デフォルト値は None です。
  • doc_stride (int, 任意) — ドキュメントの単語が長すぎて、モデルの質問と合わせて収まらない場合、ある程度の重複を伴う複数のチャンクに分割されます。この引数は、その重複のサイズを制御します。
  • handle_impossible_answer (bool, 省略可) — impossible を回答として受け入れるかどうか
  • lang (str, 省略可) — OCR 実行時に使用する言語。デフォルトは english です。
  • max_answer_len (int, オプション) — 予測された回答の最大長です(例:この長さより短い回答のみが対象となります)。
  • max_question_len (int, 任意) — トークナイズ後の質問の最大長です。必要に応じて切り詰められます。
  • max_seq_len (int, 任意) — モデルに渡される各チャンクにおける、文全体(コンテキスト + 質問)の最大トークン数です。必要に応じて、コンテキストは複数のチャンクに分割されます(重複として doc_stride を使用)。
  • top_k (int, 任意) — 返す回答の数(確率の高い順に選択されます)。コンテキスト内で十分な選択肢がない場合は、top_k 未満の回答が返されることがあります。
  • word_boxes (list[Union[list[float], str, optional) — 単語とバウンディングボックス(正規化済み 0->1000)のリストです。指定された場合、推論は OCR ステップをスキップし、指定されたバウンディングボックスを使用します。

戻り値

list[DocumentQuestionAnsweringOutputElement]

予測ラベル、関連する確率、単語 ID、ページ番号を含むDocumentQuestionAnsweringOutputElementのアイテムのリスト。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

ドキュメントの画像に関する質問に回答します。

例:

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

< >

( text: str | list[str]normalize: bool | None = Noneprompt_name: str | None = Nonetruncate: bool | None = Nonetruncation_direction: typing.Optional[typing.Literal['left', 'right']] = Nonedimensions: int | None = Noneencoding_format: typing.Optional[typing.Literal['float', 'base64']] = Nonemodel: str | None = None ) → np.ndarray

パラメータ

  • text (str または list[str]) — 埋め込むテキストまたはテキストのリスト。
  • model (str, optional) — 特徴抽出タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨される特徴抽出モデルが使用されます。デフォルト値は None です。
  • normalize (bool, optional) — 埋め込みを正規化するか否かを指定します。 Text-Embedding-Inference によって提供されるサーバーでのみ利用可能です。
  • prompt_name (str, optional) — The name of the prompt that should be used by for encoding. If not set, no prompt will be applied. Must be a key in the Sentence Transformers configuration prompts dictionary. For example if prompt_name is “query” and the prompts is {“query”: “query: ”,…}, then the sentence “What is the capital of France?” will be encoded as “query: What is the capital of France?” because the prompt text will be prepended before any text to encode.
  • truncate (bool, optional) — 埋め込みを切り詰めるかどうかを指定します。 Text-Embedding-Inference によって提供されるサーバーでのみ利用可能です。
  • truncation_direction (Literal[“left”, “right”], optional) — truncate=True が渡された場合、入力のどの側を切り詰めるかを指定します。
  • dimensions (int, optional) — 結果として得られる出力埋め込みが持つべき次元数です。 OpenAI互換の埋め込みエンドポイントでのみ利用可能です。
  • encoding_format (Literal[“float”, “base64”], optional) — 出力埋め込みの形式です。“float”または“base64”のいずれかです。 OpenAI互換の埋め込みエンドポイントでのみ利用可能です。

戻り値

np.ndarray

float32型のNumPy配列として入力テキストを表す埋め込み。

例外

[InferenceTimeoutError] または [HfHubHTTPError]

  • [InferenceTimeoutError] — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • [HfHubHTTPError] — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたテキストまたはテキストのバッチに対して埋め込みを生成します。

例:

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

< >

( text: strmodel: str | None = Nonetargets: list[str] | None = Nonetop_k: int | None = None ) → list[FillMaskOutputElement]

パラメータ

  • text (str) — 埋め込む対象の文字列です。[MASK] トークンを含む必要があります(マスクの正確な名称はモデルカードを確認してください)。
  • model (str, 省略可能) — fill mask タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨される fill mask モデルが使用されます。
  • targets (list[str, 任意) — 指定された場合、モデルは語彙全体を検索する代わりに、渡されたターゲットにスコアを限定します。提供されたターゲットがモデルの語彙に存在しない場合、それらはトークン化され、最初の結果として得られたトークンが使用されます(警告が表示され、処理が遅くなる可能性があります)。
  • top_k (int, 省略可) — 指定された場合、返す予測の数を上書きします。

戻り値

list[FillMaskOutputElement]

予測ラベル、関連する確率、トークン参照、および補完されたテキストを含むFillMaskOutputElementの項目のリスト。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

欠落した単語(正確にはトークン)で穴を埋めます。

例:

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

< >

( model: str | None = None ) → dict[str, Any]

パラメータ

  • model (str, 任意) — 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。デフォルト値は None です。

戻り値

dict[str, Any]

エンドポイントに関する情報。

デプロイされたエンドポイントに関する情報を取得します。

このエンドポイントは、Text-Generation-Inference (TGI) または Text-Embedding-Inference (TEI) によって提供されるエンドポイントでのみ利用可能です。 transformers によって提供されるエンドポイントは、空のペイロードを返します。

例:

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

< >

( model: str | None = None ) → bool

パラメータ

  • model (str, 任意) — Inference Endpoint の URL。このパラメータは、インスタンスレベルで定義されたモデルを上書きします。デフォルト値は None です。

戻り値

bool

すべてが正常に動作している場合はTrue。

デプロイされたエンドポイントの健全性を確認します。

Health checkは、Text-Generation-Inference (TGI) または Text-Embedding-Inference (TEI) による Inference Endpoints のみで利用可能です。

例:

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

image_classification

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]model: str | None = Nonefunction_to_apply: typing.Optional[ForwardRef('ImageClassificationOutputTransform')] = Nonetop_k: int | None = None ) → list[ImageClassificationOutputElement]

パラメータ

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 分類対象の画像です。生のバイト列、画像ファイル、オンライン画像のURL、またはPIL Imageを指定できます。
  • model (str, 省略可能) — 画像分類に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、画像分類用のデフォルトの推奨モデルが使用されます。
  • function_to_apply ("ImageClassificationOutputTransform", 省略可能) — スコアを取得するためにモデルの出力に適用する関数。
  • top_k (int, 省略可) — 指定すると、出力が最も確率の高い上位 K 個のクラスに制限されます。

戻り値

list[ImageClassificationOutputElement]

予測ラベルと関連する確率を含むImageClassificationOutputElementのリスト

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたモデルを使用して、与えられた画像で画像分類を実行します。

例:

>>> 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: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]model: str | None = Nonemask_threshold: float | None = Noneoverlap_mask_area_threshold: float | None = Nonesubtask: typing.Optional[ForwardRef('ImageSegmentationSubtask')] = Nonethreshold: float | None = None ) → list[ImageSegmentationOutputElement]

パラメータ

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — セグメント化対象の画像です。生のバイト列、画像ファイル、オンライン画像へのURL、またはPIL Imageを指定できます。
  • model (str, 任意) — 画像セグメンテーションに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、画像セグメンテーション用のデフォルトの推奨モデルが使用されます。
  • mask_threshold (float, 任意) — 予測されたマスクをバイナリ値に変換する際に使用する閾値。
  • overlap_mask_area_threshold (float, 任意) — 小さな断片化されたセグメントを除去するためのマスク重複の閾値です。
  • subtask ("ImageSegmentationSubtask", 任意) — モデルの機能に応じて実行されるセグメンテーションタスク。
  • threshold (float, 任意) — 予測されたマスクをフィルタリングするための確率の閾値。

戻り値

list[ImageSegmentationOutputElement]

セグメンテーションされたマスクと関連する属性を含む、ImageSegmentationOutputElement の項目のリストです。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたモデルを使用して、与えられた画像に対して画像セグメンテーションを実行します。

画像を扱うには、PILのインストールが必要です(pip install Pillow)。

例:

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

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]prompt: str | None = Nonenegative_prompt: str | None = Nonenum_inference_steps: int | None = Noneguidance_scale: float | None = Nonemodel: str | None = Nonetarget_size: huggingface_hub.inference._generated.types.image_to_image.ImageToImageTargetSize | None = None**kwargs ) → Image

パラメータ

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 翻訳の入力画像です。生のバイト列、画像ファイル、オンライン画像へのURL、またはPIL Imageを指定できます。
  • prompt (str, 任意) — 画像生成をガイドするためのテキストプロンプト。
  • negative_prompt (str, 任意) — 画像生成に含めるべきでない内容を指示するプロンプトを1つ指定します。
  • num_inference_steps (int, 任意) — 拡散モデル用。デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常、より高品質な画像が得られます。
  • guidance_scale (float, 任意) — 拡散モデル用です。guidance scale の値を高くすると、テキストプロンプトと密接に関連した画像を生成するようモデルに促されますが、その代わり画像の品質が低下します。
  • model (str, 任意) — 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。デフォルト値は None です。
  • target_size (ImageToImageTargetSize、任意) — 出力画像のピクセル単位でのサイズです。このパラメータは一部のプロバイダーおよび特定のモデルでのみサポートされています。サポートされていない場合は無視されます。

戻り値

Image

変換された画像。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたモデルを使用して、画像から画像への翻訳を実行します。

画像を扱うには、PILのインストールが必要です(pip install Pillow)。

例:

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

< >

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

パラメータ

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — キャプションを付与する入力画像です。生のバイト列、画像ファイル、オンライン画像へのURL、またはPIL Imageを指定できます。
  • model (str, 任意) — 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。デフォルト値は None です。

生成されたテキスト。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

入力画像を受け取り、テキストを返します。

モデルの出力は、ユースケース(画像キャプション生成、光学文字認識(OCR)、Pix2Struct など)によって大きく異なる場合があります。モデル固有の詳細については、モデルカードをご参照ください。

例:

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

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]model: str | None = Noneprompt: str | None = Nonenegative_prompt: str | None = Nonenum_frames: float | None = Nonenum_inference_steps: int | None = Noneguidance_scale: float | None = Noneseed: int | None = Nonetarget_size: huggingface_hub.inference._generated.types.image_to_video.ImageToVideoTargetSize | None = None**kwargs ) → bytes

パラメータ

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 動画の生成に使用する入力画像です。生のバイト列、画像ファイル、オンライン画像へのURL、またはPIL Imageを指定できます。
  • model (str, 任意) — 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。デフォルト値は None です。
  • prompt (str, 任意) — 動画生成をガイドするためのテキストプロンプト。
  • negative_prompt (str, 任意) — 動画生成に含めるべきでない内容を指示するプロンプトを1つ指定します。
  • num_frames (float, 任意) — num_frames パラメータは、生成される動画フレームの数を決定します。
  • num_inference_steps (int, 任意) — 拡散モデル用。デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常、より高品質な画像が得られます。
  • guidance_scale (float, 任意) — 拡散モデル用です。guidance scale の値を高くすると、テキストプロンプトと密接に関連した動画を生成するようモデルが促されますが、その代わり画像の品質が低下します。
  • seed (int, 任意) — 動画生成に使用するシード。
  • target_size (ImageToVideoTargetSize、任意) — 出力される動画フレームのピクセルサイズです。
  • num_inference_steps (int, 任意) — デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常、より高品質な動画が生成されます。
  • seed (int, 任意) — 乱数生成器のシード。

戻り値

bytes

生成された動画。

入力画像から動画を生成します。

例:

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

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]model: str | None = Nonethreshold: float | None = None ) → list[ObjectDetectionOutputElement]

パラメータ

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — オブジェクトを検出する対象の画像です。生のバイト列、画像ファイル、オンライン画像へのURL、またはPIL Imageを指定できます。
  • model (str, 任意) — オブジェクト検出に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、オブジェクト検出のデフォルト推奨モデル (DETR) が使用されます。
  • threshold (float, 任意) — 予測を行うために必要な確率。

戻り値

list[ObjectDetectionOutputElement]

バウンディングボックスと関連する属性を含むObjectDetectionOutputElementの項目のリスト。

例外

InferenceTimeoutError または HfHubHTTPError または ValueError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。
  • ValueError — リクエストの出力がListでない場合。

指定されたモデルを使用して、与えられた画像で物体検出を実行します。

画像を扱うには、PILのインストールが必要です(pip install Pillow)。

例:

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

< >

( question: strcontext: strmodel: str | None = Nonealign_to_words: bool | None = Nonedoc_stride: int | None = Nonehandle_impossible_answer: bool | None = Nonemax_answer_len: int | None = Nonemax_question_len: int | None = Nonemax_seq_len: int | None = Nonetop_k: int | None = None ) → Union[QuestionAnsweringOutputElement, listQuestionAnsweringOutputElement]

パラメータ

  • question (str) — 回答する質問。
  • context (str) — 質問のコンテキストです。
  • model (str) — 質問応答タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。
  • align_to_words (bool, オプション) — 回答を実際の単語に整列させようとします。スペースで単語が区切られている言語では品質が向上します。スペースで単語が区切られていない言語(日本語や中国語など)では品質が低下する可能性があります。
  • doc_stride (int, 任意) — コンテキストがモデルの質問と合わせて長くなりすぎる場合、ある程度の重複を伴う複数のチャンクに分割されます。この引数は、その重複のサイズを制御します。
  • handle_impossible_answer (bool, 省略可) — impossible を回答として受け入れるかどうか。
  • max_answer_len (int, オプション) — 予測された回答の最大長です(例:この長さより短い回答のみが対象となります)。
  • max_question_len (int, 任意) — トークナイズ後の質問の最大長です。必要に応じて切り詰められます。
  • max_seq_len (int, 任意) — モデルに渡される各チャンクにおける、文全体(コンテキスト + 質問)の最大トークン数です。必要に応じて、コンテキストは複数のチャンクに分割されます(重複として docStride を使用)。
  • top_k (int, 任意) — 返す回答の数(確率の高い順に選択されます)。コンテキスト内に十分な選択肢がない場合は、top_k より少ない数の回答が返されます。

戻り値

Union[QuestionAnsweringOutputElement, listQuestionAnsweringOutputElement]

top_k が 1 または指定されていない場合、単一の QuestionAnsweringOutputElement を返します。 top_k が 1 より大きい場合、QuestionAnsweringOutputElement のリストを返します。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

与えられたテキストから、質問に対する回答を取得します。

例:

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

< >

( sentence: strother_sentences: listmodel: str | None = None ) → list[float]

パラメータ

  • sentence (str) — 他の文と比較するための主な文。
  • other_sentences (list[str]) — 比較対象となる文のリストです。
  • model (str, 省略可) — 文の類似度タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、推奨されるデフォルトの文の類似度モデルが使用されます。デフォルト値は None です。

戻り値

list[float]

入力テキストを表す埋め込み。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

埋め込みを比較することにより、文と他の文のリストとの間の意味的類似度を計算します。

例:

>>> 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]

要約

< >

( text: strmodel: str | None = Noneclean_up_tokenization_spaces: bool | None = Nonegenerate_parameters: dict[str, typing.Any] | None = Nonetruncation: typing.Optional[ForwardRef('SummarizationTruncationStrategy')] = None ) → SummarizationOutput

パラメータ

  • text (str) — 要約する入力テキスト。
  • model (str, 任意) — 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、要約用のデフォルト推奨モデルが使用されます。
  • clean_up_tokenization_spaces (bool, 任意) — テキスト出力に含まれる可能性のある余分なスペースを整理するかどうか。
  • generate_parameters (dict[str, Any]、省略可) — テキスト生成アルゴリズムの追加のパラメータ設定。
  • truncation ("SummarizationTruncationStrategy"、任意) — 使用する切り詰め戦略です。

生成された要約テキスト。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたモデルを使用して、与えられたテキストの要約を生成します。

例:

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

< >

( table: dictquery: strmodel: str | None = Nonepadding: typing.Optional[ForwardRef('Padding')] = Nonesequential: bool | None = Nonetruncation: bool | None = None ) → TableQuestionAnsweringOutputElement

パラメータ

  • table (str) — リストの辞書として表形式で表されたデータ。エントリはヘッダー、リストはすべての値を表します。すべてのリストは同じサイズである必要があります。
  • query (str) — テーブルに尋ねたいクエリをプレーンテキストで指定します。
  • model (str) — テーブル質問応答タスクに使用するモデル。Hugging Face HubにホストされているモデルID、またはデプロイされたInference EndpointのURLを指定できます。
  • padding ("Padding"、任意) — パディングの有効化と制御を行います。
  • sequential (bool, 任意) — 推論をシーケンシャルに行うか、バッチとして行うかを指定します。バッチ処理の方が高速ですが、SQAのようなモデルは、対話的な性質から、シーケンス内の関係を抽出するためにシーケンシャルな推論が必要です。
  • truncation (bool、省略可) — 切り詰めを有効にし、切り詰めを制御します。

回答、座標、セル、および使用されたアグリゲーターを含むテーブル質問応答の出力

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

表に示された情報から、質問に対する答えを取得します。

例:

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

< >

( table: dictmodel: str | None = None ) → List

パラメータ

  • table (dict[str, Any]) — 分類する属性のセット。
  • model (str, 任意) — 表形式分類タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、推奨されるデフォルトの表形式分類モデルが使用されます。デフォルト値は None です。

戻り値

List

初期テーブルの各行に対応するラベルのリスト。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

属性のセットに基づいてターゲットカテゴリ(グループ)を分類します。

例:

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

< >

( table: dictmodel: str | None = None ) → List

パラメータ

  • table (dict[str, Any]) — テーブルに保存される属性のセットです。ターゲットを予測するために使用される属性は、数値型とカテゴリ型の両方を含むことができます。
  • model (str, 任意) — 表形式の回帰タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨される表形式の回帰モデルが使用されます。デフォルト値は None です。

戻り値

List

予測された数値ターゲット値のリスト。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

テーブル内の属性/特徴のセットが与えられたときに、数値のターゲット値を予測します。

例:

>>> 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: strmodel: str | None = Nonetop_k: int | None = Nonefunction_to_apply: typing.Optional[ForwardRef('TextClassificationOutputTransform')] = None ) → list[TextClassificationOutputElement]

パラメータ

  • text (str) — 分類対象の文字列。
  • model (str, 任意) — テキスト分類タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨されるテキスト分類モデルが使用されます。デフォルト値は None です。
  • top_k (int, 省略可) — 指定すると、出力が最も確率の高い上位 K 個のクラスに制限されます。
  • function_to_apply ("TextClassificationOutputTransform", 省略可能) — スコアを取得するためにモデルの出力に適用する関数。

戻り値

list[TextClassificationOutputElement]

予測ラベルと関連する確率を含むTextClassificationOutputElementのリスト

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

与えられたテキストに対してテキスト分類(例:感情分析)を実行します。

例:

>>> 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),
]

テキスト生成

< >

( prompt: strdetails: bool | None = Nonestream: bool | None = Nonemodel: str | None = Noneadapter_id: str | None = Nonebest_of: int | None = Nonedecoder_input_details: bool | None = Nonedo_sample: bool | None = Nonefrequency_penalty: float | None = Nonegrammar: huggingface_hub.inference._generated.types.text_generation.TextGenerationInputGrammarType | None = Nonemax_new_tokens: int | None = Nonerepetition_penalty: float | None = Nonereturn_full_text: bool | None = Noneseed: int | None = Nonestop: list[str] | None = Nonetemperature: float | None = Nonetop_k: int | None = Nonetop_n_tokens: int | None = Nonetop_p: float | None = Nonetruncate: int | None = Nonetypical_p: float | None = Nonewatermark: bool | None = None ) → Union[str, TextGenerationOutput, Iterable[str], Iterable[TextGenerationStreamOutput]]

パラメータ

  • prompt (str) — 入力テキスト。
  • details (bool, 省略可) — デフォルトでは、text_generation は文字列を返します。詳細な出力(トークン、確率、シード、終了理由など)が必要な場合は、details=True を渡してください。text-generation-inference バックエンドで実行されているモデルでのみ利用可能です。
  • stream (bool, 省略可) — デフォルトでは、text_generation は生成されたテキスト全体を返します。トークンのストリームを返す場合は、stream=True を渡してください。text-generation-inference バックエンドで実行されているモデルでのみ利用可能です。
  • model (str, 任意) — 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。デフォルト値は None です。
  • adapter_id (str, 省略可) — Lora アダプター ID。
  • best_of (int, オプション) — best_of 個のシーケンスを生成し、トークン logprobs が最も高いものを返します。
  • decoder_input_details (bool、任意) — デコーダー入力トークンの logprobs と id を返します。これを有効にするには、details=True も設定する必要があります。デフォルトは False です。
  • do_sample (bool、省略可) — logits サンプリングを有効にします
  • frequency_penalty (float, 任意) — -2.0 から 2.0 までの数値。正の値を指定すると、テキスト内でそれまでに出現した頻度に基づいて新しいトークンにペナルティが課され、同じ行をそのまま繰り返す可能性が低くなります。
  • grammar (TextGenerationInputGrammarType、任意) — 文法制約。JSONSchema または正規表現のいずれかです。
  • max_new_tokens (int, 任意) — 生成されるトークンの最大数。デフォルト値は100です。
  • repetition_penalty (float, 任意) — 反復ペナルティのパラメータです。1.0 はペナルティなしを意味します。詳細はこの論文を参照してください。
  • return_full_text (bool, 省略可) — 生成テキストの先頭にプロンプトを付加するかどうか
  • seed (int, 任意) — ランダムサンプリングのシード
  • stop (list[str], 任意) — stop のいずれかのメンバーが生成された場合、トークンの生成を停止します。
  • temperature (float, 任意) — logits の分布を調整するために使用される値。
  • top_n_tokens (int, 省略可) — サンプリングされたトークンのみではなく、各生成ステップにおける最も確率の高いtop_n_tokens個のトークンに関する情報を返します。
  • top_k (int, *optional`) — トップ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, *optional`) — 入力トークンを指定されたサイズに切り詰めます。
  • typical_p (float, *optional`) — Typical Decoding の質量 詳細は Typical Decoding for Natural Language Generation を参照してください
  • watermark (bool, 省略可) — 大規模言語モデルのためのウォーターマーク によるウォーターマーキング

戻り値

Union[str, TextGenerationOutput, Iterable[str], Iterable[TextGenerationStreamOutput]]

サーバーから返された生成テキスト:

  • stream=Falseかつdetails=Falseの場合、生成されたテキストはstrとして返されます(デフォルト)
  • stream=Trueかつdetails=Falseの場合、生成されたテキストはIterable[str]としてトークン単位で返されます。
  • stream=Falseかつdetails=Trueの場合、生成されたテキストはTextGenerationOutputとして、より詳細な情報とともに返されます。
  • details=Trueかつstream=Trueの場合、生成されたテキストはTextGenerationStreamOutputのイテラブルとしてトークン単位で返されます。

例外

ValidationError または InferenceTimeoutError または HfHubHTTPError

  • ValidationError — 入力値が有効でない場合。サーバーへのHTTP呼び出しは行われません。
  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

プロンプトが与えられた場合、以下のテキストを生成します。

チャットメッセージから応答を生成したい場合は、InferenceClient.chat_completion() メソッドを使用してください。 このメソッドは、単一のテキストプロンプトの代わりにメッセージのリストを受け取り、チャットテンプレート処理を自動で行います。

例:

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

< >

( prompt: strnegative_prompt: str | None = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int | None = Noneguidance_scale: float | None = Nonemodel: str | None = Nonescheduler: str | None = Noneseed: int | None = Noneextra_body: dict[str, typing.Any] | None = None ) → Image

パラメータ

  • prompt (str) — 画像を生成するためのプロンプト。
  • negative_prompt (str, 任意) — 画像生成に含めるべきでない内容を指示するプロンプトを1つ指定します。
  • height (int, 任意) — 出力画像のピクセル単位の縦幅
  • width (int, 任意) — 出力画像の幅(ピクセル単位)
  • num_inference_steps (int, 任意) — デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。
  • guidance_scale (float, 任意) — guidance scale の値を高くすると、テキストプロンプトと密接に関連した画像を生成するようモデルに促されますが、値が高すぎると飽和やその他のアーティファクトが発生する可能性があります。
  • model (str, 任意) — 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨されるテキストから画像生成へのモデルが使用されます。デフォルト値は None です。
  • scheduler (str, 省略可) — 互換性のあるスケジューラで上書きします。
  • seed (int, 任意) — 乱数生成器のシード。
  • extra_body (dict[str, Any], 省略可) — モデルに渡すプロバイダー固有の追加パラメータです。サポートされているパラメータについては、プロバイダーのドキュメントを参照してください。

戻り値

Image

生成された画像。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたモデルを使用して、与えられたテキストに基づいて画像を生成します。

画像を扱うには、PILのインストールが必要です(pip install Pillow)。

extra_body 引数を使用して、プロバイダー固有のパラメータをモデルに渡すことができます。

例:

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()

>>> image = client.text_to_image("An astronaut riding a horse on the moon.")
>>> image.save("astronaut.png")

>>> image = client.text_to_image(
...     "An astronaut riding a horse on the moon.",
...     negative_prompt="low resolution, blurry",
...     model="stabilityai/stable-diffusion-2-1",
... )
>>> image.save("better_astronaut.png")
Example using a third-party provider directly. Usage will be billed on your fal.ai account.
>>> 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")

Hugging Face Routing を介したサードパーティプロバイダーを使用する例。利用料は Hugging Face アカウントに請求されます。

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

Replicateプロバイダーを、追加パラメータ付きで使用する例

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

< >

( text: strmodel: str | None = Nonedo_sample: bool | None = Noneearly_stopping: typing.Union[bool, ForwardRef('TextToSpeechEarlyStoppingEnum'), NoneType] = Noneepsilon_cutoff: float | None = Noneeta_cutoff: float | None = Nonemax_length: int | None = Nonemax_new_tokens: int | None = Nonemin_length: int | None = Nonemin_new_tokens: int | None = Nonenum_beam_groups: int | None = Nonenum_beams: int | None = Nonepenalty_alpha: float | None = Nonetemperature: float | None = Nonetop_k: int | None = Nonetop_p: float | None = Nonetypical_p: float | None = Noneuse_cache: bool | None = Noneextra_body: dict[str, typing.Any] | None = None ) → bytes

パラメータ

  • text (str) — 合成するテキスト。
  • model (str, 任意) — 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨されるテキスト読み上げモデルが使用されます。デフォルト値は None です。
  • do_sample (bool, 省略可) — 新しいトークンを生成する際に、貪欲デコーディングではなくサンプリングを使用するかどうか。
  • early_stopping (Union[bool, "TextToSpeechEarlyStoppingEnum"]、省略可) — ビームベースの手法における停止条件を制御します。
  • epsilon_cutoff (float, 任意) — 0 より大きく 1 より小さい float 値に設定した場合、条件付き確率が epsilon_cutoff より大きいトークンのみがサンプリングされます。論文では、モデルサイズに応じて推奨値は 3e-4 から 9e-4 の範囲とされています。詳細は Truncation Sampling as Language Model Desmoothing を参照してください。
  • eta_cutoff (float, 省略可能) — Eta サンプリングは、ローカル・ティピカル・サンプリングとエプシロン・サンプリングのハイブリッドです。0 と 1 の間の float 値に設定すると、トークンは eta_cutoff または sqrt(eta_cutoff)
    • exp(-entropy(softmax(next_token_logits)))。後者の項は、直感的には、sqrt(eta_cutoff)でスケーリングされた次のトークンの期待確率です。論文では、モデルのサイズに応じて、提案値は3e-4から2e-3の範囲とされています。詳細については、Truncation Sampling as Language Model Desmoothingを参照してください。
  • max_length (int, 任意) — 入力を含む生成テキストの最大長(トークン数)。
  • max_new_tokens (int, 任意) — 生成するトークンの最大数です。max_length より優先されます。
  • min_length (int, 任意) — 生成テキストの最小長(トークン数)。入力を含みます。
  • min_new_tokens (int, 任意) — 生成するトークンの最小数です。min_length より優先されます。
  • num_beam_groups (int, 任意) — ビームの多様性を確保するために、num_beams を分割するグループの数。詳細はこの論文を参照してください。
  • num_beams (int, 任意) — ビームサーチに使用するビームの数。
  • penalty_alpha (float, 任意) — 対比検索デコーディングにおいて、モデルの信頼度と退化ペナルティのバランスを調整する値です。
  • temperature (float, 任意) — 次のトークンの確率を調整するために使用される値。
  • top_k (int, 任意) — トップkフィルタリングのために保持する、確率の高い語彙トークンの数。
  • top_p (float, 任意) — 1 未満の float に設定した場合、生成に使用されるのは、確率の合計が top_p 以上になる最も確率の高いトークンの最小集合のみです。
  • typical_p (float, 任意) — ローカルタイピシティは、すでに生成された部分テキストが与えられた条件下で、次のターゲットトークンを予測する条件付き確率が、次のランダムなトークンを予測する期待される条件付き確率とどれだけ類似しているかを測定します。float < 1 に設定すると、確率の合計が typical_p 以上となる最もローカルに典型的なトークンの最小集合が生成のために保持されます。詳細はこの論文を参照してください。
  • use_cache (bool, 省略可) — モデルがデコーディングを高速化するために、過去のキー/バリューの注意機構を使用するかどうか
  • extra_body (dict[str, Any], 省略可) — モデルに渡すプロバイダー固有の追加パラメータです。サポートされているパラメータについては、プロバイダーのドキュメントを参照してください。

戻り値

bytes

生成されたオーディオ。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたテキストを発音する音声のオーディオを合成します。

extra_body 引数を使用して、プロバイダー固有のパラメータをモデルに渡すことができます。

例:

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

サードパーティプロバイダーを直接使用する例。使用料はあなたのReplicateアカウントに請求されます。

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

Hugging Face Routing を介したサードパーティプロバイダーを使用する例。利用料は Hugging Face アカウントに請求されます。

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="replicate",
...     api_key="hf_...",  # Pass your HF token
... )
>>> audio =client.text_to_speech(
...     text="Hello world",
...     model="OuteAI/OuteTTS-0.3-500M",
... )
>>> Path("hello_world.flac").write_bytes(audio)
Example using Replicate provider with extra parameters
>>> 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)

fal.ai上で“YuE-s1-7B-anneal-en-cot”を使用した音楽生成の例

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

< >

( prompt: strmodel: str | None = Noneguidance_scale: float | None = Nonenegative_prompt: list[str] | None = Nonenum_frames: float | None = Nonenum_inference_steps: int | None = Noneseed: int | None = Noneextra_body: dict[str, typing.Any] | None = None ) → bytes

パラメータ

  • prompt (str) — 動画の生成に使用するプロンプト。
  • model (str, 任意) — 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨されるテキストから動画生成へのモデルが使用されます。デフォルト値は None です。
  • guidance_scale (float, 任意) — guidance scale の値を高くすると、テキストプロンプトと密接に関連した動画をモデルが生成するよう促されますが、値が高すぎると飽和やその他のアーティファクトが発生する可能性があります。
  • negative_prompt (list[str], 任意) — 動画生成に含めるべきでない内容を導くための、1つ以上のプロンプト。
  • num_frames (float, 任意) — num_frames パラメータは、生成される動画フレームの数を決定します。
  • num_inference_steps (int, 任意) — デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常、より高品質な動画が生成されます。
  • seed (int, 任意) — 乱数生成器のシード。
  • extra_body (dict[str, Any], 省略可) — モデルに渡すプロバイダー固有の追加パラメータです。サポートされているパラメータについては、プロバイダーのドキュメントを参照してください。

戻り値

bytes

生成された動画。

与えられたテキストに基づいて動画を生成します。

extra_body 引数を使用して、プロバイダー固有のパラメータをモデルに渡すことができます。

例:

サードパーティプロバイダーを直接使用する例。利用料はfal.aiアカウントに請求されます。

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

Hugging Face Routing を介したサードパーティプロバイダーを使用する例。利用料は Hugging Face アカウントに請求されます。

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

トークン分類

< >

( text: strmodel: str | None = Noneaggregation_strategy: typing.Optional[ForwardRef('TokenClassificationAggregationStrategy')] = Noneignore_labels: list[str] | None = Nonestride: int | None = None ) → list[TokenClassificationOutputElement]

パラメータ

  • text (str) — 分類対象の文字列。
  • model (str, 任意) — トークン分類タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨されるトークン分類モデルが使用されます。デフォルト値は None です。
  • aggregation_strategy ("TokenClassificationAggregationStrategy"、任意) — モデルの予測に基づいてトークンを融合するために使用される戦略
  • ignore_labels (list[str, 省略可) — 無視するラベルのリスト
  • stride (int, 省略可) — 入力テキストを分割する際に、チャンク間で重複するトークンの数。

戻り値

list[TokenClassificationOutputElement]

エンティティグループ、信頼度スコア、単語、開始および終了インデックスを含むTokenClassificationOutputElementの項目のリスト。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

与えられたテキストに対してトークン分類を実行します。 通常、文の解析(文法的な解析または)に使用され、テキストに含まれるキーワードを理解するために用いられます。

例:

>>> 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,
    )
]

翻訳

< >

( text: strmodel: str | None = Nonesrc_lang: str | None = Nonetgt_lang: str | None = Noneclean_up_tokenization_spaces: bool | None = Nonetruncation: typing.Optional[ForwardRef('TranslationTruncationStrategy')] = Nonegenerate_parameters: dict[str, typing.Any] | None = None ) → TranslationOutput

パラメータ

  • text (str) — 翻訳対象の文字列。
  • model (str, 省略可能) — 翻訳タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨される翻訳モデルが使用されます。デフォルト値は None です。
  • src_lang (str, 省略可) — テキストのソース言語です。複数言語からの翻訳に対応するモデルでは必須です。
  • tgt_lang (str, 任意) — 翻訳先の言語です。複数の言語への翻訳に対応するモデルでは必須です。
  • clean_up_tokenization_spaces (bool, 任意) — テキスト出力に含まれる可能性のある余分なスペースを整理するかどうか。
  • truncation ("TranslationTruncationStrategy"、任意) — 使用する切り詰め戦略です。
  • generate_parameters (dict[str, Any]、省略可) — テキスト生成アルゴリズムの追加のパラメータ設定。

生成された翻訳テキスト。

例外

InferenceTimeoutError または HfHubHTTPError または ValueError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。
  • ValueError — src_lang と tgt_lang の引数のうち、片方だけが提供された場合。

テキストをある言語から別の言語に変換します。

特定のユースケースに最適なモデルの選び方については、https://huggingface.co/tasks/translation をご覧ください。ソース言語とターゲット言語は通常、モデルによって決まります。 ただし、一部のモデルではソース言語とターゲット言語を指定できます。これらのモデルを使用している場合は、src_lang と tgt_lang 引数を使って関連情報を渡すことができます。

例:

>>> 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.')

言語の指定:

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

視覚的質問応答

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]question: strmodel: str | None = Nonetop_k: int | None = None ) → list[VisualQuestionAnsweringOutputElement]

パラメータ

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — コンテキスト用の入力画像です。生のバイト列、画像ファイル、オンライン画像へのURL、またはPIL Imageを指定できます。
  • question (str) — 回答する質問。
  • model (str, 任意) — 視覚的質問応答タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、推奨されるデフォルトの視覚的質問応答モデルが使用されます。デフォルト値は None です。
  • top_k (int, 任意) — 返す回答の数(確率の高い順に選択されます)。コンテキスト内に十分な選択肢がない場合は、top_k より少ない数の回答が返されます。

戻り値

list[VisualQuestionAnsweringOutputElement]

予測ラベルと関連する確率を含むVisualQuestionAnsweringOutputElementのリスト

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

画像に基づいてオープンエンドな質問に答える。

例:

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

< >

( text: strcandidate_labels: listmulti_label: bool | None = Falsehypothesis_template: str | None = Nonemodel: str | None = None ) → list[ZeroShotClassificationOutputElement]

パラメータ

  • text (str) — 分類する入力テキスト。
  • candidate_labels (list[str]) — テキストを分類するための候補となるクラスラベルの集合です。
  • multi_label (bool, 省略可) — 複数の候補ラベルが同時に真になり得るかどうかを指定します。false の場合、各シーケンスにおけるラベルの尤度の和が 1 になるようにスコアが正規化されます。true の場合、ラベルは独立であるとみなされ、各候補ごとに確率が正規化されます。
  • hypothesis_template (str, 任意) — candidate_labels と組み合わせて、プレースホルダーを候補ラベルに置き換えることでテキスト分類を試みるために使用される文です。
  • model (str, 任意) — 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。指定しない場合、デフォルトで推奨されるゼロショット分類モデルが使用されます。

戻り値

list[ZeroShotClassificationOutputElement]

予測ラベルとその信頼度を含むZeroShotClassificationOutputElementのリストです。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

入力としてテキストと、そのテキストを分類するための候補ラベルのセットを指定します。

multi_label=Falseの例:

>>> 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),
]

multi_label=Trueとカスタムのhypothesis_templateを用いた例:

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

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]candidate_labels: listmodel: str | None = Nonehypothesis_template: str | None = None ) → list[ZeroShotImageClassificationOutputElement]

パラメータ

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — キャプションを付与する入力画像です。生のバイト列、画像ファイル、オンライン画像へのURL、またはPIL Imageを指定できます。
  • candidate_labels (list[str]) — この画像の候補ラベル
  • model (str, 任意) — 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。指定しない場合、デフォルトで推奨されるゼロショット画像分類モデルが使用されます。
  • hypothesis_template (str, 任意) — candidate_labels と組み合わせて画像分類を試みる際に使用される文です。プレースホルダーを候補ラベルに置き換えます。

戻り値

list[ZeroShotImageClassificationOutputElement]

予測ラベルとその信頼度を含むZeroShotImageClassificationOutputElementのリストです。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

入力画像とテキストラベルを指定して、画像のテキストラベルを予測します。

例:

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

非同期推論クライアント

asyncioとhttpx2をベースとした、クライアントの非同期バージョンも提供されています。

クラス huggingface_hub.AsyncInferenceClient

< >

( model: str | None = Noneprovider: 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] = Nonetoken: str | None = Nonetimeout: float | None = Noneheaders: dict[str, str] | None = Nonecookies: dict[str, str] | None = Nonebill_to: str | None = Nonebase_url: str | None = Noneapi_key: str | None = None )

パラメータ

  • model (str, optional) — 推論を実行するモデルです。Hugging Face Hub にホストされているモデル ID (例: meta-llama/Meta-Llama-3-8B-Instruct) または、デプロイされた Inference Endpoint への URL を指定できます。デフォルトは None で、この場合、タスクに適した推奨モデルが自動的に選択されます。 注: OpenAI のクライアントとの互換性を高めるため、model は base_url としてエイリアス化されています。これら 2 つの引数は排他的です。チャット補完のために model または base_url として URL が渡された場合、その URL に (/v1)/chat/completions サフィックスパスが追加されます。
  • provider (str, 省略可) — 推論に使用するプロバイダーの名前。"baseten"、"cerebras"、"cohere"、"deepinfra"、"fal-ai"、"featherless-ai"、"fireworks-ai"、"groq"、"hf-inference"、"novita"、"nscale"、"openai"、"ovhcloud"、"publicai"、"replicate"、"scaleway"、"together"、"wavespeed"、または"zai-org"を指定できます。 デフォルトは“auto”です。自動ルーティングを行い、デフォルトでは“fastest”プロバイダーが選択されます。https://hf.co/settings/inference-providers で、“cheapest”または“preferred”のプロバイダー順序に切り替えることができます。 モデルが URL の場合、またはbase_url が渡された場合、provider は使用されません。
  • token (str, 省略可能) — Hugging Face トークン。指定しない場合、ローカルに保存されているトークンがデフォルトで使用されます。 注: OpenAI のクライアントとの互換性を高めるため、token は api_key としてエイリアス化されています。これら 2 つの引数は排他的であり、動作は完全に同一です。
  • timeout (float, optional) — サーバーからの応答を待機する最大秒数です。デフォルトは None で、サーバーが利用可能になるまでループし続けます。
  • headers (dict[str, str]、optional) — サーバーに送信する追加のヘッダーです。デフォルトでは、authorization ヘッダーと user-agent ヘッダーのみが送信されます。この辞書の値は、デフォルトの値を上書きします。
  • bill_to (str, optional) — リクエストに使用する請求先アカウントです。デフォルトでは、リクエストはユーザーのアカウントに請求されます。リクエストは、ユーザーがメンバーであり、かつ Enterprise Hub に加入している組織にのみ請求できます。
  • cookies (dict[str, str]、optional) — サーバーに送信する追加のクッキー。
  • base_url (str, optional) — 推論を実行するためのベースURLです。modelからの重複引数であり、InferenceClientがopenai.OpenAIクライアントと同じパターンに従うようにするためのものです。modelが設定されている場合は使用できません。デフォルトはNoneです。
  • api_key (str, optional) — 認証に使用するトークン。tokenからの重複引数であり、InferenceClientがopenai.OpenAIクライアントと同じパターンに従うようにするためのものです。tokenが設定されている場合は使用できません。デフォルトはNoneです。

新しいInference Clientを初期化します。

InferenceClientは、推論の実行に統一された体験を提供することを目的としています。このクライアントは、(無料の)Inference API、セルフホストされたInference Endpoints、またはサードパーティのInference Providersのいずれともシームレスに使用できます。

音声分類

< >

( audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]model: str | None = Nonetop_k: int | None = Nonefunction_to_apply: typing.Optional[ForwardRef('AudioClassificationOutputTransform')] = None ) → list[AudioClassificationOutputElement]

パラメータ

  • audio (Union[str, Path, bytes, BinaryIO]) — 分類対象のオーディオコンテンツです。生のオーディオバイト、ローカルのオーディオファイル、またはオーディオファイルへのURLを指定できます。
  • model (str, 省略可) — 音声分類に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、音声分類用のデフォルトの推奨モデルが使用されます。
  • top_k (int, 省略可) — 指定すると、出力が最も確率の高い上位 K 個のクラスに制限されます。
  • function_to_apply ("AudioClassificationOutputTransform", 省略可能) — スコアを取得するためにモデルの出力に適用する関数。

戻り値

list[AudioClassificationOutputElement]

予測ラベルとその信頼度を含むAudioClassificationOutputElementの項目のリスト。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

提供された音声コンテンツに対して音声分類を実行します。

例:

# 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

< >

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

パラメータ

  • audio (Union[str, Path, bytes, BinaryIO]) — モデル用のオーディオコンテンツです。生のオーディオバイト、ローカルのオーディオファイル、またはオーディオファイルへのURLを指定できます。
  • model (str, 任意) — モデルは、音声ファイルを受け取り、別の音声ファイルを返す任意のモデルです。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、audio_to_audio のデフォルトで推奨されるモデルが使用されます。

戻り値

list[AudioToAudioOutputElement]

オーディオのラベル、コンテンツタイプ、およびブロブ形式のオーディオコンテンツを含むAudioToAudioOutputElementの項目のリスト。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

モデルに応じて、音声から音声への変換に関連する複数のタスクを実行します(例:音声の品質向上、ソース分離)。

例:

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

自動音声認識

< >

( audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]model: str | None = Noneextra_body: dict | None = None ) → AutomaticSpeechRecognitionOutput

パラメータ

  • audio (Union[str, Path, bytes, BinaryIO]) — 書き起こす対象の内容です。生のオーディオバイト、ローカルのオーディオファイル、またはオーディオファイルへのURLを指定できます。
  • model (str, 任意) — ASR に使用するモデルです。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、ASR 用のデフォルトの推奨モデルが使用されます。
  • extra_body (dict, 任意) — モデルに渡すプロバイダー固有の追加パラメータです。サポートされているパラメータについては、プロバイダーのドキュメントを参照してください。

転写テキストと、任意のタイムスタンプチャンクを含むアイテム。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

与えられた音声コンテンツに対して、自動音声認識(ASRまたは音声からテキストへの変換)を実行します。

例:

# 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

< >

( messages: listmodel: str | None = Nonestream: bool = Falsefrequency_penalty: float | None = Nonelogit_bias: list[float] | None = Nonelogprobs: bool | None = Nonemax_tokens: int | None = Nonen: int | None = Nonepresence_penalty: float | None = Noneresponse_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] = Noneseed: int | None = Nonestop: list[str] | None = Nonestream_options: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputStreamOptions | None = Nonetemperature: float | None = Nonetool_choice: typing.Union[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputToolChoiceClass, ForwardRef('ChatCompletionInputToolChoiceEnum'), NoneType] = Nonetool_prompt: str | None = Nonetools: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputTool] | None = Nonetop_logprobs: int | None = Nonetop_p: float | None = Noneextra_body: dict | None = None ) → ChatCompletionOutput or Iterable of ChatCompletionStreamOutput

パラメータ

  • messages (ChatCompletionInputMessage のリスト) — ロールとコンテンツのペアで構成される会話履歴。
  • model (str, 省略可) — チャット補完に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、チャットベースのテキスト生成用のデフォルト推奨モデルが使用されます。詳細は https://huggingface.co/tasks/text-generation を参照してください。 model がモデル ID の場合、サーバーに model パラメータとして渡されます。リクエストペイロードで model を設定しながらカスタム URL を定義したい場合は、InferenceClient を初期化する際に base_url を設定する必要があります。
  • frequency_penalty (float, 任意) — これまでのテキストにおけるトークンの出現頻度に基づいて、新しいトークンにペナルティを課します。範囲: [-2.0, 2.0]。デフォルト値は 0.0 です。
  • logit_bias (list[float]、任意) — 生成出力に特定のトークンが出現する可能性を調整します。
  • logprobs (bool, 任意) — 出力トークンの対数確率を返すかどうかを指定します。true の場合、メッセージの content に返される各出力トークンの対数確率が返されます。
  • max_tokens (int, 省略可) — 応答で許可されるトークンの最大数です。デフォルト値は 100 です。
  • n (int, 省略可能) — 各プロンプトに対して生成する補完の数を指定します。
  • presence_penalty (float, 任意) — -2.0 から 2.0 までの数値。正の値を指定すると、それまでのテキストにトークンが出現しているかどうかに基づいて新しいトークンにペナルティを課し、モデルが新しい話題について述べる可能性を高めます。
  • response_format (ChatCompletionInputGrammarType()、省略可) — 文法制約です。JSONSchema または正規表現のいずれかを指定できます。
  • seed (任意int, optional) — 再現可能な制御フローのためのシード。デフォルトは None です。
  • stop (list[str]、任意) — レスポンスの終了をトリガーする、最大4つの文字列。 デフォルトはNoneです。
  • stream (bool, 省略可) — レスポンスのリアルタイムストリーミングを有効にします。デフォルトは False です。
  • stream_options (ChatCompletionInputStreamOptions、任意) — ストリーミング補完のオプション。
  • temperature (float, 任意) — 生成のランダム性を制御します。値が低いほど、より予測可能な補完になります。範囲: [0, 2]。デフォルト値は 1.0 です。
  • top_logprobs (int, 任意) — 各トークン位置で返す最も確率の高いトークンの数を指定する 0 から 5 までの整数です。各トークンには対応する対数確率が付与されます。このパラメータを使用する場合は、logprobs を true に設定する必要があります。
  • top_p (float, 任意) — サンプリング対象とする、最も確率の高い次の単語の割合。 0 以上 1 以下である必要があります。デフォルト値は 1.0 です。
  • tool_choice (ChatCompletionInputToolChoiceClass または ChatCompletionInputToolChoiceEnum()、任意) — 補完に使用するツールです。デフォルト値は “auto” です。
  • tool_prompt (str, 省略可) — ツールに付加するプロンプト。
  • tools (ChatCompletionInputTool のリスト、任意) — モデルが呼び出すことのできるツールのリストです。現在、ツールとしてサポートされているのは関数のみです。モデルが JSON 入力を生成できる関数のリストを指定するために使用します。
  • extra_body (dict, 任意) — モデルに渡すプロバイダー固有の追加パラメータです。サポートされているパラメータについては、プロバイダーのドキュメントを参照してください。

戻り値

ChatCompletionOutput または ChatCompletionStreamOutput のイテラブル

サーバーから返された生成テキスト:

  • stream=Falseの場合、生成されたテキストはChatCompletionOutputとして返されます(デフォルト)。
  • stream=Trueの場合、生成されたテキストはChatCompletionStreamOutputのシーケンスとして、トークンごとに返されます。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定された言語モデルを使用して会話を補完するためのメソッド。

client.chat_completion メソッドは、OpenAI のクライアントとの互換性のために client.chat.completions.create としてエイリアス化されています。 入力と出力は完全に同一であり、どちらの構文を使用しても同じ結果が得られます。 OpenAI の互換性に関する詳細については、推論ガイドを参照してください。

extra_body 引数を使用して、プロバイダー固有のパラメータをモデルに渡すことができます。

例:

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

ストリーミングを使用した例:

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

OpenAIの構文を使用した例:

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

サードパーティプロバイダーを直接使用し、追加の(プロバイダー固有の)パラメータを指定する例。利用料はTogether AIアカウントに請求されます。

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

Hugging Face Routing を介したサードパーティプロバイダーを使用する例。利用料は Hugging Face アカウントに請求されます。

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

画像とテキストを入力として使用する例:

# 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.

ツールを使用した例:

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

response_format を使用した例:

# 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"}'

閉じる

< >

( )

クライアントを閉じます。

このメソッドは、クライアントをコンテキストマネージャーとして使用する場合に自動的に呼び出されます。

文書質問応答

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]question: strmodel: str | None = Nonedoc_stride: int | None = Nonehandle_impossible_answer: bool | None = Nonelang: str | None = Nonemax_answer_len: int | None = Nonemax_question_len: int | None = Nonemax_seq_len: int | None = Nonetop_k: int | None = Noneword_boxes: list[list[float] | str] | None = None ) → list[DocumentQuestionAnsweringOutputElement]

パラメータ

  • image (Union[str, Path, bytes, BinaryIO]) — コンテキスト用の入力画像です。生のバイト列、画像ファイル、またはオンライン画像へのURLを指定できます。
  • question (str) — 回答する質問。
  • model (str, 任意) — ドキュメント質問応答タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨されるドキュメント質問応答モデルが使用されます。デフォルト値は None です。
  • doc_stride (int, 任意) — ドキュメントの単語が長すぎて、モデルの質問と合わせて収まらない場合、ある程度の重複を伴う複数のチャンクに分割されます。この引数は、その重複のサイズを制御します。
  • handle_impossible_answer (bool, 省略可) — impossible を回答として受け入れるかどうか
  • lang (str, 省略可) — OCR 実行時に使用する言語。デフォルトは english です。
  • max_answer_len (int, オプション) — 予測された回答の最大長です(例:この長さより短い回答のみが対象となります)。
  • max_question_len (int, 任意) — トークナイズ後の質問の最大長です。必要に応じて切り詰められます。
  • max_seq_len (int, 任意) — モデルに渡される各チャンクにおける、文全体(コンテキスト + 質問)の最大トークン数です。必要に応じて、コンテキストは複数のチャンクに分割されます(重複として doc_stride を使用)。
  • top_k (int, 任意) — 返す回答の数(確率の高い順に選択されます)。コンテキスト内で十分な選択肢がない場合は、top_k 未満の回答が返されることがあります。
  • word_boxes (list[Union[list[float], str, optional) — 単語とバウンディングボックス(正規化済み 0->1000)のリストです。指定された場合、推論は OCR ステップをスキップし、指定されたバウンディングボックスを使用します。

戻り値

list[DocumentQuestionAnsweringOutputElement]

予測ラベル、関連する確率、単語 ID、ページ番号を含むDocumentQuestionAnsweringOutputElementのアイテムのリスト。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

ドキュメントの画像に関する質問に回答します。

例:

# 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

< >

( text: str | list[str]normalize: bool | None = Noneprompt_name: str | None = Nonetruncate: bool | None = Nonetruncation_direction: typing.Optional[typing.Literal['left', 'right']] = Nonedimensions: int | None = Noneencoding_format: typing.Optional[typing.Literal['float', 'base64']] = Nonemodel: str | None = None ) → np.ndarray

パラメータ

  • text (str または list[str]) — 埋め込むテキストまたはテキストのリスト。
  • model (str, optional) — 特徴抽出タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨される特徴抽出モデルが使用されます。デフォルト値は None です。
  • normalize (bool, optional) — 埋め込みを正規化するか否かを指定します。 Text-Embedding-Inference によって提供されるサーバーでのみ利用可能です。
  • prompt_name (str, optional) — The name of the prompt that should be used by for encoding. If not set, no prompt will be applied. Must be a key in the Sentence Transformers configuration prompts dictionary. For example if prompt_name is “query” and the prompts is {“query”: “query: ”,…}, then the sentence “What is the capital of France?” will be encoded as “query: What is the capital of France?” because the prompt text will be prepended before any text to encode.
  • truncate (bool, optional) — 埋め込みを切り詰めるかどうかを指定します。 Text-Embedding-Inference によって提供されるサーバーでのみ利用可能です。
  • truncation_direction (Literal[“left”, “right”], optional) — truncate=True が渡された場合、入力のどの側を切り詰めるかを指定します。
  • dimensions (int, optional) — 結果として得られる出力埋め込みが持つべき次元数です。 OpenAI互換の埋め込みエンドポイントでのみ利用可能です。
  • encoding_format (Literal[“float”, “base64”], optional) — 出力埋め込みの形式です。“float”または“base64”のいずれかです。 OpenAI互換の埋め込みエンドポイントでのみ利用可能です。

戻り値

np.ndarray

float32型のNumPy配列として入力テキストを表す埋め込み。

例外

[InferenceTimeoutError] または [HfHubHTTPError]

  • [InferenceTimeoutError] — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • [HfHubHTTPError] — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたテキストまたはテキストのバッチに対して埋め込みを生成します。

例:

# 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

< >

( text: strmodel: str | None = Nonetargets: list[str] | None = Nonetop_k: int | None = None ) → list[FillMaskOutputElement]

パラメータ

  • text (str) — 埋め込む対象の文字列です。[MASK] トークンを含む必要があります(マスクの正確な名称はモデルカードを確認してください)。
  • model (str, 省略可能) — fill mask タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨される fill mask モデルが使用されます。
  • targets (list[str, 任意) — 指定された場合、モデルは語彙全体を検索する代わりに、渡されたターゲットにスコアを限定します。提供されたターゲットがモデルの語彙に存在しない場合、それらはトークン化され、最初の結果として得られたトークンが使用されます(警告が表示され、処理が遅くなる可能性があります)。
  • top_k (int, 省略可) — 指定された場合、返す予測の数を上書きします。

戻り値

list[FillMaskOutputElement]

予測ラベル、関連する確率、トークン参照、および補完されたテキストを含むFillMaskOutputElementの項目のリスト。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

欠落した単語(正確にはトークン)で穴を埋めます。

例:

# 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

< >

( model: str | None = None ) → dict[str, Any]

パラメータ

  • model (str, 任意) — 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。デフォルト値は None です。

戻り値

dict[str, Any]

エンドポイントに関する情報。

デプロイされたエンドポイントに関する情報を取得します。

このエンドポイントは、Text-Generation-Inference (TGI) または Text-Embedding-Inference (TEI) によって提供されるエンドポイントでのみ利用可能です。 transformers によって提供されるエンドポイントは、空のペイロードを返します。

例:

# 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

< >

( model: str | None = None ) → bool

パラメータ

  • model (str, 任意) — Inference Endpoint の URL。このパラメータは、インスタンスレベルで定義されたモデルを上書きします。デフォルト値は None です。

戻り値

bool

すべてが正常に動作している場合はTrue。

デプロイされたエンドポイントの健全性を確認します。

Health checkは、Text-Generation-Inference (TGI) または Text-Embedding-Inference (TEI) による Inference Endpoints のみで利用可能です。

例:

# 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

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]model: str | None = Nonefunction_to_apply: typing.Optional[ForwardRef('ImageClassificationOutputTransform')] = Nonetop_k: int | None = None ) → list[ImageClassificationOutputElement]

パラメータ

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 分類対象の画像です。生のバイト列、画像ファイル、オンライン画像のURL、またはPIL Imageを指定できます。
  • model (str, 省略可能) — 画像分類に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、画像分類用のデフォルトの推奨モデルが使用されます。
  • function_to_apply ("ImageClassificationOutputTransform", 省略可能) — スコアを取得するためにモデルの出力に適用する関数。
  • top_k (int, 省略可) — 指定すると、出力が最も確率の高い上位 K 個のクラスに制限されます。

戻り値

list[ImageClassificationOutputElement]

予測ラベルと関連する確率を含むImageClassificationOutputElementのリスト

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたモデルを使用して、与えられた画像で画像分類を実行します。

例:

# 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: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]model: str | None = Nonemask_threshold: float | None = Noneoverlap_mask_area_threshold: float | None = Nonesubtask: typing.Optional[ForwardRef('ImageSegmentationSubtask')] = Nonethreshold: float | None = None ) → list[ImageSegmentationOutputElement]

パラメータ

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — セグメント化対象の画像です。生のバイト列、画像ファイル、オンライン画像へのURL、またはPIL Imageを指定できます。
  • model (str, 任意) — 画像セグメンテーションに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、画像セグメンテーション用のデフォルトの推奨モデルが使用されます。
  • mask_threshold (float, 任意) — 予測されたマスクをバイナリ値に変換する際に使用する閾値。
  • overlap_mask_area_threshold (float, 任意) — 小さな断片化されたセグメントを除去するためのマスク重複の閾値です。
  • subtask ("ImageSegmentationSubtask", 任意) — モデルの機能に応じて実行されるセグメンテーションタスク。
  • threshold (float, 任意) — 予測されたマスクをフィルタリングするための確率の閾値。

戻り値

list[ImageSegmentationOutputElement]

セグメンテーションされたマスクと関連する属性を含む、ImageSegmentationOutputElement の項目のリストです。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたモデルを使用して、与えられた画像に対して画像セグメンテーションを実行します。

画像を扱うには、PILのインストールが必要です(pip install Pillow)。

例:

# 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

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]prompt: str | None = Nonenegative_prompt: str | None = Nonenum_inference_steps: int | None = Noneguidance_scale: float | None = Nonemodel: str | None = Nonetarget_size: huggingface_hub.inference._generated.types.image_to_image.ImageToImageTargetSize | None = None**kwargs ) → Image

パラメータ

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 翻訳の入力画像です。生のバイト列、画像ファイル、オンライン画像へのURL、またはPIL Imageを指定できます。
  • prompt (str, 任意) — 画像生成をガイドするためのテキストプロンプト。
  • negative_prompt (str, 任意) — 画像生成に含めるべきでない内容を指示するプロンプトを1つ指定します。
  • num_inference_steps (int, 任意) — 拡散モデル用。デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常、より高品質な画像が得られます。
  • guidance_scale (float, 任意) — 拡散モデル用です。guidance scale の値を高くすると、テキストプロンプトと密接に関連した画像を生成するようモデルに促されますが、その代わり画像の品質が低下します。
  • model (str, 任意) — 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。デフォルト値は None です。
  • target_size (ImageToImageTargetSize、任意) — 出力画像のピクセル単位でのサイズです。このパラメータは一部のプロバイダーおよび特定のモデルでのみサポートされています。サポートされていない場合は無視されます。

戻り値

Image

変換された画像。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたモデルを使用して、画像から画像への翻訳を実行します。

画像を扱うには、PILのインストールが必要です(pip install Pillow)。

例:

# 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

< >

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

パラメータ

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — キャプションを付与する入力画像です。生のバイト列、画像ファイル、オンライン画像へのURL、またはPIL Imageを指定できます。
  • model (str, 任意) — 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。デフォルト値は None です。

生成されたテキスト。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

入力画像を受け取り、テキストを返します。

モデルの出力は、ユースケース(画像キャプション生成、光学文字認識(OCR)、Pix2Struct など)によって大きく異なる場合があります。モデル固有の詳細については、モデルカードをご参照ください。

例:

# 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

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]model: str | None = Noneprompt: str | None = Nonenegative_prompt: str | None = Nonenum_frames: float | None = Nonenum_inference_steps: int | None = Noneguidance_scale: float | None = Noneseed: int | None = Nonetarget_size: huggingface_hub.inference._generated.types.image_to_video.ImageToVideoTargetSize | None = None**kwargs ) → bytes

パラメータ

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 動画の生成に使用する入力画像です。生のバイト列、画像ファイル、オンライン画像へのURL、またはPIL Imageを指定できます。
  • model (str, 任意) — 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。デフォルト値は None です。
  • prompt (str, 任意) — 動画生成をガイドするためのテキストプロンプト。
  • negative_prompt (str, 任意) — 動画生成に含めるべきでない内容を指示するプロンプトを1つ指定します。
  • num_frames (float, 任意) — num_frames パラメータは、生成される動画フレームの数を決定します。
  • num_inference_steps (int, 任意) — 拡散モデル用。デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常、より高品質な画像が得られます。
  • guidance_scale (float, 任意) — 拡散モデル用です。guidance scale の値を高くすると、テキストプロンプトと密接に関連した動画を生成するようモデルが促されますが、その代わり画像の品質が低下します。
  • seed (int, 任意) — 動画生成に使用するシード。
  • target_size (ImageToVideoTargetSize、任意) — 出力される動画フレームのピクセルサイズです。
  • num_inference_steps (int, 任意) — デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常、より高品質な動画が生成されます。
  • seed (int, 任意) — 乱数生成器のシード。

戻り値

bytes

生成された動画。

入力画像から動画を生成します。

例:

# 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

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]model: str | None = Nonethreshold: float | None = None ) → list[ObjectDetectionOutputElement]

パラメータ

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — オブジェクトを検出する対象の画像です。生のバイト列、画像ファイル、オンライン画像へのURL、またはPIL Imageを指定できます。
  • model (str, 任意) — オブジェクト検出に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、オブジェクト検出のデフォルト推奨モデル (DETR) が使用されます。
  • threshold (float, 任意) — 予測を行うために必要な確率。

戻り値

list[ObjectDetectionOutputElement]

バウンディングボックスと関連する属性を含むObjectDetectionOutputElementの項目のリスト。

例外

InferenceTimeoutError または HfHubHTTPError または ValueError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。
  • ValueError — リクエストの出力がListでない場合。

指定されたモデルを使用して、与えられた画像で物体検出を実行します。

画像を扱うには、PILのインストールが必要です(pip install Pillow)。

例:

# 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

< >

( question: strcontext: strmodel: str | None = Nonealign_to_words: bool | None = Nonedoc_stride: int | None = Nonehandle_impossible_answer: bool | None = Nonemax_answer_len: int | None = Nonemax_question_len: int | None = Nonemax_seq_len: int | None = Nonetop_k: int | None = None ) → Union[QuestionAnsweringOutputElement, listQuestionAnsweringOutputElement]

パラメータ

  • question (str) — 回答する質問。
  • context (str) — 質問のコンテキストです。
  • model (str) — 質問応答タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。
  • align_to_words (bool, オプション) — 回答を実際の単語に整列させようとします。スペースで単語が区切られている言語では品質が向上します。スペースで単語が区切られていない言語(日本語や中国語など)では品質が低下する可能性があります。
  • doc_stride (int, 任意) — コンテキストがモデルの質問と合わせて長くなりすぎる場合、ある程度の重複を伴う複数のチャンクに分割されます。この引数は、その重複のサイズを制御します。
  • handle_impossible_answer (bool, 省略可) — impossible を回答として受け入れるかどうか。
  • max_answer_len (int, オプション) — 予測された回答の最大長です(例:この長さより短い回答のみが対象となります)。
  • max_question_len (int, 任意) — トークナイズ後の質問の最大長です。必要に応じて切り詰められます。
  • max_seq_len (int, 任意) — モデルに渡される各チャンクにおける、文全体(コンテキスト + 質問)の最大トークン数です。必要に応じて、コンテキストは複数のチャンクに分割されます(重複として docStride を使用)。
  • top_k (int, 任意) — 返す回答の数(確率の高い順に選択されます)。コンテキスト内に十分な選択肢がない場合は、top_k より少ない数の回答が返されます。

戻り値

Union[QuestionAnsweringOutputElement, listQuestionAnsweringOutputElement]

top_k が 1 または指定されていない場合、単一の QuestionAnsweringOutputElement を返します。 top_k が 1 より大きい場合、QuestionAnsweringOutputElement のリストを返します。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

与えられたテキストから、質問に対する回答を取得します。

例:

# 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

< >

( sentence: strother_sentences: listmodel: str | None = None ) → list[float]

パラメータ

  • sentence (str) — 他の文と比較するための主な文。
  • other_sentences (list[str]) — 比較対象となる文のリストです。
  • model (str, 省略可) — 文の類似度タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、推奨されるデフォルトの文の類似度モデルが使用されます。デフォルト値は None です。

戻り値

list[float]

入力テキストを表す埋め込み。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

埋め込みを比較することにより、文と他の文のリストとの間の意味的類似度を計算します。

例:

# 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]

要約

< >

( text: strmodel: str | None = Noneclean_up_tokenization_spaces: bool | None = Nonegenerate_parameters: dict[str, typing.Any] | None = Nonetruncation: typing.Optional[ForwardRef('SummarizationTruncationStrategy')] = None ) → SummarizationOutput

パラメータ

  • text (str) — 要約する入力テキスト。
  • model (str, 任意) — 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、要約用のデフォルト推奨モデルが使用されます。
  • clean_up_tokenization_spaces (bool, 任意) — テキスト出力に含まれる可能性のある余分なスペースを整理するかどうか。
  • generate_parameters (dict[str, Any]、省略可) — テキスト生成アルゴリズムの追加のパラメータ設定。
  • truncation ("SummarizationTruncationStrategy"、任意) — 使用する切り詰め戦略です。

生成された要約テキスト。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたモデルを使用して、与えられたテキストの要約を生成します。

例:

# 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

< >

( table: dictquery: strmodel: str | None = Nonepadding: typing.Optional[ForwardRef('Padding')] = Nonesequential: bool | None = Nonetruncation: bool | None = None ) → TableQuestionAnsweringOutputElement

パラメータ

  • table (str) — リストの辞書として表形式で表されたデータ。エントリはヘッダー、リストはすべての値を表します。すべてのリストは同じサイズである必要があります。
  • query (str) — テーブルに尋ねたいクエリをプレーンテキストで指定します。
  • model (str) — テーブル質問応答タスクに使用するモデル。Hugging Face HubにホストされているモデルID、またはデプロイされたInference EndpointのURLを指定できます。
  • padding ("Padding"、任意) — パディングの有効化と制御を行います。
  • sequential (bool, 任意) — 推論をシーケンシャルに行うか、バッチとして行うかを指定します。バッチ処理の方が高速ですが、SQAのようなモデルは、対話的な性質から、シーケンス内の関係を抽出するためにシーケンシャルな推論が必要です。
  • truncation (bool、省略可) — 切り詰めを有効にし、切り詰めを制御します。

回答、座標、セル、および使用されたアグリゲーターを含むテーブル質問応答の出力

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

表に示された情報から、質問に対する答えを取得します。

例:

# 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

< >

( table: dictmodel: str | None = None ) → List

パラメータ

  • table (dict[str, Any]) — 分類する属性のセット。
  • model (str, 任意) — 表形式分類タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、推奨されるデフォルトの表形式分類モデルが使用されます。デフォルト値は None です。

戻り値

List

初期テーブルの各行に対応するラベルのリスト。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

属性のセットに基づいてターゲットカテゴリ(グループ)を分類します。

例:

# 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

< >

( table: dictmodel: str | None = None ) → List

パラメータ

  • table (dict[str, Any]) — テーブルに保存される属性のセットです。ターゲットを予測するために使用される属性は、数値型とカテゴリ型の両方を含むことができます。
  • model (str, 任意) — 表形式の回帰タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨される表形式の回帰モデルが使用されます。デフォルト値は None です。

戻り値

List

予測された数値ターゲット値のリスト。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

テーブル内の属性/特徴のセットが与えられたときに、数値のターゲット値を予測します。

例:

# 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: strmodel: str | None = Nonetop_k: int | None = Nonefunction_to_apply: typing.Optional[ForwardRef('TextClassificationOutputTransform')] = None ) → list[TextClassificationOutputElement]

パラメータ

  • text (str) — 分類対象の文字列。
  • model (str, 任意) — テキスト分類タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨されるテキスト分類モデルが使用されます。デフォルト値は None です。
  • top_k (int, 省略可) — 指定すると、出力が最も確率の高い上位 K 個のクラスに制限されます。
  • function_to_apply ("TextClassificationOutputTransform", 省略可能) — スコアを取得するためにモデルの出力に適用する関数。

戻り値

list[TextClassificationOutputElement]

予測ラベルと関連する確率を含むTextClassificationOutputElementのリスト

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

与えられたテキストに対してテキスト分類(例:感情分析)を実行します。

例:

# 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),
]

テキスト生成

< >

( prompt: strdetails: bool | None = Nonestream: bool | None = Nonemodel: str | None = Noneadapter_id: str | None = Nonebest_of: int | None = Nonedecoder_input_details: bool | None = Nonedo_sample: bool | None = Nonefrequency_penalty: float | None = Nonegrammar: huggingface_hub.inference._generated.types.text_generation.TextGenerationInputGrammarType | None = Nonemax_new_tokens: int | None = Nonerepetition_penalty: float | None = Nonereturn_full_text: bool | None = Noneseed: int | None = Nonestop: list[str] | None = Nonetemperature: float | None = Nonetop_k: int | None = Nonetop_n_tokens: int | None = Nonetop_p: float | None = Nonetruncate: int | None = Nonetypical_p: float | None = Nonewatermark: bool | None = None ) → Union[str, TextGenerationOutput, AsyncIterable[str], AsyncIterable[TextGenerationStreamOutput]]

パラメータ

  • prompt (str) — 入力テキスト。
  • details (bool, 省略可) — デフォルトでは、text_generation は文字列を返します。詳細な出力(トークン、確率、シード、終了理由など)が必要な場合は、details=True を渡してください。text-generation-inference バックエンドで実行されているモデルでのみ利用可能です。
  • stream (bool, 省略可) — デフォルトでは、text_generation は生成されたテキスト全体を返します。トークンのストリームを返す場合は、stream=True を渡してください。text-generation-inference バックエンドで実行されているモデルでのみ利用可能です。
  • model (str, 任意) — 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。デフォルト値は None です。
  • adapter_id (str, 省略可) — Lora アダプター ID。
  • best_of (int, オプション) — best_of 個のシーケンスを生成し、トークン logprobs が最も高いものを返します。
  • decoder_input_details (bool、任意) — デコーダー入力トークンの logprobs と id を返します。これを有効にするには、details=True も設定する必要があります。デフォルトは False です。
  • do_sample (bool、省略可) — logits サンプリングを有効にします
  • frequency_penalty (float, 任意) — -2.0 から 2.0 までの数値。正の値を指定すると、テキスト内でそれまでに出現した頻度に基づいて新しいトークンにペナルティが課され、同じ行をそのまま繰り返す可能性が低くなります。
  • grammar (TextGenerationInputGrammarType、任意) — 文法制約。JSONSchema または正規表現のいずれかです。
  • max_new_tokens (int, 任意) — 生成されるトークンの最大数。デフォルト値は100です。
  • repetition_penalty (float, 任意) — 反復ペナルティのパラメータです。1.0 はペナルティなしを意味します。詳細はこの論文を参照してください。
  • return_full_text (bool, 省略可) — 生成テキストの先頭にプロンプトを付加するかどうか
  • seed (int, 任意) — ランダムサンプリングのシード
  • stop (list[str], 任意) — stop のいずれかのメンバーが生成された場合、トークンの生成を停止します。
  • temperature (float, 任意) — logits の分布を調整するために使用される値。
  • top_n_tokens (int, 省略可) — サンプリングされたトークンのみではなく、各生成ステップにおける最も確率の高いtop_n_tokens個のトークンに関する情報を返します。
  • top_k (int, *optional`) — トップ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, *optional`) — 入力トークンを指定されたサイズに切り詰めます。
  • typical_p (float, *optional`) — Typical Decoding の質量 詳細は Typical Decoding for Natural Language Generation を参照してください
  • watermark (bool, 省略可) — 大規模言語モデルのためのウォーターマーク によるウォーターマーキング

戻り値

Union[str, TextGenerationOutput, AsyncIterable[str], AsyncIterable[TextGenerationStreamOutput]]

サーバーから返された生成テキスト:

  • stream=Falseかつdetails=Falseの場合、生成されたテキストはstrとして返されます(デフォルト)
  • stream=Trueかつdetails=Falseの場合、生成されたテキストはAsyncIterable[str]としてトークン単位で返されます。
  • stream=Falseかつdetails=Trueの場合、生成されたテキストはTextGenerationOutputとして、より詳細な情報とともに返されます。
  • details=Trueかつstream=Trueの場合、生成されたテキストはTextGenerationStreamOutputのイテラブルとしてトークン単位で返されます。

例外

ValidationError または InferenceTimeoutError または HfHubHTTPError

  • ValidationError — 入力値が有効でない場合。サーバーへのHTTP呼び出しは行われません。
  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

プロンプトが与えられた場合、以下のテキストを生成します。

チャットメッセージから応答を生成したい場合は、InferenceClient.chat_completion() メソッドを使用してください。 このメソッドは、単一のテキストプロンプトの代わりにメッセージのリストを受け取り、チャットテンプレート処理を自動で行います。

例:

# 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

< >

( prompt: strnegative_prompt: str | None = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int | None = Noneguidance_scale: float | None = Nonemodel: str | None = Nonescheduler: str | None = Noneseed: int | None = Noneextra_body: dict[str, typing.Any] | None = None ) → Image

パラメータ

  • prompt (str) — 画像を生成するためのプロンプト。
  • negative_prompt (str, 任意) — 画像生成に含めるべきでない内容を指示するプロンプトを1つ指定します。
  • height (int, 任意) — 出力画像のピクセル単位の縦幅
  • width (int, 任意) — 出力画像の幅(ピクセル単位)
  • num_inference_steps (int, 任意) — デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。
  • guidance_scale (float, 任意) — guidance scale の値を高くすると、テキストプロンプトと密接に関連した画像を生成するようモデルに促されますが、値が高すぎると飽和やその他のアーティファクトが発生する可能性があります。
  • model (str, 任意) — 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨されるテキストから画像生成へのモデルが使用されます。デフォルト値は None です。
  • scheduler (str, 省略可) — 互換性のあるスケジューラで上書きします。
  • seed (int, 任意) — 乱数生成器のシード。
  • extra_body (dict[str, Any], 省略可) — モデルに渡すプロバイダー固有の追加パラメータです。サポートされているパラメータについては、プロバイダーのドキュメントを参照してください。

戻り値

Image

生成された画像。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたモデルを使用して、与えられたテキストに基づいて画像を生成します。

画像を扱うには、PILのインストールが必要です(pip install Pillow)。

extra_body 引数を使用して、プロバイダー固有のパラメータをモデルに渡すことができます。

例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()

>>> image = await client.text_to_image("An astronaut riding a horse on the moon.")
>>> image.save("astronaut.png")

>>> image = await client.text_to_image(
...     "An astronaut riding a horse on the moon.",
...     negative_prompt="low resolution, blurry",
...     model="stabilityai/stable-diffusion-2-1",
... )
>>> image.save("better_astronaut.png")
Example using a third-party provider directly. Usage will be billed on your fal.ai account.
>>> 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")

Hugging Face Routing を介したサードパーティプロバイダーを使用する例。利用料は Hugging Face アカウントに請求されます。

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

Replicateプロバイダーを、追加パラメータ付きで使用する例

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

< >

( text: strmodel: str | None = Nonedo_sample: bool | None = Noneearly_stopping: typing.Union[bool, ForwardRef('TextToSpeechEarlyStoppingEnum'), NoneType] = Noneepsilon_cutoff: float | None = Noneeta_cutoff: float | None = Nonemax_length: int | None = Nonemax_new_tokens: int | None = Nonemin_length: int | None = Nonemin_new_tokens: int | None = Nonenum_beam_groups: int | None = Nonenum_beams: int | None = Nonepenalty_alpha: float | None = Nonetemperature: float | None = Nonetop_k: int | None = Nonetop_p: float | None = Nonetypical_p: float | None = Noneuse_cache: bool | None = Noneextra_body: dict[str, typing.Any] | None = None ) → bytes

パラメータ

  • text (str) — 合成するテキスト。
  • model (str, 任意) — 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨されるテキスト読み上げモデルが使用されます。デフォルト値は None です。
  • do_sample (bool, 省略可) — 新しいトークンを生成する際に、貪欲デコーディングではなくサンプリングを使用するかどうか。
  • early_stopping (Union[bool, "TextToSpeechEarlyStoppingEnum"]、省略可) — ビームベースの手法における停止条件を制御します。
  • epsilon_cutoff (float, 任意) — 0 より大きく 1 より小さい float 値に設定した場合、条件付き確率が epsilon_cutoff より大きいトークンのみがサンプリングされます。論文では、モデルサイズに応じて推奨値は 3e-4 から 9e-4 の範囲とされています。詳細は Truncation Sampling as Language Model Desmoothing を参照してください。
  • eta_cutoff (float, 省略可能) — Eta サンプリングは、ローカル・ティピカル・サンプリングとエプシロン・サンプリングのハイブリッドです。0 と 1 の間の float 値に設定すると、トークンは eta_cutoff または sqrt(eta_cutoff)
    • exp(-entropy(softmax(next_token_logits)))。後者の項は、直感的には、sqrt(eta_cutoff)でスケーリングされた次のトークンの期待確率です。論文では、モデルのサイズに応じて、提案値は3e-4から2e-3の範囲とされています。詳細については、Truncation Sampling as Language Model Desmoothingを参照してください。
  • max_length (int, 任意) — 入力を含む生成テキストの最大長(トークン数)。
  • max_new_tokens (int, 任意) — 生成するトークンの最大数です。max_length より優先されます。
  • min_length (int, 任意) — 生成テキストの最小長(トークン数)。入力を含みます。
  • min_new_tokens (int, 任意) — 生成するトークンの最小数です。min_length より優先されます。
  • num_beam_groups (int, 任意) — ビームの多様性を確保するために、num_beams を分割するグループの数。詳細はこの論文を参照してください。
  • num_beams (int, 任意) — ビームサーチに使用するビームの数。
  • penalty_alpha (float, 任意) — 対比検索デコーディングにおいて、モデルの信頼度と退化ペナルティのバランスを調整する値です。
  • temperature (float, 任意) — 次のトークンの確率を調整するために使用される値。
  • top_k (int, 任意) — トップkフィルタリングのために保持する、確率の高い語彙トークンの数。
  • top_p (float, 任意) — 1 未満の float に設定した場合、生成に使用されるのは、確率の合計が top_p 以上になる最も確率の高いトークンの最小集合のみです。
  • typical_p (float, 任意) — ローカルタイピシティは、すでに生成された部分テキストが与えられた条件下で、次のターゲットトークンを予測する条件付き確率が、次のランダムなトークンを予測する期待される条件付き確率とどれだけ類似しているかを測定します。float < 1 に設定すると、確率の合計が typical_p 以上となる最もローカルに典型的なトークンの最小集合が生成のために保持されます。詳細はこの論文を参照してください。
  • use_cache (bool, 省略可) — モデルがデコーディングを高速化するために、過去のキー/バリューの注意機構を使用するかどうか
  • extra_body (dict[str, Any], 省略可) — モデルに渡すプロバイダー固有の追加パラメータです。サポートされているパラメータについては、プロバイダーのドキュメントを参照してください。

戻り値

bytes

生成されたオーディオ。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたテキストを発音する音声のオーディオを合成します。

extra_body 引数を使用して、プロバイダー固有のパラメータをモデルに渡すことができます。

例:

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

サードパーティプロバイダーを直接使用する例。使用料はあなたのReplicateアカウントに請求されます。

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

Hugging Face Routing を介したサードパーティプロバイダーを使用する例。利用料は Hugging Face アカウントに請求されます。

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="replicate",
...     api_key="hf_...",  # Pass your HF token
... )
>>> audio =client.text_to_speech(
...     text="Hello world",
...     model="OuteAI/OuteTTS-0.3-500M",
... )
>>> Path("hello_world.flac").write_bytes(audio)
Example using Replicate provider with extra parameters
>>> 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)

fal.ai上で“YuE-s1-7B-anneal-en-cot”を使用した音楽生成の例

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

< >

( prompt: strmodel: str | None = Noneguidance_scale: float | None = Nonenegative_prompt: list[str] | None = Nonenum_frames: float | None = Nonenum_inference_steps: int | None = Noneseed: int | None = Noneextra_body: dict[str, typing.Any] | None = None ) → bytes

パラメータ

  • prompt (str) — 動画の生成に使用するプロンプト。
  • model (str, 任意) — 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨されるテキストから動画生成へのモデルが使用されます。デフォルト値は None です。
  • guidance_scale (float, 任意) — guidance scale の値を高くすると、テキストプロンプトと密接に関連した動画をモデルが生成するよう促されますが、値が高すぎると飽和やその他のアーティファクトが発生する可能性があります。
  • negative_prompt (list[str], 任意) — 動画生成に含めるべきでない内容を導くための、1つ以上のプロンプト。
  • num_frames (float, 任意) — num_frames パラメータは、生成される動画フレームの数を決定します。
  • num_inference_steps (int, 任意) — デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常、より高品質な動画が生成されます。
  • seed (int, 任意) — 乱数生成器のシード。
  • extra_body (dict[str, Any], 省略可) — モデルに渡すプロバイダー固有の追加パラメータです。サポートされているパラメータについては、プロバイダーのドキュメントを参照してください。

戻り値

bytes

生成された動画。

与えられたテキストに基づいて動画を生成します。

extra_body 引数を使用して、プロバイダー固有のパラメータをモデルに渡すことができます。

例:

サードパーティプロバイダーを直接使用する例。利用料はfal.aiアカウントに請求されます。

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

Hugging Face Routing を介したサードパーティプロバイダーを使用する例。利用料は Hugging Face アカウントに請求されます。

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

トークン分類

< >

( text: strmodel: str | None = Noneaggregation_strategy: typing.Optional[ForwardRef('TokenClassificationAggregationStrategy')] = Noneignore_labels: list[str] | None = Nonestride: int | None = None ) → list[TokenClassificationOutputElement]

パラメータ

  • text (str) — 分類対象の文字列。
  • model (str, 任意) — トークン分類タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨されるトークン分類モデルが使用されます。デフォルト値は None です。
  • aggregation_strategy ("TokenClassificationAggregationStrategy"、任意) — モデルの予測に基づいてトークンを融合するために使用される戦略
  • ignore_labels (list[str, 省略可) — 無視するラベルのリスト
  • stride (int, 省略可) — 入力テキストを分割する際に、チャンク間で重複するトークンの数。

戻り値

list[TokenClassificationOutputElement]

エンティティグループ、信頼度スコア、単語、開始および終了インデックスを含むTokenClassificationOutputElementの項目のリスト。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

与えられたテキストに対してトークン分類を実行します。 通常、文の解析(文法的な解析または)に使用され、テキストに含まれるキーワードを理解するために用いられます。

例:

# 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,
    )
]

翻訳

< >

( text: strmodel: str | None = Nonesrc_lang: str | None = Nonetgt_lang: str | None = Noneclean_up_tokenization_spaces: bool | None = Nonetruncation: typing.Optional[ForwardRef('TranslationTruncationStrategy')] = Nonegenerate_parameters: dict[str, typing.Any] | None = None ) → TranslationOutput

パラメータ

  • text (str) — 翻訳対象の文字列。
  • model (str, 省略可能) — 翻訳タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨される翻訳モデルが使用されます。デフォルト値は None です。
  • src_lang (str, 省略可) — テキストのソース言語です。複数言語からの翻訳に対応するモデルでは必須です。
  • tgt_lang (str, 任意) — 翻訳先の言語です。複数の言語への翻訳に対応するモデルでは必須です。
  • clean_up_tokenization_spaces (bool, 任意) — テキスト出力に含まれる可能性のある余分なスペースを整理するかどうか。
  • truncation ("TranslationTruncationStrategy"、任意) — 使用する切り詰め戦略です。
  • generate_parameters (dict[str, Any]、省略可) — テキスト生成アルゴリズムの追加のパラメータ設定。

生成された翻訳テキスト。

例外

InferenceTimeoutError または HfHubHTTPError または ValueError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。
  • ValueError — src_lang と tgt_lang の引数のうち、片方だけが提供された場合。

テキストをある言語から別の言語に変換します。

特定のユースケースに最適なモデルの選び方については、https://huggingface.co/tasks/translation をご覧ください。ソース言語とターゲット言語は通常、モデルによって決まります。 ただし、一部のモデルではソース言語とターゲット言語を指定できます。これらのモデルを使用している場合は、src_lang と tgt_lang 引数を使って関連情報を渡すことができます。

例:

# 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.')

言語の指定:

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

視覚的質問応答

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]question: strmodel: str | None = Nonetop_k: int | None = None ) → list[VisualQuestionAnsweringOutputElement]

パラメータ

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — コンテキスト用の入力画像です。生のバイト列、画像ファイル、オンライン画像へのURL、またはPIL Imageを指定できます。
  • question (str) — 回答する質問。
  • model (str, 任意) — 視覚的質問応答タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、推奨されるデフォルトの視覚的質問応答モデルが使用されます。デフォルト値は None です。
  • top_k (int, 任意) — 返す回答の数(確率の高い順に選択されます)。コンテキスト内に十分な選択肢がない場合は、top_k より少ない数の回答が返されます。

戻り値

list[VisualQuestionAnsweringOutputElement]

予測ラベルと関連する確率を含むVisualQuestionAnsweringOutputElementのリスト

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

画像に基づいてオープンエンドな質問に答える。

例:

# 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

< >

( text: strcandidate_labels: listmulti_label: bool | None = Falsehypothesis_template: str | None = Nonemodel: str | None = None ) → list[ZeroShotClassificationOutputElement]

パラメータ

  • text (str) — 分類する入力テキスト。
  • candidate_labels (list[str]) — テキストを分類するための候補となるクラスラベルの集合です。
  • multi_label (bool, 省略可) — 複数の候補ラベルが同時に真になり得るかどうかを指定します。false の場合、各シーケンスにおけるラベルの尤度の和が 1 になるようにスコアが正規化されます。true の場合、ラベルは独立であるとみなされ、各候補ごとに確率が正規化されます。
  • hypothesis_template (str, 任意) — candidate_labels と組み合わせて、プレースホルダーを候補ラベルに置き換えることでテキスト分類を試みるために使用される文です。
  • model (str, 任意) — 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。指定しない場合、デフォルトで推奨されるゼロショット分類モデルが使用されます。

戻り値

list[ZeroShotClassificationOutputElement]

予測ラベルとその信頼度を含むZeroShotClassificationOutputElementのリストです。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

入力としてテキストと、そのテキストを分類するための候補ラベルのセットを指定します。

multi_label=Falseの例:

# 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),
]

multi_label=Trueとカスタムのhypothesis_templateを用いた例:

# 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

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]candidate_labels: listmodel: str | None = Nonehypothesis_template: str | None = None ) → list[ZeroShotImageClassificationOutputElement]

パラメータ

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — キャプションを付与する入力画像です。生のバイト列、画像ファイル、オンライン画像へのURL、またはPIL Imageを指定できます。
  • candidate_labels (list[str]) — この画像の候補ラベル
  • model (str, 任意) — 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。指定しない場合、デフォルトで推奨されるゼロショット画像分類モデルが使用されます。
  • hypothesis_template (str, 任意) — candidate_labels と組み合わせて画像分類を試みる際に使用される文です。プレースホルダーを候補ラベルに置き換えます。

戻り値

list[ZeroShotImageClassificationOutputElement]

予測ラベルとその信頼度を含むZeroShotImageClassificationOutputElementのリストです。

例外

InferenceTimeoutError または HfHubHTTPError

  • InferenceTimeoutError — モデルが利用できない場合、またはリクエストがタイムアウトした場合。
  • HfHubHTTPError — HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

入力画像とテキストラベルを指定して、画像のテキストラベルを予測します。

例:

# 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

< >

( message: str )

モデルが利用できない場合、またはリクエストがタイムアウトした場合に発生するエラー。

Update on GitHub