Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
9 changes: 8 additions & 1 deletion replicate/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,13 @@ async def async_delete(self, file_id: str) -> bool:
return resp.status_code == 204


def get_file_name(file: Union[BinaryIO, io.IOBase]) -> str:
name = getattr(file, "name", None)
if isinstance(name, (str, bytes, os.PathLike)):
return os.path.basename(os.fsdecode(name))
return "file"


def _create_file_params(
file: Union[BinaryIO, io.IOBase],
**params: Unpack["Files.CreateFileParams"],
Expand All @@ -155,7 +162,7 @@ def _create_file_params(
if params is None:
params = {}

filename = params.get("filename", os.path.basename(getattr(file, "name", "file")))
filename = params.get("filename", get_file_name(file))
content_type = (
params.get("content_type")
or mimetypes.guess_type(filename)[0]
Expand Down
4 changes: 3 additions & 1 deletion replicate/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

import httpx

from replicate.file import get_file_name

if TYPE_CHECKING:
from replicate.client import Client
from replicate.file import FileEncodingStrategy
Expand Down Expand Up @@ -110,7 +112,7 @@ def base64_encode_file(file: io.IOBase) -> str:
encoded_body = base64.b64encode(body).decode("utf-8")

mime_type = (
mimetypes.guess_type(getattr(file, "name", ""))[0] or "application/octet-stream"
mimetypes.guess_type(get_file_name(file))[0] or "application/octet-stream"
)
return f"data:{mime_type};base64,{encoded_body}"

Expand Down
33 changes: 27 additions & 6 deletions tests/test_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -586,9 +586,27 @@ async def test_run_with_model_error(mock_replicate_api_token):
assert excinfo.value.prediction.status == "failed"


@pytest.fixture(params=["unnamed", "null-name", "descriptor"])
def prediction_file(request, tmp_path):
if request.param == "descriptor":
with (tmp_path / "source").open("wb+") as source:
with open(source.fileno(), "rb+", closefd=False) as file:
file.write(b"hello world")
yield file
else:
file = io.BytesIO(b"hello world")
if request.param == "null-name":
# An unrolled SpooledTemporaryFile can expose a null name.
file.name = None
with file:
yield file


@pytest.mark.asyncio
@pytest.mark.parametrize("async_flag", [True, False])
async def test_run_with_file_input_files_api(async_flag, mock_replicate_api_token):
async def test_run_with_file_input_files_api(
async_flag, mock_replicate_api_token, prediction_file
):
router = respx.Router(base_url="https://api.replicate.com/v1")
mock_predictions_create = router.route(method="POST", path="/predictions").mock(
return_value=httpx.Response(
Expand Down Expand Up @@ -633,12 +651,12 @@ async def test_run_with_file_input_files_api(async_flag, mock_replicate_api_toke
if async_flag:
await client.async_run(
"test/example:v1",
input={"file": io.BytesIO(initial_bytes=b"hello world")},
input={"file": prediction_file},
)
else:
client.run(
"test/example:v1",
input={"file": io.BytesIO(initial_bytes=b"hello world")},
input={"file": prediction_file},
)

assert mock_predictions_create.called
Expand All @@ -660,13 +678,16 @@ async def test_run_with_file_input_files_api(async_flag, mock_replicate_api_toke
next(parsed_message_generator) # wrapper
input_file = next(parsed_message_generator)
assert mock_files_create.called
assert input_file.get_filename() == "file"
assert input_file.get_content() == b"hello world"
assert input_file.get_content_type() == "application/octet-stream"


@pytest.mark.asyncio
@pytest.mark.parametrize("async_flag", [True, False])
async def test_run_with_file_input_data_url(async_flag, mock_replicate_api_token):
async def test_run_with_file_input_data_url(
async_flag, mock_replicate_api_token, prediction_file
):
router = respx.Router(base_url="https://api.replicate.com/v1")
mock_predictions_create = router.route(method="POST", path="/predictions").mock(
return_value=httpx.Response(
Expand All @@ -692,13 +713,13 @@ async def test_run_with_file_input_data_url(async_flag, mock_replicate_api_token
if async_flag:
await client.async_run(
"test/example:v1",
input={"file": io.BytesIO(initial_bytes=b"hello world")},
input={"file": prediction_file},
file_encoding_strategy="base64",
)
else:
client.run(
"test/example:v1",
input={"file": io.BytesIO(initial_bytes=b"hello world")},
input={"file": prediction_file},
file_encoding_strategy="base64",
)

Expand Down