DataChain
The DataChain
class creates a data chain, which is a sequence of data manipulation
steps such as reading data from storages, running AI or LLM models or calling external
services API to validate or enrich data. See DataChain
for examples of how to create a chain.
Column
Bases: ColumnClause
Source code in datachain/query/schema.py
glob
from_csv
from_csv(
path,
delimiter: Optional[str] = None,
header: bool = True,
output: OutputType = None,
object_name: str = "",
model_name: str = "",
source: bool = True,
nrows=None,
session: Optional[Session] = None,
settings: Optional[dict] = None,
column_types: Optional[
dict[str, Union[str, DataType]]
] = None,
parse_options: Optional[
dict[str, Union[str, Union[bool, Callable]]]
] = None,
**kwargs
) -> DataChain
Generate chain from csv files.
Parameters:
-
path
–Storage URI with directory. URI must start with storage prefix such as
s3://
,gs://
,az://
or "file:///". -
delimiter
–Character for delimiting columns. Takes precedence if also specified in
parse_options
. Defaults to ",". -
header
–Whether the files include a header row.
-
output
–Dictionary or feature class defining column names and their corresponding types. List of column names is also accepted, in which case types will be inferred.
-
object_name
–Created object column name.
-
model_name
–Generated model name.
-
source
–Whether to include info about the source file.
-
nrows
–Optional row limit.
-
session
–Session to use for the chain.
-
settings
–Settings to use for the chain.
-
column_types
–Dictionary of column names and their corresponding types. It is passed to CSV reader and for each column specified type auto inference is disabled.
-
parse_options
(Optional[dict[str, Union[str, Union[bool, Callable]]]]
, default:None
) –Tells the parser how to process lines. See https://arrow.apache.org/docs/python/generated/pyarrow.csv.ParseOptions.html
Example
Reading a csv file:
Reading csv files from a directory as a combined dataset:
Source code in datachain/lib/dc/csv.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 |
|
from_dataset
from_dataset(
name: str,
version: Optional[int] = None,
session: Optional[Session] = None,
settings: Optional[dict] = None,
fallback_to_studio: bool = True,
) -> DataChain
Get data from a saved Dataset. It returns the chain itself. If dataset or version is not found locally, it will try to pull it from Studio.
Parameters:
-
name
–dataset name
-
version
–dataset version
-
session
–Session to use for the chain.
-
settings
–Settings to use for the chain.
-
fallback_to_studio
–Try to pull dataset from Studio if not found locally. Default is True.
Example
Source code in datachain/lib/dc/datasets.py
datasets
datasets(
session: Optional[Session] = None,
settings: Optional[dict] = None,
in_memory: bool = False,
object_name: str = "dataset",
include_listing: bool = False,
studio: bool = False,
) -> DataChain
Generate chain with list of registered datasets.
Parameters:
-
session
(Optional[Session]
, default:None
) –Optional session instance. If not provided, uses default session.
-
settings
(Optional[dict]
, default:None
) –Optional dictionary of settings to configure the chain.
-
in_memory
(bool
, default:False
) –If True, creates an in-memory session. Defaults to False.
-
object_name
(str
, default:'dataset'
) –Name of the output object in the chain. Defaults to "dataset".
-
include_listing
(bool
, default:False
) –If True, includes listing datasets. Defaults to False.
-
studio
(bool
, default:False
) –If True, returns datasets from Studio only, otherwise returns all local datasets. Defaults to False.
Returns:
-
DataChain
(DataChain
) –A new DataChain instance containing dataset information.
Example
Source code in datachain/lib/dc/datasets.py
from_hf
from_hf(
dataset: Union[str, HFDatasetType],
*args,
session: Optional[Session] = None,
settings: Optional[dict] = None,
object_name: str = "",
model_name: str = "",
**kwargs
) -> DataChain
Generate chain from huggingface hub dataset.
Parameters:
-
dataset
–Path or name of the dataset to read from Hugging Face Hub, or an instance of
datasets.Dataset
-like object. -
session
–Session to use for the chain.
-
settings
–Settings to use for the chain.
-
object_name
–Generated object column name.
-
model_name
–Generated model name.
-
kwargs
–Parameters to pass to datasets.load_dataset.
Example
Load from Hugging Face Hub:
Generate chain from loaded dataset:
Source code in datachain/lib/dc/hf.py
from_json
from_json(
path: Union[str, PathLike[str]],
type: FileType = "text",
spec: Optional[DataType] = None,
schema_from: Optional[str] = "auto",
jmespath: Optional[str] = None,
object_name: Optional[str] = "",
model_name: Optional[str] = None,
format: Optional[str] = "json",
nrows=None,
**kwargs
) -> DataChain
Get data from JSON. It returns the chain itself.
Parameters:
-
path
–storage URI with directory. URI must start with storage prefix such as
s3://
,gs://
,az://
or "file:///" -
type
–read file as "binary", "text", or "image" data. Default is "text".
-
spec
–optional Data Model
-
schema_from
–path to sample to infer spec (if schema not provided)
-
object_name
–generated object column name
-
model_name
–optional generated model name
-
format
(Optional[str]
, default:'json'
) –"json", "jsonl"
-
jmespath
–optional JMESPATH expression to reduce JSON
-
nrows
–optional row limit for jsonl and JSON arrays
Example
infer JSON schema from data, reduce using JMESPATH
infer JSON schema from a particular path
Source code in datachain/lib/dc/json.py
listings
listings(
session: Optional[Session] = None,
in_memory: bool = False,
object_name: str = "listing",
**kwargs
) -> DataChain
Generate chain with list of cached listings. Listing is a special kind of dataset which has directory listing data of some underlying storage (e.g S3 bucket).
Source code in datachain/lib/dc/listings.py
from_pandas
from_pandas(
df: DataFrame,
name: str = "",
session: Optional[Session] = None,
settings: Optional[dict] = None,
in_memory: bool = False,
object_name: str = "",
) -> DataChain
Generate chain from pandas data-frame.
Example
Source code in datachain/lib/dc/pandas.py
from_parquet
from_parquet(
path,
partitioning: Any = "hive",
output: Optional[dict[str, DataType]] = None,
object_name: str = "",
model_name: str = "",
source: bool = True,
session: Optional[Session] = None,
settings: Optional[dict] = None,
**kwargs
) -> DataChain
Generate chain from parquet files.
Parameters:
-
path
–Storage URI with directory. URI must start with storage prefix such as
s3://
,gs://
,az://
or "file:///". -
partitioning
–Any pyarrow partitioning schema.
-
output
–Dictionary defining column names and their corresponding types.
-
object_name
–Created object column name.
-
model_name
–Generated model name.
-
source
–Whether to include info about the source file.
-
session
–Session to use for the chain.
-
settings
–Settings to use for the chain.
Example
Reading a single file:
Reading a partitioned dataset from a directory:
Source code in datachain/lib/dc/parquet.py
from_records
from_records(
to_insert: Optional[Union[dict, list[dict]]],
session: Optional[Session] = None,
settings: Optional[dict] = None,
in_memory: bool = False,
schema: Optional[dict[str, DataType]] = None,
) -> DataChain
Create a DataChain from the provided records. This method can be used for programmatically generating a chain in contrast of reading data from storages or other sources.
Parameters:
-
to_insert
–records (or a single record) to insert. Each record is a dictionary of signals and theirs values.
-
schema
–describes chain signals and their corresponding types
Source code in datachain/lib/dc/records.py
from_storage
from_storage(
uri: Union[str, PathLike[str]],
*,
type: FileType = "binary",
session: Optional[Session] = None,
settings: Optional[dict] = None,
in_memory: bool = False,
recursive: Optional[bool] = True,
object_name: str = "file",
update: bool = False,
anon: bool = False,
client_config: Optional[dict] = None
) -> DataChain
Get data from a storage as a list of file with all file attributes. It returns the chain itself as usual.
Parameters:
-
uri
–storage URI with directory. URI must start with storage prefix such as
s3://
,gs://
,az://
or "file:///" -
type
–read file as "binary", "text", or "image" data. Default is "binary".
-
recursive
–search recursively for the given path.
-
object_name
–Created object column name.
-
update
–force storage reindexing. Default is False.
-
anon
–If True, we will treat cloud bucket as public one
-
client_config
–Optional client configuration for the storage client.
Example
Simple call from s3
With AWS S3-compatible storage
import datachain as dc
chain = dc.from_storage(
"s3://my-bucket/my-dir",
client_config = {"aws_endpoint_url": "<minio-endpoint-url>"}
)
Pass existing session
Source code in datachain/lib/dc/storage.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
|
from_values
from_values(
ds_name: str = "",
session: Optional[Session] = None,
settings: Optional[dict] = None,
in_memory: bool = False,
output: OutputType = None,
object_name: str = "",
**fr_map
) -> DataChain
Generate chain from list of values.
Source code in datachain/lib/dc/values.py
DataChain
DataChain(
query: DatasetQuery,
settings: Settings,
signal_schema: SignalSchema,
setup: Optional[dict] = None,
_sys: bool = False,
)
DataChain - a data structure for batch data processing and evaluation.
It represents a sequence of data manipulation steps such as reading data from storages, running AI or LLM models or calling external services API to validate or enrich data.
Data in DataChain is presented as Python classes with arbitrary set of fields,
including nested classes. The data classes have to inherit from DataModel
class.
The supported set of field types include: majority of the type supported by the
underlyind library Pydantic
.
See Also
from_storage("s3://my-bucket/my-dir/")
- reading unstructured
data files from storages such as S3, gs or Azure ADLS.
DataChain.save("name")
- saving to a dataset.
from_dataset("name")
- reading from a dataset.
from_values(fib=[1, 2, 3, 5, 8])
- generating from values.
from_pandas(pd.DataFrame(...))
- generating from pandas.
from_json("file.json")
- generating from json.
from_csv("file.csv")
- generating from csv.
from_parquet("file.parquet")
- generating from parquet.
Example
import os
from mistralai.client import MistralClient
from mistralai.models.chat_completion import ChatMessage
import datachain as dc
PROMPT = (
"Was this bot dialog successful? "
"Describe the 'result' as 'Yes' or 'No' in a short JSON"
)
model = "mistral-large-latest"
api_key = os.environ["MISTRAL_API_KEY"]
chain = (
dc.from_storage("gs://datachain-demo/chatbot-KiT/")
.limit(5)
.settings(cache=True, parallel=5)
.map(
mistral_response=lambda file: MistralClient(api_key=api_key)
.chat(
model=model,
response_format={"type": "json_object"},
messages=[
ChatMessage(role="user", content=f"{PROMPT}: {file.read()}")
],
)
.choices[0]
.message.content,
)
.save()
)
try:
print(chain.select("mistral_response").results())
except Exception as e:
print(f"do you have the right Mistral API key? {e}")
Source code in datachain/lib/dc/datachain.py
__or__
__repr__
__repr__() -> str
Return a string representation of the chain.
Source code in datachain/lib/dc/datachain.py
agg
agg(
func: Optional[Callable] = None,
partition_by: Optional[PartitionByType] = None,
params: Union[None, str, Sequence[str]] = None,
output: OutputType = None,
**signal_map
) -> Self
Aggregate rows using partition_by
statement and apply a function to the
groups of aggregated rows. The function needs to return new objects for each
group of the new rows. It returns a chain itself with new signals.
Input-output relationship: N:M
This method bears similarity to gen()
and map()
, employing a comparable set
of parameters, yet differs in two crucial aspects:
1. The partition_by
parameter: This specifies the column name or a list of
column names that determine the grouping criteria for aggregation.
2. Group-based UDF function input: Instead of individual rows, the function
receives a list all rows within each group defined by partition_by
.
Examples:
chain = chain.agg(
total=lambda category, amount: [sum(amount)],
output=float,
partition_by="category",
)
chain.save("new_dataset")
An alternative syntax, when you need to specify a more complex function:
# It automatically resolves which columns to pass to the function
# by looking at the function signature.
def agg_sum(
file: list[File], amount: list[float]
) -> Iterator[tuple[File, float]]:
yield file[0], sum(amount)
chain = chain.agg(
agg_sum,
output={"file": File, "total": float},
# Alternative syntax is to use `C` (short for Column) to specify
# a column name or a nested column, e.g. C("file.path").
partition_by=C("category"),
)
chain.save("new_dataset")
Source code in datachain/lib/dc/datachain.py
apply
Apply any function to the chain.
Useful for reusing in a chain of operations.
Example
Source code in datachain/lib/dc/datachain.py
avg
avg(fr: DataType)
batch_map
batch_map(
func: Optional[Callable] = None,
params: Union[None, str, Sequence[str]] = None,
output: OutputType = None,
batch: int = 1000,
**signal_map
) -> Self
This is a batch version of map()
.
Input-output relationship: N:N
It accepts the same parameters plus an additional parameter:
batch : Size of each batch passed to `func`. Defaults to 1000.
Example
Source code in datachain/lib/dc/datachain.py
c
Returns Column instance attached to the current chain.
chunk
Split a chain into smaller chunks for e.g. parallelization.
Example
Note
Bear in mind that index
is 0-indexed but total
isn't.
Use 0/3, 1/3 and 2/3, not 1/3, 2/3 and 3/3.
Source code in datachain/lib/dc/datachain.py
clone
collect
Yields rows of values, optionally limited to the specified columns.
Parameters:
-
*cols
(str
, default:()
) –Limit to the specified columns. By default, all columns are selected.
Yields:
-
DataType
–Yields a single item if a column is selected.
-
tuple[DataType, ...]
–Yields a tuple of items if multiple columns are selected.
Example
Iterating over all rows:
Iterating over all rows with selected columns:
Iterating over a single column:
Source code in datachain/lib/dc/datachain.py
collect_flatten
collect_flatten(
*, row_factory=None, include_hidden: bool = True
)
Yields flattened rows of values as a tuple.
Parameters:
-
row_factory
–A callable to convert row to a custom format. It should accept two arguments: a list of column names and a tuple of row values.
-
include_hidden
(bool
, default:True
) –Whether to include hidden signals from the schema.
Source code in datachain/lib/dc/datachain.py
column
Returns Column instance with a type if name is found in current schema, otherwise raises an exception.
Source code in datachain/lib/dc/datachain.py
compare
compare(
other: DataChain,
on: Union[str, Sequence[str]],
right_on: Optional[Union[str, Sequence[str]]] = None,
compare: Optional[Union[str, Sequence[str]]] = None,
right_compare: Optional[
Union[str, Sequence[str]]
] = None,
added: bool = True,
deleted: bool = True,
modified: bool = True,
same: bool = False,
status_col: Optional[str] = None,
) -> DataChain
Comparing two chains by identifying rows that are added, deleted, modified
or same. Result is the new chain that has additional column with possible
values: A
, D
, M
, U
representing added, deleted, modified and same
rows respectively. Note that if only one "status" is asked, by setting proper
flags, this additional column is not created as it would have only one value
for all rows. Beside additional diff column, new chain has schema of the chain
on which method was called.
Parameters:
-
other
(DataChain
) –Chain to calculate diff from.
-
on
(Union[str, Sequence[str]]
) –Column or list of columns to match on. If both chains have the same columns then this column is enough for the match. Otherwise,
right_on
parameter has to specify the columns for the other chain. This value is used to find corresponding row in other dataset. If not found there, row is considered as added (or removed if vice versa), and if found then row can be either modified or same. -
right_on
(Optional[Union[str, Sequence[str]]]
, default:None
) –Optional column or list of columns for the
other
to match. -
compare
(Optional[Union[str, Sequence[str]]]
, default:None
) –Column or list of columns to compare on. If both chains have the same columns then this column is enough for the compare. Otherwise,
right_compare
parameter has to specify the columns for the other chain. This value is used to see if row is modified or same. If not set, all columns will be used for comparison -
right_compare
(Optional[Union[str, Sequence[str]]]
, default:None
) –Optional column or list of columns for the
other
to compare to. -
added
(bool
, default:True
) –Whether to return added rows in resulting chain.
-
deleted
(bool
, default:True
) –Whether to return deleted rows in resulting chain.
-
modified
(bool
, default:True
) –Whether to return modified rows in resulting chain.
-
same
(bool
, default:False
) –Whether to return unchanged rows in resulting chain.
-
status_col
(str
, default:None
) –Name of the new column that is created in resulting chain representing diff status.
Example
Source code in datachain/lib/dc/datachain.py
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 |
|
count
count() -> int
diff
diff(
other: DataChain,
on: str = "file",
right_on: Optional[str] = None,
added: bool = True,
modified: bool = True,
deleted: bool = False,
same: bool = False,
status_col: Optional[str] = None,
) -> DataChain
Similar to .compare()
, which is more generic method to calculate difference
between two chains. Unlike .compare()
, this method works only on those chains
that have File
object, or it's derivatives, in it. File source
and path
are used for matching, and file version
and etag
for comparing, while in
.compare()
user needs to provide arbitrary columns for matching and comparing.
Parameters:
-
other
(DataChain
) –Chain to calculate diff from.
-
on
(str
, default:'file'
) –File signal to match on. If both chains have the same file signal then this column is enough for the match. Otherwise,
right_on
parameter has to specify the file signal for the other chain. This value is used to find corresponding row in other dataset. If not found there, row is considered as added (or removed if vice versa), and if found then row can be either modified or same. -
right_on
(Optional[str]
, default:None
) –Optional file signal for the
other
to match. -
added
(bool
, default:True
) –Whether to return added rows in resulting chain.
-
deleted
(bool
, default:False
) –Whether to return deleted rows in resulting chain.
-
modified
(bool
, default:True
) –Whether to return modified rows in resulting chain.
-
same
(bool
, default:False
) –Whether to return unchanged rows in resulting chain.
-
status_col
(str
, default:None
) –Optional name of the new column that is created in resulting chain representing diff status.
Example
Source code in datachain/lib/dc/datachain.py
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 |
|
distinct
Removes duplicate rows based on uniqueness of some input column(s) i.e if rows are found with the same value of input column(s), only one row is left in the result set.
Source code in datachain/lib/dc/datachain.py
exec
explode
explode(
col: str,
model_name: Optional[str] = None,
object_name: Optional[str] = None,
schema_sample_size: int = 1,
) -> DataChain
Explodes a column containing JSON objects (dict or str DataChain type) into individual columns based on the schema of the JSON. Schema is inferred from the first row of the column.
Parameters:
-
col
(str
) –the name of the column containing JSON to be exploded.
-
model_name
(Optional[str]
, default:None
) –optional generated model name. By default generates the name automatically.
-
object_name
(Optional[str]
, default:None
) –optional generated object column name. By default generates the name automatically.
-
schema_sample_size
(int
, default:1
) –the number of rows to use for inferring the schema of the JSON (in case some fields are optional and it's not enough to analyze a single row).
Returns:
-
DataChain
(DataChain
) –A new DataChain instance with the new set of columns.
Source code in datachain/lib/dc/datachain.py
filter
filter(*args: Any) -> Self
Filter the chain according to conditions.
Example
Basic usage with built-in operators
Using glob to match patterns
Using datachain.func
Combining filters with "or"
Combining filters with "and"
Source code in datachain/lib/dc/datachain.py
gen
gen(
func: Optional[Union[Callable, Generator]] = None,
params: Union[None, str, Sequence[str]] = None,
output: OutputType = None,
**signal_map
) -> Self
Apply a function to each row to create new rows (with potentially new signals). The function needs to return a new objects for each of the new rows. It returns a chain itself with new signals.
Input-output relationship: 1:N
This method is similar to map()
, uses the same list of parameters, but with
one key differences: It produces a sequence of rows for each input row (like
extracting multiple file records from a single tar file or bounding boxes from a
single image file).
Example
Source code in datachain/lib/dc/datachain.py
group_by
group_by(
*,
partition_by: Optional[
Union[str, Func, Sequence[Union[str, Func]]]
] = None,
**kwargs: Func
) -> Self
Group rows by specified set of signals and return new signals with aggregated values.
The supported functions
count(), sum(), avg(), min(), max(), any_value(), collect(), concat()
Source code in datachain/lib/dc/datachain.py
limit
limit(n: int) -> Self
Return the first n
rows of the chain.
If the chain is unordered, which rows are returned is undefined.
If the chain has less than n
rows, the whole chain is returned.
Parameters:
-
n
(int
) –Number of rows to return.
Source code in datachain/lib/dc/datachain.py
map
map(
func: Optional[Callable] = None,
params: Union[None, str, Sequence[str]] = None,
output: OutputType = None,
**signal_map
) -> Self
Apply a function to each row to create new signals. The function should return a new object for each row. It returns a chain itself with new signals.
Input-output relationship: 1:1
Parameters:
-
func
–Function applied to each row.
-
params
–List of column names used as input for the function. Default is taken from function signature.
-
output
–Dictionary defining new signals and their corresponding types. Default type is taken from function signature. Default can be also taken from kwargs - **signal_map (see below). If signal name is defined using signal_map (see below) only a single type value can be used.
-
**signal_map
–kwargs can be used to define
func
together with it's return signal name in format ofmap(my_sign=my_func)
. This helps define signal names and function in a nicer way.
Example
Using signal_map and single type in output:
Using func and output as a map:
Source code in datachain/lib/dc/datachain.py
max
max(fr: DataType)
merge
merge(
right_ds: DataChain,
on: Union[MergeColType, Sequence[MergeColType]],
right_on: Optional[
Union[MergeColType, Sequence[MergeColType]]
] = None,
inner=False,
full=False,
rname="right_",
) -> Self
Merge two chains based on the specified criteria.
Parameters:
-
right_ds
(DataChain
) –Chain to join with.
-
on
(Union[MergeColType, Sequence[MergeColType]]
) –Predicate ("column.name", C("column.name"), or Func) or list of Predicates to join on. If both chains have the same predicates then this predicate is enough for the join. Otherwise,
right_on
parameter has to specify the predicates for the other chain. -
right_on
(Optional[Union[MergeColType, Sequence[MergeColType]]]
, default:None
) –Optional predicate or list of Predicates for the
right_ds
to join. -
inner
(bool
, default:False
) –Whether to run inner join or outer join.
-
full
(bool
, default:False
) –Whether to run full outer join.
-
rname
(str
, default:'right_'
) –Name prefix for conflicting signal names.
Examples:
imgs.merge(captions,
on=func.path.file_stem(imgs.c("file.path")),
right_on=func.path.file_stem(captions.c("file.path"))
)
Source code in datachain/lib/dc/datachain.py
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 |
|
min
min(fr: DataType)
mutate
Create new signals based on existing signals.
This method cannot modify existing columns. If you need to modify an
existing column, use a different name for the new column and then use
select()
to choose which columns to keep.
This method is vectorized and more efficient compared to map(), and it does not extract or download any data from the internal database. However, it can only utilize predefined built-in functions and their combinations.
The supported functions
Numerical: +, -, *, /, rand(), avg(), count(), func(), greatest(), least(), max(), min(), sum() String: length(), split(), replace(), regexp_replace() Filename: name(), parent(), file_stem(), file_ext() Array: length(), sip_hash_64(), euclidean_distance(), cosine_distance() Window: row_number(), rank(), dense_rank(), first()
Example:
dc.mutate(
area=Column("image.height") * Column("image.width"),
extension=file_ext(Column("file.name")),
dist=cosine_distance(embedding_text, embedding_image)
)
Window function example:
window = func.window(partition_by="file.parent", order_by="file.size")
dc.mutate(
row_number=func.row_number().over(window),
)
This method can be also used to rename signals. If the Column("name") provided as value for the new signal - the old column will be dropped. Otherwise a new column is created.
Example:
Source code in datachain/lib/dc/datachain.py
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 |
|
offset
offset(offset: int) -> Self
Return the results starting with the offset row.
If the chain is unordered, which rows are skipped in undefined.
If the chain has less than offset
rows, the result is an empty chain.
Parameters:
-
offset
(int
) –Number of rows to skip.
Source code in datachain/lib/dc/datachain.py
order_by
order_by(*args, descending: bool = False) -> Self
Orders by specified set of columns.
Parameters:
-
descending
(bool
, default:False
) –Whether to sort in descending order or not.
Note
Order is not guaranteed when steps are added after an order_by
statement.
I.e. when using from_dataset
an order_by
statement should be used if
the order of the records in the chain is important.
Using order_by
directly before limit
, collect
and collect_flatten
will give expected results.
See https://github.com/iterative/datachain/issues/477 for further details.
Source code in datachain/lib/dc/datachain.py
parse_tabular
parse_tabular(
output: OutputType = None,
object_name: str = "",
model_name: str = "",
source: bool = True,
nrows: Optional[int] = None,
**kwargs
) -> Self
Generate chain from list of tabular files.
Parameters:
-
output
–Dictionary or feature class defining column names and their corresponding types. List of column names is also accepted, in which case types will be inferred.
-
object_name
–Generated object column name.
-
model_name
–Generated model name.
-
source
–Whether to include info about the source file.
-
nrows
–Optional row limit.
-
kwargs
–Parameters to pass to pyarrow.dataset.dataset.
Example
Reading a json lines file:
Reading a filtered list of files as a dataset:
Source code in datachain/lib/dc/datachain.py
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 |
|
print_schema
reset_settings
reset_settings(settings: Optional[Settings] = None) -> Self
sample
Return a random sample from the chain.
Parameters:
-
n
(int
) –Number of samples to draw.
NOTE: Samples are not deterministic, and streamed/paginated queries or multiple workers will draw samples with replacement.
Source code in datachain/lib/dc/datachain.py
save
save(
name: Optional[str] = None,
version: Optional[int] = None,
description: Optional[str] = None,
labels: Optional[list[str]] = None,
**kwargs
) -> Self
Save to a Dataset. It returns the chain itself.
Parameters:
-
name
–dataset name. Empty name saves to a temporary dataset that will be removed after process ends. Temp dataset are useful for optimization.
-
version
–version of a dataset. Default - the last version that exist.
-
description
–description of a dataset.
-
labels
–labels of a dataset.
Source code in datachain/lib/dc/datachain.py
select
Select only a specified set of signals.
Source code in datachain/lib/dc/datachain.py
select_except
select_except(*args: str) -> Self
Select all the signals expect the specified signals.
Source code in datachain/lib/dc/datachain.py
settings
settings(
cache=None,
parallel=None,
workers=None,
min_task_size=None,
prefetch: Optional[int] = None,
sys: Optional[bool] = None,
) -> Self
Change settings for chain.
This function changes specified settings without changing not specified ones. It returns chain, so, it can be chained later with next operation.
Parameters:
-
cache
–data caching (default=False)
-
parallel
–number of thread for processors. True is a special value to enable all available CPUs (default=1)
-
workers
–number of distributed workers. Only for Studio mode. (default=1)
-
min_task_size
–minimum number of tasks (default=1)
-
prefetch
(Optional[int]
, default:None
) –number of workers to use for downloading files in advance. This is enabled by default and uses 2 workers. To disable prefetching, set it to 0.
Example
Source code in datachain/lib/dc/datachain.py
setup
Setup variables to pass to UDF functions.
Use before running map/gen/agg/batch_map to save an object and pass it as an argument to the UDF.
Example
import anthropic
from anthropic.types import Message
(
DataChain.from_storage(DATA, type="text")
.settings(parallel=4, cache=True)
.setup(client=lambda: anthropic.Anthropic(api_key=API_KEY))
.map(
claude=lambda client, file: client.messages.create(
model=MODEL,
system=PROMPT,
messages=[{"role": "user", "content": file.get_value()}],
),
output=Message,
)
)
Source code in datachain/lib/dc/datachain.py
show
show(
limit: int = 20,
flatten=False,
transpose=False,
truncate=True,
include_hidden=False,
) -> None
Show a preview of the chain results.
Parameters:
-
limit
–How many rows to show.
-
flatten
–Whether to use a multiindex or flatten column names.
-
transpose
–Whether to transpose rows and columns.
-
truncate
–Whether or not to truncate the contents of columns.
-
include_hidden
–Whether to include hidden columns.
Source code in datachain/lib/dc/datachain.py
shuffle
subtract
subtract(
other: DataChain,
on: Optional[Union[str, Sequence[str]]] = None,
right_on: Optional[Union[str, Sequence[str]]] = None,
) -> Self
Remove rows that appear in another chain.
Parameters:
-
other
(DataChain
) –chain whose rows will be removed from
self
-
on
(Optional[Union[str, Sequence[str]]]
, default:None
) –columns to consider for determining row equality in
self
. If unspecified, defaults to all common columns betweenself
andother
. -
right_on
(Optional[Union[str, Sequence[str]]]
, default:None
) –columns to consider for determining row equality in
other
. If unspecified, defaults to the same values ason
.
Source code in datachain/lib/dc/datachain.py
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 |
|
sum
sum(fr: DataType)
to_columnar_data_with_names
to_columnar_data_with_names(
chunk_size: int = DEFAULT_PARQUET_CHUNK_SIZE,
) -> tuple[list[str], Iterator[list[list[Any]]]]
Returns column names and the results as an iterator that provides chunks, with each chunk containing a list of columns, where each column contains a list of the row values for that column in that chunk. Useful for columnar data formats, such as parquet or other OLAP databases.
Source code in datachain/lib/dc/datachain.py
to_csv
to_csv(
path: Union[str, PathLike[str]],
delimiter: str = ",",
fs_kwargs: Optional[dict[str, Any]] = None,
**kwargs
) -> None
Save chain to a csv (comma-separated values) file.
Parameters:
-
path
–Path to save the file. This supports local paths as well as remote paths, such as s3:// or hf:// with fsspec.
-
delimiter
–Delimiter to use for the resulting file.
-
fs_kwargs
–Optional kwargs to pass to the fsspec filesystem, used only for write, for fsspec-type URLs, such as s3:// or hf:// when provided as the destination path.
Source code in datachain/lib/dc/datachain.py
to_json
to_json(
path: Union[str, PathLike[str]],
fs_kwargs: Optional[dict[str, Any]] = None,
include_outer_list: bool = True,
) -> None
Save chain to a JSON file.
Parameters:
-
path
–Path to save the file. This supports local paths as well as remote paths, such as s3:// or hf:// with fsspec.
-
fs_kwargs
–Optional kwargs to pass to the fsspec filesystem, used only for write, for fsspec-type URLs, such as s3:// or hf:// when provided as the destination path.
-
include_outer_list
–Sets whether to include an outer list for all rows. Setting this to True makes the file valid JSON, while False instead writes in the JSON lines format.
Source code in datachain/lib/dc/datachain.py
to_jsonl
Save chain to a JSON lines file.
Parameters:
-
path
–Path to save the file. This supports local paths as well as remote paths, such as s3:// or hf:// with fsspec.
-
fs_kwargs
–Optional kwargs to pass to the fsspec filesystem, used only for write, for fsspec-type URLs, such as s3:// or hf:// when provided as the destination path.
Source code in datachain/lib/dc/datachain.py
to_pandas
to_pandas(flatten=False, include_hidden=True) -> DataFrame
Return a pandas DataFrame from the chain.
Parameters:
-
flatten
–Whether to use a multiindex or flatten column names.
-
include_hidden
–Whether to include hidden columns.
Source code in datachain/lib/dc/datachain.py
to_parquet
to_parquet(
path: Union[str, PathLike[str], BinaryIO],
partition_cols: Optional[Sequence[str]] = None,
chunk_size: int = DEFAULT_PARQUET_CHUNK_SIZE,
fs_kwargs: Optional[dict[str, Any]] = None,
**kwargs
) -> None
Save chain to parquet file with SignalSchema metadata.
Parameters:
-
path
–Path or a file-like binary object to save the file. This supports local paths as well as remote paths, such as s3:// or hf:// with fsspec.
-
partition_cols
–Column names by which to partition the dataset.
-
chunk_size
–The chunk size of results to read and convert to columnar data, to avoid running out of memory.
-
fs_kwargs
–Optional kwargs to pass to the fsspec filesystem, used only for write, for fsspec-type URLs, such as s3:// or hf:// when provided as the destination path.
Source code in datachain/lib/dc/datachain.py
1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 |
|
to_pytorch
to_pytorch(
transform=None,
tokenizer=None,
tokenizer_kwargs=None,
num_samples=0,
remove_prefetched: bool = False,
)
Convert to pytorch dataset format.
Parameters:
-
transform
(Transform
, default:None
) –Torchvision transforms to apply to the dataset.
-
tokenizer
(Callable
, default:None
) –Tokenizer to use to tokenize text values.
-
tokenizer_kwargs
(dict
, default:None
) –Additional kwargs to pass when calling tokenizer.
-
num_samples
(int
, default:0
) –Number of random samples to draw for each epoch. This argument is ignored if
num_samples=0
(the default). -
remove_prefetched
(bool
, default:False
) –Whether to remove prefetched files after reading.
Example
Source code in datachain/lib/dc/datachain.py
to_records
Convert every row to a dictionary.
Source code in datachain/lib/dc/datachain.py
to_storage
to_storage(
output: Union[str, PathLike[str]],
signal: str = "file",
placement: ExportPlacement = "fullpath",
link_type: Literal["copy", "symlink"] = "copy",
num_threads: Optional[int] = EXPORT_FILES_MAX_THREADS,
anon: bool = False,
client_config: Optional[dict] = None,
) -> None
Export files from a specified signal to a directory. Files can be exported to a local or cloud directory.
Parameters:
-
output
(Union[str, PathLike[str]]
) –Path to the target directory for exporting files.
-
signal
(str
, default:'file'
) –Name of the signal to export files from.
-
placement
(ExportPlacement
, default:'fullpath'
) –The method to use for naming exported files. The possible values are: "filename", "etag", "fullpath", and "checksum".
-
link_type
(Literal['copy', 'symlink']
, default:'copy'
) –Method to use for exporting files. Falls back to
'copy'
if symlinking fails. -
num_threads
–number of threads to use for exporting files. By default it uses 5 threads.
-
anon
(bool
, default:False
) –If true, we will treat cloud bucket as public one
-
client_config
(Optional[dict]
, default:None
) –Optional configuration for the destination storage client
Example
Cross cloud transfer
Source code in datachain/lib/dc/datachain.py
union
Return the set union of the two datasets.
Parameters:
-
other
(Self
) –chain whose rows will be added to
self
.
DataChainError
Session
Session(
name="",
catalog: Optional[Catalog] = None,
client_config: Optional[dict] = None,
in_memory: bool = False,
)
Session is a context that keeps track of temporary DataChain datasets for a proper cleanup. By default, a global session is created.
Temporary or ephemeral datasets are the ones created without specified name. They are useful for optimization purposes and should be automatically removed.
Temp dataset has specific name format
"session_
The
Temp dataset examples
session_myname_624b41_48e8b4 session_4b962d_2a5dff
Parameters:
name (str): The name of the session. Only latters and numbers are supported. It can be empty. catalog (Catalog): Catalog object.
Source code in datachain/query/session.py
get
classmethod
get(
session: Optional[Session] = None,
catalog: Optional[Catalog] = None,
client_config: Optional[dict] = None,
in_memory: bool = False,
) -> Session
Creates a Session() object from a catalog.
Parameters:
-
session
(Session
, default:None
) –Optional Session(). If not provided a new session will be created. It's needed mostly for simple API purposes.
-
catalog
(Catalog
, default:None
) –Optional catalog. By default, a new catalog is created.