Skip to content

Commit c754874

Browse files
authored
Support os.PathLike output from models (#2388)
This commit updates two pieces of our file handling code to work with `os.PathLike` objects. 1. When transforming the output into a data-structure suitable for encoding in `make_encodable` we convert the `PathLike` into a `pathlib.Path` instance. 2. When reading the file data from disk in `upload_files` we use `open()` instead of `Path.open()`. This provides broader support for path-like objects, particularly the new replicate-python client which will return path-like objects from the new `use()` helper.
1 parent 267eaeb commit c754874

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

python/cog/json.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import io
2+
import os
23
import pathlib
34
from datetime import datetime
45
from enum import Enum
@@ -39,6 +40,8 @@ def make_encodeable(obj: Any) -> Any: # pylint: disable=too-many-return-stateme
3940
return obj.value
4041
if isinstance(obj, datetime):
4142
return obj.isoformat()
43+
if isinstance(obj, os.PathLike):
44+
return pathlib.Path(obj)
4245
if np:
4346
if isinstance(obj, np.integer):
4447
return int(obj)
@@ -62,8 +65,8 @@ def upload_files(obj: Any, upload_file: Callable[[io.IOBase], str]) -> Any:
6265
return {key: upload_files(value, upload_file) for key, value in obj.items()}
6366
if isinstance(obj, list):
6467
return [upload_files(value, upload_file) for value in obj]
65-
if isinstance(obj, pathlib.Path):
66-
with obj.open("rb") as f:
68+
if isinstance(obj, os.PathLike):
69+
with open(obj, "rb") as f:
6770
return upload_file(f)
6871
if isinstance(obj, io.IOBase):
6972
return upload_file(obj)

0 commit comments

Comments
 (0)