diff --git a/replicate/helpers.py b/replicate/helpers.py index 62c7d67..2f935f2 100644 --- a/replicate/helpers.py +++ b/replicate/helpers.py @@ -21,6 +21,77 @@ HAS_NUMPY = False +class FileOutput(httpx.SyncByteStream, httpx.AsyncByteStream): + """ + An object that can be used to read the contents of an output file + created by running a Replicate model. + """ + + url: str + """ + The file URL. + """ + + _client: "Client" + + def __init__(self, url: str, client: "Client") -> None: + self.url = url + self._client = client + + def read(self) -> bytes: + if self.url.startswith("data:"): + _, encoded = self.url.split(",", 1) + return base64.b64decode(encoded) + + with self._client._client.stream("GET", self.url) as response: + response.raise_for_status() + return response.read() + + def __iter__(self) -> Iterator[bytes]: + if self.url.startswith("data:"): + yield self.read() + return + + with self._client._client.stream("GET", self.url) as response: + response.raise_for_status() + yield from response.iter_bytes() + + async def aread(self) -> bytes: + if self.url.startswith("data:"): + _, encoded = self.url.split(",", 1) + return base64.b64decode(encoded) + + async with self._client._async_client.stream("GET", self.url) as response: + response.raise_for_status() + return await response.aread() + + async def __aiter__(self) -> AsyncIterator[bytes]: + if self.url.startswith("data:"): + yield await self.aread() + return + + async with self._client._async_client.stream("GET", self.url) as response: + response.raise_for_status() + async for chunk in response.aiter_bytes(): + yield chunk + + def __str__(self) -> str: + return self.url + + def __repr__(self) -> str: + return f"FileOutput({self.url!r})" + + def __eq__(self, other: Any) -> bool: # noqa: ANN401 + if isinstance(other, FileOutput): + return self.url == other.url + if isinstance(other, str): + return self.url == other + return NotImplemented + + def __hash__(self) -> int: + return hash(self.url) + + # pylint: disable=too-many-return-statements def encode_json( obj: Any, # noqa: ANN401 @@ -45,6 +116,15 @@ def encode_json( if file_encoding_strategy == "base64": return base64_encode_file(obj) return client.files.create(obj).urls["get"] + if isinstance(obj, FileOutput): + if file_encoding_strategy == "base64": + if obj.url.startswith("data:"): + return obj.url + data = obj.read() + encoded = base64.b64encode(data).decode("utf-8") + mime_type = mimetypes.guess_type(obj.url)[0] or "application/octet-stream" + return f"data:{mime_type};base64,{encoded}" + return obj.url if HAS_NUMPY: if isinstance(obj, np.integer): # type: ignore return int(obj) @@ -82,6 +162,15 @@ async def async_encode_json( # TODO: This should ideally use an async based file reader path. return base64_encode_file(obj) return (await client.files.async_create(obj)).urls["get"] + if isinstance(obj, FileOutput): + if file_encoding_strategy == "base64": + if obj.url.startswith("data:"): + return obj.url + data = await obj.aread() + encoded = base64.b64encode(data).decode("utf-8") + mime_type = mimetypes.guess_type(obj.url)[0] or "application/octet-stream" + return f"data:{mime_type};base64,{encoded}" + return obj.url if HAS_NUMPY: if isinstance(obj, np.integer): # type: ignore return int(obj) @@ -115,64 +204,6 @@ def base64_encode_file(file: io.IOBase) -> str: return f"data:{mime_type};base64,{encoded_body}" -class FileOutput(httpx.SyncByteStream, httpx.AsyncByteStream): - """ - An object that can be used to read the contents of an output file - created by running a Replicate model. - """ - - url: str - """ - The file URL. - """ - - _client: "Client" - - def __init__(self, url: str, client: "Client") -> None: - self.url = url - self._client = client - - def read(self) -> bytes: - if self.url.startswith("data:"): - _, encoded = self.url.split(",", 1) - return base64.b64decode(encoded) - - with self._client._client.stream("GET", self.url) as response: - response.raise_for_status() - return response.read() - - def __iter__(self) -> Iterator[bytes]: - if self.url.startswith("data:"): - yield self.read() - return - - with self._client._client.stream("GET", self.url) as response: - response.raise_for_status() - yield from response.iter_bytes() - - async def aread(self) -> bytes: - if self.url.startswith("data:"): - _, encoded = self.url.split(",", 1) - return base64.b64decode(encoded) - - async with self._client._async_client.stream("GET", self.url) as response: - response.raise_for_status() - return await response.aread() - - async def __aiter__(self) -> AsyncIterator[bytes]: - if self.url.startswith("data:"): - yield await self.aread() - return - - async with self._client._async_client.stream("GET", self.url) as response: - response.raise_for_status() - async for chunk in response.aiter_bytes(): - yield chunk - - def __str__(self) -> str: - return self.url - - def transform_output(value: Any, client: "Client") -> Any: """ Transform the output of a prediction to a `FileOutput` object if it's a URL. diff --git a/tests/test_helpers.py b/tests/test_helpers.py index 0c41cab..9d2ba46 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -33,3 +33,77 @@ def test_base64_encode_file(content, filename, expected): # Call the function and check the result result = base64_encode_file(file) assert result == expected + + +def test_file_output_equality_and_repr(): + from replicate.client import Client + from replicate.helpers import FileOutput + + client = Client(api_token="test") + fo1 = FileOutput("https://replicate.delivery/test.png", client) + fo2 = FileOutput("https://replicate.delivery/test.png", client) + fo3 = FileOutput("https://replicate.delivery/other.png", client) + + assert fo1 == fo2 + assert fo1 != fo3 + assert fo1 == "https://replicate.delivery/test.png" + assert "https://replicate.delivery/test.png" == fo1 + assert fo1 != "https://replicate.delivery/other.png" + assert repr(fo1) == "FileOutput('https://replicate.delivery/test.png')" + assert hash(fo1) == hash("https://replicate.delivery/test.png") + assert {fo1, fo2} == {fo1} + + +def test_encode_json_with_file_output(): + import json + + from replicate.client import Client + from replicate.helpers import FileOutput, encode_json + + client = Client(api_token="test") + url = "https://replicate.delivery/test.png" + fo = FileOutput(url, client) + + # Direct FileOutput encoding + encoded = encode_json(fo, client) + assert encoded == url + assert json.dumps({"image": encoded}) == f'{{"image": "{url}"}}' + + # Nested FileOutput in dict and list + nested = {"image": fo, "images": [fo]} + encoded_nested = encode_json(nested, client) + assert encoded_nested == {"image": url, "images": [url]} + assert json.dumps(encoded_nested) == f'{{"image": "{url}", "images": ["{url}"]}}' + + # Data URI FileOutput with base64 strategy + data_uri = "data:image/png;base64,iVBORw0KGgo=" + fo_data = FileOutput(data_uri, client) + assert encode_json(fo_data, client, file_encoding_strategy="base64") == data_uri + + +@pytest.mark.asyncio +async def test_async_encode_json_with_file_output(): + import json + + from replicate.client import Client + from replicate.helpers import FileOutput, async_encode_json + + client = Client(api_token="test") + url = "https://replicate.delivery/test.png" + fo = FileOutput(url, client) + + encoded = await async_encode_json(fo, client) + assert encoded == url + assert json.dumps({"image": encoded}) == f'{{"image": "{url}"}}' + + nested = {"image": fo, "images": [fo]} + encoded_nested = await async_encode_json(nested, client) + assert encoded_nested == {"image": url, "images": [url]} + assert json.dumps(encoded_nested) == f'{{"image": "{url}", "images": ["{url}"]}}' + + data_uri = "data:image/png;base64,iVBORw0KGgo=" + fo_data = FileOutput(data_uri, client) + assert ( + await async_encode_json(fo_data, client, file_encoding_strategy="base64") + == data_uri + ) diff --git a/tests/test_prediction.py b/tests/test_prediction.py index b3c110e..0c14445 100644 --- a/tests/test_prediction.py +++ b/tests/test_prediction.py @@ -189,9 +189,80 @@ async def test_predictions_create_by_deployment(async_flag): assert prediction.status == "starting" +@pytest.mark.asyncio +@pytest.mark.parametrize("async_flag", [True, False]) +async def test_predictions_create_with_file_output_input(async_flag): + import json + + from replicate.helpers import FileOutput + + router = respx.Router(base_url="https://api.replicate.com/v1") + captured_request = {} + + def mock_create(request): + captured_request["body"] = json.loads(request.content) + return httpx.Response( + 201, + json={ + "id": "p_file_out", + "model": "owner/model", + "version": "v1", + "urls": { + "get": "https://api.replicate.com/v1/predictions/p_file_out", + "cancel": "https://api.replicate.com/v1/predictions/p_file_out/cancel", + }, + "created_at": "2024-01-01T00:00:00Z", + "source": "api", + "status": "starting", + "input": captured_request["body"]["input"], + "output": None, + "error": None, + "logs": "", + }, + ) + + router.route( + method="POST", + path="/predictions", + name="predictions.create", + ).mock(side_effect=mock_create) + router.route(host="api.replicate.com").pass_through() + + client = replicate.Client( + api_token="test-token", transport=httpx.MockTransport(router.handler) + ) + + fo = FileOutput("https://replicate.delivery/pbxt/sample.png", client) + input_data = { + "image": fo, + "gallery": [fo], + } + + if async_flag: + prediction = await client.predictions.async_create( + version="v1", + input=input_data, + ) + else: + prediction = client.predictions.create( + version="v1", + input=input_data, + ) + + assert prediction.id == "p_file_out" + assert ( + captured_request["body"]["input"]["image"] + == "https://replicate.delivery/pbxt/sample.png" + ) + assert captured_request["body"]["input"]["gallery"] == [ + "https://replicate.delivery/pbxt/sample.png" + ] + + @pytest.mark.asyncio @pytest.mark.parametrize("async_flag", [True, False]) async def test_predictions_create_fail_with_too_many_arguments(async_flag): + router = respx.Router(base_url="https://api.replicate.com/v1") client = replicate.Client(