Theme Serializer#
- class ThemePickleJSONSerializer[source]#
Bases:
objectSerialize plotnine themes to JSON with embedded pickle data.
This class provides a high-level interface for serializing and deserializing plotnine theme objects to/from JSON format. It combines JSON readability with pickle’s perfect object serialization capabilities, allowing complex theme objects to be stored and transferred as JSON while maintaining complete fidelity.
The serializer uses the PickleJSONEncoder and PickleJSONDecoder classes internally to handle the conversion between plotnine objects and JSON structures with embedded pickled data.
- Attributes:
- encoderPickleJSONEncoder
The JSON encoder class for serializing plotnine objects
- decoderPickleJSONDecoder
The JSON decoder class for deserializing pickled objects
Notes
This serializer is specifically designed for plotnine theme objects but can handle any plotnine object that contains “plotnine” in its type string.
Examples
>>> from brisk.theme.theme_serializer import ThemePickleJSONSerializer >>> import plotnine as pn >>> >>> # Create a theme >>> theme = pn.theme_minimal() + pn.theme(text=pn.element_text(size=14)) >>> >>> # Serialize to JSON >>> serializer = ThemePickleJSONSerializer() >>> json_str = serializer.theme_to_json(theme) >>> >>> # Deserialize from JSON >>> restored_theme = serializer.theme_from_json(json_str) >>> >>> # Get theme metadata >>> info = serializer.get_theme_info(json_str)
- get_theme_info(json_str: str) Dict[str, Any][source]#
Extract metadata from JSON without fully deserializing the theme.
This method extracts metadata about a pickled theme object from a JSON string without actually deserializing the theme. This is useful for inspecting theme properties without the overhead of full deserialization.
- Parameters:
- json_strstr
JSON string containing the pickled theme object
- Returns:
- Dict[str, Any]
Dictionary containing metadata about the pickled theme: - pickled_type: Class name of the pickled object - pickled_module: Module where the class is defined - data_size_bytes: Approximate size of the pickled data - has_checksum: Whether the data includes a checksum - error: Error message if parsing failed
Notes
The method calculates the approximate size of the pickled data by multiplying the base64 string length by 3/4, which gives a rough estimate of the original binary data size.
Examples
>>> from brisk.theme.theme_serializer import ThemePickleJSONSerializer >>> import plotnine as pn >>> >>> theme = pn.theme_minimal() >>> serializer = ThemePickleJSONSerializer() >>> json_str = serializer.theme_to_json(theme) >>> info = serializer.get_theme_info(json_str) >>> print(f"Type: {info['pickled_type']}") >>> print(f"Size: {info['data_size_bytes']} bytes")
- theme_from_json(json_str: str) Any[source]#
Deserialize theme object from JSON with embedded pickle data.
This method converts a JSON string containing pickled theme data back into a plotnine theme object. It uses the custom decoder to handle the deserialization of pickled objects.
- Parameters:
- json_strstr
JSON string containing the pickled theme object
- Returns:
- Any
The deserialized plotnine theme object
Notes
The method uses json.loads with the custom decoder hook to automatically deserialize any pickled objects in the JSON. If the JSON contains a “theme” key, it returns that value; otherwise, it returns the entire deserialized data.
Examples
>>> from brisk.theme.theme_serializer import ThemePickleJSONSerializer >>> >>> # JSON string containing pickled theme >>> json_str = '{"theme": {"_pickled_object": true, ...}}' >>> serializer = ThemePickleJSONSerializer() >>> theme = serializer.theme_from_json(json_str) >>> # theme is now a plotnine theme object
- theme_to_json(theme_obj: Any) str[source]#
Serialize theme object to JSON with embedded pickle data.
This method converts a plotnine theme object into a JSON string that contains the pickled theme data. The theme is wrapped in a container object and serialized using the custom encoder.
- Parameters:
- theme_objAny
The plotnine theme object to serialize
- Returns:
- str
JSON string containing the pickled theme object
Notes
The method wraps the theme object in a container with the key “theme” and uses the custom PickleJSONEncoder to handle the serialization. The resulting JSON is compact with no extra spaces.
Examples
>>> from brisk.theme.theme_serializer import ThemePickleJSONSerializer >>> import plotnine as pn >>> >>> theme = pn.theme_minimal() >>> serializer = ThemePickleJSONSerializer() >>> json_str = serializer.theme_to_json(theme) >>> print(json_str[:100]) # Shows start of JSON string
- class PickleJSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]#
Bases:
JSONEncoderCustom JSON encoder that can embed pickled objects as base64 strings.
This encoder extends the standard JSON encoder to handle plotnine theme objects by pickling them and embedding the pickled data as base64-encoded strings within the JSON structure. This allows for perfect serialization of complex theme objects while maintaining JSON compatibility.
The encoder automatically detects plotnine objects and converts them to a special JSON structure containing the pickled data, metadata, and integrity checksum.
Notes
The encoder creates a special JSON structure for plotnine objects: - _pickled_object: Boolean flag indicating this is a pickled object - _type: Class name of the original object - _module: Module name where the class is defined - _data: Base64-encoded pickled data - _checksum: MD5 checksum for data integrity verification
Examples
>>> import plotnine as pn >>> from brisk.theme.theme_serializer import PickleJSONEncoder >>> import json >>> >>> theme = pn.theme_minimal() >>> encoder = PickleJSONEncoder() >>> json_str = json.dumps(theme, cls=encoder)
- default(o: Any) Any[source]#
Encode plotnine objects as pickled base64 strings.
This method overrides the default JSON encoding behavior to handle plotnine theme objects specially. It detects plotnine objects and converts them to a JSON-compatible structure containing pickled data.
- Parameters:
- oAny
The object to encode
- Returns:
- Any
JSON-serializable representation of the object, or calls super().default(o) for non-plotnine objects
Notes
The method checks if the object is a plotnine object by looking for “plotnine” in the type string. If it is, it pickles the object, encodes it as base64, and wraps it in a special JSON structure.
- class PickleJSONDecoder[source]#
Bases:
objectCustom JSON decoder that can restore pickled objects from base64 strings.
This decoder provides functionality to restore plotnine theme objects from JSON structures that contain embedded pickled data. It works as a hook function for json.loads to automatically detect and deserialize pickled objects during JSON parsing.
The decoder includes integrity checking through MD5 checksums to ensure that the pickled data has not been corrupted during storage or transfer.
Notes
The decoder looks for objects with the “_pickled_object” flag and attempts to deserialize them. If deserialization fails or checksums don’t match, it returns the original object and prints a warning.
Examples
>>> from brisk.theme.theme_serializer import PickleJSONDecoder >>> import json >>> >>> # JSON string containing pickled theme >>> json_str = '{"theme": {"_pickled_object": true, ...}}' >>> data = json.loads(json_str, object_hook=PickleJSONDecoder.decode_hook) >>> theme = data["theme"] # Restored plotnine theme object
- static decode_hook(obj: Any) Any[source]#
Hook function for json.loads to decode pickled objects.
This static method serves as a hook function for json.loads to automatically detect and deserialize pickled objects embedded in JSON structures. It includes integrity checking and error handling.
- Parameters:
- objAny
The object being processed during JSON deserialization
- Returns:
- Any
The deserialized object if it was pickled, or the original object if it wasn’t a pickled object
Notes
The method checks for the “_pickled_object” flag and attempts to deserialize the object. It verifies data integrity using MD5 checksums and handles errors gracefully by returning the original object and printing a warning.