audformat 1.3.4__tar.gz → 1.4.0__tar.gz
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.
- {audformat-1.3.4 → audformat-1.4.0}/CHANGELOG.rst +28 -0
- {audformat-1.3.4 → audformat-1.4.0}/PKG-INFO +1 -1
- {audformat-1.3.4 → audformat-1.4.0}/audformat/core/database.py +7 -4
- {audformat-1.3.4 → audformat-1.4.0}/audformat/core/scheme.py +120 -7
- {audformat-1.3.4 → audformat-1.4.0}/audformat/core/table.py +91 -21
- {audformat-1.3.4 → audformat-1.4.0}/audformat/core/utils.py +125 -71
- {audformat-1.3.4 → audformat-1.4.0}/audformat.egg-info/PKG-INFO +1 -1
- {audformat-1.3.4 → audformat-1.4.0}/audformat.egg-info/SOURCES.txt +1 -0
- audformat-1.4.0/benchmarks/benchmark_hash.py +118 -0
- {audformat-1.3.4 → audformat-1.4.0}/tests/test_database.py +261 -0
- {audformat-1.3.4 → audformat-1.4.0}/tests/test_scheme.py +138 -0
- {audformat-1.3.4 → audformat-1.4.0}/tests/test_table.py +136 -23
- {audformat-1.3.4 → audformat-1.4.0}/tests/test_utils.py +193 -28
- {audformat-1.3.4 → audformat-1.4.0}/.github/workflows/doc.yml +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/.github/workflows/linter.yml +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/.github/workflows/publish.yml +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/.github/workflows/test.yml +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/.gitignore +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/.pre-commit-config.yaml +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/CONTRIBUTING.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/LICENSE +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/README.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/audformat/__init__.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/audformat/core/__init__.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/audformat/core/attachment.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/audformat/core/column.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/audformat/core/common.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/audformat/core/conftest.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/audformat/core/define.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/audformat/core/errors.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/audformat/core/index.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/audformat/core/media.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/audformat/core/rater.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/audformat/core/split.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/audformat/core/testing.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/audformat/core/typing.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/audformat/define/__init__.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/audformat/errors/__init__.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/audformat/testing/__init__.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/audformat/utils/__init__.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/audformat.egg-info/dependency_links.txt +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/audformat.egg-info/requires.txt +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/audformat.egg-info/top_level.txt +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/benchmarks/benchmark_union.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/accessing-data.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/api/audformat.define.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/api/audformat.errors.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/api/audformat.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/api/audformat.testing.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/api/audformat.utils.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/api-src/audformat.define.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/api-src/audformat.errors.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/api-src/audformat.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/api-src/audformat.testing.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/api-src/audformat.utils.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/changelog.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/combine-tables.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/conf.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/conftest.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/contributing.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/create-database.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/data-conventions.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/data-example.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/data-format.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/data-header.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/data-introduction.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/data-misc-tables.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/data-tables.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/emodb-example.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/genindex.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/index.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/install.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/map-scheme.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/pics/audformat-database.dot +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/pics/audformat-misc-table.dot +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/pics/audformat-table.dot +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/docs/update-database.rst +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/pyproject.toml +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/setup.cfg +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/tests/conftest.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/tests/test_attachment.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/tests/test_column.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/tests/test_common.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/tests/test_database_get.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/tests/test_eq.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/tests/test_errors.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/tests/test_index.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/tests/test_misc_table.py +0 -0
- {audformat-1.3.4 → audformat-1.4.0}/tests/test_utils_concat.py +0 -0
|
@@ -7,6 +7,34 @@ The format is based on `Keep a Changelog`_,
|
|
|
7
7
|
and this project adheres to `Semantic Versioning`_.
|
|
8
8
|
|
|
9
9
|
|
|
10
|
+
Version 1.4.0 (2026-04-08)
|
|
11
|
+
--------------------------
|
|
12
|
+
|
|
13
|
+
* Added: ``audformat.Scheme.set_labels()``
|
|
14
|
+
to add labels to an existing scheme
|
|
15
|
+
that has none.
|
|
16
|
+
To replace labels
|
|
17
|
+
use ``audformat.Scheme.replace_labels()``
|
|
18
|
+
* Added: store ``audformat`` version in table files.
|
|
19
|
+
For parquet files it is stored under the ``audformat-version`` metadata key.
|
|
20
|
+
Pickle files store now a dictionary with the keys
|
|
21
|
+
``audformat-version`` and ``df``,
|
|
22
|
+
whereas ``df`` contains the table data
|
|
23
|
+
* Fixed: ``audformat.utils.hash()`` for large dataframes.
|
|
24
|
+
Before it resulted in the same hash
|
|
25
|
+
for large dataframes
|
|
26
|
+
that differed only in rows in their center.
|
|
27
|
+
This is a breaking change
|
|
28
|
+
and will result in different hash values.
|
|
29
|
+
When using ``audb.publish()``
|
|
30
|
+
to update a database
|
|
31
|
+
not published with ``audformat>=1.4.0``,
|
|
32
|
+
it will result in republishing all existing tables,
|
|
33
|
+
which is the desired behavior
|
|
34
|
+
* Fixed: loading scheme labels from misc table,
|
|
35
|
+
when using ``audformat.Database.load(..., load_data=True)``
|
|
36
|
+
|
|
37
|
+
|
|
10
38
|
Version 1.3.4 (2026-02-18)
|
|
11
39
|
--------------------------
|
|
12
40
|
|
|
@@ -1444,14 +1444,17 @@ class Database(HeaderBase):
|
|
|
1444
1444
|
params = []
|
|
1445
1445
|
table_ids = []
|
|
1446
1446
|
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1447
|
+
# Load misc_tables first,
|
|
1448
|
+
# as they might be used as scheme labels
|
|
1449
|
+
# by regular tables
|
|
1451
1450
|
if "misc_tables" in header and header["misc_tables"]:
|
|
1452
1451
|
for table_id in header["misc_tables"]:
|
|
1453
1452
|
table_ids.append(table_id)
|
|
1454
1453
|
|
|
1454
|
+
if "tables" in header and header["tables"]:
|
|
1455
|
+
for table_id in header["tables"]:
|
|
1456
|
+
table_ids.append(table_id)
|
|
1457
|
+
|
|
1455
1458
|
for table_id in table_ids:
|
|
1456
1459
|
table = db[table_id]
|
|
1457
1460
|
if load_data:
|
|
@@ -363,20 +363,133 @@ class Scheme(common.HeaderBase):
|
|
|
363
363
|
)
|
|
364
364
|
|
|
365
365
|
self.labels = labels
|
|
366
|
+
self._update_column_categories(labels)
|
|
367
|
+
|
|
368
|
+
def set_labels(
|
|
369
|
+
self,
|
|
370
|
+
labels: dict | list | str,
|
|
371
|
+
):
|
|
372
|
+
r"""Set labels on a scheme that has none.
|
|
373
|
+
|
|
374
|
+
If scheme is part of a :class:`audformat.Database`
|
|
375
|
+
the dtype of all :class:`audformat.Column` objects
|
|
376
|
+
that reference the scheme will be converted
|
|
377
|
+
to :class:`pandas.CategoricalDtype`.
|
|
378
|
+
|
|
379
|
+
Args:
|
|
380
|
+
labels: new labels
|
|
381
|
+
|
|
382
|
+
Raises:
|
|
383
|
+
ValueError: if scheme already defines labels
|
|
384
|
+
ValueError: if dtype of labels does not match dtype of scheme
|
|
385
|
+
ValueError: if ``labels`` is not a list, dictionary,
|
|
386
|
+
or ID of a misc table
|
|
387
|
+
ValueError: if ``labels`` is a misc table ID
|
|
388
|
+
and the scheme is already assigned to a database,
|
|
389
|
+
but the corresponding misc table is not part of the database,
|
|
390
|
+
or the given table ID is not a misc table,
|
|
391
|
+
or its index is multi-dimensional,
|
|
392
|
+
or its index contains duplicates,
|
|
393
|
+
or the misc table has a column
|
|
394
|
+
that is already assigned to a scheme
|
|
395
|
+
with labels from another misc table
|
|
396
|
+
ValueError: if existing column data contains values
|
|
397
|
+
not covered by ``labels``
|
|
398
|
+
|
|
399
|
+
Examples:
|
|
400
|
+
>>> emotion = Scheme("str")
|
|
401
|
+
>>> emotion
|
|
402
|
+
{dtype: str}
|
|
403
|
+
>>> emotion.set_labels(["happy", "sad", "angry"])
|
|
404
|
+
>>> emotion
|
|
405
|
+
dtype: str
|
|
406
|
+
labels: [happy, sad, angry]
|
|
407
|
+
>>> emotion = Scheme("int")
|
|
408
|
+
>>> emotion.set_labels(
|
|
409
|
+
... {
|
|
410
|
+
... 0: {"emotion": "happy"},
|
|
411
|
+
... 1: {"emotion": "sad"},
|
|
412
|
+
... }
|
|
413
|
+
... )
|
|
414
|
+
>>> emotion
|
|
415
|
+
dtype: int
|
|
416
|
+
labels:
|
|
417
|
+
0: {emotion: happy}
|
|
418
|
+
1: {emotion: sad}
|
|
419
|
+
|
|
420
|
+
"""
|
|
421
|
+
if self.labels is not None:
|
|
422
|
+
raise ValueError(
|
|
423
|
+
"Cannot set labels when scheme already defines labels. "
|
|
424
|
+
"Use replace_labels() instead."
|
|
425
|
+
)
|
|
426
|
+
self._check_labels(labels)
|
|
427
|
+
|
|
428
|
+
if not isinstance(labels, str) or self._db is not None:
|
|
429
|
+
# Check change of data type
|
|
430
|
+
# for list, dict and assigned misc table
|
|
431
|
+
dtype_labels = self._dtype_from_labels(labels)
|
|
432
|
+
if dtype_labels != self.dtype:
|
|
433
|
+
raise ValueError(
|
|
434
|
+
"Data type of labels "
|
|
435
|
+
f"'{dtype_labels}' "
|
|
436
|
+
f"does not match data type of scheme "
|
|
437
|
+
f"'{self.dtype}'."
|
|
438
|
+
)
|
|
366
439
|
|
|
367
440
|
if self._db is not None and self._id is not None:
|
|
368
|
-
|
|
441
|
+
# Check existing data match new labels
|
|
442
|
+
labels_set = set(self._labels_to_list(labels))
|
|
369
443
|
for table in list(self._db.tables.values()) + list(
|
|
370
444
|
self._db.misc_tables.values()
|
|
371
445
|
):
|
|
372
446
|
for column in table.columns.values():
|
|
373
447
|
if column.scheme_id == self._id:
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
448
|
+
values = set(table.df[column._id].dropna().unique())
|
|
449
|
+
bad_values = values - labels_set
|
|
450
|
+
if bad_values:
|
|
451
|
+
raise ValueError(
|
|
452
|
+
f"Column '{column._id}' "
|
|
453
|
+
f"of table '{table._id}' "
|
|
454
|
+
f"contains values not in labels: "
|
|
455
|
+
f"{sorted(bad_values)}."
|
|
456
|
+
)
|
|
457
|
+
|
|
458
|
+
self.labels = labels
|
|
459
|
+
self._update_column_categories(labels, convert_to_categorical=True)
|
|
460
|
+
|
|
461
|
+
def _update_column_categories(
|
|
462
|
+
self,
|
|
463
|
+
labels: dict | list | str,
|
|
464
|
+
*,
|
|
465
|
+
convert_to_categorical: bool = False,
|
|
466
|
+
):
|
|
467
|
+
r"""Update categories of columns referencing this scheme.
|
|
468
|
+
|
|
469
|
+
Args:
|
|
470
|
+
labels: new labels
|
|
471
|
+
convert_to_categorical: if ``True``,
|
|
472
|
+
convert columns from plain dtype
|
|
473
|
+
to categorical first
|
|
474
|
+
|
|
475
|
+
"""
|
|
476
|
+
if self._db is None or self._id is None:
|
|
477
|
+
return
|
|
478
|
+
|
|
479
|
+
labels_list = self._labels_to_list(labels)
|
|
480
|
+
for table in list(self._db.tables.values()) + list(
|
|
481
|
+
self._db.misc_tables.values()
|
|
482
|
+
):
|
|
483
|
+
for column in table.columns.values():
|
|
484
|
+
if column.scheme_id == self._id:
|
|
485
|
+
y = column._table.df[column._id]
|
|
486
|
+
if convert_to_categorical:
|
|
487
|
+
y = y.astype(self.to_pandas_dtype())
|
|
488
|
+
y = y.cat.set_categories(
|
|
489
|
+
new_categories=labels_list,
|
|
490
|
+
ordered=False,
|
|
491
|
+
)
|
|
492
|
+
column._table.df[column._id] = y
|
|
380
493
|
|
|
381
494
|
def _check_labels(
|
|
382
495
|
self,
|
|
@@ -26,11 +26,18 @@ from audformat.core.index import filewise_index
|
|
|
26
26
|
from audformat.core.index import index_type
|
|
27
27
|
from audformat.core.index import is_filewise_index
|
|
28
28
|
from audformat.core.index import is_segmented_index
|
|
29
|
+
from audformat.core.index import to_timedelta
|
|
29
30
|
from audformat.core.media import Media
|
|
30
31
|
from audformat.core.split import Split
|
|
31
32
|
from audformat.core.typing import Values
|
|
32
33
|
|
|
33
34
|
|
|
35
|
+
# Keys used in parquet metadata and pickle wrapper dict
|
|
36
|
+
_KEY_VERSION = "audformat-version"
|
|
37
|
+
_KEY_DATAFRAME = "df"
|
|
38
|
+
_KEY_HASH = "hash"
|
|
39
|
+
|
|
40
|
+
|
|
34
41
|
class Base(HeaderBase):
|
|
35
42
|
r"""Table base class."""
|
|
36
43
|
|
|
@@ -923,9 +930,9 @@ class Base(HeaderBase):
|
|
|
923
930
|
dtypes_wo_converters = {}
|
|
924
931
|
for column, dtype in columns_and_dtypes.items():
|
|
925
932
|
if dtype == define.DataType.DATE:
|
|
926
|
-
converters[column] =
|
|
933
|
+
converters[column] = pd.to_datetime
|
|
927
934
|
elif dtype == define.DataType.TIME:
|
|
928
|
-
converters[column] =
|
|
935
|
+
converters[column] = to_timedelta
|
|
929
936
|
else:
|
|
930
937
|
dtypes_wo_converters[column] = to_pandas_dtype(dtype)
|
|
931
938
|
|
|
@@ -953,6 +960,13 @@ class Base(HeaderBase):
|
|
|
953
960
|
table = parquet.read_table(path)
|
|
954
961
|
df = self._pyarrow_table_to_dataframe(table)
|
|
955
962
|
|
|
963
|
+
# Read audformat version from metadata.
|
|
964
|
+
# Files written before 1.4.0 don't have this key.
|
|
965
|
+
metadata = table.schema.metadata or {}
|
|
966
|
+
self._audformat_version = (
|
|
967
|
+
metadata.get(_KEY_VERSION.encode(), b"").decode() or None
|
|
968
|
+
)
|
|
969
|
+
|
|
956
970
|
self._df = df
|
|
957
971
|
|
|
958
972
|
def _load_pickled(self, path: str):
|
|
@@ -969,22 +983,47 @@ class Base(HeaderBase):
|
|
|
969
983
|
# but was slower.
|
|
970
984
|
# The try-except statement allows backward compatibility
|
|
971
985
|
try:
|
|
972
|
-
|
|
986
|
+
data = pd.read_pickle(path)
|
|
973
987
|
except pickle.UnpicklingError:
|
|
974
|
-
|
|
988
|
+
data = pd.read_pickle(path, compression="xz")
|
|
989
|
+
|
|
990
|
+
# Since 1.4.0, pickle files store a dict
|
|
991
|
+
# with audformat version and dataframe.
|
|
992
|
+
# Older files store a bare dataframe.
|
|
993
|
+
if isinstance(data, dict) and _KEY_DATAFRAME in data:
|
|
994
|
+
version = data.get(_KEY_VERSION)
|
|
995
|
+
df = data[_KEY_DATAFRAME]
|
|
996
|
+
else:
|
|
997
|
+
version = None
|
|
998
|
+
df = data if isinstance(data, pd.DataFrame) else None
|
|
999
|
+
|
|
1000
|
+
if df is None:
|
|
1001
|
+
raise RuntimeError(
|
|
1002
|
+
f"Cannot load pickle file '{path}', "
|
|
1003
|
+
"expected a pandas DataFrame "
|
|
1004
|
+
"or a dictionary with an "
|
|
1005
|
+
f"'{_KEY_DATAFRAME}' entry."
|
|
1006
|
+
)
|
|
1007
|
+
|
|
1008
|
+
self._audformat_version = version
|
|
975
1009
|
|
|
976
1010
|
# Older versions of audformat stored columns
|
|
977
1011
|
# assigned to a string scheme as 'object',
|
|
978
|
-
# so we need to convert those to 'string'
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
1012
|
+
# so we need to convert those to 'string'.
|
|
1013
|
+
# This was fixed in 1.4.0.
|
|
1014
|
+
if _needs_legacy_fixup(version, "1.4.0"):
|
|
1015
|
+
for column_id, column in self.columns.items():
|
|
1016
|
+
if (
|
|
1017
|
+
column.scheme_id is not None
|
|
1018
|
+
and (
|
|
1019
|
+
self.db.schemes[column.scheme_id].dtype
|
|
1020
|
+
== define.DataType.STRING
|
|
1021
|
+
)
|
|
1022
|
+
and df[column_id].dtype == "object"
|
|
1023
|
+
):
|
|
1024
|
+
df[column_id] = df[column_id].astype("string")
|
|
1025
|
+
# Fix index entries as well
|
|
1026
|
+
df.index = _maybe_convert_dtype_to_string(df.index)
|
|
988
1027
|
|
|
989
1028
|
self._df = df
|
|
990
1029
|
|
|
@@ -1072,8 +1111,7 @@ class Base(HeaderBase):
|
|
|
1072
1111
|
for column in time_columns:
|
|
1073
1112
|
df[column] = df[column].astype("timedelta64[ns]")
|
|
1074
1113
|
for column in object_columns:
|
|
1075
|
-
df[column] = df[column].astype("object")
|
|
1076
|
-
df[column] = df[column].replace(pd.NA, None)
|
|
1114
|
+
df[column] = df[column].astype("object").replace(pd.NA, None)
|
|
1077
1115
|
for column in labeled_columns:
|
|
1078
1116
|
scheme = self.db.schemes[self.columns[column].scheme_id]
|
|
1079
1117
|
labels = scheme._labels_to_list()
|
|
@@ -1190,20 +1228,29 @@ class Base(HeaderBase):
|
|
|
1190
1228
|
path: path, including file extension
|
|
1191
1229
|
|
|
1192
1230
|
"""
|
|
1193
|
-
table = pa.Table.from_pandas(self.df.reset_index(), preserve_index=False)
|
|
1194
|
-
|
|
1195
1231
|
# Create hash of table
|
|
1196
1232
|
table_hash = utils.hash(self.df, strict=True)
|
|
1197
1233
|
|
|
1198
|
-
|
|
1234
|
+
table = pa.Table.from_pandas(self.df.reset_index(), preserve_index=False)
|
|
1235
|
+
|
|
1236
|
+
# Store hash in metadata of file,
|
|
1199
1237
|
# see https://stackoverflow.com/a/58978449
|
|
1200
|
-
|
|
1238
|
+
import audformat
|
|
1239
|
+
|
|
1240
|
+
metadata = {_KEY_HASH: table_hash, _KEY_VERSION: audformat.__version__}
|
|
1201
1241
|
table = table.replace_schema_metadata({**metadata, **table.schema.metadata})
|
|
1202
1242
|
|
|
1203
1243
|
parquet.write_table(table, path, compression="snappy")
|
|
1204
1244
|
|
|
1205
1245
|
def _save_pickled(self, path: str):
|
|
1206
|
-
|
|
1246
|
+
import audformat
|
|
1247
|
+
|
|
1248
|
+
data = {
|
|
1249
|
+
_KEY_VERSION: audformat.__version__,
|
|
1250
|
+
_KEY_DATAFRAME: self.df,
|
|
1251
|
+
}
|
|
1252
|
+
pd.to_pickle(
|
|
1253
|
+
data,
|
|
1207
1254
|
path,
|
|
1208
1255
|
protocol=4, # supported by Python >= 3.4
|
|
1209
1256
|
)
|
|
@@ -1846,6 +1893,29 @@ class Table(Base):
|
|
|
1846
1893
|
return levels_and_dtypes
|
|
1847
1894
|
|
|
1848
1895
|
|
|
1896
|
+
def _needs_legacy_fixup(version: str | None, fixed_in: str) -> bool:
|
|
1897
|
+
r"""Return if a file needs a legacy fixup.
|
|
1898
|
+
|
|
1899
|
+
Returns ``True`` if ``version`` is ``None``
|
|
1900
|
+
(file written before version tracking was added)
|
|
1901
|
+
or if ``version`` is older than ``fixed_in``.
|
|
1902
|
+
|
|
1903
|
+
Args:
|
|
1904
|
+
version: audformat version that wrote the file,
|
|
1905
|
+
or ``None`` for unknown
|
|
1906
|
+
fixed_in: version in which the fixup was applied
|
|
1907
|
+
|
|
1908
|
+
Returns:
|
|
1909
|
+
``True`` if the legacy fixup should be run
|
|
1910
|
+
|
|
1911
|
+
"""
|
|
1912
|
+
if version is None:
|
|
1913
|
+
return True
|
|
1914
|
+
from packaging.version import Version
|
|
1915
|
+
|
|
1916
|
+
return Version(version) < Version(fixed_in)
|
|
1917
|
+
|
|
1918
|
+
|
|
1849
1919
|
def _assert_table_index(
|
|
1850
1920
|
table: Base,
|
|
1851
1921
|
index: pd.Index,
|
|
@@ -15,7 +15,6 @@ from iso639.exceptions import InvalidLanguageValue
|
|
|
15
15
|
import iso3166
|
|
16
16
|
import numpy as np
|
|
17
17
|
import pandas as pd
|
|
18
|
-
import pyarrow as pa
|
|
19
18
|
|
|
20
19
|
import audeer
|
|
21
20
|
import audiofile
|
|
@@ -38,6 +37,12 @@ if platform.system() in ["Windows"]: # pragma: no cover
|
|
|
38
37
|
"to_filewise_index",
|
|
39
38
|
]
|
|
40
39
|
|
|
40
|
+
# Separator used when hashing object arrays in hash().
|
|
41
|
+
# Null byte is used as it's unlikely to appear in typical data
|
|
42
|
+
# (file paths, labels). Note: if data contains \x00, collisions
|
|
43
|
+
# are theoretically possible - see tests for details.
|
|
44
|
+
_OBJECT_ARRAY_SEPARATOR = "\x00"
|
|
45
|
+
|
|
41
46
|
|
|
42
47
|
def concat(
|
|
43
48
|
objs: Sequence[pd.Series | pd.DataFrame],
|
|
@@ -673,6 +678,74 @@ def expand_file_path(
|
|
|
673
678
|
return index
|
|
674
679
|
|
|
675
680
|
|
|
681
|
+
def _normalize_dtype_name(dtype) -> str:
|
|
682
|
+
r"""Normalize a pandas dtype to a canonical string for hashing.
|
|
683
|
+
|
|
684
|
+
Maps different representations of the same logical type
|
|
685
|
+
to a single string, e.g. both ``"string"`` and ``"object"``
|
|
686
|
+
dtypes map to ``"string"``.
|
|
687
|
+
|
|
688
|
+
Preserves precision for numeric types
|
|
689
|
+
(e.g. ``int32`` and ``int64`` produce different strings).
|
|
690
|
+
|
|
691
|
+
"""
|
|
692
|
+
if isinstance(dtype, pd.CategoricalDtype):
|
|
693
|
+
# Include category dtype to distinguish e.g.
|
|
694
|
+
# categorical-with-strings from categorical-with-ints
|
|
695
|
+
if dtype.categories is not None:
|
|
696
|
+
cat_dtype = _normalize_dtype_name(dtype.categories.dtype)
|
|
697
|
+
else:
|
|
698
|
+
cat_dtype = "empty"
|
|
699
|
+
return f"categorical[{cat_dtype}]"
|
|
700
|
+
if pd.api.types.is_string_dtype(dtype):
|
|
701
|
+
# Normalize string/object/StringDtype
|
|
702
|
+
return "string"
|
|
703
|
+
if pd.api.types.is_bool_dtype(dtype):
|
|
704
|
+
# Normalize bool/BooleanDtype
|
|
705
|
+
return "bool"
|
|
706
|
+
# Standard numpy dtypes: preserve precise type name
|
|
707
|
+
# (int32, int64, float32, float64, timedelta64[ns], datetime64[ns], etc.)
|
|
708
|
+
try:
|
|
709
|
+
return np.dtype(dtype).name
|
|
710
|
+
except TypeError:
|
|
711
|
+
pass
|
|
712
|
+
# Nullable extension dtypes (Int8, Int64, Float32, Float64, etc.)
|
|
713
|
+
if hasattr(dtype, "numpy_dtype"):
|
|
714
|
+
return dtype.numpy_dtype.name
|
|
715
|
+
|
|
716
|
+
|
|
717
|
+
def _hash_update_array(
|
|
718
|
+
md5,
|
|
719
|
+
arr_like: pd.Index | pd.Series,
|
|
720
|
+
):
|
|
721
|
+
r"""Update md5 hash with array data.
|
|
722
|
+
|
|
723
|
+
Handles numeric arrays via ``tobytes()``
|
|
724
|
+
and object arrays via explicit string encoding.
|
|
725
|
+
|
|
726
|
+
"""
|
|
727
|
+
if pd.api.types.is_integer_dtype(arr_like.dtype) and hasattr(
|
|
728
|
+
arr_like.dtype, "numpy_dtype"
|
|
729
|
+
):
|
|
730
|
+
# Nullable integer extension types (Int8, ..., Int64, UInt8, ..., UInt64)
|
|
731
|
+
# need conversion to float for consistent numpy array representation
|
|
732
|
+
# (since pandas 2.2.x, nullable integers with <NA> convert to float anyway,
|
|
733
|
+
# but older versions may produce object arrays)
|
|
734
|
+
arr = arr_like.astype("float").to_numpy()
|
|
735
|
+
else:
|
|
736
|
+
arr = np.asarray(arr_like)
|
|
737
|
+
if arr.dtype == object:
|
|
738
|
+
# Object arrays (strings, etc.) need explicit encoding
|
|
739
|
+
md5.update(_OBJECT_ARRAY_SEPARATOR.join(str(x) for x in arr).encode("utf-8"))
|
|
740
|
+
else:
|
|
741
|
+
# Use platform-independent byte representation:
|
|
742
|
+
# convert to big-endian before hashing to ensure
|
|
743
|
+
# consistent hashes across different architectures
|
|
744
|
+
if arr.dtype.byteorder in ("=", "<"):
|
|
745
|
+
arr = arr.astype(arr.dtype.newbyteorder(">"), copy=False)
|
|
746
|
+
md5.update(arr.tobytes())
|
|
747
|
+
|
|
748
|
+
|
|
676
749
|
def hash(
|
|
677
750
|
obj: pd.Index | pd.Series | pd.DataFrame,
|
|
678
751
|
strict: bool = False,
|
|
@@ -692,6 +765,11 @@ def hash(
|
|
|
692
765
|
and ``strict`` is ``False``,
|
|
693
766
|
the returned hash value changes with ``pandas>=2.2.0``.
|
|
694
767
|
|
|
768
|
+
.. warning::
|
|
769
|
+
|
|
770
|
+
The returned hash with ``strict`` is ``True``
|
|
771
|
+
has changed in ``audformat>=1.4.0``.
|
|
772
|
+
|
|
695
773
|
Args:
|
|
696
774
|
obj: object
|
|
697
775
|
strict: if ``True``,
|
|
@@ -713,84 +791,60 @@ def hash(
|
|
|
713
791
|
>>> hash(y)
|
|
714
792
|
'5251663970176285425'
|
|
715
793
|
>>> hash(index, strict=True)
|
|
716
|
-
'
|
|
794
|
+
'fb9a35ca0492404e5f9dba30eebb3bfb'
|
|
717
795
|
>>> hash(index[::-1], strict=True) # reversed index
|
|
718
|
-
'
|
|
796
|
+
'b59b53388eb3ecf5a04ddd0edb89152a'
|
|
719
797
|
|
|
720
798
|
"""
|
|
721
799
|
if strict:
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
800
|
+
# Collect column/index names and normalized dtypes.
|
|
801
|
+
dtypes = []
|
|
802
|
+
|
|
803
|
+
# Collect index levels
|
|
804
|
+
if isinstance(obj, (pd.DataFrame, pd.Series)):
|
|
805
|
+
index = obj.index
|
|
726
806
|
else:
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
# (pandas 3.0 uses "string" dtype which maps to pyarrow "large_string",
|
|
735
|
-
# while "object" dtype maps to pyarrow "string")
|
|
736
|
-
# For empty DataFrames, we also need to specify an explicit schema
|
|
737
|
-
# because pyarrow infers "null" type for empty object columns
|
|
738
|
-
schema_fields = []
|
|
739
|
-
for col in df.columns:
|
|
740
|
-
if pd.api.types.is_string_dtype(df[col].dtype):
|
|
741
|
-
df[col] = df[col].astype("object")
|
|
742
|
-
schema_fields.append((col, pa.string()))
|
|
743
|
-
elif isinstance(df[col].dtype, pd.CategoricalDtype):
|
|
744
|
-
# Normalize categorical with string categories to object
|
|
745
|
-
cat_dtype = df[col].dtype.categories.dtype
|
|
746
|
-
if pd.api.types.is_string_dtype(cat_dtype):
|
|
747
|
-
new_categories = df[col].dtype.categories.astype("object")
|
|
748
|
-
ordered = df[col].dtype.ordered
|
|
749
|
-
df[col] = df[col].astype(
|
|
750
|
-
pd.CategoricalDtype(new_categories, ordered=ordered)
|
|
751
|
-
)
|
|
752
|
-
schema_fields.append((col, None))
|
|
753
|
-
else:
|
|
754
|
-
# Let pyarrow infer
|
|
755
|
-
schema_fields.append((col, None))
|
|
756
|
-
# Build schema for columns that need explicit types
|
|
757
|
-
if len(df) == 0 and any(f[1] is not None for f in schema_fields):
|
|
758
|
-
# For empty DataFrames with index of type string/object,
|
|
759
|
-
# specify schema explicitly
|
|
760
|
-
schema = pa.schema(
|
|
761
|
-
[
|
|
762
|
-
(
|
|
763
|
-
name,
|
|
764
|
-
typ if typ is not None else pa.from_numpy_dtype(df[name].dtype),
|
|
765
|
-
)
|
|
766
|
-
for name, typ in schema_fields
|
|
767
|
-
]
|
|
768
|
-
)
|
|
769
|
-
table = pa.Table.from_pandas(df, preserve_index=False, schema=schema)
|
|
807
|
+
index = obj
|
|
808
|
+
|
|
809
|
+
if isinstance(index, pd.MultiIndex):
|
|
810
|
+
for i in range(index.nlevels):
|
|
811
|
+
name = str(index.names[i]) if index.names[i] is not None else str(i)
|
|
812
|
+
dtype = index.get_level_values(i).dtype
|
|
813
|
+
dtypes.append(f"{name}: {_normalize_dtype_name(dtype)}")
|
|
770
814
|
else:
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
815
|
+
name = str(index.name) if index.name is not None else "0"
|
|
816
|
+
dtypes.append(f"{name}: {_normalize_dtype_name(index.dtype)}")
|
|
817
|
+
|
|
818
|
+
# Collect column/value dtypes
|
|
819
|
+
if isinstance(obj, pd.DataFrame):
|
|
820
|
+
for col in obj.columns:
|
|
821
|
+
dtypes.append(f"{str(col)}: {_normalize_dtype_name(obj[col].dtype)}")
|
|
822
|
+
elif isinstance(obj, pd.Series):
|
|
823
|
+
name = str(obj.name) if obj.name is not None else "0"
|
|
824
|
+
dtypes.append(f"{name}: {_normalize_dtype_name(obj.dtype)}")
|
|
825
|
+
|
|
826
|
+
dtypes_str = "\n".join(dtypes)
|
|
827
|
+
dtypes_md5 = hashlib.md5(dtypes_str.encode())
|
|
828
|
+
|
|
829
|
+
# Hash data: index levels, then values
|
|
782
830
|
data_md5 = hashlib.md5()
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
831
|
+
|
|
832
|
+
# Hash index levels
|
|
833
|
+
if isinstance(index, pd.MultiIndex):
|
|
834
|
+
for i in range(index.nlevels):
|
|
835
|
+
_hash_update_array(data_md5, index.get_level_values(i))
|
|
836
|
+
else:
|
|
837
|
+
_hash_update_array(data_md5, index)
|
|
838
|
+
|
|
839
|
+
# Hash values
|
|
840
|
+
if isinstance(obj, pd.DataFrame):
|
|
841
|
+
for _, y in obj.items():
|
|
842
|
+
_hash_update_array(data_md5, y)
|
|
843
|
+
elif isinstance(obj, pd.Series):
|
|
844
|
+
_hash_update_array(data_md5, obj)
|
|
845
|
+
|
|
792
846
|
md5 = hashlib.md5()
|
|
793
|
-
md5.update(
|
|
847
|
+
md5.update(dtypes_md5.digest())
|
|
794
848
|
md5.update(data_md5.digest())
|
|
795
849
|
md5 = md5.hexdigest()
|
|
796
850
|
else:
|