pixeltable 0.4.0rc3__py3-none-any.whl → 0.4.20__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 +23 -5
- pixeltable/_version.py +1 -0
- pixeltable/catalog/__init__.py +5 -3
- pixeltable/catalog/catalog.py +1318 -404
- pixeltable/catalog/column.py +186 -115
- pixeltable/catalog/dir.py +1 -2
- pixeltable/catalog/globals.py +11 -43
- pixeltable/catalog/insertable_table.py +167 -79
- pixeltable/catalog/path.py +61 -23
- pixeltable/catalog/schema_object.py +9 -10
- pixeltable/catalog/table.py +626 -308
- pixeltable/catalog/table_metadata.py +101 -0
- pixeltable/catalog/table_version.py +713 -569
- pixeltable/catalog/table_version_handle.py +37 -6
- pixeltable/catalog/table_version_path.py +42 -29
- pixeltable/catalog/tbl_ops.py +50 -0
- pixeltable/catalog/update_status.py +191 -0
- pixeltable/catalog/view.py +108 -94
- pixeltable/config.py +128 -22
- pixeltable/dataframe.py +188 -100
- pixeltable/env.py +407 -136
- pixeltable/exceptions.py +6 -0
- pixeltable/exec/__init__.py +3 -0
- pixeltable/exec/aggregation_node.py +7 -8
- pixeltable/exec/cache_prefetch_node.py +83 -110
- pixeltable/exec/cell_materialization_node.py +231 -0
- pixeltable/exec/cell_reconstruction_node.py +135 -0
- pixeltable/exec/component_iteration_node.py +4 -3
- pixeltable/exec/data_row_batch.py +8 -65
- pixeltable/exec/exec_context.py +16 -4
- pixeltable/exec/exec_node.py +13 -36
- pixeltable/exec/expr_eval/evaluators.py +7 -6
- pixeltable/exec/expr_eval/expr_eval_node.py +27 -12
- pixeltable/exec/expr_eval/globals.py +8 -5
- pixeltable/exec/expr_eval/row_buffer.py +1 -2
- pixeltable/exec/expr_eval/schedulers.py +190 -30
- pixeltable/exec/globals.py +32 -0
- pixeltable/exec/in_memory_data_node.py +18 -18
- pixeltable/exec/object_store_save_node.py +293 -0
- pixeltable/exec/row_update_node.py +16 -9
- pixeltable/exec/sql_node.py +206 -101
- pixeltable/exprs/__init__.py +1 -1
- pixeltable/exprs/arithmetic_expr.py +27 -22
- pixeltable/exprs/array_slice.py +3 -3
- pixeltable/exprs/column_property_ref.py +34 -30
- pixeltable/exprs/column_ref.py +92 -96
- pixeltable/exprs/comparison.py +5 -5
- pixeltable/exprs/compound_predicate.py +5 -4
- pixeltable/exprs/data_row.py +152 -55
- pixeltable/exprs/expr.py +62 -43
- pixeltable/exprs/expr_dict.py +3 -3
- pixeltable/exprs/expr_set.py +17 -10
- pixeltable/exprs/function_call.py +75 -37
- pixeltable/exprs/globals.py +1 -2
- pixeltable/exprs/in_predicate.py +4 -4
- pixeltable/exprs/inline_expr.py +10 -27
- pixeltable/exprs/is_null.py +1 -3
- pixeltable/exprs/json_mapper.py +8 -8
- pixeltable/exprs/json_path.py +56 -22
- pixeltable/exprs/literal.py +5 -5
- pixeltable/exprs/method_ref.py +2 -2
- pixeltable/exprs/object_ref.py +2 -2
- pixeltable/exprs/row_builder.py +127 -53
- pixeltable/exprs/rowid_ref.py +8 -12
- pixeltable/exprs/similarity_expr.py +50 -25
- pixeltable/exprs/sql_element_cache.py +4 -4
- pixeltable/exprs/string_op.py +5 -5
- pixeltable/exprs/type_cast.py +3 -5
- pixeltable/func/__init__.py +1 -0
- pixeltable/func/aggregate_function.py +8 -8
- pixeltable/func/callable_function.py +9 -9
- pixeltable/func/expr_template_function.py +10 -10
- pixeltable/func/function.py +18 -20
- pixeltable/func/function_registry.py +6 -7
- pixeltable/func/globals.py +2 -3
- pixeltable/func/mcp.py +74 -0
- pixeltable/func/query_template_function.py +20 -18
- pixeltable/func/signature.py +43 -16
- pixeltable/func/tools.py +23 -13
- pixeltable/func/udf.py +18 -20
- pixeltable/functions/__init__.py +6 -0
- pixeltable/functions/anthropic.py +93 -33
- pixeltable/functions/audio.py +114 -10
- pixeltable/functions/bedrock.py +13 -6
- pixeltable/functions/date.py +1 -1
- pixeltable/functions/deepseek.py +20 -9
- pixeltable/functions/fireworks.py +2 -2
- pixeltable/functions/gemini.py +28 -11
- pixeltable/functions/globals.py +13 -13
- pixeltable/functions/groq.py +108 -0
- pixeltable/functions/huggingface.py +1046 -23
- pixeltable/functions/image.py +9 -18
- pixeltable/functions/llama_cpp.py +23 -8
- pixeltable/functions/math.py +3 -4
- pixeltable/functions/mistralai.py +4 -15
- pixeltable/functions/ollama.py +16 -9
- pixeltable/functions/openai.py +104 -82
- pixeltable/functions/openrouter.py +143 -0
- pixeltable/functions/replicate.py +2 -2
- pixeltable/functions/reve.py +250 -0
- pixeltable/functions/string.py +21 -28
- pixeltable/functions/timestamp.py +13 -14
- pixeltable/functions/together.py +4 -6
- pixeltable/functions/twelvelabs.py +92 -0
- pixeltable/functions/util.py +6 -1
- pixeltable/functions/video.py +1388 -106
- pixeltable/functions/vision.py +7 -7
- pixeltable/functions/whisper.py +15 -7
- pixeltable/functions/whisperx.py +179 -0
- pixeltable/{ext/functions → functions}/yolox.py +2 -4
- pixeltable/globals.py +332 -105
- pixeltable/index/base.py +13 -22
- pixeltable/index/btree.py +23 -22
- pixeltable/index/embedding_index.py +32 -44
- pixeltable/io/__init__.py +4 -2
- pixeltable/io/datarows.py +7 -6
- pixeltable/io/external_store.py +49 -77
- pixeltable/io/fiftyone.py +11 -11
- pixeltable/io/globals.py +29 -28
- pixeltable/io/hf_datasets.py +17 -9
- pixeltable/io/label_studio.py +70 -66
- pixeltable/io/lancedb.py +3 -0
- pixeltable/io/pandas.py +12 -11
- pixeltable/io/parquet.py +13 -93
- pixeltable/io/table_data_conduit.py +71 -47
- pixeltable/io/utils.py +3 -3
- pixeltable/iterators/__init__.py +2 -1
- pixeltable/iterators/audio.py +21 -11
- pixeltable/iterators/document.py +116 -55
- pixeltable/iterators/image.py +5 -2
- pixeltable/iterators/video.py +293 -13
- pixeltable/metadata/__init__.py +4 -2
- pixeltable/metadata/converters/convert_18.py +2 -2
- pixeltable/metadata/converters/convert_19.py +2 -2
- pixeltable/metadata/converters/convert_20.py +2 -2
- pixeltable/metadata/converters/convert_21.py +2 -2
- pixeltable/metadata/converters/convert_22.py +2 -2
- pixeltable/metadata/converters/convert_24.py +2 -2
- pixeltable/metadata/converters/convert_25.py +2 -2
- pixeltable/metadata/converters/convert_26.py +2 -2
- pixeltable/metadata/converters/convert_29.py +4 -4
- pixeltable/metadata/converters/convert_34.py +2 -2
- pixeltable/metadata/converters/convert_36.py +2 -2
- pixeltable/metadata/converters/convert_37.py +15 -0
- pixeltable/metadata/converters/convert_38.py +39 -0
- pixeltable/metadata/converters/convert_39.py +124 -0
- pixeltable/metadata/converters/convert_40.py +73 -0
- pixeltable/metadata/converters/util.py +13 -12
- pixeltable/metadata/notes.py +4 -0
- pixeltable/metadata/schema.py +79 -42
- pixeltable/metadata/utils.py +74 -0
- pixeltable/mypy/__init__.py +3 -0
- pixeltable/mypy/mypy_plugin.py +123 -0
- pixeltable/plan.py +274 -223
- pixeltable/share/__init__.py +1 -1
- pixeltable/share/packager.py +259 -129
- pixeltable/share/protocol/__init__.py +34 -0
- pixeltable/share/protocol/common.py +170 -0
- pixeltable/share/protocol/operation_types.py +33 -0
- pixeltable/share/protocol/replica.py +109 -0
- pixeltable/share/publish.py +213 -57
- pixeltable/store.py +238 -175
- pixeltable/type_system.py +104 -63
- pixeltable/utils/__init__.py +2 -3
- pixeltable/utils/arrow.py +108 -13
- pixeltable/utils/av.py +298 -0
- pixeltable/utils/azure_store.py +305 -0
- pixeltable/utils/code.py +3 -3
- pixeltable/utils/console_output.py +4 -1
- pixeltable/utils/coroutine.py +6 -23
- pixeltable/utils/dbms.py +31 -5
- pixeltable/utils/description_helper.py +4 -5
- pixeltable/utils/documents.py +5 -6
- pixeltable/utils/exception_handler.py +7 -30
- pixeltable/utils/filecache.py +6 -6
- pixeltable/utils/formatter.py +4 -6
- pixeltable/utils/gcs_store.py +283 -0
- pixeltable/utils/http_server.py +2 -3
- pixeltable/utils/iceberg.py +1 -2
- pixeltable/utils/image.py +17 -0
- pixeltable/utils/lancedb.py +88 -0
- pixeltable/utils/local_store.py +316 -0
- pixeltable/utils/misc.py +5 -0
- pixeltable/utils/object_stores.py +528 -0
- pixeltable/utils/pydantic.py +60 -0
- pixeltable/utils/pytorch.py +5 -6
- pixeltable/utils/s3_store.py +392 -0
- pixeltable-0.4.20.dist-info/METADATA +587 -0
- pixeltable-0.4.20.dist-info/RECORD +218 -0
- {pixeltable-0.4.0rc3.dist-info → pixeltable-0.4.20.dist-info}/WHEEL +1 -1
- pixeltable-0.4.20.dist-info/entry_points.txt +2 -0
- pixeltable/__version__.py +0 -3
- pixeltable/ext/__init__.py +0 -17
- pixeltable/ext/functions/__init__.py +0 -11
- pixeltable/ext/functions/whisperx.py +0 -77
- pixeltable/utils/media_store.py +0 -77
- pixeltable/utils/s3.py +0 -17
- pixeltable/utils/sample.py +0 -25
- pixeltable-0.4.0rc3.dist-info/METADATA +0 -435
- pixeltable-0.4.0rc3.dist-info/RECORD +0 -189
- pixeltable-0.4.0rc3.dist-info/entry_points.txt +0 -3
- {pixeltable-0.4.0rc3.dist-info → pixeltable-0.4.20.dist-info/licenses}/LICENSE +0 -0
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import shutil
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Literal
|
|
7
|
+
|
|
8
|
+
import pixeltable as pxt
|
|
9
|
+
import pixeltable.exceptions as excs
|
|
10
|
+
from pixeltable.catalog import Catalog
|
|
11
|
+
from pixeltable.env import Env
|
|
12
|
+
|
|
13
|
+
_logger = logging.getLogger('pixeltable')
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def export_lancedb(
|
|
17
|
+
table_or_df: pxt.Table | pxt.DataFrame,
|
|
18
|
+
db_uri: Path,
|
|
19
|
+
table_name: str,
|
|
20
|
+
batch_size_bytes: int = 128 * 2**20,
|
|
21
|
+
if_exists: Literal['error', 'overwrite', 'append'] = 'error',
|
|
22
|
+
) -> None:
|
|
23
|
+
"""
|
|
24
|
+
Exports a dataframe's data to a LanceDB table.
|
|
25
|
+
|
|
26
|
+
This utilizes LanceDB's streaming interface for efficient table creation, via a sequence of in-memory pyarrow
|
|
27
|
+
`RecordBatches`, the size of which can be controlled with the `batch_size_bytes` parameter.
|
|
28
|
+
|
|
29
|
+
__Requirements:__
|
|
30
|
+
|
|
31
|
+
- `pip install lancedb`
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
table_or_df : Table or Dataframe to export.
|
|
35
|
+
db_uri: Local Path to the LanceDB database.
|
|
36
|
+
table_name : Name of the table in the LanceDB database.
|
|
37
|
+
batch_size_bytes : Maximum size in bytes for each batch.
|
|
38
|
+
if_exists: Determines the behavior if the table already exists. Must be one of the following:
|
|
39
|
+
|
|
40
|
+
- `'error'`: raise an error
|
|
41
|
+
- `'overwrite'`: overwrite the existing table
|
|
42
|
+
- `'append'`: append to the existing table
|
|
43
|
+
"""
|
|
44
|
+
Env.get().require_package('lancedb')
|
|
45
|
+
|
|
46
|
+
import lancedb # type: ignore[import-untyped]
|
|
47
|
+
|
|
48
|
+
from pixeltable.utils.arrow import to_arrow_schema, to_record_batches
|
|
49
|
+
|
|
50
|
+
if if_exists not in ('error', 'overwrite', 'append'):
|
|
51
|
+
raise excs.Error("export_lancedb(): 'if_exists' must be one of: ['error', 'overwrite', 'append']")
|
|
52
|
+
|
|
53
|
+
df: pxt.DataFrame
|
|
54
|
+
if isinstance(table_or_df, pxt.catalog.Table):
|
|
55
|
+
df = table_or_df._df()
|
|
56
|
+
else:
|
|
57
|
+
df = table_or_df
|
|
58
|
+
|
|
59
|
+
db_exists = False
|
|
60
|
+
if db_uri.exists():
|
|
61
|
+
if not db_uri.is_dir():
|
|
62
|
+
raise excs.Error(f"export_lancedb(): '{db_uri!s}' exists and is not a directory")
|
|
63
|
+
db_exists = True
|
|
64
|
+
|
|
65
|
+
try:
|
|
66
|
+
db = lancedb.connect(str(db_uri))
|
|
67
|
+
lance_tbl: lancedb.LanceTable | None = None
|
|
68
|
+
try:
|
|
69
|
+
lance_tbl = db.open_table(table_name)
|
|
70
|
+
if if_exists == 'error':
|
|
71
|
+
raise excs.Error(f'export_lancedb(): table {table_name!r} already exists in {db_uri!r}')
|
|
72
|
+
except ValueError:
|
|
73
|
+
# table doesn't exist
|
|
74
|
+
pass
|
|
75
|
+
|
|
76
|
+
with Catalog.get().begin_xact(for_write=False):
|
|
77
|
+
if lance_tbl is None or if_exists == 'overwrite':
|
|
78
|
+
mode = 'overwrite' if lance_tbl is not None else 'create'
|
|
79
|
+
arrow_schema = to_arrow_schema(df.schema)
|
|
80
|
+
_ = db.create_table(table_name, to_record_batches(df, batch_size_bytes), schema=arrow_schema, mode=mode)
|
|
81
|
+
else:
|
|
82
|
+
lance_tbl.add(to_record_batches(df, batch_size_bytes))
|
|
83
|
+
|
|
84
|
+
except Exception as e:
|
|
85
|
+
# cleanup
|
|
86
|
+
if not db_exists:
|
|
87
|
+
shutil.rmtree(db_uri)
|
|
88
|
+
raise e
|
|
@@ -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
|
|
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: StorageObjectAddress | None
|
|
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) -> Path | None:
|
|
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: str | None) -> 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: str | None) -> 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: str | None = 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: str | None = 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.get_tbl() is not None, 'Column must be associated with a table'
|
|
130
|
+
return self._prepare_path_raw(col.get_tbl().id, col.id, col.get_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: str | None) -> Path | None:
|
|
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: str | None) -> 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: int | None = None) -> int | None:
|
|
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: UUID | None, tbl_version: int | None = 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: UUID | None = None, tbl_version: int | None = 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: str | None) -> Path | None:
|
|
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: str | None) -> 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: UUID | None = 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()
|