💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows
Python agentsaiai-agentsembeddingsinformation-retrievallanguage-modellarge-language-modelsllmnlppythonragretrieval-augmented-generationsearchsearch-enginesemantic-searchsentence-embeddingstransformerstxtaivector-databasevector-search
Add serialization package for handling supported data serialization methods, closes #770
davidmezzetti5cad89271aa4
diff --git a/src/python/txtai/serialize/__init__.py b/src/python/txtai/serialize/__init__.pynew file mode 100644index 00000000..72eb3d94--- /dev/null+++ b/src/python/txtai/serialize/__init__.py@@ -0,0 +1,10 @@+"""+Serialize imports+"""++from .base import Serialize+from .errors import SerializeError+from .factory import SerializeFactory+from .messagepack import MessagePack+from .pickle import Pickle+from .serializer import Serializerdiff --git a/src/python/txtai/serialize/base.py b/src/python/txtai/serialize/base.pynew file mode 100644index 00000000..76410dae--- /dev/null+++ b/src/python/txtai/serialize/base.py@@ -0,0 +1,85 @@+"""+Serialize module+"""+++class Serialize:+ """+ Base class for Serialize instances. This class serializes data to files, streams and bytes.+ """++ def load(self, path):+ """+ Loads data from path.++ Args:+ path: input path++ Returns:+ deserialized data+ """++ with open(path, "rb") as handle:+ return self.loadstream(handle)++ def save(self, data, path):+ """+ Saves data to path.++ Args:+ data: data to save+ path: output path+ """++ with open(path, "wb") as handle:+ self.savestream(data, handle)++ def loadstream(self, stream):+ """+ Loads data from stream.++ Args:+ stream: input stream++ Returns:+ deserialized data+ """++ raise NotImplementedError++ def savestream(self, data, stream):+ """+ Saves data to stream.++ Args:+ data: data to save+ stream: output stream+ """++ raise NotImplementedError++ def loadbytes(self, data):+ """+ Loads data from bytes.++ Args:+ data: input bytes++ Returns:+ deserialized data+ """++ raise NotImplementedError++ def savebytes(self, data):+ """+ Saves data as bytes.++ Args:+ data: data to save++ Returns:+ serialized data+ """++ raise NotImplementedErrordiff --git a/src/python/txtai/serialize/errors.py b/src/python/txtai/serialize/errors.pynew file mode 100644index 00000000..18d2d8c3--- /dev/null+++ b/src/python/txtai/serialize/errors.py@@ -0,0 +1,9 @@+"""+Errors module+"""+++class SerializeError(Exception):+ """+ Raised when data serialization fails+ """diff --git a/src/python/txtai/serialize/factory.py b/src/python/txtai/serialize/factory.pynew file mode 100644index 00000000..2d1bfcc1--- /dev/null+++ b/src/python/txtai/serialize/factory.py@@ -0,0 +1,29 @@+"""+Factory module+"""++from .messagepack import MessagePack+from .pickle import Pickle+++class SerializeFactory:+ """+ Methods to create data serializers.+ """++ @staticmethod+ def create(method=None, **kwargs):+ """+ Creates a new Serialize instance.++ Args:+ method: serialization method+ kwargs: additional keyword arguments to pass to serialize instance+ """++ # Pickle serialization+ if method == "pickle":+ return Pickle(**kwargs)++ # Default serialization+ return MessagePack(**kwargs)diff --git a/src/python/txtai/serialize/messagepack.py b/src/python/txtai/serialize/messagepack.pynew file mode 100644index 00000000..92397d54--- /dev/null+++ b/src/python/txtai/serialize/messagepack.py@@ -0,0 +1,38 @@+"""+MessagePack module+"""++import msgpack+from msgpack import Unpacker+from msgpack.exceptions import ExtraData++from .base import Serialize+from .errors import SerializeError+++class MessagePack(Serialize):+ """+ MessagePack serialization.+ """++ def __init__(self, streaming=False):+ # Parent constructor+ super().__init__()++ self.streaming = streaming++ def loadstream(self, stream):+ try:+ # Support both streaming and non-streaming unpacking of data+ return Unpacker(stream) if self.streaming else msgpack.unpack(stream)+ except ExtraData as e:+ raise SerializeError(e) from e++ def savestream(self, data, stream):+ msgpack.pack(data, stream)++ def loadbytes(self, data):+ return msgpack.unpackb(data)++ def savebytes(self, data):+ return msgpack.packb(data)diff --git a/src/python/txtai/serialize/pickle.py b/src/python/txtai/serialize/pickle.pynew file mode 100644index 00000000..b6915afa--- /dev/null+++ b/src/python/txtai/serialize/pickle.py@@ -0,0 +1,98 @@+"""+Pickle module+"""++import os+import logging+import pickle+import warnings++from .base import Serialize++# Logging configuration+logger = logging.getLogger(__name__)+++class Pickle(Serialize):+ """+ Pickle serialization.+ """++ def __init__(self, allowpickle=False):+ """+ Creates a new instance for Pickle serialization.++ This class ensures the allowpickle parameter or the `ALLOW_PICKLE` environment variable is True. All methods will+ raise errors if this isn't the case.++ Pickle serialization is OK for local data but it isn't recommended when sharing data externally.++ Args:+ allowpickle: default pickle allow mode, only True with methods that generate local temporary data+ """++ # Parent constructor+ super().__init__()++ # Default allow pickle mode+ self.allowpickle = allowpickle++ # Current pickle protocol+ self.version = 4++ def load(self, path):+ # Load pickled data from path, if allowed+ return super().load(path) if self.allow(path) else None++ def save(self, data, path):+ # Save pickled data to path, if allowed+ if self.allow():+ super().save(data, path)++ def loadstream(self, stream):+ # Load pickled data from stream, if allowed+ return pickle.load(stream) if self.allow() else None++ def savestream(self, data, stream):+ # Save pickled data to stream, if allowed+ if self.allow():+ pickle.dump(data, stream, protocol=self.version)++ def loadbytes(self, data):+ # Load pickled data from bytes, if allowed+ return pickle.loads(data) if self.allow() else None++ def savebytes(self, data):+ # Save pickled data to stream, if allowed+ return pickle.dumps(data, protocol=self.version) if self.allow() else None++ def allow(self, path=None):+ """+ Checks if loading and saving pickled data is allowed. Raises an error if it's not allowed.++ Args:+ path: optional path to add to generated error messages+ """++ enablepickle = self.allowpickle or os.environ.get("ALLOW_PICKLE", "True") in ("True", "1")+ if not enablepickle:+ raise ValueError(+ (+ "Loading of pickled index data is disabled. "+ f"`{path if path else 'stream'}` was not loaded. "+ "Set the env variable `ALLOW_PICKLE=True` to enable loading pickled index data. "+ "This should only be done for trusted and/or local data."+ )+ )++ if not self.allowpickle:+ warnings.warn(+ (+ "Pickled index data formats are deprecated and loading will be disabled by default in the future. "+ "Set the env variable `ALLOW_PICKLE=False` to disable the loading of pickled index data formats. "+ "Saving this index will replace pickled index data formats with the latest index formats and remove this warning."+ ),+ FutureWarning,+ )++ return enablepicklediff --git a/src/python/txtai/serialize/serializer.py b/src/python/txtai/serialize/serializer.pynew file mode 100644index 00000000..37de81d2--- /dev/null+++ b/src/python/txtai/serialize/serializer.py@@ -0,0 +1,46 @@+"""+Serializer module+"""++from .errors import SerializeError+from .factory import SerializeFactory+++class Serializer:+ """+ Methods to serialize and deserialize data.+ """++ @staticmethod+ def load(path):+ """+ Loads data from path. This method first tries to load the default serialization format.+ If that fails, it will fallback to pickle format for backwards-compatability purposes.++ Note that loading pickle files requires the env variable `ALLOW_PICKLE=True`.++ Args:+ path: data to load++ Returns:+ data+ """++ try:+ return SerializeFactory.create().load(path)+ except SerializeError:+ # Backwards compatible check for pickled data+ return SerializeFactory.create("pickle").load(path)++ @staticmethod+ def save(data, path):+ """+ Saves data to path.++ Args:+ data: data to save+ path: output path+ """++ # Save using default serialization method+ SerializeFactory.create().save(data, path)diff --git a/test/python/testserialize.py b/test/python/testserialize.pynew file mode 100644index 00000000..07a34a49--- /dev/null+++ b/test/python/testserialize.py@@ -0,0 +1,48 @@+"""+Serialize module tests+"""++import os+import unittest++from unittest.mock import patch++from txtai.serialize import Serialize, SerializeFactory+++class TestSerialize(unittest.TestCase):+ """+ Serialize tests.+ """++ def testNotImplemented(self):+ """+ Test exceptions for non-implemented methods+ """++ serialize = Serialize()++ self.assertRaises(NotImplementedError, serialize.loadstream, None)+ self.assertRaises(NotImplementedError, serialize.savestream, None, None)+ self.assertRaises(NotImplementedError, serialize.loadbytes, None)+ self.assertRaises(NotImplementedError, serialize.savebytes, None)++ def testMessagePack(self):+ """+ Test MessagePack encoder+ """++ serializer = SerializeFactory.create()+ self.assertEqual(serializer.loadbytes(serializer.savebytes("test")), "test")++ @patch.dict(os.environ, {"ALLOW_PICKLE": "False"})+ def testPickleDisabled(self):+ """+ Test disabled pickle serialization+ """++ # Validate an error is raised+ with self.assertRaises(ValueError):+ serializer = SerializeFactory.create("pickle")+ data = serializer.savebytes("Test")+ serializer.loadbytes(data)