|
1 | | -from dataclasses import dataclass |
2 | | -from typing import Optional, Tuple, Union |
| 1 | +from pydantic import ConfigDict, GetCoreSchemaHandler |
| 2 | +from pydantic.dataclasses import dataclass |
| 3 | +from pydantic_core import core_schema |
| 4 | +from typing import Any, Optional, Tuple, Union |
3 | 5 | import warnings |
4 | 6 | from labelbox.orm.db_object import DbObject |
5 | 7 | from labelbox.orm.model import Field |
@@ -47,6 +49,35 @@ def to_hash(self): |
47 | 49 | "global_key": self.global_key.key if self.global_key else None, |
48 | 50 | } |
49 | 51 |
|
| 52 | + model_config = ConfigDict(arbitrary_types_allowed=True) |
| 53 | + |
| 54 | + @classmethod |
| 55 | + def __get_pydantic_core_schema__( |
| 56 | + self, source: type[Any], handler: GetCoreSchemaHandler |
| 57 | + ) -> core_schema.CoreSchema: |
| 58 | + print(source) |
| 59 | + return core_schema.no_info_after_validator_function( |
| 60 | + self._validate, |
| 61 | + core_schema.dict_schema(), |
| 62 | + serialization=core_schema.plain_serializer_function_ser_schema( |
| 63 | + lambda x: x.to_hash(), |
| 64 | + return_schema=core_schema.dict_schema(), |
| 65 | + ), |
| 66 | + ) |
| 67 | + |
| 68 | + @classmethod |
| 69 | + def _validate(cls, value: Any) -> Any: |
| 70 | + if isinstance(value, cls): |
| 71 | + return value |
| 72 | + if isinstance(value, dict): |
| 73 | + id_val = value.get("id") |
| 74 | + if id_val is None: |
| 75 | + raise ValueError( |
| 76 | + f"Missing required 'id' field in dict {value}" |
| 77 | + ) |
| 78 | + return cls(id=id_val, global_key=value.get("global_key")) |
| 79 | + raise ValueError(f"Cannot convert {value} to {cls.__name__}") |
| 80 | + |
50 | 81 |
|
51 | 82 | class CatalogSlice(Slice): |
52 | 83 | """ |
|
0 commit comments