Bug fixes

This commit is contained in:
Andras Schmelczer 2026-10-28 22:32:31 +00:00
commit bd7a0586b6
2 changed files with 117 additions and 8 deletions

View file

@ -1,11 +1,19 @@
from copy import deepcopy
from typing import Any, Dict, Tuple
import numpy as np
from pydantic import BaseModel
def make_hashable(value: Any) -> Any:
"""Build an immutable value key without retaining mutable container contents."""
if isinstance(value, np.ndarray):
contents = (
make_hashable(value.tolist()) if value.dtype.hasobject else value.tobytes()
)
return type(value), value.dtype, value.shape, contents
if isinstance(value, np.generic):
return type(value), value.dtype, value.tobytes()
if isinstance(value, BaseModel):
return type(value), make_hashable(value.model_dump())
if isinstance(value, dict):

View file

@ -0,0 +1,20 @@
from typing import Any
import numpy as np
from pydantic_core import PydanticSerializationError
def numpy_to_python(value: Any) -> Any:
"""Convert NumPy values encountered by Pydantic's JSON serializer."""
if isinstance(value, np.ndarray):
return value.tolist()
if isinstance(value, np.floating):
return float(value)
if isinstance(value, np.generic):
converted = value.item()
if not isinstance(converted, type(value)):
return converted
raise PydanticSerializationError(
f"Unable to serialize {type(value).__name__}; convert it to a JSON-compatible "
"Python value before returning or logging it."
)