datachain 0.6.9__py3-none-any.whl → 0.6.11__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 datachain might be problematic. Click here for more details.

@@ -603,9 +603,10 @@ class Catalog:
603
603
  )
604
604
 
605
605
  lst = Listing(
606
+ self.metastore.clone(),
606
607
  self.warehouse.clone(),
607
608
  Client.get_client(list_uri, self.cache, **self.client_config),
608
- self.get_dataset(list_ds_name),
609
+ dataset_name=list_ds_name,
609
610
  object_name=object_name,
610
611
  )
611
612
 
@@ -698,9 +699,13 @@ class Catalog:
698
699
 
699
700
  client = self.get_client(source, **client_config)
700
701
  uri = client.uri
701
- st = self.warehouse.clone()
702
702
  dataset_name, _, _, _ = DataChain.parse_uri(uri, self.session)
703
- listing = Listing(st, client, self.get_dataset(dataset_name))
703
+ listing = Listing(
704
+ self.metastore.clone(),
705
+ self.warehouse.clone(),
706
+ client,
707
+ dataset_name=dataset_name,
708
+ )
704
709
  rows = DatasetQuery(
705
710
  name=dataset.name, version=ds_version, catalog=self
706
711
  ).to_db_records()
@@ -1354,6 +1359,13 @@ class Catalog:
1354
1359
  # we will create new one if it doesn't exist
1355
1360
  pass
1356
1361
 
1362
+ if dataset and version and dataset.has_version(version):
1363
+ """No need to communicate with Studio at all"""
1364
+ dataset_uri = create_dataset_uri(remote_dataset_name, version)
1365
+ print(f"Local copy of dataset {dataset_uri} already present")
1366
+ _instantiate_dataset()
1367
+ return
1368
+
1357
1369
  remote_dataset = self.get_remote_dataset(remote_dataset_name)
1358
1370
  # if version is not specified in uri, take the latest one
1359
1371
  if not version:
@@ -747,8 +747,12 @@ class SQLiteWarehouse(AbstractWarehouse):
747
747
 
748
748
  ids = self.db.execute(select_ids).fetchall()
749
749
 
750
- select_q = query.with_only_columns(
751
- *[c for c in query.selected_columns if c.name != "sys__id"]
750
+ select_q = (
751
+ query.with_only_columns(
752
+ *[c for c in query.selected_columns if c.name != "sys__id"]
753
+ )
754
+ .offset(None)
755
+ .limit(None)
752
756
  )
753
757
 
754
758
  for batch in batched_it(ids, 10_000):
datachain/lib/dc.py CHANGED
@@ -642,6 +642,59 @@ class DataChain:
642
642
  }
643
643
  return chain.gen(**signal_dict) # type: ignore[misc, arg-type]
644
644
 
645
+ def explode(
646
+ self,
647
+ col: str,
648
+ model_name: Optional[str] = None,
649
+ object_name: Optional[str] = None,
650
+ ) -> "DataChain":
651
+ """Explodes a column containing JSON objects (dict or str DataChain type) into
652
+ individual columns based on the schema of the JSON. Schema is inferred from
653
+ the first row of the column.
654
+
655
+ Args:
656
+ col: the name of the column containing JSON to be exploded.
657
+ model_name: optional generated model name. By default generates the name
658
+ automatically.
659
+ object_name: optional generated object column name. By default generates the
660
+ name automatically.
661
+
662
+ Returns:
663
+ DataChain: A new DataChain instance with the new set of columns.
664
+ """
665
+ import json
666
+
667
+ import pyarrow as pa
668
+
669
+ from datachain.lib.arrow import schema_to_output
670
+
671
+ json_value = next(self.limit(1).collect(col))
672
+ json_dict = (
673
+ json.loads(json_value) if isinstance(json_value, str) else json_value
674
+ )
675
+
676
+ if not isinstance(json_dict, dict):
677
+ raise TypeError(f"Column {col} should be a string or dict type with JSON")
678
+
679
+ schema = pa.Table.from_pylist([json_dict]).schema
680
+ output = schema_to_output(schema, None)
681
+
682
+ if not model_name:
683
+ model_name = f"{col.title()}ExplodedModel"
684
+
685
+ model = dict_to_data_model(model_name, output)
686
+
687
+ def json_to_model(json_value: Union[str, dict]):
688
+ json_dict = (
689
+ json.loads(json_value) if isinstance(json_value, str) else json_value
690
+ )
691
+ return model.model_validate(json_dict)
692
+
693
+ if not object_name:
694
+ object_name = f"{col}_expl"
695
+
696
+ return self.map(json_to_model, params=col, output={object_name: model})
697
+
645
698
  @classmethod
646
699
  def datasets(
647
700
  cls,
datachain/listing.py CHANGED
@@ -1,6 +1,7 @@
1
1
  import glob
2
2
  import os
3
3
  from collections.abc import Iterable, Iterator
4
+ from functools import cached_property
4
5
  from itertools import zip_longest
5
6
  from typing import TYPE_CHECKING, Optional
6
7
 
@@ -15,28 +16,34 @@ from datachain.utils import suffix_to_number
15
16
  if TYPE_CHECKING:
16
17
  from datachain.catalog.datasource import DataSource
17
18
  from datachain.client import Client
18
- from datachain.data_storage import AbstractWarehouse
19
+ from datachain.data_storage import AbstractMetastore, AbstractWarehouse
19
20
  from datachain.dataset import DatasetRecord
20
21
 
21
22
 
22
23
  class Listing:
23
24
  def __init__(
24
25
  self,
26
+ metastore: "AbstractMetastore",
25
27
  warehouse: "AbstractWarehouse",
26
28
  client: "Client",
27
- dataset: Optional["DatasetRecord"],
29
+ dataset_name: Optional["str"] = None,
30
+ dataset_version: Optional[int] = None,
28
31
  object_name: str = "file",
29
32
  ):
33
+ self.metastore = metastore
30
34
  self.warehouse = warehouse
31
35
  self.client = client
32
- self.dataset = dataset # dataset representing bucket listing
36
+ self.dataset_name = dataset_name # dataset representing bucket listing
37
+ self.dataset_version = dataset_version # dataset representing bucket listing
33
38
  self.object_name = object_name
34
39
 
35
40
  def clone(self) -> "Listing":
36
41
  return self.__class__(
42
+ self.metastore.clone(),
37
43
  self.warehouse.clone(),
38
44
  self.client,
39
- self.dataset,
45
+ self.dataset_name,
46
+ self.dataset_version,
40
47
  self.object_name,
41
48
  )
42
49
 
@@ -53,12 +60,22 @@ class Listing:
53
60
  def uri(self):
54
61
  from datachain.lib.listing import listing_uri_from_name
55
62
 
56
- return listing_uri_from_name(self.dataset.name)
63
+ assert self.dataset_name
57
64
 
58
- @property
65
+ return listing_uri_from_name(self.dataset_name)
66
+
67
+ @cached_property
68
+ def dataset(self) -> "DatasetRecord":
69
+ assert self.dataset_name
70
+ return self.metastore.get_dataset(self.dataset_name)
71
+
72
+ @cached_property
59
73
  def dataset_rows(self):
74
+ dataset = self.dataset
60
75
  return self.warehouse.dataset_rows(
61
- self.dataset, self.dataset.latest_version, object_name=self.object_name
76
+ dataset,
77
+ self.dataset_version or dataset.latest_version,
78
+ object_name=self.object_name,
62
79
  )
63
80
 
64
81
  def expand_path(self, path, use_glob=True) -> list[Node]:
@@ -36,7 +36,14 @@ def convert_array(arr):
36
36
 
37
37
 
38
38
  def adapt_np_array(arr):
39
- return orjson.dumps(arr, option=orjson.OPT_SERIALIZE_NUMPY).decode("utf-8")
39
+ def _json_serialize(obj):
40
+ if isinstance(obj, np.ndarray):
41
+ return obj.tolist()
42
+ return obj
43
+
44
+ return orjson.dumps(
45
+ arr, option=orjson.OPT_SERIALIZE_NUMPY, default=_json_serialize
46
+ ).decode("utf-8")
40
47
 
41
48
 
42
49
  def adapt_np_generic(val):
@@ -0,0 +1,3 @@
1
+ from .split import train_test_split
2
+
3
+ __all__ = ["train_test_split"]
@@ -0,0 +1,67 @@
1
+ from datachain import C, DataChain
2
+
3
+
4
+ def train_test_split(dc: DataChain, weights: list[float]) -> list[DataChain]:
5
+ """
6
+ Splits a DataChain into multiple subsets based on the provided weights.
7
+
8
+ This function partitions the rows or items of a DataChain into disjoint subsets,
9
+ ensuring that the relative sizes of the subsets correspond to the given weights.
10
+ It is particularly useful for creating training, validation, and test datasets.
11
+
12
+ Args:
13
+ dc (DataChain):
14
+ The DataChain instance to split.
15
+ weights (list[float]):
16
+ A list of weights indicating the relative proportions of the splits.
17
+ The weights do not need to sum to 1; they will be normalized internally.
18
+ For example:
19
+ - `[0.7, 0.3]` corresponds to a 70/30 split;
20
+ - `[2, 1, 1]` corresponds to a 50/25/25 split.
21
+
22
+ Returns:
23
+ list[DataChain]:
24
+ A list of DataChain instances, one for each weight in the weights list.
25
+
26
+ Examples:
27
+ Train-test split:
28
+ ```python
29
+ from datachain import DataChain
30
+ from datachain.toolkit import train_test_split
31
+
32
+ # Load a DataChain from a storage source (e.g., S3 bucket)
33
+ dc = DataChain.from_storage("s3://bucket/dir/")
34
+
35
+ # Perform a 70/30 train-test split
36
+ train, test = train_test_split(dc, [0.7, 0.3])
37
+
38
+ # Save the resulting splits
39
+ train.save("dataset_train")
40
+ test.save("dataset_test")
41
+ ```
42
+
43
+ Train-test-validation split:
44
+ ```python
45
+ train, test, val = train_test_split(dc, [0.7, 0.2, 0.1])
46
+ train.save("dataset_train")
47
+ test.save("dataset_test")
48
+ val.save("dataset_val")
49
+ ```
50
+
51
+ Note:
52
+ The splits are random but deterministic, based on Dataset `sys__rand` field.
53
+ """
54
+ if len(weights) < 2:
55
+ raise ValueError("Weights should have at least two elements")
56
+ if any(weight < 0 for weight in weights):
57
+ raise ValueError("Weights should be non-negative")
58
+
59
+ weights_normalized = [weight / sum(weights) for weight in weights]
60
+
61
+ return [
62
+ dc.filter(
63
+ C("sys__rand") % 1000 >= round(sum(weights_normalized[:index]) * 1000),
64
+ C("sys__rand") % 1000 < round(sum(weights_normalized[: index + 1]) * 1000),
65
+ )
66
+ for index, _ in enumerate(weights_normalized)
67
+ ]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: datachain
3
- Version: 0.6.9
3
+ Version: 0.6.11
4
4
  Summary: Wrangle unstructured AI data at scale
5
5
  Author-email: Dmitry Petrov <support@dvc.org>
6
6
  License: Apache-2.0
@@ -82,7 +82,7 @@ Requires-Dist: pytest <9,>=8 ; extra == 'tests'
82
82
  Requires-Dist: pytest-sugar >=0.9.6 ; extra == 'tests'
83
83
  Requires-Dist: pytest-cov >=4.1.0 ; extra == 'tests'
84
84
  Requires-Dist: pytest-mock >=3.12.0 ; extra == 'tests'
85
- Requires-Dist: pytest-servers[all] >=0.5.7 ; extra == 'tests'
85
+ Requires-Dist: pytest-servers[all] >=0.5.8 ; extra == 'tests'
86
86
  Requires-Dist: pytest-benchmark[histogram] ; extra == 'tests'
87
87
  Requires-Dist: pytest-xdist >=3.3.1 ; extra == 'tests'
88
88
  Requires-Dist: virtualenv ; extra == 'tests'
@@ -8,7 +8,7 @@ datachain/config.py,sha256=g8qbNV0vW2VEKpX-dGZ9pAn0DAz6G2ZFcr7SAV3PoSM,4272
8
8
  datachain/dataset.py,sha256=0IN-5y723y-bnFlieKtOFZLCjwX_yplFo3q0DV7LRPw,14821
9
9
  datachain/error.py,sha256=bxAAL32lSeMgzsQDEHbGTGORj-mPzzpCRvWDPueJNN4,1092
10
10
  datachain/job.py,sha256=Jt4sNutMHJReaGsj3r3scueN5aESLGfhimAa8pUP7Is,1271
11
- datachain/listing.py,sha256=AV23WZq-k6e2zeeNBhVQP1-2PrwNCYidO0HBDKzpVaA,7152
11
+ datachain/listing.py,sha256=TgKg25ZWAP5enzKgw2_2GUPJVdnQUh6uySHB5SJrUY4,7773
12
12
  datachain/node.py,sha256=i7_jC8VcW6W5VYkDszAOu0H-rNBuqXB4UnLEh4wFzjc,5195
13
13
  datachain/nodes_fetcher.py,sha256=F-73-h19HHNGtHFBGKk7p3mc0ALm4a9zGnzhtuUjnp4,1107
14
14
  datachain/nodes_thread_pool.py,sha256=uPo-xl8zG5m9YgODjPFBpbcqqHjI-dcxH87yAbj_qco,3192
@@ -18,7 +18,7 @@ datachain/studio.py,sha256=6kxF7VxPAbh9D7_Bk8_SghS5OXrwUwSpDaw19eNCTP4,4083
18
18
  datachain/telemetry.py,sha256=0A4IOPPp9VlP5pyW9eBfaTK3YhHGzHl7dQudQjUAx9A,994
19
19
  datachain/utils.py,sha256=-mSFowjIidJ4_sMXInvNHLn4rK_QnHuIlLuH1_lMGmI,13897
20
20
  datachain/catalog/__init__.py,sha256=g2iAAFx_gEIrqshXlhSEbrc8qDaEH11cjU40n3CHDz4,409
21
- datachain/catalog/catalog.py,sha256=Iwb562grttdGcrNVHCna_n7e884BqwGhQwAgYagBwyg,57347
21
+ datachain/catalog/catalog.py,sha256=J1nUWLI4RYCvvR6fB4neQBtB7V-CTh4PM71irhNmJc4,57817
22
22
  datachain/catalog/datasource.py,sha256=D-VWIVDCM10A8sQavLhRXdYSCG7F4o4ifswEF80_NAQ,1412
23
23
  datachain/catalog/loader.py,sha256=-6VelNfXUdgUnwInVyA8g86Boxv2xqhTh9xNS-Zlwig,8242
24
24
  datachain/client/__init__.py,sha256=T4wiYL9KIM0ZZ_UqIyzV8_ufzYlewmizlV4iymHNluE,86
@@ -36,14 +36,14 @@ datachain/data_storage/job.py,sha256=w-7spowjkOa1P5fUVtJou3OltT0L48P0RYWZ9rSJ9-s
36
36
  datachain/data_storage/metastore.py,sha256=5b7o_CSHC2djottebYn-Hq5q0yaSLOKPIRCnaVRvjsU,36056
37
37
  datachain/data_storage/schema.py,sha256=scANMQqozita3HjEtq7eupMgh6yYkrZHoXtfuL2RoQg,9879
38
38
  datachain/data_storage/serializer.py,sha256=6G2YtOFqqDzJf1KbvZraKGXl2XHZyVml2krunWUum5o,927
39
- datachain/data_storage/sqlite.py,sha256=wb8xlMJYYyt59wft0psJj587d-AwpNThzIqspVcKnRI,27388
39
+ datachain/data_storage/sqlite.py,sha256=CspRUlYsIcubgzvcQxTACnmcuKESSLZcqCl0dcrtRiA,27471
40
40
  datachain/data_storage/warehouse.py,sha256=xwMaR4jBpR13vjG3zrhphH4z2_CFLNj0KPF0LJCXCJ8,30727
41
41
  datachain/lib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
42
42
  datachain/lib/arrow.py,sha256=-hu9tic79a01SY2UBqkA3U6wUr6tnE3T3q5q_BnO93A,9156
43
43
  datachain/lib/clip.py,sha256=lm5CzVi4Cj1jVLEKvERKArb-egb9j1Ls-fwTItT6vlI,6150
44
44
  datachain/lib/data_model.py,sha256=dau4AlZBhOFvF7pEKMeqCeRkcFFg5KFvTBWW_2CdH5g,2371
45
45
  datachain/lib/dataset_info.py,sha256=q0EW9tj5jXGSD9Lzct9zbH4P1lfIGd_cIWqhnMxv7Q0,2464
46
- datachain/lib/dc.py,sha256=RQ8p95rzCMRY4ygFecO_hhQ3IgQHmbLXNqhcaINvGcI,85841
46
+ datachain/lib/dc.py,sha256=BmRgCt5fXvBqlFV07KN-nWszueRyCkC7td1x7T4BZ7k,87688
47
47
  datachain/lib/file.py,sha256=lHxE1wOGR4QJBQ3AYjhPLwpX72dOi06vkcwA-WSAGlg,14817
48
48
  datachain/lib/hf.py,sha256=BW2NPpqxkpPwkSaGlppT8Rbs8zPpyYC-tR6htY08c-0,5817
49
49
  datachain/lib/image.py,sha256=AMXYwQsmarZjRbPCZY3M1jDsM2WAB_b3cTY4uOIuXNU,2675
@@ -101,12 +101,14 @@ datachain/sql/functions/random.py,sha256=vBwEEj98VH4LjWixUCygQ5Bz1mv1nohsCG0-ZTE
101
101
  datachain/sql/functions/string.py,sha256=DYgiw8XSk7ge7GXvyRI1zbaMruIizNeI-puOjriQGZQ,1148
102
102
  datachain/sql/sqlite/__init__.py,sha256=TAdJX0Bg28XdqPO-QwUVKy8rg78cgMileHvMNot7d04,166
103
103
  datachain/sql/sqlite/base.py,sha256=aHSZVvh4XSVkvZ07h3jMoRlHI4sWD8y3SnmGs9xMG9Y,14375
104
- datachain/sql/sqlite/types.py,sha256=yzvp0sXSEoEYXs6zaYC_2YubarQoZH-MiUNXcpuEP4s,1573
104
+ datachain/sql/sqlite/types.py,sha256=lPXS1XbkmUtlkkiRxy_A_UzsgpPv2VSkXYOD4zIHM4w,1734
105
105
  datachain/sql/sqlite/vector.py,sha256=ncW4eu2FlJhrP_CIpsvtkUabZlQdl2D5Lgwy_cbfqR0,469
106
+ datachain/toolkit/__init__.py,sha256=eQ58Q5Yf_Fgv1ZG0IO5dpB4jmP90rk8YxUWmPc1M2Bo,68
107
+ datachain/toolkit/split.py,sha256=6FcEJgUsJsUcCqKW5aXuJy4DvbcQ7_dFbsfNPhn8EVg,2377
106
108
  datachain/torch/__init__.py,sha256=gIS74PoEPy4TB3X6vx9nLO0Y3sLJzsA8ckn8pRWihJM,579
107
- datachain-0.6.9.dist-info/LICENSE,sha256=8DnqK5yoPI_E50bEg_zsHKZHY2HqPy4rYN338BHQaRA,11344
108
- datachain-0.6.9.dist-info/METADATA,sha256=McKhuW43_7Q3iJKxueIYbk-rpYF6rbIKeFinzeeUzMo,18037
109
- datachain-0.6.9.dist-info/WHEEL,sha256=R06PA3UVYHThwHvxuRWMqaGcr-PuniXahwjmQRFMEkY,91
110
- datachain-0.6.9.dist-info/entry_points.txt,sha256=0GMJS6B_KWq0m3VT98vQI2YZodAMkn4uReZ_okga9R4,49
111
- datachain-0.6.9.dist-info/top_level.txt,sha256=lZPpdU_2jJABLNIg2kvEOBi8PtsYikbN1OdMLHk8bTg,10
112
- datachain-0.6.9.dist-info/RECORD,,
109
+ datachain-0.6.11.dist-info/LICENSE,sha256=8DnqK5yoPI_E50bEg_zsHKZHY2HqPy4rYN338BHQaRA,11344
110
+ datachain-0.6.11.dist-info/METADATA,sha256=L9Z8Hr_bTC8AWCl3bjakzsdej3lgFMCsFJ6wDdE1heU,18038
111
+ datachain-0.6.11.dist-info/WHEEL,sha256=R06PA3UVYHThwHvxuRWMqaGcr-PuniXahwjmQRFMEkY,91
112
+ datachain-0.6.11.dist-info/entry_points.txt,sha256=0GMJS6B_KWq0m3VT98vQI2YZodAMkn4uReZ_okga9R4,49
113
+ datachain-0.6.11.dist-info/top_level.txt,sha256=lZPpdU_2jJABLNIg2kvEOBi8PtsYikbN1OdMLHk8bTg,10
114
+ datachain-0.6.11.dist-info/RECORD,,