pixeltable 0.2.4__py3-none-any.whl → 0.2.6__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 (99) hide show
  1. pixeltable/__init__.py +18 -9
  2. pixeltable/__version__.py +3 -0
  3. pixeltable/catalog/column.py +31 -50
  4. pixeltable/catalog/insertable_table.py +7 -6
  5. pixeltable/catalog/table.py +171 -57
  6. pixeltable/catalog/table_version.py +417 -140
  7. pixeltable/catalog/table_version_path.py +2 -2
  8. pixeltable/dataframe.py +239 -121
  9. pixeltable/env.py +82 -16
  10. pixeltable/exec/__init__.py +2 -1
  11. pixeltable/exec/cache_prefetch_node.py +1 -1
  12. pixeltable/exec/data_row_batch.py +6 -7
  13. pixeltable/exec/expr_eval_node.py +28 -28
  14. pixeltable/exec/in_memory_data_node.py +11 -7
  15. pixeltable/exec/sql_scan_node.py +7 -6
  16. pixeltable/exprs/__init__.py +4 -3
  17. pixeltable/exprs/column_ref.py +9 -0
  18. pixeltable/exprs/comparison.py +3 -3
  19. pixeltable/exprs/data_row.py +5 -1
  20. pixeltable/exprs/expr.py +15 -7
  21. pixeltable/exprs/function_call.py +17 -15
  22. pixeltable/exprs/image_member_access.py +9 -28
  23. pixeltable/exprs/in_predicate.py +96 -0
  24. pixeltable/exprs/inline_array.py +13 -11
  25. pixeltable/exprs/inline_dict.py +15 -13
  26. pixeltable/exprs/literal.py +16 -4
  27. pixeltable/exprs/row_builder.py +15 -41
  28. pixeltable/exprs/similarity_expr.py +65 -0
  29. pixeltable/ext/__init__.py +5 -0
  30. pixeltable/ext/functions/yolox.py +92 -0
  31. pixeltable/func/__init__.py +0 -2
  32. pixeltable/func/aggregate_function.py +18 -15
  33. pixeltable/func/callable_function.py +57 -13
  34. pixeltable/func/expr_template_function.py +20 -3
  35. pixeltable/func/function.py +35 -4
  36. pixeltable/func/globals.py +24 -14
  37. pixeltable/func/signature.py +23 -27
  38. pixeltable/func/udf.py +13 -12
  39. pixeltable/functions/__init__.py +8 -8
  40. pixeltable/functions/eval.py +7 -8
  41. pixeltable/functions/huggingface.py +64 -17
  42. pixeltable/functions/openai.py +36 -3
  43. pixeltable/functions/pil/image.py +61 -64
  44. pixeltable/functions/together.py +21 -0
  45. pixeltable/functions/util.py +11 -0
  46. pixeltable/globals.py +425 -0
  47. pixeltable/index/__init__.py +2 -0
  48. pixeltable/index/base.py +51 -0
  49. pixeltable/index/embedding_index.py +168 -0
  50. pixeltable/io/__init__.py +3 -0
  51. pixeltable/{utils → io}/hf_datasets.py +48 -17
  52. pixeltable/io/pandas.py +148 -0
  53. pixeltable/{utils → io}/parquet.py +58 -33
  54. pixeltable/iterators/__init__.py +1 -1
  55. pixeltable/iterators/base.py +4 -0
  56. pixeltable/iterators/document.py +218 -97
  57. pixeltable/iterators/video.py +8 -9
  58. pixeltable/metadata/__init__.py +7 -3
  59. pixeltable/metadata/converters/convert_12.py +3 -0
  60. pixeltable/metadata/converters/convert_13.py +41 -0
  61. pixeltable/metadata/schema.py +45 -22
  62. pixeltable/plan.py +15 -51
  63. pixeltable/store.py +38 -41
  64. pixeltable/tool/create_test_db_dump.py +39 -4
  65. pixeltable/type_system.py +47 -96
  66. pixeltable/utils/documents.py +42 -12
  67. pixeltable/utils/http_server.py +70 -0
  68. {pixeltable-0.2.4.dist-info → pixeltable-0.2.6.dist-info}/METADATA +14 -10
  69. pixeltable-0.2.6.dist-info/RECORD +119 -0
  70. {pixeltable-0.2.4.dist-info → pixeltable-0.2.6.dist-info}/WHEEL +1 -1
  71. pixeltable/client.py +0 -604
  72. pixeltable/exprs/image_similarity_predicate.py +0 -58
  73. pixeltable/func/batched_function.py +0 -53
  74. pixeltable/tests/conftest.py +0 -177
  75. pixeltable/tests/functions/test_fireworks.py +0 -42
  76. pixeltable/tests/functions/test_functions.py +0 -60
  77. pixeltable/tests/functions/test_huggingface.py +0 -158
  78. pixeltable/tests/functions/test_openai.py +0 -152
  79. pixeltable/tests/functions/test_together.py +0 -111
  80. pixeltable/tests/test_audio.py +0 -65
  81. pixeltable/tests/test_catalog.py +0 -27
  82. pixeltable/tests/test_client.py +0 -21
  83. pixeltable/tests/test_component_view.py +0 -370
  84. pixeltable/tests/test_dataframe.py +0 -439
  85. pixeltable/tests/test_dirs.py +0 -107
  86. pixeltable/tests/test_document.py +0 -120
  87. pixeltable/tests/test_exprs.py +0 -805
  88. pixeltable/tests/test_function.py +0 -324
  89. pixeltable/tests/test_migration.py +0 -43
  90. pixeltable/tests/test_nos.py +0 -54
  91. pixeltable/tests/test_snapshot.py +0 -208
  92. pixeltable/tests/test_table.py +0 -1267
  93. pixeltable/tests/test_transactional_directory.py +0 -42
  94. pixeltable/tests/test_types.py +0 -22
  95. pixeltable/tests/test_video.py +0 -159
  96. pixeltable/tests/test_view.py +0 -530
  97. pixeltable/tests/utils.py +0 -408
  98. pixeltable-0.2.4.dist-info/RECORD +0 -132
  99. {pixeltable-0.2.4.dist-info → pixeltable-0.2.6.dist-info}/LICENSE +0 -0
pixeltable/client.py DELETED
@@ -1,604 +0,0 @@
1
- from typing import List, Optional, Dict, Type, Any, Union
2
- import pandas as pd
3
- import logging
4
- import dataclasses
5
-
6
- import sqlalchemy as sql
7
- import sqlalchemy.orm as orm
8
-
9
- import pixeltable
10
- from pixeltable.metadata import schema
11
- from pixeltable.env import Env
12
- import pixeltable.func as func
13
- import pixeltable.catalog as catalog
14
- from pixeltable import exceptions as excs
15
- from pixeltable.exprs import Predicate
16
- from pixeltable.iterators import ComponentIterator
17
-
18
- from typing import TYPE_CHECKING
19
- if TYPE_CHECKING:
20
- import datasets
21
-
22
- __all__ = [
23
- 'Client',
24
- ]
25
-
26
-
27
- _logger = logging.getLogger('pixeltable')
28
-
29
- class Client:
30
- """
31
- Client for interacting with a Pixeltable environment.
32
- """
33
-
34
- def __init__(self, reload: bool = False) -> None:
35
- """Constructs a client.
36
- """
37
- env = Env.get()
38
- env.set_up()
39
- env.upgrade_metadata()
40
- if reload:
41
- catalog.Catalog.clear()
42
- self.catalog = catalog.Catalog.get()
43
-
44
- def logging(
45
- self, *, to_stdout: Optional[bool] = None, level: Optional[int] = None,
46
- add: Optional[str] = None, remove: Optional[str] = None
47
- ) -> None:
48
- """Configure logging.
49
-
50
- Args:
51
- to_stdout: if True, also log to stdout
52
- level: default log level
53
- add: comma-separated list of 'module name:log level' pairs; ex.: add='video:10'
54
- remove: comma-separated list of module names
55
- """
56
- if to_stdout is not None:
57
- Env.get().log_to_stdout(to_stdout)
58
- if level is not None:
59
- Env.get().set_log_level(level)
60
- if add is not None:
61
- for module, level in [t.split(':') for t in add.split(',')]:
62
- Env.get().set_module_log_level(module, int(level))
63
- if remove is not None:
64
- for module in remove.split(','):
65
- Env.get().set_module_log_level(module, None)
66
- if to_stdout is None and level is None and add is None and remove is None:
67
- Env.get().print_log_config()
68
-
69
- def list_functions(self) -> pd.DataFrame:
70
- """Returns information about all registered functions.
71
-
72
- Returns:
73
- Pandas DataFrame with columns 'Path', 'Name', 'Parameters', 'Return Type', 'Is Agg', 'Library'
74
- """
75
- functions = func.FunctionRegistry.get().list_functions()
76
- paths = ['.'.join(f.self_path.split('.')[:-1]) for f in functions]
77
- names = [f.name for f in functions]
78
- params = [
79
- ', '.join(
80
- [param_name + ': ' + str(param_type) for param_name, param_type in f.signature.parameters.items()])
81
- for f in functions
82
- ]
83
- pd_df = pd.DataFrame({
84
- 'Path': paths,
85
- 'Function Name': names,
86
- 'Parameters': params,
87
- 'Return Type': [str(f.signature.get_return_type()) for f in functions],
88
- })
89
- pd_df = pd_df.style.set_properties(**{'text-align': 'left'}) \
90
- .set_table_styles([dict(selector='th', props=[('text-align', 'center')])]) # center-align headings
91
- return pd_df.hide(axis='index')
92
-
93
- def get_path(self, schema_obj: catalog.SchemaObject) -> str:
94
- """Returns the path to a SchemaObject.
95
-
96
- Args:
97
- schema_obj: SchemaObject to get the path for.
98
-
99
- Returns:
100
- Path to the SchemaObject.
101
- """
102
- path_elements: List[str] = []
103
- dir_id = schema_obj._dir_id
104
- while dir_id is not None:
105
- dir = self.catalog.paths.get_schema_obj(dir_id)
106
- if dir._dir_id is None:
107
- # this is the root dir with name '', which we don't want to include in the path
108
- break
109
- path_elements.insert(0, dir._name)
110
- dir_id = dir._dir_id
111
- path_elements.append(schema_obj._name)
112
- return '.'.join(path_elements)
113
-
114
- def create_table(
115
- self, path_str: str, schema: Dict[str, Any], primary_key: Optional[Union[str, List[str]]] = None,
116
- num_retained_versions: int = 10, comment: str = ''
117
- ) -> catalog.InsertableTable:
118
- """Create a new `InsertableTable`.
119
-
120
- Args:
121
- path_str: Path to the table.
122
- schema: dictionary mapping column names to column types, value expressions, or to column specifications.
123
- num_retained_versions: Number of versions of the table to retain.
124
-
125
- Returns:
126
- The newly created table.
127
-
128
- Raises:
129
- Error: if the path already exists or is invalid.
130
-
131
- Examples:
132
- Create a table with an int and a string column:
133
-
134
- >>> table = cl.create_table('my_table', schema={'col1': IntType(), 'col2': StringType()})
135
-
136
- Create a table with a single indexed image column:
137
-
138
- >>> table = cl.create_table('my_table', schema={'col1': {'type': ImageType(), 'indexed': True}})
139
- """
140
- path = catalog.Path(path_str)
141
- self.catalog.paths.check_is_valid(path, expected=None)
142
- dir = self.catalog.paths[path.parent]
143
-
144
- if len(schema) == 0:
145
- raise excs.Error(f'Table schema is empty: `{path_str}`')
146
-
147
- if primary_key is None:
148
- primary_key = []
149
- elif isinstance(primary_key, str):
150
- primary_key = [primary_key]
151
- else:
152
- if not isinstance(primary_key, list) or not all(isinstance(pk, str) for pk in primary_key):
153
- raise excs.Error('primary_key must be a single column name or a list of column names')
154
-
155
- tbl = catalog.InsertableTable.create(
156
- dir._id, path.name, schema, primary_key=primary_key, num_retained_versions=num_retained_versions, comment=comment)
157
- self.catalog.paths[path] = tbl
158
- _logger.info(f'Created table `{path_str}`.')
159
- return tbl
160
-
161
- def import_parquet(
162
- self,
163
- table_path: str,
164
- *,
165
- parquet_path: str,
166
- schema_override: Optional[Dict[str, Any]] = None,
167
- **kwargs,
168
- ) -> catalog.InsertableTable:
169
- """Create a new `InsertableTable` from a Parquet file or set of files. Requires pyarrow to be installed.
170
- Args:
171
- path_str: Path to the table within pixeltable.
172
- parquet_path: Path to an individual Parquet file or directory of Parquet files.
173
- schema_override: Optional dictionary mapping column names to column type to override the default
174
- schema inferred from the Parquet file. The column type should be a pixeltable ColumnType.
175
- For example, {'col_vid': VideoType()}, rather than {'col_vid': StringType()}.
176
- Any fields not provided explicitly will map to types with `pixeltable.utils.parquet.parquet_schema_to_pixeltable_schema`
177
- kwargs: Additional arguments to pass to `Client.create_table`.
178
-
179
- Returns:
180
- The newly created table. The table will have loaded the data from the Parquet file(s).
181
- """
182
- from pixeltable.utils import parquet
183
-
184
- return parquet.import_parquet(
185
- self,
186
- table_path=table_path,
187
- parquet_path=parquet_path,
188
- schema_override=schema_override,
189
- **kwargs,
190
- )
191
-
192
- def import_huggingface_dataset(
193
- self,
194
- table_path: str,
195
- dataset: Union['datasets.Dataset', 'datasets.DatasetDict'],
196
- *,
197
- column_name_for_split: Optional[str] = 'split',
198
- schema_override: Optional[Dict[str, Any]] = None,
199
- **kwargs
200
- ) -> catalog.InsertableTable:
201
- """Create a new `InsertableTable` from a Huggingface dataset, or dataset dict with multiple splits.
202
- Requires datasets library to be installed.
203
-
204
- Args:
205
- path_str: Path to the table.
206
- dataset: Huggingface datasts.Dataset or datasts.DatasetDict to insert into the table.
207
- column_name_for_split: column name to use for split information. If None, no split information will be stored.
208
- schema_override: Optional dictionary mapping column names to column type to override the corresponding defaults from
209
- `pixeltable.utils.hf_datasets.huggingface_schema_to_pixeltable_schema`. The column type should be a pixeltable ColumnType.
210
- For example, {'col_vid': VideoType()}, rather than {'col_vid': StringType()}.
211
-
212
- kwargs: Additional arguments to pass to `create_table`.
213
-
214
- Returns:
215
- The newly created table. The table will have loaded the data from the dataset.
216
- """
217
- from pixeltable.utils import hf_datasets
218
-
219
- return hf_datasets.import_huggingface_dataset(
220
- self,
221
- table_path,
222
- dataset,
223
- column_name_for_split=column_name_for_split,
224
- schema_override=schema_override,
225
- **kwargs,
226
- )
227
-
228
- def create_view(
229
- self, path_str: str, base: catalog.Table, *, schema: Optional[Dict[str, Any]] = None,
230
- filter: Optional[Predicate] = None,
231
- is_snapshot: bool = False, iterator_class: Optional[Type[ComponentIterator]] = None,
232
- iterator_args: Optional[Dict[str, Any]] = None, num_retained_versions: int = 10, comment: str = '',
233
- ignore_errors: bool = False) -> catalog.View:
234
- """Create a new `View`.
235
-
236
- Args:
237
- path_str: Path to the view.
238
- base: Table (ie, table or view or snapshot) to base the view on.
239
- schema: dictionary mapping column names to column types, value expressions, or to column specifications.
240
- filter: Predicate to filter rows of the base table.
241
- is_snapshot: Whether the view is a snapshot.
242
- iterator_class: Class of the iterator to use for the view.
243
- iterator_args: Arguments to pass to the iterator class.
244
- num_retained_versions: Number of versions of the view to retain.
245
- ignore_errors: if True, fail silently if the path already exists or is invalid.
246
-
247
- Returns:
248
- The newly created view.
249
-
250
- Raises:
251
- Error: if the path already exists or is invalid.
252
-
253
- Examples:
254
- Create a view with an additional int and a string column and a filter:
255
-
256
- >>> view = cl.create_view(
257
- 'my_view', base, schema={'col3': IntType(), 'col4': StringType()}, filter=base.col1 > 10)
258
-
259
- Create a table snapshot:
260
-
261
- >>> snapshot_view = cl.create_view('my_snapshot_view', base, is_snapshot=True)
262
-
263
- Create an immutable view with additional computed columns and a filter:
264
-
265
- >>> snapshot_view = cl.create_view(
266
- 'my_snapshot', base, schema={'col3': base.col2 + 1}, filter=base.col1 > 10, is_snapshot=True)
267
- """
268
- assert (iterator_class is None) == (iterator_args is None)
269
- assert isinstance(base, catalog.Table)
270
- path = catalog.Path(path_str)
271
- try:
272
- self.catalog.paths.check_is_valid(path, expected=None)
273
- except Exception as e:
274
- if ignore_errors:
275
- return
276
- else:
277
- raise e
278
- dir = self.catalog.paths[path.parent]
279
-
280
- if schema is None:
281
- schema = {}
282
- view = catalog.View.create(
283
- dir._id, path.name, base=base, schema=schema, predicate=filter, is_snapshot=is_snapshot,
284
- iterator_cls=iterator_class, iterator_args=iterator_args, num_retained_versions=num_retained_versions, comment=comment)
285
- self.catalog.paths[path] = view
286
- _logger.info(f'Created view `{path_str}`.')
287
- return view
288
-
289
- def get_table(self, path: str) -> catalog.Table:
290
- """Get a handle to a table (including views and snapshots).
291
-
292
- Args:
293
- path: Path to the table.
294
-
295
- Returns:
296
- A `InsertableTable` or `View` object.
297
-
298
- Raises:
299
- Error: If the path does not exist or does not designate a table.
300
-
301
- Examples:
302
- Get handle for a table in the top-level directory:
303
-
304
- >>> table = cl.get_table('my_table')
305
-
306
- For a table in a subdirectory:
307
-
308
- >>> table = cl.get_table('subdir.my_table')
309
-
310
- For a snapshot in the top-level directory:
311
-
312
- >>> table = cl.get_table('my_snapshot')
313
- """
314
- p = catalog.Path(path)
315
- self.catalog.paths.check_is_valid(p, expected=catalog.Table)
316
- obj = self.catalog.paths[p]
317
- return obj
318
-
319
- def move(self, path: str, new_path: str) -> None:
320
- """Move a schema object to a new directory and/or rename a schema object.
321
-
322
- Args:
323
- path: absolute path to the existing schema object.
324
- new_path: absolute new path for the schema object.
325
-
326
- Raises:
327
- Error: If path does not exist or new_path already exists.
328
-
329
- Examples:
330
- Move a table to a different directory:
331
-
332
- >>>> cl.move('dir1.my_table', 'dir2.my_table')
333
-
334
- Rename a table:
335
-
336
- >>>> cl.move('dir1.my_table', 'dir1.new_name')
337
- """
338
- p = catalog.Path(path)
339
- self.catalog.paths.check_is_valid(p, expected=catalog.SchemaObject)
340
- new_p = catalog.Path(new_path)
341
- self.catalog.paths.check_is_valid(new_p, expected=None)
342
- obj = self.catalog.paths[p]
343
- self.catalog.paths.move(p, new_p)
344
- new_dir = self.catalog.paths[new_p.parent]
345
- obj.move(new_p.name, new_dir._id)
346
-
347
- def list_tables(self, dir_path: str = '', recursive: bool = True) -> List[str]:
348
- """List the tables in a directory.
349
-
350
- Args:
351
- dir_path: Path to the directory. Defaults to the root directory.
352
- recursive: Whether to list tables in subdirectories as well.
353
-
354
- Returns:
355
- A list of table paths.
356
-
357
- Raises:
358
- Error: If the path does not exist or does not designate a directory.
359
-
360
- Examples:
361
- List tables in top-level directory:
362
-
363
- >>> cl.list_tables()
364
- ['my_table', ...]
365
-
366
- List tables in 'dir1':
367
-
368
- >>> cl.list_tables('dir1')
369
- [...]
370
- """
371
- assert dir_path is not None
372
- path = catalog.Path(dir_path, empty_is_valid=True)
373
- self.catalog.paths.check_is_valid(path, expected=catalog.Dir)
374
- return [str(p) for p in self.catalog.paths.get_children(path, child_type=catalog.Table, recursive=recursive)]
375
-
376
- def drop_table(self, path: str, force: bool = False, ignore_errors: bool = False) -> None:
377
- """Drop a table.
378
-
379
- Args:
380
- path: Path to the table.
381
- force: Whether to drop the table even if it has unsaved changes.
382
- ignore_errors: Whether to ignore errors if the table does not exist.
383
-
384
- Raises:
385
- Error: If the path does not exist or does not designate a table and ignore_errors is False.
386
-
387
- Examples:
388
- >>> cl.drop_table('my_table')
389
- """
390
- path_obj = catalog.Path(path)
391
- try:
392
- self.catalog.paths.check_is_valid(path_obj, expected=catalog.Table)
393
- except Exception as e:
394
- if ignore_errors:
395
- _logger.info(f'Skipped table `{path}` (does not exist).')
396
- return
397
- else:
398
- raise e
399
- tbl = self.catalog.paths[path_obj]
400
- if len(self.catalog.tbl_dependents[tbl._id]) > 0:
401
- dependent_paths = [self.get_path(dep) for dep in self.catalog.tbl_dependents[tbl._id]]
402
- raise excs.Error(f'Table {path} has dependents: {", ".join(dependent_paths)}')
403
- tbl._drop()
404
- del self.catalog.paths[path_obj]
405
- _logger.info(f'Dropped table `{path}`.')
406
-
407
- def create_dir(self, path_str: str, ignore_errors: bool = False) -> None:
408
- """Create a directory.
409
-
410
- Args:
411
- path_str: Path to the directory.
412
- ignore_errors: if True, silently returns on error
413
-
414
- Raises:
415
- Error: If the path already exists or the parent is not a directory.
416
-
417
- Examples:
418
- >>> cl.create_dir('my_dir')
419
-
420
- Create a subdirectory:
421
-
422
- >>> cl.create_dir('my_dir.sub_dir')
423
- """
424
- try:
425
- path = catalog.Path(path_str)
426
- self.catalog.paths.check_is_valid(path, expected=None)
427
- parent = self.catalog.paths[path.parent]
428
- assert parent is not None
429
- with orm.Session(Env.get().engine, future=True) as session:
430
- dir_md = schema.DirMd(name=path.name)
431
- dir_record = schema.Dir(parent_id=parent._id, md=dataclasses.asdict(dir_md))
432
- session.add(dir_record)
433
- session.flush()
434
- assert dir_record.id is not None
435
- self.catalog.paths[path] = catalog.Dir(dir_record.id, parent._id, path.name)
436
- session.commit()
437
- _logger.info(f'Created directory `{path_str}`.')
438
- print(f'Created directory `{path_str}`.')
439
- except excs.Error as e:
440
- if ignore_errors:
441
- return
442
- else:
443
- raise e
444
-
445
- def rm_dir(self, path_str: str) -> None:
446
- """Remove a directory.
447
-
448
- Args:
449
- path_str: Path to the directory.
450
-
451
- Raises:
452
- Error: If the path does not exist or does not designate a directory or if the directory is not empty.
453
-
454
- Examples:
455
- >>> cl.rm_dir('my_dir')
456
-
457
- Remove a subdirectory:
458
-
459
- >>> cl.rm_dir('my_dir.sub_dir')
460
- """
461
- path = catalog.Path(path_str)
462
- self.catalog.paths.check_is_valid(path, expected=catalog.Dir)
463
-
464
- # make sure it's empty
465
- if len(self.catalog.paths.get_children(path, child_type=None, recursive=True)) > 0:
466
- raise excs.Error(f'Directory {path_str} is not empty')
467
- # TODO: figure out how to make force=True work in the presence of snapshots
468
- # # delete tables
469
- # for tbl_path in self.paths.get_children(path, child_type=MutableTable, recursive=True):
470
- # self.drop_table(str(tbl_path), force=True)
471
- # # rm subdirs
472
- # for dir_path in self.paths.get_children(path, child_type=Dir, recursive=False):
473
- # self.rm_dir(str(dir_path), force=True)
474
-
475
- with Env.get().engine.begin() as conn:
476
- dir = self.catalog.paths[path]
477
- conn.execute(sql.delete(schema.Dir.__table__).where(schema.Dir.id == dir._id))
478
- del self.catalog.paths[path]
479
- _logger.info(f'Removed directory {path_str}')
480
-
481
- def list_dirs(self, path_str: str = '', recursive: bool = True) -> List[str]:
482
- """List the directories in a directory.
483
-
484
- Args:
485
- path_str: Path to the directory.
486
- recursive: Whether to list subdirectories recursively.
487
-
488
- Returns:
489
- List of directory paths.
490
-
491
- Raises:
492
- Error: If the path does not exist or does not designate a directory.
493
-
494
- Examples:
495
- >>> cl.list_dirs('my_dir', recursive=True)
496
- ['my_dir', 'my_dir.sub_dir1']
497
- """
498
- path = catalog.Path(path_str, empty_is_valid=True)
499
- self.catalog.paths.check_is_valid(path, expected=catalog.Dir)
500
- return [str(p) for p in self.catalog.paths.get_children(path, child_type=catalog.Dir, recursive=recursive)]
501
-
502
- # TODO: for now, named functions are deprecated, until we understand the use case and requirements better
503
- # def create_function(self, path_str: str, fn: func.Function) -> None:
504
- # """Create a stored function.
505
- #
506
- # Args:
507
- # path_str: path where the function gets stored
508
- # func: previously created Function object
509
- #
510
- # Raises:
511
- # Error: if the path already exists or the parent is not a directory
512
- #
513
- # Examples:
514
- # Create a function ``detect()`` that takes an image and returns a JSON object, and store it in ``my_dir``:
515
- #
516
- # >>> @pxt.udf(param_types=[ImageType()], return_type=JsonType())
517
- # ... def detect(img):
518
- # ... ...
519
- # >>> cl.create_function('my_dir.detect', detect)
520
- # """
521
- # if fn.is_module_function:
522
- # raise excs.Error(f'Cannot create a named function for a library function')
523
- # path = catalog.Path(path_str)
524
- # self.catalog.paths.check_is_valid(path, expected=None)
525
- # dir = self.catalog.paths[path.parent]
526
- #
527
- # func.FunctionRegistry.get().create_function(fn, dir._id, path.name)
528
- # self.catalog.paths[path] = catalog.NamedFunction(fn.id, dir._id, path.name)
529
- # fn.md.fqn = str(path)
530
- # _logger.info(f'Created function {path_str}')
531
- #
532
- # def update_function(self, path_str: str, fn: func.Function) -> None:
533
- # """Update the implementation of a stored function.
534
- #
535
- # Args:
536
- # path_str: path to the function to be updated
537
- # func: new function implementation
538
- #
539
- # Raises:
540
- # Error: if the path does not exist or ``func`` has a different signature than the stored function.
541
- # """
542
- # if fn.is_module_function:
543
- # raise excs.Error(f'Cannot update a named function to a library function')
544
- # path = catalog.Path(path_str)
545
- # self.catalog.paths.check_is_valid(path, expected=catalog.NamedFunction)
546
- # named_fn = self.catalog.paths[path]
547
- # f = func.FunctionRegistry.get().get_function(id=named_fn._id)
548
- # if f.md.signature != fn.md.signature:
549
- # raise excs.Error(
550
- # f'The function signature cannot be changed. The existing signature is {f.md.signature}')
551
- # if f.is_aggregate != fn.is_aggregate:
552
- # raise excs.Error(f'Cannot change an aggregate function into a non-aggregate function and vice versa')
553
- # func.FunctionRegistry.get().update_function(named_fn._id, fn)
554
- # _logger.info(f'Updated function {path_str}')
555
- #
556
- # def get_function(self, path_str: str) -> func.Function:
557
- # """Get a handle to a stored function.
558
- #
559
- # Args:
560
- # path_str: path to the function
561
- #
562
- # Returns:
563
- # Function object
564
- #
565
- # Raises:
566
- # Error: if the path does not exist or is not a function
567
- #
568
- # Examples:
569
- # >>> detect = cl.get_function('my_dir.detect')
570
- # """
571
- # path = catalog.Path(path_str)
572
- # self.catalog.paths.check_is_valid(path, expected=catalog.NamedFunction)
573
- # named_fn = self.catalog.paths[path]
574
- # assert isinstance(named_fn, catalog.NamedFunction)
575
- # fn = func.FunctionRegistry.get().get_function(id=named_fn._id)
576
- # fn.md.fqn = str(path)
577
- # return fn
578
- #
579
- # def drop_function(self, path_str: str, ignore_errors: bool = False) -> None:
580
- # """Deletes stored function.
581
- #
582
- # Args:
583
- # path_str: path to the function
584
- # ignore_errors: if True, does not raise if the function does not exist
585
- #
586
- # Raises:
587
- # Error: if the path does not exist or is not a function
588
- #
589
- # Examples:
590
- # >>> cl.drop_function('my_dir.detect')
591
- # """
592
- # path = catalog.Path(path_str)
593
- # try:
594
- # self.catalog.paths.check_is_valid(path, expected=catalog.NamedFunction)
595
- # except excs.Error as e:
596
- # if ignore_errors:
597
- # return
598
- # else:
599
- # raise e
600
- # named_fn = self.catalog.paths[path]
601
- # func.FunctionRegistry.get().delete_function(named_fn._id)
602
- # del self.catalog.paths[path]
603
- # _logger.info(f'Dropped function {path_str}')
604
-
@@ -1,58 +0,0 @@
1
- from __future__ import annotations
2
- from typing import Optional, List, Any, Dict, Tuple
3
-
4
- import sqlalchemy as sql
5
- import PIL
6
- import numpy as np
7
-
8
- from .expr import Expr
9
- from .predicate import Predicate
10
- from .column_ref import ColumnRef
11
- from .data_row import DataRow
12
- from .row_builder import RowBuilder
13
- import pixeltable.catalog as catalog
14
- import pixeltable.utils.clip as clip
15
-
16
- class ImageSimilarityPredicate(Predicate):
17
- def __init__(self, img_col_ref: ColumnRef, img: Optional[PIL.Image.Image] = None, text: Optional[str] = None):
18
- assert (img is None) != (text is None)
19
- super().__init__()
20
- self.img_col_ref = img_col_ref
21
- self.components = [img_col_ref]
22
- self.img = img
23
- self.text = text
24
- self.id = self._create_id()
25
-
26
- def embedding(self) -> np.ndarray:
27
- if self.text is not None:
28
- return clip.embed_text(self.text)
29
- else:
30
- return clip.embed_image(self.img)
31
-
32
- def __str__(self) -> str:
33
- return f'{str(self.img_col_ref)}.nearest({"<img>" if self.img is not None else self.text})'
34
-
35
- def _equals(self, other: ImageSimilarityPredicate) -> bool:
36
- return False
37
-
38
- def _id_attrs(self) -> List[Tuple[str, Any]]:
39
- return super()._id_attrs() + [('img', id(self.img)), ('text', self.text)]
40
-
41
- def sql_expr(self) -> Optional[sql.ClauseElement]:
42
- return None
43
-
44
- def eval(self, data_row: DataRow, row_builder: RowBuilder) -> None:
45
- assert False
46
-
47
- def _as_dict(self) -> Dict:
48
- assert False, 'not implemented'
49
- # TODO: convert self.img into a serializable string
50
- return {'img': self.img, 'text': self.text, **super()._as_dict()}
51
-
52
- @classmethod
53
- def _from_dict(cls, d: Dict, components: List[Expr]) -> Expr:
54
- assert 'img' in d
55
- assert 'text' in d
56
- assert len(components) == 1
57
- return cls(components[0], d['img'], d['text'])
58
-