audformat 1.3.3__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.
Files changed (89) hide show
  1. {audformat-1.3.3 → audformat-1.4.0}/CHANGELOG.rst +34 -0
  2. {audformat-1.3.3 → audformat-1.4.0}/PKG-INFO +1 -1
  3. {audformat-1.3.3 → audformat-1.4.0}/audformat/core/common.py +15 -0
  4. {audformat-1.3.3 → audformat-1.4.0}/audformat/core/database.py +25 -11
  5. {audformat-1.3.3 → audformat-1.4.0}/audformat/core/index.py +8 -4
  6. {audformat-1.3.3 → audformat-1.4.0}/audformat/core/scheme.py +122 -16
  7. {audformat-1.3.3 → audformat-1.4.0}/audformat/core/table.py +99 -32
  8. {audformat-1.3.3 → audformat-1.4.0}/audformat/core/testing.py +3 -2
  9. {audformat-1.3.3 → audformat-1.4.0}/audformat/core/utils.py +144 -41
  10. {audformat-1.3.3 → audformat-1.4.0}/audformat.egg-info/PKG-INFO +1 -1
  11. {audformat-1.3.3 → audformat-1.4.0}/audformat.egg-info/SOURCES.txt +1 -0
  12. audformat-1.4.0/benchmarks/benchmark_hash.py +118 -0
  13. {audformat-1.3.3 → audformat-1.4.0}/docs/data-misc-tables.rst +1 -0
  14. {audformat-1.3.3 → audformat-1.4.0}/tests/test_column.py +3 -3
  15. {audformat-1.3.3 → audformat-1.4.0}/tests/test_database.py +261 -0
  16. {audformat-1.3.3 → audformat-1.4.0}/tests/test_database_get.py +57 -4
  17. {audformat-1.3.3 → audformat-1.4.0}/tests/test_index.py +58 -4
  18. {audformat-1.3.3 → audformat-1.4.0}/tests/test_misc_table.py +52 -61
  19. {audformat-1.3.3 → audformat-1.4.0}/tests/test_scheme.py +227 -3
  20. {audformat-1.3.3 → audformat-1.4.0}/tests/test_table.py +139 -25
  21. {audformat-1.3.3 → audformat-1.4.0}/tests/test_utils.py +752 -38
  22. {audformat-1.3.3 → audformat-1.4.0}/tests/test_utils_concat.py +5 -2
  23. {audformat-1.3.3 → audformat-1.4.0}/.github/workflows/doc.yml +0 -0
  24. {audformat-1.3.3 → audformat-1.4.0}/.github/workflows/linter.yml +0 -0
  25. {audformat-1.3.3 → audformat-1.4.0}/.github/workflows/publish.yml +0 -0
  26. {audformat-1.3.3 → audformat-1.4.0}/.github/workflows/test.yml +0 -0
  27. {audformat-1.3.3 → audformat-1.4.0}/.gitignore +0 -0
  28. {audformat-1.3.3 → audformat-1.4.0}/.pre-commit-config.yaml +0 -0
  29. {audformat-1.3.3 → audformat-1.4.0}/CONTRIBUTING.rst +0 -0
  30. {audformat-1.3.3 → audformat-1.4.0}/LICENSE +0 -0
  31. {audformat-1.3.3 → audformat-1.4.0}/README.rst +0 -0
  32. {audformat-1.3.3 → audformat-1.4.0}/audformat/__init__.py +0 -0
  33. {audformat-1.3.3 → audformat-1.4.0}/audformat/core/__init__.py +0 -0
  34. {audformat-1.3.3 → audformat-1.4.0}/audformat/core/attachment.py +0 -0
  35. {audformat-1.3.3 → audformat-1.4.0}/audformat/core/column.py +0 -0
  36. {audformat-1.3.3 → audformat-1.4.0}/audformat/core/conftest.py +0 -0
  37. {audformat-1.3.3 → audformat-1.4.0}/audformat/core/define.py +0 -0
  38. {audformat-1.3.3 → audformat-1.4.0}/audformat/core/errors.py +0 -0
  39. {audformat-1.3.3 → audformat-1.4.0}/audformat/core/media.py +0 -0
  40. {audformat-1.3.3 → audformat-1.4.0}/audformat/core/rater.py +0 -0
  41. {audformat-1.3.3 → audformat-1.4.0}/audformat/core/split.py +0 -0
  42. {audformat-1.3.3 → audformat-1.4.0}/audformat/core/typing.py +0 -0
  43. {audformat-1.3.3 → audformat-1.4.0}/audformat/define/__init__.py +0 -0
  44. {audformat-1.3.3 → audformat-1.4.0}/audformat/errors/__init__.py +0 -0
  45. {audformat-1.3.3 → audformat-1.4.0}/audformat/testing/__init__.py +0 -0
  46. {audformat-1.3.3 → audformat-1.4.0}/audformat/utils/__init__.py +0 -0
  47. {audformat-1.3.3 → audformat-1.4.0}/audformat.egg-info/dependency_links.txt +0 -0
  48. {audformat-1.3.3 → audformat-1.4.0}/audformat.egg-info/requires.txt +0 -0
  49. {audformat-1.3.3 → audformat-1.4.0}/audformat.egg-info/top_level.txt +0 -0
  50. {audformat-1.3.3 → audformat-1.4.0}/benchmarks/benchmark_union.py +0 -0
  51. {audformat-1.3.3 → audformat-1.4.0}/docs/accessing-data.rst +0 -0
  52. {audformat-1.3.3 → audformat-1.4.0}/docs/api/audformat.define.rst +0 -0
  53. {audformat-1.3.3 → audformat-1.4.0}/docs/api/audformat.errors.rst +0 -0
  54. {audformat-1.3.3 → audformat-1.4.0}/docs/api/audformat.rst +0 -0
  55. {audformat-1.3.3 → audformat-1.4.0}/docs/api/audformat.testing.rst +0 -0
  56. {audformat-1.3.3 → audformat-1.4.0}/docs/api/audformat.utils.rst +0 -0
  57. {audformat-1.3.3 → audformat-1.4.0}/docs/api-src/audformat.define.rst +0 -0
  58. {audformat-1.3.3 → audformat-1.4.0}/docs/api-src/audformat.errors.rst +0 -0
  59. {audformat-1.3.3 → audformat-1.4.0}/docs/api-src/audformat.rst +0 -0
  60. {audformat-1.3.3 → audformat-1.4.0}/docs/api-src/audformat.testing.rst +0 -0
  61. {audformat-1.3.3 → audformat-1.4.0}/docs/api-src/audformat.utils.rst +0 -0
  62. {audformat-1.3.3 → audformat-1.4.0}/docs/changelog.rst +0 -0
  63. {audformat-1.3.3 → audformat-1.4.0}/docs/combine-tables.rst +0 -0
  64. {audformat-1.3.3 → audformat-1.4.0}/docs/conf.py +0 -0
  65. {audformat-1.3.3 → audformat-1.4.0}/docs/conftest.py +0 -0
  66. {audformat-1.3.3 → audformat-1.4.0}/docs/contributing.rst +0 -0
  67. {audformat-1.3.3 → audformat-1.4.0}/docs/create-database.rst +0 -0
  68. {audformat-1.3.3 → audformat-1.4.0}/docs/data-conventions.rst +0 -0
  69. {audformat-1.3.3 → audformat-1.4.0}/docs/data-example.rst +0 -0
  70. {audformat-1.3.3 → audformat-1.4.0}/docs/data-format.rst +0 -0
  71. {audformat-1.3.3 → audformat-1.4.0}/docs/data-header.rst +0 -0
  72. {audformat-1.3.3 → audformat-1.4.0}/docs/data-introduction.rst +0 -0
  73. {audformat-1.3.3 → audformat-1.4.0}/docs/data-tables.rst +0 -0
  74. {audformat-1.3.3 → audformat-1.4.0}/docs/emodb-example.rst +0 -0
  75. {audformat-1.3.3 → audformat-1.4.0}/docs/genindex.rst +0 -0
  76. {audformat-1.3.3 → audformat-1.4.0}/docs/index.rst +0 -0
  77. {audformat-1.3.3 → audformat-1.4.0}/docs/install.rst +0 -0
  78. {audformat-1.3.3 → audformat-1.4.0}/docs/map-scheme.rst +0 -0
  79. {audformat-1.3.3 → audformat-1.4.0}/docs/pics/audformat-database.dot +0 -0
  80. {audformat-1.3.3 → audformat-1.4.0}/docs/pics/audformat-misc-table.dot +0 -0
  81. {audformat-1.3.3 → audformat-1.4.0}/docs/pics/audformat-table.dot +0 -0
  82. {audformat-1.3.3 → audformat-1.4.0}/docs/update-database.rst +0 -0
  83. {audformat-1.3.3 → audformat-1.4.0}/pyproject.toml +0 -0
  84. {audformat-1.3.3 → audformat-1.4.0}/setup.cfg +0 -0
  85. {audformat-1.3.3 → audformat-1.4.0}/tests/conftest.py +0 -0
  86. {audformat-1.3.3 → audformat-1.4.0}/tests/test_attachment.py +0 -0
  87. {audformat-1.3.3 → audformat-1.4.0}/tests/test_common.py +0 -0
  88. {audformat-1.3.3 → audformat-1.4.0}/tests/test_eq.py +0 -0
  89. {audformat-1.3.3 → audformat-1.4.0}/tests/test_errors.py +0 -0
@@ -7,6 +7,40 @@ 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
+
38
+ Version 1.3.4 (2026-02-18)
39
+ --------------------------
40
+
41
+ * Added: support for ``pandas >=3.0``
42
+
43
+
10
44
  Version 1.3.3 (2026-01-12)
11
45
  --------------------------
12
46
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: audformat
3
- Version: 1.3.3
3
+ Version: 1.4.0
4
4
  Summary: Python implementation of audformat
5
5
  Author: Johannes Wagner, BahaEddine Abrougui
6
6
  Author-email: Hagen Wierstorf <hwierstorf@audeering.com>, Christian Geng <cgeng@audeering.com>
@@ -362,6 +362,21 @@ def to_audformat_dtype(dtype: str | type) -> str:
362
362
  return define.DataType.OBJECT
363
363
 
364
364
 
365
+ def to_categorical_dtype(labels: list[object]) -> pd.api.types.CategoricalDtype:
366
+ """Create categorical dtype for labels."""
367
+ if len(labels) > 0:
368
+ if all(isinstance(label, int) for label in labels):
369
+ # allow nullable
370
+ labels = pd.array(labels, dtype="int64")
371
+ elif all(isinstance(label, str) for label in labels):
372
+ # object for string categories
373
+ labels = pd.Index(labels, dtype="object")
374
+ return pd.api.types.CategoricalDtype(
375
+ categories=labels,
376
+ ordered=False,
377
+ )
378
+
379
+
365
380
  def to_pandas_dtype(dtype: str) -> str | None:
366
381
  r"""Convert audformat to pandas dtype.
367
382
 
@@ -7,6 +7,7 @@ import itertools
7
7
  import os
8
8
  import shutil
9
9
 
10
+ import numpy as np
10
11
  import oyaml as yaml
11
12
 
12
13
 
@@ -696,12 +697,16 @@ class Database(HeaderBase):
696
697
  ys.append(y)
697
698
 
698
699
  def dtypes_of_categories(objs):
699
- dtypes = [
700
- obj.dtype.categories.dtype
701
- for obj in objs
702
- if isinstance(obj.dtype, pd.CategoricalDtype)
703
- ]
704
- return sorted(list(set(dtypes)))
700
+ cat_dtypes = []
701
+ for obj in objs:
702
+ if isinstance(obj.dtype, pd.CategoricalDtype):
703
+ # Normalize string-like categorical dtypes to object
704
+ cat_dtype = obj.dtype.categories.dtype
705
+ if isinstance(cat_dtype, pd.StringDtype):
706
+ cat_dtype = np.dtype("O")
707
+ cat_dtypes.append(cat_dtype)
708
+ # Deduplicate and sort for consistent ordering
709
+ return sorted(list(set(cat_dtypes)), key=str)
705
710
 
706
711
  def empty_frame(name):
707
712
  return pd.DataFrame(
@@ -823,7 +828,7 @@ class Database(HeaderBase):
823
828
  raise TypeError( # pragma: nocover
824
829
  f"Cannot join labels for scheme '{requested_scheme}' "
825
830
  "with different data types: "
826
- f"{', '.join(dtypes)}"
831
+ f"{', '.join(str(d) for d in dtypes)}"
827
832
  )
828
833
  dtype = dtypes[0]
829
834
  # Convert everything to categorical data
@@ -832,6 +837,12 @@ class Database(HeaderBase):
832
837
  ys[n] = y.astype(
833
838
  pd.CategoricalDtype(y.array.dropna().unique().astype(dtype))
834
839
  )
840
+ # Normalize string-like categorical dtypes to object
841
+ for n, y in enumerate(ys):
842
+ cat_dtype = y.dtype.categories.dtype
843
+ if isinstance(cat_dtype, pd.StringDtype):
844
+ new_categories = y.dtype.categories.astype("object")
845
+ ys[n] = y.astype(pd.CategoricalDtype(new_categories))
835
846
  # Find union of categorical data
836
847
  data = [y.array for y in ys]
837
848
  try:
@@ -1433,14 +1444,17 @@ class Database(HeaderBase):
1433
1444
  params = []
1434
1445
  table_ids = []
1435
1446
 
1436
- if "tables" in header and header["tables"]:
1437
- for table_id in header["tables"]:
1438
- table_ids.append(table_id)
1439
-
1447
+ # Load misc_tables first,
1448
+ # as they might be used as scheme labels
1449
+ # by regular tables
1440
1450
  if "misc_tables" in header and header["misc_tables"]:
1441
1451
  for table_id in header["misc_tables"]:
1442
1452
  table_ids.append(table_id)
1443
1453
 
1454
+ if "tables" in header and header["tables"]:
1455
+ for table_id in header["tables"]:
1456
+ table_ids.append(table_id)
1457
+
1444
1458
  for table_id in table_ids:
1445
1459
  table = db[table_id]
1446
1460
  if load_data:
@@ -27,9 +27,13 @@ def to_array(value: object) -> list | np.ndarray:
27
27
  def to_timedelta(times):
28
28
  r"""Convert time value to pd.Timedelta."""
29
29
  try:
30
- return pd.to_timedelta(times, unit="s")
30
+ result = pd.to_timedelta(times, unit="s")
31
31
  except ValueError: # catches values like '1s'
32
- return pd.to_timedelta(times)
32
+ result = pd.to_timedelta(times)
33
+ if isinstance(result, pd.Timedelta):
34
+ return result.as_unit("ns")
35
+ else:
36
+ return result.astype("timedelta64[ns]")
33
37
 
34
38
 
35
39
  def assert_index(
@@ -100,12 +104,12 @@ def assert_index(
100
104
  "Index not conform to audformat. "
101
105
  "Level 'file' must contain values of type 'string'."
102
106
  )
103
- if not pd.api.types.is_timedelta64_dtype(obj.levels[1].dtype):
107
+ if not pd.api.types.is_timedelta64_ns_dtype(obj.levels[1].dtype):
104
108
  raise ValueError(
105
109
  "Index not conform to audformat. "
106
110
  "Level 'start' must contain values of type 'timedelta64[ns]'."
107
111
  )
108
- if not pd.api.types.is_timedelta64_dtype(obj.levels[2].dtype):
112
+ if not pd.api.types.is_timedelta64_ns_dtype(obj.levels[2].dtype):
109
113
  raise ValueError(
110
114
  "Index not conform to audformat. "
111
115
  "Level 'end' must contain values of type 'timedelta64[ns]'."
@@ -287,16 +287,9 @@ class Scheme(common.HeaderBase):
287
287
  """
288
288
  if self.labels is not None:
289
289
  labels = self._labels_to_list()
290
- if len(labels) > 0 and isinstance(labels[0], int):
291
- # allow nullable
292
- labels = pd.array(labels, dtype="int64")
293
- dtype = pd.api.types.CategoricalDtype(
294
- categories=labels,
295
- ordered=False,
296
- )
290
+ return common.to_categorical_dtype(labels)
297
291
  else:
298
- dtype = common.to_pandas_dtype(self.dtype)
299
- return dtype
292
+ return common.to_pandas_dtype(self.dtype)
300
293
 
301
294
  def replace_labels(
302
295
  self,
@@ -370,20 +363,133 @@ class Scheme(common.HeaderBase):
370
363
  )
371
364
 
372
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
+ )
373
439
 
374
440
  if self._db is not None and self._id is not None:
375
- labels = self._labels_to_list(labels)
441
+ # Check existing data match new labels
442
+ labels_set = set(self._labels_to_list(labels))
376
443
  for table in list(self._db.tables.values()) + list(
377
444
  self._db.misc_tables.values()
378
445
  ):
379
446
  for column in table.columns.values():
380
447
  if column.scheme_id == self._id:
381
- y = column._table.df[column._id]
382
- y = y.cat.set_categories(
383
- new_categories=labels,
384
- ordered=False,
385
- )
386
- column._table.df[column._id] = y
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
387
493
 
388
494
  def _check_labels(
389
495
  self,
@@ -19,17 +19,25 @@ from audformat.core import utils
19
19
  from audformat.core.column import Column
20
20
  from audformat.core.common import HeaderBase
21
21
  from audformat.core.common import HeaderDict
22
+ from audformat.core.common import to_categorical_dtype
22
23
  from audformat.core.common import to_pandas_dtype
23
24
  from audformat.core.errors import BadIdError
24
25
  from audformat.core.index import filewise_index
25
26
  from audformat.core.index import index_type
26
27
  from audformat.core.index import is_filewise_index
27
28
  from audformat.core.index import is_segmented_index
29
+ from audformat.core.index import to_timedelta
28
30
  from audformat.core.media import Media
29
31
  from audformat.core.split import Split
30
32
  from audformat.core.typing import Values
31
33
 
32
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
+
33
41
  class Base(HeaderBase):
34
42
  r"""Table base class."""
35
43
 
@@ -922,9 +930,9 @@ class Base(HeaderBase):
922
930
  dtypes_wo_converters = {}
923
931
  for column, dtype in columns_and_dtypes.items():
924
932
  if dtype == define.DataType.DATE:
925
- converters[column] = lambda x: pd.to_datetime(x)
933
+ converters[column] = pd.to_datetime
926
934
  elif dtype == define.DataType.TIME:
927
- converters[column] = lambda x: pd.to_timedelta(x)
935
+ converters[column] = to_timedelta
928
936
  else:
929
937
  dtypes_wo_converters[column] = to_pandas_dtype(dtype)
930
938
 
@@ -952,6 +960,13 @@ class Base(HeaderBase):
952
960
  table = parquet.read_table(path)
953
961
  df = self._pyarrow_table_to_dataframe(table)
954
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
+
955
970
  self._df = df
956
971
 
957
972
  def _load_pickled(self, path: str):
@@ -968,22 +983,47 @@ class Base(HeaderBase):
968
983
  # but was slower.
969
984
  # The try-except statement allows backward compatibility
970
985
  try:
971
- df = pd.read_pickle(path)
986
+ data = pd.read_pickle(path)
972
987
  except pickle.UnpicklingError:
973
- df = pd.read_pickle(path, compression="xz")
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
974
1009
 
975
1010
  # Older versions of audformat stored columns
976
1011
  # assigned to a string scheme as 'object',
977
- # so we need to convert those to 'string'
978
- for column_id, column in self.columns.items():
979
- if (
980
- column.scheme_id is not None
981
- and (self.db.schemes[column.scheme_id].dtype == define.DataType.STRING)
982
- and df[column_id].dtype == "object"
983
- ):
984
- df[column_id] = df[column_id].astype("string", copy=False)
985
- # Fix index entries as well
986
- df.index = _maybe_convert_dtype_to_string(df.index)
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)
987
1027
 
988
1028
  self._df = df
989
1029
 
@@ -1004,11 +1044,13 @@ class Base(HeaderBase):
1004
1044
  df: dataframe,
1005
1045
  convert_all: if ``False``,
1006
1046
  converts all columns with
1007
- ``"object"`` audformat dtype,
1047
+ ``"object"``,
1048
+ and ``"time"``
1049
+ audformat dtype,
1008
1050
  and all columns with a scheme with labels.
1009
1051
  If ``"True"``,
1010
1052
  it converts additionally all columns with
1011
- ``"bool"``, ``"int"``, and ``"time"`` audformat dtypes
1053
+ ``"bool"``, and ``"int"`` audformat dtypes
1012
1054
 
1013
1055
  Returns:
1014
1056
  dataframe with converted dtypes
@@ -1066,21 +1108,14 @@ class Base(HeaderBase):
1066
1108
  df[column] = df[column].astype("boolean")
1067
1109
  for column in int_columns:
1068
1110
  df[column] = df[column].astype("Int64")
1069
- for column in time_columns:
1070
- df[column] = df[column].astype("timedelta64[ns]")
1111
+ for column in time_columns:
1112
+ df[column] = df[column].astype("timedelta64[ns]")
1071
1113
  for column in object_columns:
1072
- df[column] = df[column].astype("object")
1073
- df[column] = df[column].replace(pd.NA, None)
1114
+ df[column] = df[column].astype("object").replace(pd.NA, None)
1074
1115
  for column in labeled_columns:
1075
1116
  scheme = self.db.schemes[self.columns[column].scheme_id]
1076
1117
  labels = scheme._labels_to_list()
1077
- if len(labels) > 0 and isinstance(labels[0], int):
1078
- # allow nullable
1079
- labels = pd.array(labels, dtype="int64")
1080
- dtype = pd.api.types.CategoricalDtype(
1081
- categories=labels,
1082
- ordered=False,
1083
- )
1118
+ dtype = to_categorical_dtype(labels)
1084
1119
  df[column] = df[column].astype(dtype)
1085
1120
  return df
1086
1121
 
@@ -1193,20 +1228,29 @@ class Base(HeaderBase):
1193
1228
  path: path, including file extension
1194
1229
 
1195
1230
  """
1196
- table = pa.Table.from_pandas(self.df.reset_index(), preserve_index=False)
1197
-
1198
1231
  # Create hash of table
1199
1232
  table_hash = utils.hash(self.df, strict=True)
1200
1233
 
1201
- # Store in metadata of file,
1234
+ table = pa.Table.from_pandas(self.df.reset_index(), preserve_index=False)
1235
+
1236
+ # Store hash in metadata of file,
1202
1237
  # see https://stackoverflow.com/a/58978449
1203
- metadata = {"hash": table_hash}
1238
+ import audformat
1239
+
1240
+ metadata = {_KEY_HASH: table_hash, _KEY_VERSION: audformat.__version__}
1204
1241
  table = table.replace_schema_metadata({**metadata, **table.schema.metadata})
1205
1242
 
1206
1243
  parquet.write_table(table, path, compression="snappy")
1207
1244
 
1208
1245
  def _save_pickled(self, path: str):
1209
- self.df.to_pickle(
1246
+ import audformat
1247
+
1248
+ data = {
1249
+ _KEY_VERSION: audformat.__version__,
1250
+ _KEY_DATAFRAME: self.df,
1251
+ }
1252
+ pd.to_pickle(
1253
+ data,
1210
1254
  path,
1211
1255
  protocol=4, # supported by Python >= 3.4
1212
1256
  )
@@ -1849,6 +1893,29 @@ class Table(Base):
1849
1893
  return levels_and_dtypes
1850
1894
 
1851
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
+
1852
1919
  def _assert_table_index(
1853
1920
  table: Base,
1854
1921
  index: pd.Index,
@@ -17,6 +17,7 @@ from audformat.core.index import filewise_index
17
17
  from audformat.core.index import is_filewise_index
18
18
  from audformat.core.index import is_segmented_index
19
19
  from audformat.core.index import segmented_index
20
+ from audformat.core.index import to_timedelta
20
21
  from audformat.core.media import Media
21
22
  from audformat.core.rater import Rater
22
23
  from audformat.core.scheme import Scheme
@@ -115,7 +116,7 @@ def add_table(
115
116
 
116
117
  """
117
118
  if isinstance(file_duration, str):
118
- file_duration = pd.Timedelta(file_duration)
119
+ file_duration = to_timedelta(file_duration)
119
120
 
120
121
  audio_format = "wav"
121
122
  if media_id and db.media[media_id].format:
@@ -143,7 +144,7 @@ def add_table(
143
144
 
144
145
  for file in files:
145
146
  times = [
146
- pd.to_timedelta(random.random() * file_duration, unit="s")
147
+ random.random() * file_duration
147
148
  for _ in range(num_segments_per_file * 2)
148
149
  ]
149
150
  times.sort()