Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
fix(inference): support Path, file object and PIL inputs in fal-ai AS…
…R and WaveSpeed image tasks

`FalAIAutomaticSpeechRecognitionTask` and `WavespeedAIImageToImageTask`
(inherited by `WavespeedAIImageToVideoTask`) built data URLs by hand and only
handled URL strings, plain str paths and raw bytes. A `Path`, an opened file
object or a PIL Image went straight into `base64.b64encode`, raising
`TypeError: a bytes-like object is required, not 'PosixPath'/'_io.BufferedReader'/'PngImageFile'`
before any request was sent.

Replace the hand-written encoding with the shared `_as_url` helper from
`inference/_common.py` (already used by fal-ai image-to-image, Replicate ASR,
Together, ...), which handles every input type documented by `InferenceClient`
and guesses the MIME type from the file name.

Fixes #5419
  • Loading branch information
theguysudo committed Nov 22, 2026
commit 54837f56259fcf4e128afd7cebc64ce9f1187f08
13 changes: 1 addition & 12 deletions src/huggingface_hub/inference/_providers/fal_ai.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,18 +93,7 @@ def __init__(self):
def _prepare_payload_as_dict(
self, inputs: Any, parameters: dict, provider_mapping_info: InferenceProviderMapping
) -> dict | None:
if isinstance(inputs, str) and inputs.startswith(("http://", "https://")):
# If input is a URL, pass it directly
audio_url = inputs
else:
# If input is a file path, read it first
if isinstance(inputs, str):
with open(inputs, "rb") as f:
inputs = f.read()

audio_b64 = base64.b64encode(inputs).decode()
content_type = "audio/mpeg"
audio_url = f"data:{content_type};base64,{audio_b64}"
audio_url = _as_url(inputs, default_mime_type="audio/mpeg")

return {"audio_url": audio_url, **filter_none(parameters)}

Expand Down
17 changes: 2 additions & 15 deletions src/huggingface_hub/inference/_providers/wavespeed.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import base64
import time
from abc import ABC
from typing import Any
from urllib.parse import urlparse

from huggingface_hub.hf_api import InferenceProviderMapping
from huggingface_hub.inference._common import RequestParameters, _as_dict
from huggingface_hub.inference._common import RequestParameters, _as_dict, _as_url
from huggingface_hub.inference._providers._common import TaskProviderHelper, filter_none
from huggingface_hub.utils import get_session, hf_raise_for_status
from huggingface_hub.utils.logging import get_logger
Expand Down Expand Up @@ -110,19 +109,7 @@ def _prepare_payload_as_dict(
parameters: dict,
provider_mapping_info: InferenceProviderMapping,
) -> dict | None:
# Convert inputs to image (URL or base64)
if isinstance(inputs, str) and inputs.startswith(("http://", "https://")):
image = inputs
elif isinstance(inputs, str):
# If input is a file path, read it first
with open(inputs, "rb") as f:
file_content = f.read()
image_b64 = base64.b64encode(file_content).decode("utf-8")
image = f"data:image/jpeg;base64,{image_b64}"
else:
# If input is binary data
image_b64 = base64.b64encode(inputs).decode("utf-8")
image = f"data:image/jpeg;base64,{image_b64}"
image = _as_url(inputs, default_mime_type="image/jpeg")

# Extract prompt from parameters if present
prompt = parameters.pop("prompt", None)
Expand Down
82 changes: 81 additions & 1 deletion tests/test_inference_providers.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import base64
import io
import logging
from unittest.mock import MagicMock, patch

import pytest
from PIL import Image
from pytest import LogCaptureFixture

from huggingface_hub import constants
Expand Down Expand Up @@ -462,14 +464,25 @@ def test_prepare_url(self):
url = FalAITextToImageTask()._prepare_url("hf_token", "username/repo_name")
assert url == "https://router.huggingface.co/fal-ai/username/repo_name"

def test_automatic_speech_recognition_payload(self):
def test_automatic_speech_recognition_payload(self, tmp_path):
helper = FalAIAutomaticSpeechRecognitionTask()
payload = helper._prepare_payload_as_dict("https://example.com/audio.mp3", {}, "username/repo_name")
assert payload == {"audio_url": "https://example.com/audio.mp3"}

payload = helper._prepare_payload_as_dict(b"dummy_audio_data", {}, "username/repo_name")
assert payload == {"audio_url": f"data:audio/mpeg;base64,{base64.b64encode(b'dummy_audio_data').decode()}"}

# Path input
audio_path = tmp_path / "audio.mp3"
audio_path.write_bytes(b"dummy_audio_data")
payload = helper._prepare_payload_as_dict(audio_path, {}, "username/repo_name")
assert payload == {"audio_url": f"data:audio/mpeg;base64,{base64.b64encode(b'dummy_audio_data').decode()}"}

# Opened file input
with open(audio_path, "rb") as f:
payload = helper._prepare_payload_as_dict(f, {}, "username/repo_name")
assert payload == {"audio_url": f"data:audio/mpeg;base64,{base64.b64encode(b'dummy_audio_data').decode()}"}

def test_automatic_speech_recognition_response(self):
helper = FalAIAutomaticSpeechRecognitionTask()
response = helper.get_response({"text": "Hello world"})
Expand Down Expand Up @@ -2158,6 +2171,73 @@ def test_prepare_image_to_video_payload(self, mocker):
}
mock_encode.assert_called_once_with(image_data)

def test_prepare_image_to_image_payload_from_path_and_file_object(self, tmp_path):
"""Test payload preparation for image-to-image task with Path and opened file inputs."""
helper = WavespeedAIImageToImageTask()
image_path = tmp_path / "image.jpg"
image_path.write_bytes(b"dummy_image_data")
expected_image = f"data:image/jpeg;base64,{base64.b64encode(b'dummy_image_data').decode()}"
mapping = InferenceProviderMapping(
provider="wavespeed",
hf_model_id="HiDream-ai/HiDream-E1-Full",
providerId="wavespeed-ai/hidream-e1-full",
task="image-to-image",
status="live",
)

# Path input
payload = helper._prepare_payload_as_dict(image_path, {"prompt": "The leopard chases its prey"}, mapping)
assert payload == {"image": expected_image, "prompt": "The leopard chases its prey"}

# Opened file input
with open(image_path, "rb") as f:
payload = helper._prepare_payload_as_dict(f, {}, mapping)
assert payload == {"image": expected_image}

def test_prepare_image_to_image_payload_from_pil_image(self):
"""Test payload preparation for image-to-image task with a PIL Image input."""
helper = WavespeedAIImageToImageTask()
buffer = io.BytesIO()
Image.new("RGB", (4, 4)).save(buffer, format="PNG")
buffer.seek(0)
pil_image = Image.open(buffer)

payload = helper._prepare_payload_as_dict(
pil_image,
{},
InferenceProviderMapping(
provider="wavespeed",
hf_model_id="HiDream-ai/HiDream-E1-Full",
providerId="wavespeed-ai/hidream-e1-full",
task="image-to-image",
status="live",
),
)
assert payload is not None
assert payload["image"].startswith("data:image/png;base64,")

def test_prepare_image_to_video_payload_from_path(self, tmp_path):
"""Test payload preparation for image-to-video task with a Path input."""
helper = WavespeedAIImageToVideoTask()
image_path = tmp_path / "image.jpg"
image_path.write_bytes(b"dummy_image_data")

payload = helper._prepare_payload_as_dict(
image_path,
{"prompt": "The leopard chases its prey"},
InferenceProviderMapping(
provider="wavespeed",
hf_model_id="Wan-AI/Wan2.1-I2V-14B-480P",
providerId="wavespeed-ai/wan-2.1/i2v-480p",
task="image-to-video",
status="live",
),
)
assert payload == {
"image": f"data:image/jpeg;base64,{base64.b64encode(b'dummy_image_data').decode()}",
"prompt": "The leopard chases its prey",
}

def test_prepare_urls(self):
"""Test URL preparation for different tasks."""
# Text to Image
Expand Down