pixeltable 0.4.12__py3-none-any.whl → 0.4.14__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of pixeltable might be problematic. Click here for more details.
- pixeltable/__init__.py +11 -1
- pixeltable/catalog/__init__.py +2 -1
- pixeltable/catalog/catalog.py +179 -63
- pixeltable/catalog/column.py +24 -20
- pixeltable/catalog/table.py +96 -124
- pixeltable/catalog/table_metadata.py +96 -0
- pixeltable/catalog/table_version.py +15 -6
- pixeltable/catalog/view.py +22 -22
- pixeltable/config.py +2 -0
- pixeltable/dataframe.py +3 -2
- pixeltable/env.py +43 -21
- pixeltable/exec/__init__.py +1 -0
- pixeltable/exec/aggregation_node.py +0 -1
- pixeltable/exec/cache_prefetch_node.py +74 -98
- pixeltable/exec/data_row_batch.py +2 -18
- pixeltable/exec/in_memory_data_node.py +1 -1
- pixeltable/exec/object_store_save_node.py +299 -0
- pixeltable/exec/sql_node.py +28 -33
- pixeltable/exprs/data_row.py +31 -25
- pixeltable/exprs/json_path.py +6 -5
- pixeltable/exprs/row_builder.py +6 -12
- pixeltable/functions/gemini.py +1 -1
- pixeltable/functions/openai.py +1 -1
- pixeltable/functions/video.py +5 -6
- pixeltable/globals.py +6 -7
- pixeltable/index/embedding_index.py +5 -8
- pixeltable/io/__init__.py +2 -1
- pixeltable/io/fiftyone.py +1 -1
- pixeltable/io/label_studio.py +4 -5
- pixeltable/io/lancedb.py +3 -0
- pixeltable/io/parquet.py +9 -89
- pixeltable/io/table_data_conduit.py +2 -2
- pixeltable/iterators/audio.py +1 -1
- pixeltable/iterators/document.py +10 -12
- pixeltable/iterators/video.py +1 -1
- pixeltable/metadata/schema.py +7 -0
- pixeltable/plan.py +26 -1
- pixeltable/share/packager.py +8 -2
- pixeltable/share/publish.py +3 -9
- pixeltable/type_system.py +1 -3
- pixeltable/utils/arrow.py +97 -2
- pixeltable/utils/dbms.py +31 -5
- pixeltable/utils/gcs_store.py +283 -0
- pixeltable/utils/lancedb.py +88 -0
- pixeltable/utils/local_store.py +316 -0
- pixeltable/utils/object_stores.py +497 -0
- pixeltable/utils/pytorch.py +5 -6
- pixeltable/utils/s3_store.py +354 -0
- {pixeltable-0.4.12.dist-info → pixeltable-0.4.14.dist-info}/METADATA +162 -127
- {pixeltable-0.4.12.dist-info → pixeltable-0.4.14.dist-info}/RECORD +53 -47
- pixeltable/utils/media_store.py +0 -248
- pixeltable/utils/s3.py +0 -17
- {pixeltable-0.4.12.dist-info → pixeltable-0.4.14.dist-info}/WHEEL +0 -0
- {pixeltable-0.4.12.dist-info → pixeltable-0.4.14.dist-info}/entry_points.txt +0 -0
- {pixeltable-0.4.12.dist-info → pixeltable-0.4.14.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import glob
|
|
4
|
+
import logging
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import shutil
|
|
8
|
+
import urllib.parse
|
|
9
|
+
import urllib.request
|
|
10
|
+
import uuid
|
|
11
|
+
from collections import defaultdict
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import TYPE_CHECKING, Optional
|
|
14
|
+
from uuid import UUID
|
|
15
|
+
|
|
16
|
+
import PIL.Image
|
|
17
|
+
|
|
18
|
+
from pixeltable import env, exceptions as excs
|
|
19
|
+
from pixeltable.utils.object_stores import ObjectPath, ObjectStoreBase, StorageObjectAddress
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
from pixeltable.catalog import Column
|
|
23
|
+
|
|
24
|
+
_logger = logging.getLogger('pixeltable')
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class LocalStore(ObjectStoreBase):
|
|
28
|
+
"""
|
|
29
|
+
Utilities to manage files stored in a local filesystem directory.
|
|
30
|
+
|
|
31
|
+
Media file names are a composite of: table id, column id, tbl_version, new uuid:
|
|
32
|
+
the table id/column id/tbl_version are redundant but useful for identifying all files for a table
|
|
33
|
+
or all files created for a particular version of a table
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
__base_dir: Path
|
|
37
|
+
|
|
38
|
+
soa: Optional[StorageObjectAddress]
|
|
39
|
+
|
|
40
|
+
def __init__(self, location: Path | StorageObjectAddress):
|
|
41
|
+
if isinstance(location, Path):
|
|
42
|
+
self.__base_dir = location
|
|
43
|
+
self.soa = None
|
|
44
|
+
else:
|
|
45
|
+
assert isinstance(location, StorageObjectAddress)
|
|
46
|
+
self.__base_dir = location.to_path
|
|
47
|
+
self.soa = location
|
|
48
|
+
|
|
49
|
+
def validate(self, error_col_name: str) -> str:
|
|
50
|
+
"""Convert a Column destination parameter to a URI, else raise errors."""
|
|
51
|
+
dest_path = self.__base_dir
|
|
52
|
+
|
|
53
|
+
# Check if path exists and validate it's a directory
|
|
54
|
+
if not dest_path.exists():
|
|
55
|
+
raise excs.Error(f'{error_col_name}`destination` does not exist')
|
|
56
|
+
if not dest_path.is_dir():
|
|
57
|
+
raise excs.Error(f'{error_col_name}`destination` must be a directory, not a file')
|
|
58
|
+
|
|
59
|
+
# Check if path is absolute
|
|
60
|
+
if dest_path.is_absolute():
|
|
61
|
+
# Convert to file URI
|
|
62
|
+
return dest_path.as_uri()
|
|
63
|
+
|
|
64
|
+
# For relative paths, convert to absolute first
|
|
65
|
+
try:
|
|
66
|
+
absolute_path = dest_path.resolve()
|
|
67
|
+
return absolute_path.as_uri()
|
|
68
|
+
except (OSError, ValueError) as e:
|
|
69
|
+
raise excs.Error(f'{error_col_name}`destination` must be a valid path. Error: {e}') from None
|
|
70
|
+
|
|
71
|
+
@staticmethod
|
|
72
|
+
def file_url_to_path(url: str) -> Optional[Path]:
|
|
73
|
+
"""Convert a file:// URI to a Path object with support for Windows UNC paths."""
|
|
74
|
+
assert isinstance(url, str), type(url)
|
|
75
|
+
parsed = urllib.parse.urlparse(url)
|
|
76
|
+
|
|
77
|
+
# Verify it's a file scheme
|
|
78
|
+
# We should never be passed a local file path here. The "len > 1" ensures that Windows
|
|
79
|
+
# file paths aren't mistaken for URLs with a single-character scheme.
|
|
80
|
+
assert len(parsed.scheme) > 1, url
|
|
81
|
+
if parsed.scheme.lower() != 'file':
|
|
82
|
+
return None
|
|
83
|
+
|
|
84
|
+
pth = parsed.path
|
|
85
|
+
if parsed.netloc:
|
|
86
|
+
# This is a UNC path, ie, file://host/share/path/to/file
|
|
87
|
+
pth = f'//{parsed.netloc}{pth}'
|
|
88
|
+
|
|
89
|
+
path_str = urllib.parse.unquote(urllib.request.url2pathname(pth))
|
|
90
|
+
return Path(path_str)
|
|
91
|
+
|
|
92
|
+
@classmethod
|
|
93
|
+
def _save_binary_media_file(cls, file_data: bytes, dest_path: Path, format: Optional[str]) -> Path:
|
|
94
|
+
"""Save binary data to a file in a LocalStore. format is ignored for binary data."""
|
|
95
|
+
assert isinstance(file_data, bytes)
|
|
96
|
+
with open(dest_path, 'wb') as f:
|
|
97
|
+
f.write(file_data)
|
|
98
|
+
f.flush() # Ensures Python buffers are written to OS
|
|
99
|
+
os.fsync(f.fileno()) # Forces OS to write to physical storage
|
|
100
|
+
return dest_path
|
|
101
|
+
|
|
102
|
+
@classmethod
|
|
103
|
+
def _save_pil_image_file(cls, image: PIL.Image.Image, dest_path: Path, format: Optional[str]) -> Path:
|
|
104
|
+
"""Save a PIL Image to a file in a LocalStore with the specified format."""
|
|
105
|
+
if dest_path.suffix != f'.{format}':
|
|
106
|
+
dest_path = dest_path.with_name(f'{dest_path.name}.{format}')
|
|
107
|
+
|
|
108
|
+
with open(dest_path, 'wb') as f:
|
|
109
|
+
image.save(f, format=format)
|
|
110
|
+
f.flush() # Ensures Python buffers are written to OS
|
|
111
|
+
os.fsync(f.fileno()) # Forces OS to write to physical storage
|
|
112
|
+
return dest_path
|
|
113
|
+
|
|
114
|
+
def _prepare_path_raw(self, tbl_id: UUID, col_id: int, tbl_version: int, ext: Optional[str] = None) -> Path:
|
|
115
|
+
"""
|
|
116
|
+
Construct a new, unique Path name in the __base_dir for a persisted file.
|
|
117
|
+
Create the parent directory for the new Path if it does not already exist.
|
|
118
|
+
"""
|
|
119
|
+
prefix, filename = ObjectPath.create_prefix_raw(tbl_id, col_id, tbl_version, ext)
|
|
120
|
+
parent = self.__base_dir / Path(prefix)
|
|
121
|
+
parent.mkdir(parents=True, exist_ok=True)
|
|
122
|
+
return parent / filename
|
|
123
|
+
|
|
124
|
+
def _prepare_path(self, col: Column, ext: Optional[str] = None) -> Path:
|
|
125
|
+
"""
|
|
126
|
+
Construct a new, unique Path name in the __base_dir for a persisted file.
|
|
127
|
+
Create the parent directory for the new Path if it does not already exist.
|
|
128
|
+
"""
|
|
129
|
+
assert col.tbl is not None, 'Column must be associated with a table'
|
|
130
|
+
return self._prepare_path_raw(col.tbl.id, col.id, col.tbl.version, ext)
|
|
131
|
+
|
|
132
|
+
def contains_path(self, file_path: Path) -> bool:
|
|
133
|
+
"""Return True if the given path refers to a file managed by this LocalStore, else False."""
|
|
134
|
+
return str(file_path).startswith(str(self.__base_dir))
|
|
135
|
+
|
|
136
|
+
def resolve_url(self, file_url: Optional[str]) -> Optional[Path]:
|
|
137
|
+
"""Return path if the given url refers to a file managed by this LocalStore, else None.
|
|
138
|
+
|
|
139
|
+
Args:
|
|
140
|
+
file_url: URL to check
|
|
141
|
+
|
|
142
|
+
Returns:
|
|
143
|
+
If the url is a managed file, return a Path() to the file, None, otherwise
|
|
144
|
+
"""
|
|
145
|
+
if file_url is None:
|
|
146
|
+
return None
|
|
147
|
+
file_path = self.file_url_to_path(file_url)
|
|
148
|
+
if file_path is None:
|
|
149
|
+
return None
|
|
150
|
+
if not str(file_path).startswith(str(self.__base_dir)):
|
|
151
|
+
# not a tmp file
|
|
152
|
+
return None
|
|
153
|
+
return file_path
|
|
154
|
+
|
|
155
|
+
def move_local_file(self, col: Column, src_path: Path) -> str:
|
|
156
|
+
"""Move a local file to this store, and return its new URL"""
|
|
157
|
+
dest_path = self._prepare_path(col, ext=src_path.suffix)
|
|
158
|
+
src_path.rename(dest_path)
|
|
159
|
+
new_file_url = urllib.parse.urljoin('file:', urllib.request.pathname2url(str(dest_path)))
|
|
160
|
+
_logger.debug(f'Media Storage: moved {src_path} to {new_file_url}')
|
|
161
|
+
return new_file_url
|
|
162
|
+
|
|
163
|
+
def copy_local_file(self, col: Column, src_path: Path) -> str:
|
|
164
|
+
"""Copy a local file to a this store, and return its new URL"""
|
|
165
|
+
dest_path = self._prepare_path(col, ext=src_path.suffix)
|
|
166
|
+
shutil.copy2(src_path, dest_path)
|
|
167
|
+
new_file_url = urllib.parse.urljoin('file:', urllib.request.pathname2url(str(dest_path)))
|
|
168
|
+
_logger.debug(f'Media Storage: copied {src_path} to {new_file_url}')
|
|
169
|
+
return new_file_url
|
|
170
|
+
|
|
171
|
+
def save_media_object(self, data: bytes | PIL.Image.Image, col: Column, format: Optional[str]) -> tuple[Path, str]:
|
|
172
|
+
"""Save a data object to a file in a LocalStore
|
|
173
|
+
Returns:
|
|
174
|
+
dest_path: Path to the saved file
|
|
175
|
+
url: URL of the saved file
|
|
176
|
+
"""
|
|
177
|
+
assert col.col_type.is_media_type(), f'LocalStore: request to store non media_type Column {col.name}'
|
|
178
|
+
dest_path = self._prepare_path(col)
|
|
179
|
+
if isinstance(data, bytes):
|
|
180
|
+
dest_path = self._save_binary_media_file(data, dest_path, format)
|
|
181
|
+
elif isinstance(data, PIL.Image.Image):
|
|
182
|
+
dest_path = self._save_pil_image_file(data, dest_path, format)
|
|
183
|
+
else:
|
|
184
|
+
raise ValueError(f'Unsupported object type: {type(data)}')
|
|
185
|
+
new_file_url = urllib.parse.urljoin('file:', urllib.request.pathname2url(str(dest_path)))
|
|
186
|
+
return dest_path, new_file_url
|
|
187
|
+
|
|
188
|
+
def delete(self, tbl_id: UUID, tbl_version: Optional[int] = None) -> Optional[int]:
|
|
189
|
+
"""Delete all files belonging to tbl_id. If tbl_version is not None, delete
|
|
190
|
+
only those files belonging to the specified tbl_version.
|
|
191
|
+
|
|
192
|
+
Return:
|
|
193
|
+
Number of files deleted or None
|
|
194
|
+
"""
|
|
195
|
+
assert tbl_id is not None
|
|
196
|
+
table_prefix = ObjectPath.table_prefix(tbl_id)
|
|
197
|
+
if tbl_version is None:
|
|
198
|
+
# Remove the entire folder for this table id.
|
|
199
|
+
path = self.__base_dir / table_prefix
|
|
200
|
+
if path.exists():
|
|
201
|
+
shutil.rmtree(path)
|
|
202
|
+
return None
|
|
203
|
+
else:
|
|
204
|
+
# Remove only the elements for the specified tbl_version.
|
|
205
|
+
paths = glob.glob(
|
|
206
|
+
str(self.__base_dir / table_prefix) + f'/**/{table_prefix}_*_{tbl_version}_*', recursive=True
|
|
207
|
+
)
|
|
208
|
+
for p in paths:
|
|
209
|
+
os.remove(p)
|
|
210
|
+
return len(paths)
|
|
211
|
+
|
|
212
|
+
def count(self, tbl_id: Optional[UUID], tbl_version: Optional[int] = None) -> int:
|
|
213
|
+
"""
|
|
214
|
+
Return number of files for given tbl_id.
|
|
215
|
+
"""
|
|
216
|
+
if tbl_id is None:
|
|
217
|
+
paths = glob.glob(str(self.__base_dir / '*'), recursive=True)
|
|
218
|
+
elif tbl_version is None:
|
|
219
|
+
table_prefix = ObjectPath.table_prefix(tbl_id)
|
|
220
|
+
paths = glob.glob(str(self.__base_dir / table_prefix) + f'/**/{table_prefix}_*', recursive=True)
|
|
221
|
+
else:
|
|
222
|
+
table_prefix = ObjectPath.table_prefix(tbl_id)
|
|
223
|
+
paths = glob.glob(
|
|
224
|
+
str(self.__base_dir / table_prefix) + f'/**/{table_prefix}_*_{tbl_version}_*', recursive=True
|
|
225
|
+
)
|
|
226
|
+
# Filter out directories, only count files
|
|
227
|
+
return len([p for p in paths if not os.path.isdir(p)])
|
|
228
|
+
|
|
229
|
+
def stats(self) -> list[tuple[UUID, int, int, int]]:
|
|
230
|
+
paths = glob.glob(str(self.__base_dir) + '/**', recursive=True)
|
|
231
|
+
# key: (tbl_id, col_id), value: (num_files, size)
|
|
232
|
+
d: dict[tuple[UUID, int], list[int]] = defaultdict(lambda: [0, 0])
|
|
233
|
+
for p in paths:
|
|
234
|
+
if not os.path.isdir(p):
|
|
235
|
+
matched = re.match(ObjectPath.PATTERN, Path(p).name)
|
|
236
|
+
assert matched is not None
|
|
237
|
+
tbl_id, col_id = UUID(hex=matched[1]), int(matched[2])
|
|
238
|
+
file_info = os.stat(p)
|
|
239
|
+
t = d[tbl_id, col_id]
|
|
240
|
+
t[0] += 1
|
|
241
|
+
t[1] += file_info.st_size
|
|
242
|
+
result = [(tbl_id, col_id, num_files, size) for (tbl_id, col_id), (num_files, size) in d.items()]
|
|
243
|
+
result.sort(key=lambda e: e[3], reverse=True)
|
|
244
|
+
return result
|
|
245
|
+
|
|
246
|
+
def list_objects(self, return_uri: bool, n_max: int = 10) -> list[str]:
|
|
247
|
+
"""Return a list of objects found with the specified location
|
|
248
|
+
Each returned object includes the full set of prefixes.
|
|
249
|
+
if return_uri is True, the full GCS URI is returned; otherwise, just the object key.
|
|
250
|
+
"""
|
|
251
|
+
r = []
|
|
252
|
+
for root, _, files in os.walk(self.__base_dir):
|
|
253
|
+
for file in files:
|
|
254
|
+
r.append(Path(root, file).as_uri() if return_uri else os.path.join(root, file))
|
|
255
|
+
return r
|
|
256
|
+
|
|
257
|
+
def clear(self) -> None:
|
|
258
|
+
"""Clear all files from the store."""
|
|
259
|
+
if self.__base_dir.exists():
|
|
260
|
+
shutil.rmtree(self.__base_dir)
|
|
261
|
+
self.__base_dir.mkdir()
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
class TempStore:
|
|
265
|
+
"""
|
|
266
|
+
A temporary store for files of data that are not yet persisted to their destination(s).
|
|
267
|
+
A destination is typically either a LocalStore (local persisted files) or a cloud object store.
|
|
268
|
+
|
|
269
|
+
The TempStore class has no internal state. It provides functionality to manage temporary files
|
|
270
|
+
in the env.Env.get().tmp_dir directory.
|
|
271
|
+
It reuses some of the LocalStore functionality to create unique file names and save objects.
|
|
272
|
+
"""
|
|
273
|
+
|
|
274
|
+
@classmethod
|
|
275
|
+
def _tmp_dir(cls) -> Path:
|
|
276
|
+
"""Returns the path to the temporary directory where files are stored."""
|
|
277
|
+
return env.Env.get().tmp_dir
|
|
278
|
+
|
|
279
|
+
@classmethod
|
|
280
|
+
def count(cls, tbl_id: Optional[UUID] = None, tbl_version: Optional[int] = None) -> int:
|
|
281
|
+
return LocalStore(cls._tmp_dir()).count(tbl_id, tbl_version)
|
|
282
|
+
|
|
283
|
+
@classmethod
|
|
284
|
+
def contains_path(cls, file_path: Path) -> bool:
|
|
285
|
+
return LocalStore(cls._tmp_dir()).contains_path(file_path)
|
|
286
|
+
|
|
287
|
+
@classmethod
|
|
288
|
+
def resolve_url(cls, file_url: Optional[str]) -> Optional[Path]:
|
|
289
|
+
return LocalStore(cls._tmp_dir()).resolve_url(file_url)
|
|
290
|
+
|
|
291
|
+
@classmethod
|
|
292
|
+
def save_media_object(cls, data: bytes | PIL.Image.Image, col: Column, format: Optional[str]) -> tuple[Path, str]:
|
|
293
|
+
return LocalStore(cls._tmp_dir()).save_media_object(data, col, format)
|
|
294
|
+
|
|
295
|
+
@classmethod
|
|
296
|
+
def delete_media_file(cls, file_path: Path) -> None:
|
|
297
|
+
"""Delete an object from the temporary store."""
|
|
298
|
+
assert file_path is not None, 'Object path must be provided'
|
|
299
|
+
assert file_path.exists(), f'Object path does not exist: {file_path}'
|
|
300
|
+
assert cls.contains_path(file_path), f'Object path must be in the TempStore: {file_path}'
|
|
301
|
+
file_path.unlink()
|
|
302
|
+
_logger.debug(f'Media Storage: deleted {file_path}')
|
|
303
|
+
|
|
304
|
+
@classmethod
|
|
305
|
+
def create_path(cls, tbl_id: Optional[UUID] = None, extension: str = '') -> Path:
|
|
306
|
+
"""Return a new, unique Path located in the temporary store.
|
|
307
|
+
If tbl_id is provided, the path name will be similar to a LocalStore path based on the tbl_id.
|
|
308
|
+
If tbl_id is None, a random UUID will be used to create the path."""
|
|
309
|
+
if tbl_id is not None:
|
|
310
|
+
return LocalStore(cls._tmp_dir())._prepare_path_raw(tbl_id, 0, 0, extension)
|
|
311
|
+
return cls._tmp_dir() / f'{uuid.uuid4()}{extension}'
|
|
312
|
+
|
|
313
|
+
@classmethod
|
|
314
|
+
def clear(cls) -> None:
|
|
315
|
+
"""Clear all files from the temporary store."""
|
|
316
|
+
LocalStore(cls._tmp_dir()).clear()
|