pipelime-python 2.2.0__py3-none-any.whl → 3.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. pipelime/__init__.py +1 -1
  2. pipelime/choixe/ast/nodes.py +41 -3
  3. pipelime/choixe/utils/common.py +35 -1
  4. pipelime/choixe/visitors/decoder.py +5 -2
  5. pipelime/choixe/visitors/inspector.py +8 -5
  6. pipelime/choixe/visitors/processor.py +19 -8
  7. pipelime/choixe/xconfig.py +3 -3
  8. pipelime/cli/main.py +16 -8
  9. pipelime/cli/pretty_print.py +72 -77
  10. pipelime/cli/tui/tui.py +3 -2
  11. pipelime/cli/tui/utils.py +27 -24
  12. pipelime/cli/utils.py +64 -37
  13. pipelime/commands/general.py +56 -53
  14. pipelime/commands/interfaces.py +92 -106
  15. pipelime/commands/piper.py +13 -19
  16. pipelime/commands/resume.py +9 -7
  17. pipelime/commands/shell.py +1 -3
  18. pipelime/commands/split_ops.py +15 -28
  19. pipelime/commands/tempman.py +2 -2
  20. pipelime/commands/toy_dataset.py +1 -3
  21. pipelime/piper/__init__.py +1 -0
  22. pipelime/piper/checkpoint.py +5 -3
  23. pipelime/piper/model.py +105 -80
  24. pipelime/piper/parsers/choixe_parser.py +1 -1
  25. pipelime/piper/progress/listener/receiver/zmq.py +1 -1
  26. pipelime/piper/progress/model.py +3 -3
  27. pipelime/piper/progress/tracker/zmq.py +1 -1
  28. pipelime/sequences/grabber.py +3 -2
  29. pipelime/sequences/pipes/base.py +2 -3
  30. pipelime/sequences/pipes/mapping.py +4 -3
  31. pipelime/sequences/pipes/operations.py +7 -14
  32. pipelime/sequences/pipes/validation.py +3 -5
  33. pipelime/sequences/pipes/writers.py +9 -7
  34. pipelime/sequences/sample.py +6 -2
  35. pipelime/sequences/samples_sequence.py +16 -17
  36. pipelime/sequences/sources/from_callable.py +1 -1
  37. pipelime/sequences/sources/raw.py +1 -1
  38. pipelime/sequences/sources/readers.py +22 -13
  39. pipelime/sequences/sources/toy_dataset.py +3 -2
  40. pipelime/sequences/utils.py +3 -8
  41. pipelime/stages/augmentations.py +30 -36
  42. pipelime/stages/base.py +33 -42
  43. pipelime/stages/entities.py +167 -99
  44. pipelime/stages/item_info.py +3 -2
  45. pipelime/stages/item_replacement.py +7 -8
  46. pipelime/stages/item_sources.py +1 -1
  47. pipelime/stages/key_transformations.py +3 -2
  48. pipelime/utils/pydantic_compat.py +1064 -0
  49. pipelime/utils/pydantic_types.py +186 -220
  50. {pipelime_python-2.2.0.dist-info → pipelime_python-3.0.0.dist-info}/METADATA +9 -4
  51. {pipelime_python-2.2.0.dist-info → pipelime_python-3.0.0.dist-info}/RECORD +54 -53
  52. {pipelime_python-2.2.0.dist-info → pipelime_python-3.0.0.dist-info}/WHEEL +1 -1
  53. {pipelime_python-2.2.0.dist-info → pipelime_python-3.0.0.dist-info}/entry_points.txt +0 -0
  54. {pipelime_python-2.2.0.dist-info → pipelime_python-3.0.0.dist-info}/licenses/LICENSE +0 -0
@@ -5,13 +5,43 @@ import typing as t
5
5
  import uuid
6
6
  from pathlib import Path
7
7
 
8
- import pydantic.v1 as pyd
9
- from pydantic.v1.generics import GenericModel
8
+ import pydantic as pyd
10
9
 
11
10
  from pipelime.piper import PiperPortType
11
+ from pipelime.utils.pydantic_compat import Field, PipelimeModel
12
12
  from pipelime.utils.pydantic_types import ItemType, SampleValidationInterface, YamlInput
13
13
 
14
14
 
15
+ class CompactFormModel(PipelimeModel):
16
+ """A model that also accepts a *compact form* (a string, a number, a list...)
17
+ when used as a field type or validated with `model_validate`.
18
+ Subclasses implement `_compact_to_data`, returning the field mapping."""
19
+
20
+ @classmethod
21
+ def _compact_to_data(cls, value: t.Any) -> t.Mapping[str, t.Any]:
22
+ if isinstance(value, t.Mapping):
23
+ return value
24
+ raise ValueError(f"Invalid {cls.__name__} definition: {value!r}")
25
+
26
+ @pyd.model_validator(mode="wrap")
27
+ @classmethod
28
+ def _validate_compact(cls, value, handler):
29
+ # an instance of `cls` or of its generic origin (`OutputValueInterface`
30
+ # for `OutputValueInterface[int]`) is kept as is, as v1's
31
+ # `isinstance(value, OutputValueInterface)` did: the caller's own
32
+ # reference must be the object the command writes to
33
+ origin = cls.__pydantic_generic_metadata__["origin"] or cls
34
+ if isinstance(value, (cls, origin)):
35
+ return value
36
+ if isinstance(value, pyd.BaseModel):
37
+ return handler(value) # pydantic rejects unrelated models
38
+ return handler(cls._compact_to_data(value))
39
+
40
+ @classmethod
41
+ def validate(cls, value): # v1 name kept for downstream code
42
+ return cls.model_validate(value)
43
+
44
+
15
45
  class PydanticFieldMixinBase:
16
46
  # override in derived clasess
17
47
  _default_type_description: t.ClassVar[t.Optional[str]] = None
@@ -43,7 +73,7 @@ class PydanticFieldWithDefaultMixin(PydanticFieldMixinBase):
43
73
  piper_port: t.Optional[PiperPortType] = None,
44
74
  **kwargs,
45
75
  ):
46
- return pyd.Field(
76
+ return Field(
47
77
  default_factory=cls, # type: ignore
48
78
  description=cls._description(description), # type: ignore
49
79
  piper_port=piper_port or cls._default_port_type,
@@ -61,7 +91,7 @@ class PydanticFieldNoDefaultMixin(PydanticFieldMixinBase):
61
91
  piper_port: t.Optional[PiperPortType] = None,
62
92
  **kwargs,
63
93
  ):
64
- return pyd.Field(
94
+ return Field(
65
95
  ... if is_required else None,
66
96
  description=cls._description(description), # type: ignore
67
97
  piper_port=piper_port or cls._default_port_type,
@@ -69,7 +99,7 @@ class PydanticFieldNoDefaultMixin(PydanticFieldMixinBase):
69
99
  )
70
100
 
71
101
 
72
- class GrabberInterface(PydanticFieldWithDefaultMixin, pyd.BaseModel, extra="forbid"):
102
+ class GrabberInterface(PydanticFieldWithDefaultMixin, CompactFormModel, extra="forbid"):
73
103
  """Multiprocessing grabbing options.
74
104
 
75
105
  Examples:
@@ -112,14 +142,7 @@ class GrabberInterface(PydanticFieldWithDefaultMixin, pyd.BaseModel, extra="forb
112
142
  )
113
143
 
114
144
  @classmethod
115
- def __get_validators__(cls):
116
- yield cls.validate
117
-
118
- @classmethod
119
- def validate(cls, value):
120
- if isinstance(value, GrabberInterface):
121
- return value
122
-
145
+ def _compact_to_data(cls, value):
123
146
  if isinstance(value, (str, bytes, int)):
124
147
  data = {}
125
148
  if isinstance(value, int):
@@ -138,7 +161,7 @@ class GrabberInterface(PydanticFieldWithDefaultMixin, pyd.BaseModel, extra="forb
138
161
  value = data
139
162
 
140
163
  if isinstance(value, t.Mapping):
141
- return GrabberInterface(**value)
164
+ return value
142
165
 
143
166
  raise ValueError("Invalid grabber definition.")
144
167
 
@@ -264,10 +287,9 @@ class GrabberInterface(PydanticFieldWithDefaultMixin, pyd.BaseModel, extra="forb
264
287
 
265
288
  class InputDatasetInterface(
266
289
  PydanticFieldNoDefaultMixin,
267
- pyd.BaseModel,
290
+ CompactFormModel,
268
291
  extra="forbid",
269
- copy_on_model_validation="none",
270
- allow_population_by_field_name=True,
292
+ populate_by_name=True,
271
293
  ):
272
294
  """Input dataset options.
273
295
 
@@ -312,6 +334,7 @@ class InputDatasetInterface(
312
334
  skip_empty: bool = pyd.Field(False, description="Filter out empty samples.")
313
335
  pipe: t.Optional[YamlInput] = pyd.Field(
314
336
  None,
337
+ validate_default=True,
315
338
  description=(
316
339
  "The pipeline to run or a path to a yaml/json file as "
317
340
  "<filepath>[:<key-path>]. Either `folder` is not `None` or the "
@@ -328,33 +351,26 @@ class InputDatasetInterface(
328
351
  description="Sample schema validation, verified after all operations.",
329
352
  )
330
353
 
331
- @pyd.validator("folder")
354
+ @pyd.field_validator("folder")
355
+ @classmethod
332
356
  def resolve_folder(cls, v: t.Optional[Path]):
333
357
  if v:
334
358
  # see https://bugs.python.org/issue38671
335
359
  return v.resolve().absolute()
336
360
  return v
337
361
 
338
- @pyd.validator("pipe", always=True)
339
- def check_pipe_and_folder(
340
- cls, v: t.Optional[YamlInput], values: t.Mapping[str, t.Any]
341
- ):
362
+ @pyd.field_validator("pipe")
363
+ @classmethod
364
+ def check_pipe_and_folder(cls, v: t.Optional[YamlInput], info: pyd.ValidationInfo):
342
365
  if v is None:
343
- if values.get("folder", None) is None:
366
+ if info.data.get("folder", None) is None:
344
367
  raise ValueError("Either `folder` or `pipe` (or both) must be defined.")
345
368
  elif not v.value or not isinstance(v.value, (t.Mapping, t.Sequence)):
346
369
  raise ValueError(f"Invalid pipeline: {v.value}")
347
370
  return v
348
371
 
349
372
  @classmethod
350
- def __get_validators__(cls):
351
- yield cls.validate
352
-
353
- @classmethod
354
- def validate(cls, value):
355
- if isinstance(value, InputDatasetInterface):
356
- return value
357
-
373
+ def _compact_to_data(cls, value):
358
374
  if isinstance(value, (str, bytes, Path)):
359
375
  fld, _, sk_emp = str(value).partition(",")
360
376
  data: t.Mapping[str, t.Any] = {"folder": fld}
@@ -369,7 +385,7 @@ class InputDatasetInterface(
369
385
  value = data
370
386
 
371
387
  if isinstance(value, t.Mapping):
372
- return InputDatasetInterface(**value)
388
+ return value
373
389
  raise ValueError("Invalid input dataset definition.")
374
390
 
375
391
  @staticmethod
@@ -414,12 +430,7 @@ any_serialization_t = t.Literal["CREATE_NEW_FILE", "DEEP_COPY", "SYM_LINK", "HAR
414
430
  any_item_t = t.Union[None, t.Literal["_"], ItemType]
415
431
 
416
432
 
417
- class SerializationModeInterface(
418
- pyd.BaseModel,
419
- extra="forbid",
420
- copy_on_model_validation="none",
421
- underscore_attrs_are_private=True,
422
- ):
433
+ class SerializationModeInterface(PipelimeModel, extra="forbid"):
423
434
  """Serialization modes for items and keys."""
424
435
 
425
436
  override: t.Mapping[
@@ -485,10 +496,9 @@ class SerializationModeInterface(
485
496
 
486
497
  class OutputDatasetInterface(
487
498
  PydanticFieldNoDefaultMixin,
488
- pyd.BaseModel,
499
+ CompactFormModel,
489
500
  extra="forbid",
490
- copy_on_model_validation="none",
491
- allow_population_by_field_name=True,
501
+ populate_by_name=True,
492
502
  ):
493
503
  """Output dataset options.
494
504
 
@@ -526,7 +536,9 @@ class OutputDatasetInterface(
526
536
  None, description="Custom index zero-filling."
527
537
  )
528
538
  exists_ok: bool = pyd.Field(
529
- False, description="If False raises an error when `folder` exists."
539
+ False,
540
+ validate_default=True,
541
+ description="If False raises an error when `folder` exists.",
530
542
  )
531
543
  serialization: SerializationModeInterface = pyd.Field(
532
544
  default_factory=SerializationModeInterface,
@@ -534,6 +546,7 @@ class OutputDatasetInterface(
534
546
  )
535
547
  pipe: t.Optional[YamlInput] = pyd.Field(
536
548
  None,
549
+ validate_default=True,
537
550
  description=(
538
551
  "The pipeline to run or a path to a yaml/json file as "
539
552
  "<filepath>[:<key-path>]. It cannot start with a generator sequence. "
@@ -550,46 +563,40 @@ class OutputDatasetInterface(
550
563
  description="Sample schema validation, verified before any other operation.",
551
564
  )
552
565
 
553
- @pyd.validator("folder")
566
+ @pyd.field_validator("folder")
567
+ @classmethod
554
568
  def resolve_folder(cls, v: t.Optional[Path]):
555
569
  if v:
556
570
  # see https://bugs.python.org/issue38671
557
571
  return v.resolve().absolute()
558
572
  return v
559
573
 
560
- @pyd.validator("exists_ok", always=True)
561
- def _check_folder_exists(cls, v: bool, values: t.Mapping[str, t.Any]) -> bool:
574
+ @pyd.field_validator("exists_ok")
575
+ @classmethod
576
+ def _check_folder_exists(cls, v: bool, info: pyd.ValidationInfo) -> bool:
562
577
  if (
563
578
  not v
564
- and values.get("folder", None) is not None
565
- and values["folder"].exists()
579
+ and info.data.get("folder", None) is not None
580
+ and info.data["folder"].exists()
566
581
  ):
567
582
  raise ValueError(
568
- f"Trying to overwrite an existing dataset: `{values['folder']}`. "
583
+ f"Trying to overwrite an existing dataset: `{info.data['folder']}`. "
569
584
  "Please use `exists_ok=True` to overwrite."
570
585
  )
571
586
  return v
572
587
 
573
- @pyd.validator("pipe", always=True)
574
- def check_pipe_and_folder(
575
- cls, v: t.Optional[YamlInput], values: t.Mapping[str, t.Any]
576
- ):
588
+ @pyd.field_validator("pipe")
589
+ @classmethod
590
+ def check_pipe_and_folder(cls, v: t.Optional[YamlInput], info: pyd.ValidationInfo):
577
591
  if v is None:
578
- if values.get("folder", None) is None:
592
+ if info.data.get("folder", None) is None:
579
593
  raise ValueError("Either `folder` or `pipe` (or both) must be defined.")
580
594
  elif not v.value or not isinstance(v.value, (t.Mapping, t.Sequence)):
581
595
  raise ValueError(f"Invalid pipeline: {v.value}")
582
596
  return v
583
597
 
584
598
  @classmethod
585
- def __get_validators__(cls):
586
- yield cls.validate
587
-
588
- @classmethod
589
- def validate(cls, value):
590
- if isinstance(value, OutputDatasetInterface):
591
- return value
592
-
599
+ def _compact_to_data(cls, value):
593
600
  if isinstance(value, (str, bytes, Path)):
594
601
  data = {}
595
602
  raw_data = str(value).split(",")
@@ -610,7 +617,7 @@ class OutputDatasetInterface(
610
617
  value = data
611
618
 
612
619
  if isinstance(value, t.Mapping):
613
- return OutputDatasetInterface(**value)
620
+ return value
614
621
  raise ValueError("Invalid output dataset definition.")
615
622
 
616
623
  def serialization_cm(self) -> t.ContextManager:
@@ -671,9 +678,7 @@ class OutputDatasetInterface(
671
678
  ODataset = OutputDatasetInterface
672
679
 
673
680
 
674
- class ToyDatasetInterface(
675
- pyd.BaseModel, extra="forbid", copy_on_model_validation="none"
676
- ):
681
+ class ToyDatasetInterface(PipelimeModel, extra="forbid"):
677
682
  """Toy dataset creation options."""
678
683
 
679
684
  length: pyd.PositiveInt = pyd.Field(
@@ -714,7 +719,8 @@ class ToyDatasetInterface(
714
719
  )
715
720
  seed: t.Optional[int] = pyd.Field(None, description="The optional random seed.")
716
721
 
717
- @pyd.validator("key_format")
722
+ @pyd.field_validator("key_format")
723
+ @classmethod
718
724
  def validate_key_format(cls, v):
719
725
  if "*" in v:
720
726
  return v
@@ -739,7 +745,7 @@ class ToyDatasetInterface(
739
745
  )
740
746
 
741
747
 
742
- class Interval(PydanticFieldWithDefaultMixin, pyd.BaseModel, extra="forbid"):
748
+ class Interval(PydanticFieldWithDefaultMixin, CompactFormModel, extra="forbid"):
743
749
  """An interval of indexes, with optional start and stop indices.
744
750
 
745
751
  Accepts a single value as ``start`` index, a sequence as ``start`` and ``stop``
@@ -764,14 +770,7 @@ class Interval(PydanticFieldWithDefaultMixin, pyd.BaseModel, extra="forbid"):
764
770
  )
765
771
 
766
772
  @classmethod
767
- def __get_validators__(cls):
768
- yield cls.validate
769
-
770
- @classmethod
771
- def validate(cls, value) -> Interval:
772
- if isinstance(value, cls):
773
- return value
774
-
773
+ def _compact_to_data(cls, value):
775
774
  if isinstance(value, str):
776
775
  value = value.split(":")
777
776
 
@@ -790,7 +789,7 @@ class Interval(PydanticFieldWithDefaultMixin, pyd.BaseModel, extra="forbid"):
790
789
  else:
791
790
  raise ValueError(f"Invalid interval: {value}")
792
791
 
793
- return cls(**data)
792
+ return data
794
793
 
795
794
 
796
795
  class ExtendedInterval(Interval):
@@ -807,14 +806,7 @@ class ExtendedInterval(Interval):
807
806
  )
808
807
 
809
808
  @classmethod
810
- def __get_validators__(cls):
811
- yield cls.validate
812
-
813
- @classmethod
814
- def validate(cls, value) -> Interval:
815
- if isinstance(value, cls):
816
- return value
817
-
809
+ def _compact_to_data(cls, value):
818
810
  if isinstance(value, str):
819
811
  value = value.split(":")
820
812
 
@@ -835,7 +827,7 @@ class ExtendedInterval(Interval):
835
827
  else:
836
828
  raise ValueError(f"Invalid interval: {value}")
837
829
 
838
- return cls(**data)
830
+ return data
839
831
 
840
832
 
841
833
  ValueType = t.TypeVar("ValueType")
@@ -843,11 +835,9 @@ ValueType = t.TypeVar("ValueType")
843
835
 
844
836
  class OutputValueInterface(
845
837
  PydanticFieldNoDefaultMixin,
846
- GenericModel,
838
+ CompactFormModel,
847
839
  t.Generic[ValueType],
848
840
  extra="forbid",
849
- copy_on_model_validation="none",
850
- underscore_attrs_are_private=True,
851
841
  ):
852
842
  """Interface that allows to store a value in a file.
853
843
 
@@ -875,22 +865,21 @@ class OutputValueInterface(
875
865
  )
876
866
  exists_ok: bool = pyd.Field(
877
867
  False,
868
+ validate_default=True,
878
869
  description=(
879
870
  "If `True`, the output file will be overwritten if it exists. "
880
871
  "If `False`, an error will be raised."
881
872
  ),
882
873
  )
883
874
 
884
- @pyd.validator("file")
875
+ @pyd.field_validator("file")
876
+ @classmethod
885
877
  def resolve_file(cls, v: Path):
886
878
  # see https://bugs.python.org/issue38671
887
879
  return v.resolve().absolute()
888
880
 
889
881
  @classmethod
890
- def validate(cls, value):
891
- if isinstance(value, OutputValueInterface):
892
- return value
893
-
882
+ def _compact_to_data(cls, value):
894
883
  if isinstance(value, (str, bytes, Path)):
895
884
  data = {}
896
885
  raw_data = str(value).split(",")
@@ -906,37 +895,34 @@ class OutputValueInterface(
906
895
  value = data
907
896
 
908
897
  if isinstance(value, t.Mapping):
909
- return OutputValueInterface(**value)
898
+ return value
910
899
 
911
900
  raise ValueError("Invalid OutputValueInterface definition.")
912
901
 
902
+ @pyd.field_validator("exists_ok")
913
903
  @classmethod
914
- def __get_validators__(cls):
915
- yield cls.validate
916
-
917
- @pyd.validator("exists_ok", always=True)
918
- def _check_file_exists(cls, v: bool, values: t.Mapping[str, t.Any]) -> bool:
919
- if "file" not in values:
904
+ def _check_file_exists(cls, v: bool, info: pyd.ValidationInfo) -> bool:
905
+ if "file" not in info.data:
920
906
  # the "file" validator already failed
921
907
  return v
922
908
 
923
909
  if v is True:
924
- if values["file"].is_dir():
910
+ if info.data["file"].is_dir():
925
911
  raise ValueError(
926
- f"Cannot overwrite the directory: `{values['file']}`. "
912
+ f"Cannot overwrite the directory: `{info.data['file']}`. "
927
913
  "Please provide a file path."
928
914
  )
929
915
 
930
916
  if v is False:
931
- if values["file"].is_dir():
917
+ if info.data["file"].is_dir():
932
918
  raise ValueError(
933
- f"Trying to overwrite the directory: `{values['file']}`. "
919
+ f"Trying to overwrite the directory: `{info.data['file']}`. "
934
920
  "Please provide a file path and use `exists_ok=True` to overwrite."
935
921
  )
936
922
 
937
- if values["file"].exists():
923
+ if info.data["file"].exists():
938
924
  raise ValueError(
939
- f"Trying to overwrite an existing file: `{values['file']}`. "
925
+ f"Trying to overwrite an existing file: `{info.data['file']}`. "
940
926
  "Please use `exists_ok=True` to overwrite."
941
927
  )
942
928
 
@@ -4,16 +4,11 @@ from enum import Enum
4
4
  from pathlib import Path
5
5
 
6
6
  from loguru import logger
7
- from pydantic.v1 import (
8
- BaseModel,
9
- Field,
10
- PositiveInt,
11
- PrivateAttr,
12
- create_model,
13
- validator,
14
- )
7
+ from pydantic import PositiveInt, PrivateAttr, create_model, field_validator
15
8
 
9
+ from pipelime.piper import Field
16
10
  from pipelime.piper.model import T_NODES, LazyCommand, PipelimeCommand, PiperPortType
11
+ from pipelime.utils.pydantic_compat import PipelimeModel, model_title
17
12
 
18
13
  if t.TYPE_CHECKING:
19
14
  from pipelime.piper.checkpoint import CheckpointNamespace
@@ -286,7 +281,7 @@ class RunCommandBase(GraphPortForwardingCommand):
286
281
  self.command_checkpoint.write_data("exclude", exc, lock)
287
282
 
288
283
 
289
- class ClassicPiperGraphCommand(BaseModel):
284
+ class ClassicPiperGraphCommand(PipelimeModel):
290
285
  nodes: T_NODES = Field(
291
286
  ...,
292
287
  alias="n",
@@ -489,7 +484,9 @@ class DagBaseCommand(RunCommandBase):
489
484
  a custom name for the input and output data keys.
490
485
  """
491
486
 
492
- folder_debug: Path = Field(None, description="Path to Debug dir folder.")
487
+ folder_debug: Path = Field(
488
+ None, validate_default=True, description="Path to Debug dir folder."
489
+ )
493
490
  draw: t.Union[bool, Path, t.Mapping] = Field(
494
491
  False,
495
492
  description=(
@@ -502,7 +499,8 @@ class DagBaseCommand(RunCommandBase):
502
499
 
503
500
  _nodes: T_NODES = PrivateAttr(None)
504
501
 
505
- @validator("folder_debug", always=True)
502
+ @field_validator("folder_debug")
503
+ @classmethod
506
504
  def _validate_folder_debug(cls, v):
507
505
  from pipelime.choixe.utils.io import PipelimeTmp
508
506
 
@@ -606,13 +604,7 @@ class DagBaseCommand(RunCommandBase):
606
604
  return super().run()
607
605
 
608
606
 
609
- class PiperDAG(
610
- BaseModel,
611
- ABC,
612
- allow_population_by_field_name=True,
613
- extra="forbid",
614
- copy_on_model_validation="none",
615
- ):
607
+ class PiperDAG(PipelimeModel, ABC, populate_by_name=True, extra="forbid"):
616
608
  """Base class to ease the creation of Python DAG Object.
617
609
 
618
610
  Derived classes should add custom properties as pydantic fields and implement
@@ -686,7 +678,7 @@ def piper_dag(cls: t.Type[PiperDAG]):
686
678
  cls.__name__,
687
679
  __base__=_PiperDagCommandHelper,
688
680
  __module__=cls.__module__,
689
- __cls_kwargs__={"title": cls.schema()["title"]},
681
+ __cls_kwargs__={"title": model_title(cls)},
690
682
  )
691
683
  dag_command.__doc__ = cls.__doc__
692
684
 
@@ -695,5 +687,7 @@ def piper_dag(cls: t.Type[PiperDAG]):
695
687
  f"{cls.__qualname__}.{dag_command.PropertyModel.__name__}"
696
688
  )
697
689
  dag_command.PropertyModel.__module__ = cls.__module__
690
+ # pydantic v2 does not inherit the docstring of the parent class in the schema
691
+ dag_command.PropertyModel.__doc__ = cls.__doc__
698
692
 
699
693
  return dag_command
@@ -1,10 +1,10 @@
1
1
  import typing as t
2
2
  from pathlib import Path
3
3
 
4
- from pydantic.v1 import DirectoryPath, Field, ValidationError, conint, validator
4
+ from pydantic import DirectoryPath, ValidationError, conint, field_validator
5
5
 
6
6
  from pipelime.cli.utils import PipelimeUserAppDir
7
- from pipelime.piper import PipelimeCommand
7
+ from pipelime.piper import Field, PipelimeCommand
8
8
 
9
9
 
10
10
  class ResumeCommand(
@@ -14,11 +14,12 @@ class ResumeCommand(
14
14
  Any extra field is forwarded to the original command line as '+' option.
15
15
  """
16
16
 
17
- ckpt: t.Union[
18
- DirectoryPath, conint(ge=1, le=PipelimeUserAppDir.MAX_CHECKPOINTS) # type: ignore
17
+ ckpt: t.Optional[
18
+ t.Union[DirectoryPath, conint(ge=1, le=PipelimeUserAppDir.MAX_CHECKPOINTS)] # type: ignore
19
19
  ] = Field(
20
20
  None,
21
21
  alias="c",
22
+ validate_default=True,
22
23
  description=(
23
24
  "The checkpoint folder, or the nth-last default checkpoint "
24
25
  f"(up to {PipelimeUserAppDir.MAX_CHECKPOINTS}). "
@@ -26,7 +27,8 @@ class ResumeCommand(
26
27
  ),
27
28
  )
28
29
 
29
- @validator("ckpt", always=True)
30
+ @field_validator("ckpt")
31
+ @classmethod
30
32
  def _validate_ckpt(cls, v):
31
33
  if v is None:
32
34
  return PipelimeUserAppDir.last_checkpoint_path()
@@ -40,12 +42,12 @@ class ResumeCommand(
40
42
 
41
43
  ckpt = LocalCheckpoint(folder=self.ckpt)
42
44
  try:
43
- cli_opts = cli.PlCliOptions.parse_obj(
45
+ cli_opts = cli.PlCliOptions.model_validate(
44
46
  ckpt.read_data(cli.PlCliOptions._namespace, "", None)
45
47
  )
46
48
 
47
49
  flattened_extra = {}
48
- for k, v in self.dict(exclude={"ckpt"}).items():
50
+ for k, v in self.model_dump(exclude={"ckpt"}).items():
49
51
  self._flatten_values(v, k, flattened_extra)
50
52
  cli_opts.command_args.extend(
51
53
  x for k, v in flattened_extra.items() for x in [f"+{k}", v]
@@ -2,9 +2,7 @@ import subprocess
2
2
  from string import Formatter
3
3
  from typing import Any, Dict, Mapping, Sequence
4
4
 
5
- from pydantic.v1 import Field
6
-
7
- from pipelime.piper import PipelimeCommand, PiperPortType
5
+ from pipelime.piper import Field, PipelimeCommand, PiperPortType
8
6
 
9
7
 
10
8
  class ShellCommand(PipelimeCommand, title="shell"):