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.

Files changed (202) hide show
  1. pixeltable/__init__.py +23 -5
  2. pixeltable/_version.py +1 -0
  3. pixeltable/catalog/__init__.py +5 -3
  4. pixeltable/catalog/catalog.py +1318 -404
  5. pixeltable/catalog/column.py +186 -115
  6. pixeltable/catalog/dir.py +1 -2
  7. pixeltable/catalog/globals.py +11 -43
  8. pixeltable/catalog/insertable_table.py +167 -79
  9. pixeltable/catalog/path.py +61 -23
  10. pixeltable/catalog/schema_object.py +9 -10
  11. pixeltable/catalog/table.py +626 -308
  12. pixeltable/catalog/table_metadata.py +101 -0
  13. pixeltable/catalog/table_version.py +713 -569
  14. pixeltable/catalog/table_version_handle.py +37 -6
  15. pixeltable/catalog/table_version_path.py +42 -29
  16. pixeltable/catalog/tbl_ops.py +50 -0
  17. pixeltable/catalog/update_status.py +191 -0
  18. pixeltable/catalog/view.py +108 -94
  19. pixeltable/config.py +128 -22
  20. pixeltable/dataframe.py +188 -100
  21. pixeltable/env.py +407 -136
  22. pixeltable/exceptions.py +6 -0
  23. pixeltable/exec/__init__.py +3 -0
  24. pixeltable/exec/aggregation_node.py +7 -8
  25. pixeltable/exec/cache_prefetch_node.py +83 -110
  26. pixeltable/exec/cell_materialization_node.py +231 -0
  27. pixeltable/exec/cell_reconstruction_node.py +135 -0
  28. pixeltable/exec/component_iteration_node.py +4 -3
  29. pixeltable/exec/data_row_batch.py +8 -65
  30. pixeltable/exec/exec_context.py +16 -4
  31. pixeltable/exec/exec_node.py +13 -36
  32. pixeltable/exec/expr_eval/evaluators.py +7 -6
  33. pixeltable/exec/expr_eval/expr_eval_node.py +27 -12
  34. pixeltable/exec/expr_eval/globals.py +8 -5
  35. pixeltable/exec/expr_eval/row_buffer.py +1 -2
  36. pixeltable/exec/expr_eval/schedulers.py +190 -30
  37. pixeltable/exec/globals.py +32 -0
  38. pixeltable/exec/in_memory_data_node.py +18 -18
  39. pixeltable/exec/object_store_save_node.py +293 -0
  40. pixeltable/exec/row_update_node.py +16 -9
  41. pixeltable/exec/sql_node.py +206 -101
  42. pixeltable/exprs/__init__.py +1 -1
  43. pixeltable/exprs/arithmetic_expr.py +27 -22
  44. pixeltable/exprs/array_slice.py +3 -3
  45. pixeltable/exprs/column_property_ref.py +34 -30
  46. pixeltable/exprs/column_ref.py +92 -96
  47. pixeltable/exprs/comparison.py +5 -5
  48. pixeltable/exprs/compound_predicate.py +5 -4
  49. pixeltable/exprs/data_row.py +152 -55
  50. pixeltable/exprs/expr.py +62 -43
  51. pixeltable/exprs/expr_dict.py +3 -3
  52. pixeltable/exprs/expr_set.py +17 -10
  53. pixeltable/exprs/function_call.py +75 -37
  54. pixeltable/exprs/globals.py +1 -2
  55. pixeltable/exprs/in_predicate.py +4 -4
  56. pixeltable/exprs/inline_expr.py +10 -27
  57. pixeltable/exprs/is_null.py +1 -3
  58. pixeltable/exprs/json_mapper.py +8 -8
  59. pixeltable/exprs/json_path.py +56 -22
  60. pixeltable/exprs/literal.py +5 -5
  61. pixeltable/exprs/method_ref.py +2 -2
  62. pixeltable/exprs/object_ref.py +2 -2
  63. pixeltable/exprs/row_builder.py +127 -53
  64. pixeltable/exprs/rowid_ref.py +8 -12
  65. pixeltable/exprs/similarity_expr.py +50 -25
  66. pixeltable/exprs/sql_element_cache.py +4 -4
  67. pixeltable/exprs/string_op.py +5 -5
  68. pixeltable/exprs/type_cast.py +3 -5
  69. pixeltable/func/__init__.py +1 -0
  70. pixeltable/func/aggregate_function.py +8 -8
  71. pixeltable/func/callable_function.py +9 -9
  72. pixeltable/func/expr_template_function.py +10 -10
  73. pixeltable/func/function.py +18 -20
  74. pixeltable/func/function_registry.py +6 -7
  75. pixeltable/func/globals.py +2 -3
  76. pixeltable/func/mcp.py +74 -0
  77. pixeltable/func/query_template_function.py +20 -18
  78. pixeltable/func/signature.py +43 -16
  79. pixeltable/func/tools.py +23 -13
  80. pixeltable/func/udf.py +18 -20
  81. pixeltable/functions/__init__.py +6 -0
  82. pixeltable/functions/anthropic.py +93 -33
  83. pixeltable/functions/audio.py +114 -10
  84. pixeltable/functions/bedrock.py +13 -6
  85. pixeltable/functions/date.py +1 -1
  86. pixeltable/functions/deepseek.py +20 -9
  87. pixeltable/functions/fireworks.py +2 -2
  88. pixeltable/functions/gemini.py +28 -11
  89. pixeltable/functions/globals.py +13 -13
  90. pixeltable/functions/groq.py +108 -0
  91. pixeltable/functions/huggingface.py +1046 -23
  92. pixeltable/functions/image.py +9 -18
  93. pixeltable/functions/llama_cpp.py +23 -8
  94. pixeltable/functions/math.py +3 -4
  95. pixeltable/functions/mistralai.py +4 -15
  96. pixeltable/functions/ollama.py +16 -9
  97. pixeltable/functions/openai.py +104 -82
  98. pixeltable/functions/openrouter.py +143 -0
  99. pixeltable/functions/replicate.py +2 -2
  100. pixeltable/functions/reve.py +250 -0
  101. pixeltable/functions/string.py +21 -28
  102. pixeltable/functions/timestamp.py +13 -14
  103. pixeltable/functions/together.py +4 -6
  104. pixeltable/functions/twelvelabs.py +92 -0
  105. pixeltable/functions/util.py +6 -1
  106. pixeltable/functions/video.py +1388 -106
  107. pixeltable/functions/vision.py +7 -7
  108. pixeltable/functions/whisper.py +15 -7
  109. pixeltable/functions/whisperx.py +179 -0
  110. pixeltable/{ext/functions → functions}/yolox.py +2 -4
  111. pixeltable/globals.py +332 -105
  112. pixeltable/index/base.py +13 -22
  113. pixeltable/index/btree.py +23 -22
  114. pixeltable/index/embedding_index.py +32 -44
  115. pixeltable/io/__init__.py +4 -2
  116. pixeltable/io/datarows.py +7 -6
  117. pixeltable/io/external_store.py +49 -77
  118. pixeltable/io/fiftyone.py +11 -11
  119. pixeltable/io/globals.py +29 -28
  120. pixeltable/io/hf_datasets.py +17 -9
  121. pixeltable/io/label_studio.py +70 -66
  122. pixeltable/io/lancedb.py +3 -0
  123. pixeltable/io/pandas.py +12 -11
  124. pixeltable/io/parquet.py +13 -93
  125. pixeltable/io/table_data_conduit.py +71 -47
  126. pixeltable/io/utils.py +3 -3
  127. pixeltable/iterators/__init__.py +2 -1
  128. pixeltable/iterators/audio.py +21 -11
  129. pixeltable/iterators/document.py +116 -55
  130. pixeltable/iterators/image.py +5 -2
  131. pixeltable/iterators/video.py +293 -13
  132. pixeltable/metadata/__init__.py +4 -2
  133. pixeltable/metadata/converters/convert_18.py +2 -2
  134. pixeltable/metadata/converters/convert_19.py +2 -2
  135. pixeltable/metadata/converters/convert_20.py +2 -2
  136. pixeltable/metadata/converters/convert_21.py +2 -2
  137. pixeltable/metadata/converters/convert_22.py +2 -2
  138. pixeltable/metadata/converters/convert_24.py +2 -2
  139. pixeltable/metadata/converters/convert_25.py +2 -2
  140. pixeltable/metadata/converters/convert_26.py +2 -2
  141. pixeltable/metadata/converters/convert_29.py +4 -4
  142. pixeltable/metadata/converters/convert_34.py +2 -2
  143. pixeltable/metadata/converters/convert_36.py +2 -2
  144. pixeltable/metadata/converters/convert_37.py +15 -0
  145. pixeltable/metadata/converters/convert_38.py +39 -0
  146. pixeltable/metadata/converters/convert_39.py +124 -0
  147. pixeltable/metadata/converters/convert_40.py +73 -0
  148. pixeltable/metadata/converters/util.py +13 -12
  149. pixeltable/metadata/notes.py +4 -0
  150. pixeltable/metadata/schema.py +79 -42
  151. pixeltable/metadata/utils.py +74 -0
  152. pixeltable/mypy/__init__.py +3 -0
  153. pixeltable/mypy/mypy_plugin.py +123 -0
  154. pixeltable/plan.py +274 -223
  155. pixeltable/share/__init__.py +1 -1
  156. pixeltable/share/packager.py +259 -129
  157. pixeltable/share/protocol/__init__.py +34 -0
  158. pixeltable/share/protocol/common.py +170 -0
  159. pixeltable/share/protocol/operation_types.py +33 -0
  160. pixeltable/share/protocol/replica.py +109 -0
  161. pixeltable/share/publish.py +213 -57
  162. pixeltable/store.py +238 -175
  163. pixeltable/type_system.py +104 -63
  164. pixeltable/utils/__init__.py +2 -3
  165. pixeltable/utils/arrow.py +108 -13
  166. pixeltable/utils/av.py +298 -0
  167. pixeltable/utils/azure_store.py +305 -0
  168. pixeltable/utils/code.py +3 -3
  169. pixeltable/utils/console_output.py +4 -1
  170. pixeltable/utils/coroutine.py +6 -23
  171. pixeltable/utils/dbms.py +31 -5
  172. pixeltable/utils/description_helper.py +4 -5
  173. pixeltable/utils/documents.py +5 -6
  174. pixeltable/utils/exception_handler.py +7 -30
  175. pixeltable/utils/filecache.py +6 -6
  176. pixeltable/utils/formatter.py +4 -6
  177. pixeltable/utils/gcs_store.py +283 -0
  178. pixeltable/utils/http_server.py +2 -3
  179. pixeltable/utils/iceberg.py +1 -2
  180. pixeltable/utils/image.py +17 -0
  181. pixeltable/utils/lancedb.py +88 -0
  182. pixeltable/utils/local_store.py +316 -0
  183. pixeltable/utils/misc.py +5 -0
  184. pixeltable/utils/object_stores.py +528 -0
  185. pixeltable/utils/pydantic.py +60 -0
  186. pixeltable/utils/pytorch.py +5 -6
  187. pixeltable/utils/s3_store.py +392 -0
  188. pixeltable-0.4.20.dist-info/METADATA +587 -0
  189. pixeltable-0.4.20.dist-info/RECORD +218 -0
  190. {pixeltable-0.4.0rc3.dist-info → pixeltable-0.4.20.dist-info}/WHEEL +1 -1
  191. pixeltable-0.4.20.dist-info/entry_points.txt +2 -0
  192. pixeltable/__version__.py +0 -3
  193. pixeltable/ext/__init__.py +0 -17
  194. pixeltable/ext/functions/__init__.py +0 -11
  195. pixeltable/ext/functions/whisperx.py +0 -77
  196. pixeltable/utils/media_store.py +0 -77
  197. pixeltable/utils/s3.py +0 -17
  198. pixeltable/utils/sample.py +0 -25
  199. pixeltable-0.4.0rc3.dist-info/METADATA +0 -435
  200. pixeltable-0.4.0rc3.dist-info/RECORD +0 -189
  201. pixeltable-0.4.0rc3.dist-info/entry_points.txt +0 -3
  202. {pixeltable-0.4.0rc3.dist-info → pixeltable-0.4.20.dist-info/licenses}/LICENSE +0 -0
pixeltable/utils/dbms.py CHANGED
@@ -1,6 +1,6 @@
1
1
  import abc
2
2
 
3
- from sqlalchemy import URL
3
+ import sqlalchemy as sql
4
4
 
5
5
 
6
6
  class Dbms(abc.ABC):
@@ -11,9 +11,9 @@ class Dbms(abc.ABC):
11
11
  name: str
12
12
  transaction_isolation_level: str
13
13
  version_index_type: str
14
- db_url: URL
14
+ db_url: sql.URL
15
15
 
16
- def __init__(self, name: str, transaction_isolation_level: str, version_index_type: str, db_url: URL) -> None:
16
+ def __init__(self, name: str, transaction_isolation_level: str, version_index_type: str, db_url: sql.URL) -> None:
17
17
  self.name = name
18
18
  self.transaction_isolation_level = transaction_isolation_level
19
19
  self.version_index_type = version_index_type
@@ -28,13 +28,18 @@ class Dbms(abc.ABC):
28
28
  @abc.abstractmethod
29
29
  def default_system_db_url(self) -> str: ...
30
30
 
31
+ @abc.abstractmethod
32
+ def create_vector_index_stmt(
33
+ self, store_index_name: str, sa_value_col: sql.Column, metric: str
34
+ ) -> sql.Compiled: ...
35
+
31
36
 
32
37
  class PostgresqlDbms(Dbms):
33
38
  """
34
39
  Implements utilities to interact with Postgres database.
35
40
  """
36
41
 
37
- def __init__(self, db_url: URL):
42
+ def __init__(self, db_url: sql.URL):
38
43
  super().__init__('postgresql', 'SERIALIZABLE', 'brin', db_url)
39
44
 
40
45
  def drop_db_stmt(self, database: str) -> str:
@@ -47,13 +52,25 @@ class PostgresqlDbms(Dbms):
47
52
  a = self.db_url.set(database='postgres').render_as_string(hide_password=False)
48
53
  return a
49
54
 
55
+ def create_vector_index_stmt(self, store_index_name: str, sa_value_col: sql.Column, metric: str) -> sql.Compiled:
56
+ from sqlalchemy.dialects import postgresql
57
+
58
+ sa_idx = sql.Index(
59
+ store_index_name,
60
+ sa_value_col,
61
+ postgresql_using='hnsw',
62
+ postgresql_with={'m': 16, 'ef_construction': 64},
63
+ postgresql_ops={sa_value_col.name: metric},
64
+ )
65
+ return sql.schema.CreateIndex(sa_idx, if_not_exists=True).compile(dialect=postgresql.dialect())
66
+
50
67
 
51
68
  class CockroachDbms(Dbms):
52
69
  """
53
70
  Implements utilities to interact with CockroachDb database.
54
71
  """
55
72
 
56
- def __init__(self, db_url: URL):
73
+ def __init__(self, db_url: sql.URL):
57
74
  super().__init__('cockroachdb', 'SERIALIZABLE', 'btree', db_url)
58
75
 
59
76
  def drop_db_stmt(self, database: str) -> str:
@@ -64,3 +81,12 @@ class CockroachDbms(Dbms):
64
81
 
65
82
  def default_system_db_url(self) -> str:
66
83
  return self.db_url.set(database='defaultdb').render_as_string(hide_password=False)
84
+
85
+ def sa_vector_index(self, store_index_name: str, sa_value_col: sql.schema.Column, metric: str) -> sql.Index | None:
86
+ return None
87
+
88
+ def create_vector_index_stmt(self, store_index_name: str, sa_value_col: sql.Column, metric: str) -> sql.Compiled:
89
+ return sql.text(
90
+ f'CREATE VECTOR INDEX IF NOT EXISTS {store_index_name} ON {sa_value_col.table.name}'
91
+ f'({sa_value_col.name} {metric})'
92
+ ).compile()
@@ -1,5 +1,4 @@
1
1
  import dataclasses
2
- from typing import Optional, Union
3
2
 
4
3
  import pandas as pd
5
4
  from pandas.io.formats.style import Styler
@@ -7,11 +6,11 @@ from pandas.io.formats.style import Styler
7
6
 
8
7
  @dataclasses.dataclass
9
8
  class _Descriptor:
10
- body: Union[str, pd.DataFrame]
9
+ body: str | pd.DataFrame
11
10
  # The remaining fields only affect the behavior if `body` is a pd.DataFrame.
12
11
  show_index: bool
13
12
  show_header: bool
14
- styler: Optional[Styler] = None
13
+ styler: Styler | None = None
15
14
 
16
15
 
17
16
  class DescriptionHelper:
@@ -33,10 +32,10 @@ class DescriptionHelper:
33
32
 
34
33
  def append(
35
34
  self,
36
- descriptor: Union[str, pd.DataFrame],
35
+ descriptor: str | pd.DataFrame,
37
36
  show_index: bool = False,
38
37
  show_header: bool = True,
39
- styler: Optional[Styler] = None,
38
+ styler: Styler | None = None,
40
39
  ) -> None:
41
40
  self.__descriptors.append(_Descriptor(descriptor, show_index, show_header, styler))
42
41
 
@@ -1,6 +1,5 @@
1
1
  import dataclasses
2
2
  import os
3
- from typing import Optional
4
3
 
5
4
  import bs4
6
5
  import fitz # type: ignore[import-untyped]
@@ -13,10 +12,10 @@ from pixeltable.env import Env
13
12
  @dataclasses.dataclass
14
13
  class DocumentHandle:
15
14
  format: ts.DocumentType.DocumentFormat
16
- bs_doc: Optional[bs4.BeautifulSoup] = None
17
- md_ast: Optional[dict] = None
18
- pdf_doc: Optional[fitz.Document] = None
19
- txt_doc: Optional[str] = None
15
+ bs_doc: bs4.BeautifulSoup | None = None
16
+ md_ast: dict | None = None
17
+ pdf_doc: fitz.Document | None = None
18
+ txt_doc: str | None = None
20
19
 
21
20
 
22
21
  def get_document_handle(path: str) -> DocumentHandle:
@@ -34,7 +33,7 @@ def get_document_handle(path: str) -> DocumentHandle:
34
33
  raise excs.Error(f'Unrecognized document format: {path}')
35
34
 
36
35
 
37
- def get_handle_by_extension(path: str, extension: str) -> Optional[DocumentHandle]:
36
+ def get_handle_by_extension(path: str, extension: str) -> DocumentHandle | None:
38
37
  doc_format = ts.DocumentType.DocumentFormat.from_extension(extension)
39
38
 
40
39
  try:
@@ -1,35 +1,12 @@
1
1
  import logging
2
- import sys
3
- from typing import Any, Callable, Optional, TypeVar
2
+ from typing import Any, Callable, TypeVar
4
3
 
5
4
  R = TypeVar('R')
6
5
 
7
-
8
- def _is_in_exception() -> bool:
9
- """
10
- Check if code is currently executing within an exception context.
11
- """
12
- current_exception = sys.exc_info()[1]
13
- return current_exception is not None
14
-
15
-
16
- def run_cleanup_on_exception(cleanup_func: Callable[..., R], *args: Any, **kwargs: Any) -> Optional[R]:
17
- """
18
- Runs cleanup only when running in exception context.
19
-
20
- The function `run_cleanup_on_exception()` should be used to clean up resources when an operation fails.
21
- This is typically done using a try, except, and finally block, with the resource cleanup logic placed within
22
- the except block. However, this pattern may not handle KeyboardInterrupt exceptions.
23
- To ensure that resources are always cleaned up at least once when an exception or KeyboardInterrupt occurs,
24
- create an idempotent function for cleaning up resources and pass it to the `run_cleanup_on_exception()` function
25
- from the finally block.
26
- """
27
- if _is_in_exception():
28
- return run_cleanup(cleanup_func, *args, raise_error=False, **kwargs)
29
- return None
6
+ logger = logging.getLogger('pixeltable')
30
7
 
31
8
 
32
- def run_cleanup(cleanup_func: Callable[..., R], *args: Any, raise_error: bool = True, **kwargs: Any) -> Optional[R]:
9
+ def run_cleanup(cleanup_func: Callable[..., R], *args: Any, raise_error: bool = True, **kwargs: Any) -> R | None:
33
10
  """
34
11
  Runs a cleanup function. If interrupted, retry cleanup.
35
12
  The `run_cleanup()` function ensures that the `cleanup_func()` function executes at least once.
@@ -40,20 +17,20 @@ def run_cleanup(cleanup_func: Callable[..., R], *args: Any, raise_error: bool =
40
17
  raise_error: raise an exception if an error occurs during cleanup.
41
18
  """
42
19
  try:
43
- logging.debug(f'Running cleanup function: {cleanup_func.__name__!r}')
20
+ logger.debug(f'Running cleanup function: {cleanup_func.__name__!r}')
44
21
  return cleanup_func(*args, **kwargs)
45
22
  except KeyboardInterrupt as interrupt:
46
23
  # Save original exception and re-attempt cleanup
47
24
  original_exception = interrupt
48
- logging.debug(f'Cleanup {cleanup_func.__name__!r} interrupted, retrying')
25
+ logger.debug(f'Cleanup {cleanup_func.__name__!r} interrupted, retrying')
49
26
  try:
50
27
  return cleanup_func(*args, **kwargs)
51
28
  except Exception as e:
52
29
  # Suppress this exception
53
- logging.error(f'Cleanup {cleanup_func.__name__!r} failed with exception {e}')
30
+ logger.error(f'Cleanup {cleanup_func.__name__!r} failed with exception {e.__class__}: {e}')
54
31
  raise KeyboardInterrupt from original_exception
55
32
  except Exception as e:
56
- logging.error(f'Cleanup {cleanup_func.__name__!r} failed with exception {e}')
33
+ logger.error(f'Cleanup {cleanup_func.__name__!r} failed with exception {e.__class__}: {e}')
57
34
  if raise_error:
58
35
  raise e
59
36
  return None
@@ -9,7 +9,7 @@ from collections import OrderedDict, defaultdict
9
9
  from dataclasses import dataclass
10
10
  from datetime import datetime, timezone
11
11
  from pathlib import Path
12
- from typing import NamedTuple, Optional
12
+ from typing import NamedTuple
13
13
  from uuid import UUID
14
14
 
15
15
  import pixeltable.exceptions as excs
@@ -58,7 +58,7 @@ class FileCache:
58
58
  - implement MRU eviction for queries that exceed the capacity
59
59
  """
60
60
 
61
- __instance: Optional[FileCache] = None
61
+ __instance: FileCache | None = None
62
62
 
63
63
  cache: OrderedDict[str, CacheEntry]
64
64
  total_size: int
@@ -126,12 +126,12 @@ class FileCache:
126
126
  return 0
127
127
  return int(self.total_size / len(self.cache))
128
128
 
129
- def num_files(self, tbl_id: Optional[UUID] = None) -> int:
129
+ def num_files(self, tbl_id: UUID | None = None) -> int:
130
130
  if tbl_id is None:
131
131
  return len(self.cache)
132
132
  return sum(e.tbl_id == tbl_id for e in self.cache.values())
133
133
 
134
- def clear(self, tbl_id: Optional[UUID] = None) -> None:
134
+ def clear(self, tbl_id: UUID | None = None) -> None:
135
135
  """
136
136
  For testing purposes: allow resetting capacity and stats.
137
137
  """
@@ -174,7 +174,7 @@ class FileCache:
174
174
  h.update(url.encode())
175
175
  return h.hexdigest()
176
176
 
177
- def lookup(self, url: str) -> Optional[Path]:
177
+ def lookup(self, url: str) -> Path | None:
178
178
  self.num_requests += 1
179
179
  key = self._url_hash(url)
180
180
  entry = self.cache.get(key, None)
@@ -214,7 +214,7 @@ class FileCache:
214
214
  new_path = entry.path
215
215
  os.rename(str(path), str(new_path))
216
216
  new_path.touch(exist_ok=True)
217
- _logger.debug(f'added entry for cell {url} to file cache')
217
+ _logger.debug(f'FileCache: cached url {url} with file name {new_path}')
218
218
  return new_path
219
219
 
220
220
  def ensure_capacity(self, size: int) -> None:
@@ -4,7 +4,7 @@ import io
4
4
  import json
5
5
  import logging
6
6
  import mimetypes
7
- from typing import Any, Callable, Optional
7
+ from typing import Any, Callable
8
8
 
9
9
  import av
10
10
  import numpy as np
@@ -39,7 +39,7 @@ class Formatter:
39
39
  self.__num_cols = num_cols
40
40
  self.__http_address = http_address
41
41
 
42
- def get_pandas_formatter(self, col_type: ts.ColumnType) -> Optional[Callable]:
42
+ def get_pandas_formatter(self, col_type: ts.ColumnType) -> Callable | None:
43
43
  if col_type.is_string_type():
44
44
  return self.format_string
45
45
  if col_type.is_float_type():
@@ -184,7 +184,7 @@ class Formatter:
184
184
  """
185
185
 
186
186
  @classmethod
187
- def extract_first_video_frame(cls, file_path: str) -> Optional[Image.Image]:
187
+ def extract_first_video_frame(cls, file_path: str) -> Image.Image | None:
188
188
  with av.open(file_path) as container:
189
189
  try:
190
190
  img = next(container.decode(video=0)).to_image()
@@ -224,9 +224,7 @@ class Formatter:
224
224
  """
225
225
 
226
226
  @classmethod
227
- def make_document_thumbnail(
228
- cls, file_path: str, max_width: int = 320, max_height: int = 320
229
- ) -> Optional[Image.Image]:
227
+ def make_document_thumbnail(cls, file_path: str, max_width: int = 320, max_height: int = 320) -> Image.Image | None:
230
228
  """
231
229
  Returns a thumbnail image of a document.
232
230
  """
@@ -0,0 +1,283 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import re
5
+ import urllib.parse
6
+ import uuid
7
+ from pathlib import Path
8
+ from typing import TYPE_CHECKING, Any, Iterator
9
+
10
+ from google.api_core.exceptions import GoogleAPIError
11
+ from google.cloud import storage # type: ignore[attr-defined]
12
+ from google.cloud.exceptions import Forbidden, NotFound
13
+ from google.cloud.storage.client import Client # type: ignore[import-untyped]
14
+
15
+ from pixeltable import env, exceptions as excs
16
+ from pixeltable.utils.object_stores import ObjectPath, ObjectStoreBase, StorageObjectAddress, StorageTarget
17
+
18
+ if TYPE_CHECKING:
19
+ from pixeltable.catalog import Column
20
+
21
+ _logger = logging.getLogger('pixeltable')
22
+
23
+
24
+ @env.register_client('gcs_store')
25
+ def _() -> 'Client':
26
+ """Create and return a GCS client, using default credentials if available,
27
+ otherwise creating an anonymous client for public buckets.
28
+ """
29
+ try:
30
+ # Create a client with default credentials
31
+ # Note that if the default credentials have expired, gcloud will still create a client,
32
+ # which will report the expiry error when it is used.
33
+ # To create and use an anonymous client, expired credentials must be removed.
34
+ # For application default credentials, delete the file in ~/.config/gcloud/, or
35
+ # gcloud auth application-default revoke
36
+ # OR
37
+ # For service account keys, you must delete the downloaded key file.
38
+ client = storage.Client()
39
+ return client
40
+ except Exception:
41
+ # If no credentials are found, create an anonymous client which can be used for public buckets.
42
+ client = storage.Client.create_anonymous_client()
43
+ return client
44
+
45
+
46
+ class GCSStore(ObjectStoreBase):
47
+ """Class to handle Google Cloud Storage operations."""
48
+
49
+ # URI of the GCS bucket in the format gs://bucket_name/prefix/
50
+ # Always ends with a slash
51
+ __base_uri: str
52
+
53
+ # bucket name extracted from the URI
54
+ __bucket_name: str
55
+
56
+ # prefix path within the bucket, either empty or ending with a slash
57
+ __prefix_name: str
58
+
59
+ # The parsed form of the given destination address
60
+ soa: StorageObjectAddress
61
+
62
+ def __init__(self, soa: StorageObjectAddress):
63
+ assert soa.storage_target == StorageTarget.GCS_STORE, f'Expected storage_target "gs", got {soa.storage_target}'
64
+ self.soa = soa
65
+ self.__base_uri = soa.prefix_free_uri + soa.prefix
66
+ self.__bucket_name = soa.container
67
+ self.__prefix_name = soa.prefix
68
+
69
+ @classmethod
70
+ def client(cls) -> 'Client':
71
+ """Return the GCS client."""
72
+ return env.Env.get().get_client('gcs_store')
73
+
74
+ @property
75
+ def bucket_name(self) -> str:
76
+ """Return the bucket name from the base URI."""
77
+ return self.__bucket_name
78
+
79
+ @property
80
+ def prefix(self) -> str:
81
+ """Return the prefix from the base URI."""
82
+ return self.__prefix_name
83
+
84
+ def validate(self, error_col_name: str) -> str | None:
85
+ """
86
+ Checks if the URI exists.
87
+
88
+ Returns:
89
+ str: The base URI if the GCS bucket exists and is accessible, None otherwise.
90
+ """
91
+ try:
92
+ client = self.client()
93
+ bucket = client.bucket(self.bucket_name)
94
+ blobs = bucket.list_blobs(max_results=1)
95
+ # This will raise an exception if the destination doesn't exist or cannot be listed
96
+ _ = list(blobs) # Force evaluation to check access
97
+ return self.__base_uri
98
+ except (NotFound, Forbidden, GoogleAPIError) as e:
99
+ self.handle_gcs_error(e, self.bucket_name, f'validate bucket {error_col_name}')
100
+ return None
101
+
102
+ def _prepare_uri_raw(self, tbl_id: uuid.UUID, col_id: int, tbl_version: int, ext: str | None = None) -> str:
103
+ """
104
+ Construct a new, unique URI for a persisted media file.
105
+ """
106
+ prefix, filename = ObjectPath.create_prefix_raw(tbl_id, col_id, tbl_version, ext)
107
+ parent = f'{self.__base_uri}{prefix}'
108
+ return f'{parent}/{filename}'
109
+
110
+ def _prepare_uri(self, col: Column, ext: str | None = None) -> str:
111
+ """
112
+ Construct a new, unique URI for a persisted media file.
113
+ """
114
+ assert col.get_tbl() is not None, 'Column must be associated with a table'
115
+ return self._prepare_uri_raw(col.get_tbl().id, col.id, col.get_tbl().version, ext=ext)
116
+
117
+ def copy_local_file(self, col: Column, src_path: Path) -> str:
118
+ """Copy a local file, and return its new URL"""
119
+ new_file_uri = self._prepare_uri(col, ext=src_path.suffix)
120
+ parsed = urllib.parse.urlparse(new_file_uri)
121
+ blob_name = parsed.path.lstrip('/')
122
+
123
+ try:
124
+ client = self.client()
125
+ bucket = client.bucket(self.bucket_name)
126
+ blob = bucket.blob(blob_name)
127
+ blob.upload_from_filename(str(src_path))
128
+ _logger.debug(f'Media Storage: copied {src_path} to {new_file_uri}')
129
+ return new_file_uri
130
+ except GoogleAPIError as e:
131
+ self.handle_gcs_error(e, self.bucket_name, f'upload file {src_path}')
132
+ raise
133
+
134
+ def copy_object_to_local_file(self, src_path: str, dest_path: Path) -> None:
135
+ """Copies an object to a local file. Thread safe"""
136
+ try:
137
+ client = self.client()
138
+ bucket = client.bucket(self.bucket_name)
139
+ blob = bucket.blob(self.prefix + src_path)
140
+ blob.download_to_filename(str(dest_path))
141
+ except GoogleAPIError as e:
142
+ self.handle_gcs_error(e, self.bucket_name, f'download file {src_path}')
143
+ raise
144
+
145
+ def _get_filtered_objects(self, bucket: Any, tbl_id: uuid.UUID, tbl_version: int | None = None) -> Iterator:
146
+ """Private method to get filtered objects for a table, optionally filtered by version.
147
+
148
+ Args:
149
+ tbl_id: Table UUID to filter by
150
+ tbl_version: Optional table version to filter by
151
+
152
+ Returns:
153
+ Tuple of (iterator over GCS objects matching the criteria, bucket object)
154
+ """
155
+ table_prefix = ObjectPath.table_prefix(tbl_id)
156
+ prefix = f'{self.prefix}{table_prefix}/'
157
+
158
+ if tbl_version is None:
159
+ # Return all blobs with the table prefix
160
+ blob_iterator = bucket.list_blobs(prefix=prefix)
161
+ else:
162
+ # Filter by both table_id and table_version using the ObjectPath pattern
163
+ # Pattern: tbl_id_col_id_version_uuid
164
+ version_pattern = re.compile(rf'{re.escape(table_prefix)}_\d+_{re.escape(str(tbl_version))}_[0-9a-fA-F]+.*')
165
+ # Return filtered collection - this still uses lazy loading
166
+ all_blobs = bucket.list_blobs(prefix=prefix)
167
+ blob_iterator = (blob for blob in all_blobs if version_pattern.match(blob.name.split('/')[-1]))
168
+
169
+ return blob_iterator
170
+
171
+ def count(self, tbl_id: uuid.UUID, tbl_version: int | None = None) -> int:
172
+ """Count the number of files belonging to tbl_id. If tbl_version is not None,
173
+ count only those files belonging to the specified tbl_version.
174
+
175
+ Args:
176
+ tbl_id: Table UUID to count objects for
177
+ tbl_version: Optional table version to filter by
178
+
179
+ Returns:
180
+ Number of objects matching the criteria
181
+ """
182
+ assert tbl_id is not None
183
+
184
+ try:
185
+ client = self.client()
186
+ bucket = client.bucket(self.bucket_name)
187
+
188
+ blob_iterator = self._get_filtered_objects(bucket, tbl_id, tbl_version)
189
+
190
+ return sum(1 for _ in blob_iterator)
191
+
192
+ except GoogleAPIError as e:
193
+ self.handle_gcs_error(e, self.bucket_name, f'setup iterator {self.prefix}')
194
+ raise
195
+
196
+ def delete(self, tbl_id: uuid.UUID, tbl_version: int | None = None) -> int:
197
+ """Delete all files belonging to tbl_id. If tbl_version is not None, delete
198
+ only those files belonging to the specified tbl_version.
199
+
200
+ Args:
201
+ tbl_id: Table UUID to delete objects for
202
+ tbl_version: Optional table version to filter by
203
+
204
+ Returns:
205
+ Number of objects deleted
206
+ """
207
+ assert tbl_id is not None
208
+ total_deleted = 0
209
+
210
+ try:
211
+ client = self.client()
212
+ bucket = client.bucket(self.bucket_name)
213
+ blob_iterator = self._get_filtered_objects(bucket, tbl_id, tbl_version)
214
+
215
+ # Collect blob names for batch deletion
216
+ blobs_to_delete = []
217
+
218
+ for blob in blob_iterator:
219
+ blobs_to_delete.append(blob)
220
+
221
+ # Process in batches for efficiency
222
+ if len(blobs_to_delete) >= 100:
223
+ with client.batch():
224
+ for b in blobs_to_delete:
225
+ b.delete()
226
+ total_deleted += len(blobs_to_delete)
227
+ blobs_to_delete = []
228
+
229
+ # Delete any remaining blobs in the final batch
230
+ if len(blobs_to_delete) > 0:
231
+ with client.batch():
232
+ for b in blobs_to_delete:
233
+ b.delete()
234
+ total_deleted += len(blobs_to_delete)
235
+
236
+ return total_deleted
237
+
238
+ except GoogleAPIError as e:
239
+ self.handle_gcs_error(e, self.bucket_name, f'deleting with {self.prefix}')
240
+ raise
241
+
242
+ def list_objects(self, return_uri: bool, n_max: int = 10) -> list[str]:
243
+ """Return a list of objects found in the specified destination bucket.
244
+ Each returned object includes the full set of prefixes.
245
+ if return_uri is True, full URI's are returned; otherwise, just the object keys.
246
+ """
247
+ p = self.soa.prefix_free_uri if return_uri else ''
248
+ gcs_client = self.client()
249
+ r: list[str] = []
250
+
251
+ try:
252
+ bucket = gcs_client.bucket(self.bucket_name)
253
+ # List blobs with the given prefix, limiting to n_max
254
+ blobs = bucket.list_blobs(prefix=self.prefix, max_results=n_max)
255
+
256
+ for blob in blobs:
257
+ r.append(f'{p}{blob.name}')
258
+ if len(r) >= n_max:
259
+ break
260
+
261
+ except GoogleAPIError as e:
262
+ self.handle_gcs_error(e, self.bucket_name, f'list objects from {self.prefix}')
263
+ return r
264
+
265
+ @classmethod
266
+ def handle_gcs_error(cls, e: Exception, bucket_name: str, operation: str = '', *, ignore_404: bool = False) -> None:
267
+ """Handle GCS-specific errors and convert them to appropriate exceptions"""
268
+ if isinstance(e, NotFound):
269
+ if ignore_404:
270
+ return
271
+ raise excs.Error(f'Bucket or object {bucket_name} not found during {operation}: {str(e)!r}')
272
+ elif isinstance(e, Forbidden):
273
+ raise excs.Error(f'Access denied to bucket {bucket_name} during {operation}: {str(e)!r}')
274
+ elif isinstance(e, GoogleAPIError):
275
+ # Handle other Google API errors
276
+ error_message = str(e)
277
+ if 'Precondition' in error_message:
278
+ raise excs.Error(f'Precondition failed for bucket {bucket_name} during {operation}: {error_message}')
279
+ else:
280
+ raise excs.Error(f'Error during {operation} in bucket {bucket_name}: {error_message}')
281
+ else:
282
+ # Generic error handling
283
+ raise excs.Error(f'Unexpected error during {operation} in bucket {bucket_name}: {str(e)!r}')
@@ -2,7 +2,7 @@ import http
2
2
  import http.server
3
3
  import logging
4
4
  import pathlib
5
- import urllib
5
+ import urllib.request
6
6
  from typing import Any
7
7
 
8
8
  _logger = logging.getLogger('pixeltable.http.server')
@@ -36,8 +36,7 @@ class AbsolutePathHandler(http.server.SimpleHTTPRequestHandler):
36
36
  path = path.split('?', 1)[0]
37
37
  path = path.split('#', 1)[0]
38
38
 
39
- path = pathlib.Path(urllib.request.url2pathname(path))
40
- return str(path)
39
+ return str(pathlib.Path(urllib.request.url2pathname(path)))
41
40
 
42
41
  def log_message(self, format: str, *args: Any) -> None:
43
42
  """override logging to stderr in http.server.BaseHTTPRequestHandler"""
@@ -1,10 +1,9 @@
1
1
  from pathlib import Path
2
- from typing import Union
3
2
 
4
3
  from pyiceberg.catalog.sql import SqlCatalog
5
4
 
6
5
 
7
- def sqlite_catalog(warehouse_path: Union[str, Path], name: str = 'pixeltable') -> SqlCatalog:
6
+ def sqlite_catalog(warehouse_path: str | Path, name: str = 'pixeltable') -> SqlCatalog:
8
7
  """
9
8
  Instantiate a sqlite Iceberg catalog at the specified path. If no catalog exists, one will be created.
10
9
  """
@@ -0,0 +1,17 @@
1
+ import base64
2
+ from io import BytesIO
3
+
4
+ import PIL.Image
5
+
6
+
7
+ def default_format(img: PIL.Image.Image) -> str:
8
+ # Default to JPEG unless the image has a transparency layer (which isn't supported by JPEG).
9
+ # In that case, use WebP instead.
10
+ return 'webp' if img.has_transparency_data else 'jpeg'
11
+
12
+
13
+ def to_base64(image: PIL.Image.Image, format: str | None = None) -> str:
14
+ buffer = BytesIO()
15
+ image.save(buffer, format=format or image.format)
16
+ image_bytes = buffer.getvalue()
17
+ return base64.b64encode(image_bytes).decode('utf-8')