-
Notifications
You must be signed in to change notification settings - Fork 271
Expand file tree
/
Copy pathfile.py
More file actions
177 lines (129 loc) · 5.07 KB
/
Copy pathfile.py
File metadata and controls
177 lines (129 loc) · 5.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import io
import json
import mimetypes
import os
import pathlib
from typing import Any, BinaryIO, Dict, List, Optional, TypedDict, Union
from typing_extensions import Literal, NotRequired, Unpack
from replicate.resource import Namespace, Resource
FileEncodingStrategy = Literal["base64", "url"]
class File(Resource):
"""
A file uploaded to Replicate that can be used as an input to a model.
"""
id: str
"""The ID of the file."""
name: str
"""The name of the file."""
content_type: str
"""The content type of the file."""
size: int
"""The size of the file in bytes."""
etag: str
"""The ETag of the file."""
checksums: Dict[str, str]
"""The checksums of the file."""
metadata: Dict[str, Any]
"""The metadata of the file."""
created_at: str
"""The time the file was created."""
expires_at: Optional[str]
"""The time the file will expire."""
urls: Dict[str, str]
"""The URLs of the file."""
class Files(Namespace):
class CreateFileParams(TypedDict):
"""Parameters for creating a file."""
filename: NotRequired[str]
"""The name of the file."""
content_type: NotRequired[str]
"""The content type of the file."""
metadata: NotRequired[Dict[str, Any]]
"""The file metadata."""
def create(
self,
file: Union[str, pathlib.Path, BinaryIO, io.IOBase],
**params: Unpack["Files.CreateFileParams"],
) -> File:
"""
Upload a file that can be passed as an input when running a model.
"""
if isinstance(file, (str, pathlib.Path)):
file_path = pathlib.Path(file)
params["filename"] = file_path.name
with open(file, "rb") as f:
return self.create(f, **params)
elif not isinstance(file, (io.IOBase, BinaryIO)):
raise ValueError(
"Unsupported file type. Must be a file path or file-like object."
)
resp = self._client._request(
"POST", "/v1/files", timeout=None, **_create_file_params(file, **params)
)
return _json_to_file(resp.json())
async def async_create(
self,
file: Union[str, pathlib.Path, BinaryIO, io.IOBase],
**params: Unpack["Files.CreateFileParams"],
) -> File:
"""Upload a file asynchronously that can be passed as an input when running a model."""
if isinstance(file, (str, pathlib.Path)):
file_path = pathlib.Path(file)
params["filename"] = file_path.name
with open(file_path, "rb") as f:
return await self.async_create(f, **params)
elif not isinstance(file, (io.IOBase, BinaryIO)):
raise ValueError(
"Unsupported file type. Must be a file path or file-like object."
)
resp = await self._client._async_request(
"POST", "/v1/files", timeout=None, **_create_file_params(file, **params)
)
return _json_to_file(resp.json())
def get(self, file_id: str) -> File:
"""Get an uploaded file by its ID."""
resp = self._client._request("GET", f"/v1/files/{file_id}")
return _json_to_file(resp.json())
async def async_get(self, file_id: str) -> File:
"""Get an uploaded file by its ID asynchronously."""
resp = await self._client._async_request("GET", f"/v1/files/{file_id}")
return _json_to_file(resp.json())
def list(self) -> List[File]:
"""List all uploaded files."""
resp = self._client._request("GET", "/v1/files")
return [_json_to_file(obj) for obj in resp.json().get("results", [])]
async def async_list(self) -> List[File]:
"""List all uploaded files asynchronously."""
resp = await self._client._async_request("GET", "/v1/files")
return [_json_to_file(obj) for obj in resp.json().get("results", [])]
def delete(self, file_id: str) -> bool:
"""Delete an uploaded file by its ID."""
resp = self._client._request("DELETE", f"/v1/files/{file_id}")
return resp.status_code == 204
async def async_delete(self, file_id: str) -> bool:
"""Delete an uploaded file by its ID asynchronously."""
resp = await self._client._async_request("DELETE", f"/v1/files/{file_id}")
return resp.status_code == 204
def _create_file_params(
file: Union[BinaryIO, io.IOBase],
**params: Unpack["Files.CreateFileParams"],
) -> Dict[str, Any]:
file.seek(0)
if params is None:
params = {}
filename = params.get("filename", os.path.basename(getattr(file, "name", "file")))
content_type = (
params.get("content_type")
or mimetypes.guess_type(filename)[0]
or "application/octet-stream"
)
metadata = params.get("metadata")
data = {}
if metadata:
data["metadata"] = json.dumps(metadata)
return {
"files": {"content": (filename, file, content_type)},
"data": data,
}
def _json_to_file(json: Dict[str, Any]) -> File: # pylint: disable=redefined-outer-name
return File(**json)