"""Serialization utilities for models."""frompathlibimportPathfromtypingimportAny,Unionimportcloudpickle
[docs]defsave(model:Any)->bytes:"""Save a model to bytes using `cloudpickle`. Companion to `~tempor.utils.serialization.load`. Args: model (Any): Model object to be saved. Returns: bytes: Model serialized to bytes. """returncloudpickle.dumps(model)
[docs]defload(buff:bytes)->Any:"""Load a model from bytes using `cloudpickle`. Companion to `~tempor.utils.serialization.save`. Args: buff (bytes): Model as serialized to bytes (buffer), e.g. loaded from file. Returns: Any: The model object. """returncloudpickle.loads(buff)
[docs]defsave_to_file(path:Union[str,Path],model:Any)->None:"""Save a model to file using `cloudpickle`. Companion to `~tempor.utils.serialization.load_from_file`. Args: path (Union[str, Path]): Path to save the model to. model (Any): The model object to be saved. """path=Path(path)ppath=path.absolute().parentifnotppath.exists():ppath.mkdir(parents=True,exist_ok=True)withopen(path,"wb")asf:cloudpickle.dump(model,f)
[docs]defload_from_file(path:Union[str,Path])->Any:"""Load a model from file using `cloudpickle`. Companion to `~tempor.utils.serialization.save_to_file`. Args: path (Union[str, Path]): The file path to load the model from. Returns: Any: The loaded model object. """withopen(path,"rb")asf:returncloudpickle.load(f)