serializer.py 802 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import pickle
  2. from io import BytesIO
  3. import joblib
  4. import torch
  5. class JoblibSerializer:
  6. @staticmethod
  7. def dumps(obj) -> bytes:
  8. s = BytesIO()
  9. joblib.dump(obj, s)
  10. return s.getvalue()
  11. @staticmethod
  12. def loads(buf: bytes):
  13. return joblib.load(BytesIO(buf))
  14. class PickleSerializer:
  15. @staticmethod
  16. def dumps(obj) -> bytes:
  17. return pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)
  18. @staticmethod
  19. def loads(buf: bytes):
  20. return pickle.loads(buf)
  21. class PytorchSerializer:
  22. @staticmethod
  23. def dumps(obj) -> bytes:
  24. s = BytesIO()
  25. torch.save(obj, s, pickle_protocol=pickle.HIGHEST_PROTOCOL)
  26. return s.getvalue()
  27. @staticmethod
  28. def loads(buf: bytes):
  29. return torch.load(BytesIO(buf))