Skip to content

Renderer

Renderer

This module provides utilities for rendering data in various formats, specifically focusing on rendering Volatility framework data into JSON and pandas DataFrames.

Classes:

Name Description
TreeGrid_to_json

A class for rendering Volatility TreeGrid data into JSON format.

Renderer

A class for rendering data into human-readable formats such as lists, JSON strings, and pandas DataFrames.

Renderer

Class for rendering data in various formats.

This class provides methods to render data into human-readable formats such as lists, JSON strings, and pandas DataFrames.

Attributes:

Name Type Description
data Any

The input data to be rendered.

Source code in pydfirram/core/renderer.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
class Renderer():
    """
    Class for rendering data in various formats.

    This class provides methods to render data into human-readable formats
    such as lists, JSON strings, and pandas DataFrames.

    Attributes:
        data (Any): The input data to be rendered.
    """

    def __init__(self, data: Any) -> None:
        """
        Initialize the Renderer with the provided data.

        Args:
            data (Any): The input data to be rendered.
        """
        self.data = data

    def to_list(self):
        """
        Convert the data to a list format.

        This method attempts to render the input data using the
        TreeGrid_to_json class, and convert it to a dictionary.

        Returns:
            Dict: The rendered data in list format.

        Raises:
            Exception: If rendering the data fails.
        """
        try:
            # (fixme) : `render()` should return nothing
            parsed_data : dict[str, Any] = TreeGrid_to_json().render(self.data)
            return parsed_data.get("data")
        except Exception as e:
            logger.error("Impossible to render data in dictionary form.")
            raise e

    def file_render(self)-> None:
        """
        Convert the data to a list format.

        This method attempts to render the input data using the
        TreeGrid_to_json class, and convert it to a dictionary.

        Returns:
            Dict: The rendered data in list format.

        Raises:
            Exception: If rendering the data fails.
        """
        try:
            # (fixme) : `render()` return nothing
            TreeGrid_to_json().render(self.data)
        except Exception as e:
            logger.error("Impossible to render data in dictionary form.")
            raise e

    def to_json(self) -> str:
        """
        Convert the data to a JSON string.

        This method first converts the data to a list format, and then
        serializes it to a JSON string.

        Returns:
            str: The data serialized as a JSON string.

        Raises:
            Exception: If converting the data to JSON fails.
        """
        try:
            data_as_dict = self.to_list()
            return dumps(data_as_dict)
        except Exception as e:
            logger.error("Unable to convert data to JSON.")
            raise e

    def to_df(self,max_row: bool = False) -> pd.DataFrame:
        """
        Convert the data to a pandas DataFrame.

        This method first converts the data to a list format, and then
        constructs a pandas DataFrame from it.

        Returns:
            pd.DataFrame: The data as a pandas DataFrame.

        Raises:
            Exception: If rendering the data as a DataFrame fails.
        """
        try:
            data_as_dict = self.to_list()
            if max_row:
                pd.set_option('display.max_rows', None)
                pd.set_option('display.max_columns', None)
            return pd.DataFrame(data_as_dict)
        except Exception as e:
            logger.error("Data cannot be rendered as a DataFrame.")
            raise e

__init__(data)

Initialize the Renderer with the provided data.

Parameters:

Name Type Description Default
data Any

The input data to be rendered.

required
Source code in pydfirram/core/renderer.py
151
152
153
154
155
156
157
158
def __init__(self, data: Any) -> None:
    """
    Initialize the Renderer with the provided data.

    Args:
        data (Any): The input data to be rendered.
    """
    self.data = data

file_render()

Convert the data to a list format.

This method attempts to render the input data using the TreeGrid_to_json class, and convert it to a dictionary.

Returns:

Name Type Description
Dict None

The rendered data in list format.

Raises:

Type Description
Exception

If rendering the data fails.

Source code in pydfirram/core/renderer.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
def file_render(self)-> None:
    """
    Convert the data to a list format.

    This method attempts to render the input data using the
    TreeGrid_to_json class, and convert it to a dictionary.

    Returns:
        Dict: The rendered data in list format.

    Raises:
        Exception: If rendering the data fails.
    """
    try:
        # (fixme) : `render()` return nothing
        TreeGrid_to_json().render(self.data)
    except Exception as e:
        logger.error("Impossible to render data in dictionary form.")
        raise e

to_df(max_row=False)

Convert the data to a pandas DataFrame.

This method first converts the data to a list format, and then constructs a pandas DataFrame from it.

Returns:

Type Description
DataFrame

pd.DataFrame: The data as a pandas DataFrame.

Raises:

Type Description
Exception

If rendering the data as a DataFrame fails.

Source code in pydfirram/core/renderer.py
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
def to_df(self,max_row: bool = False) -> pd.DataFrame:
    """
    Convert the data to a pandas DataFrame.

    This method first converts the data to a list format, and then
    constructs a pandas DataFrame from it.

    Returns:
        pd.DataFrame: The data as a pandas DataFrame.

    Raises:
        Exception: If rendering the data as a DataFrame fails.
    """
    try:
        data_as_dict = self.to_list()
        if max_row:
            pd.set_option('display.max_rows', None)
            pd.set_option('display.max_columns', None)
        return pd.DataFrame(data_as_dict)
    except Exception as e:
        logger.error("Data cannot be rendered as a DataFrame.")
        raise e

to_json()

Convert the data to a JSON string.

This method first converts the data to a list format, and then serializes it to a JSON string.

Returns:

Name Type Description
str str

The data serialized as a JSON string.

Raises:

Type Description
Exception

If converting the data to JSON fails.

Source code in pydfirram/core/renderer.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
def to_json(self) -> str:
    """
    Convert the data to a JSON string.

    This method first converts the data to a list format, and then
    serializes it to a JSON string.

    Returns:
        str: The data serialized as a JSON string.

    Raises:
        Exception: If converting the data to JSON fails.
    """
    try:
        data_as_dict = self.to_list()
        return dumps(data_as_dict)
    except Exception as e:
        logger.error("Unable to convert data to JSON.")
        raise e

to_list()

Convert the data to a list format.

This method attempts to render the input data using the TreeGrid_to_json class, and convert it to a dictionary.

Returns:

Name Type Description
Dict

The rendered data in list format.

Raises:

Type Description
Exception

If rendering the data fails.

Source code in pydfirram/core/renderer.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def to_list(self):
    """
    Convert the data to a list format.

    This method attempts to render the input data using the
    TreeGrid_to_json class, and convert it to a dictionary.

    Returns:
        Dict: The rendered data in list format.

    Raises:
        Exception: If rendering the data fails.
    """
    try:
        # (fixme) : `render()` should return nothing
        parsed_data : dict[str, Any] = TreeGrid_to_json().render(self.data)
        return parsed_data.get("data")
    except Exception as e:
        logger.error("Impossible to render data in dictionary form.")
        raise e

TreeGrid_to_json

Bases: CLIRenderer

simple TreeGrid to JSON

Source code in pydfirram/core/renderer.py
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
class TreeGrid_to_json(V3CLIRenderer):  # type: ignore
    """ simple TreeGrid to JSON
    """
    _type_renderers: Any = {
        V3HexBytes: lambda x: v3_quoted_optional(
            v3_hex_bytes_as_text,
        )(x),
        V3Disassembly: lambda x: v3_quoted_optional(
            v3_display_disassembly,
        )(x),
        V3MultiTypeData: lambda x: v3_quoted_optional(
            v3_multitypedata_as_text,
        )(x),
        bytes: lambda x: v3_optional(
            lambda x: " ".join([f"{b:02x}" for b in x])
        )(x),
        datetime.datetime: lambda x: (
            x.isoformat() if not isinstance(x, V3BaseAbsentValue) else None
        ),
        "default": lambda x: x,
    }

    name = "JSON"
    structured_output = True

    def get_render_options(self) -> list[V3RenderOption]:
        """
        Get render options.
        """
        return []

    # (fixme): This method should return nothing as defined in V3CLIRenderer
    def render(self, grid: V3TreeGrid) -> dict[str, Any]:
        """
        Render the TreeGrid to JSON format.

        Args:
            grid (interfaces.renderers.TreeGrid): The TreeGrid to render.

        Returns:
            Dict: The JSON representation of the TreeGrid.
        """
        final_output: tuple[
            dict[str, dict[str, Any]],
            list[dict[str, Any]],
        ] = ({}, [])

        def visitor(
            node: V3TreeNode,
            accumulator: tuple[dict[str, Any], list[dict[str, Any]]],
        ) -> tuple[dict[str, Any], list[dict[str, Any]]]:
            """
            A visitor function to process each node in the TreeGrid.

            Args:
                node (V3TreeNode): The current node being visited.
                accumulator (Tuple[Dict[str, Any], List[Dict[str, Any]]]):
                    The accumulator containing the accumulated results.

            Returns:
                Tuple[Dict[str, Any], List[Dict[str, Any]]]: The updated
                    accumulator.
            """
            acc_map = accumulator[0]
            final_tree = accumulator[1]
            node_dict: dict[str, Any] = {"__children": []}

            for column_index, column in enumerate(grid.columns):
                renderer = self._type_renderers.get(
                    column.type,
                    self._type_renderers["default"]
                )
                data = renderer(
                    list(node.values)[column_index],
                )
                if isinstance(data, V3BaseAbsentValue):
                    data = None
                node_dict[column.name] = data

            if node.parent:
                acc_map[node.parent.path]["__children"].append(node_dict)
            else:
                final_tree.append(node_dict)
            acc_map[node.path] = node_dict
            return acc_map, final_tree

        if not grid.populated:
            grid.populate(visitor, final_output)
        else:
            grid.visit(
                node=None,
                function=visitor,
                initial_accumulator=final_output,
            )
        return {"data": final_output[1]}

get_render_options()

Get render options.

Source code in pydfirram/core/renderer.py
68
69
70
71
72
def get_render_options(self) -> list[V3RenderOption]:
    """
    Get render options.
    """
    return []

render(grid)

Render the TreeGrid to JSON format.

Parameters:

Name Type Description Default
grid TreeGrid

The TreeGrid to render.

required

Returns:

Name Type Description
Dict dict[str, Any]

The JSON representation of the TreeGrid.

Source code in pydfirram/core/renderer.py
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def render(self, grid: V3TreeGrid) -> dict[str, Any]:
    """
    Render the TreeGrid to JSON format.

    Args:
        grid (interfaces.renderers.TreeGrid): The TreeGrid to render.

    Returns:
        Dict: The JSON representation of the TreeGrid.
    """
    final_output: tuple[
        dict[str, dict[str, Any]],
        list[dict[str, Any]],
    ] = ({}, [])

    def visitor(
        node: V3TreeNode,
        accumulator: tuple[dict[str, Any], list[dict[str, Any]]],
    ) -> tuple[dict[str, Any], list[dict[str, Any]]]:
        """
        A visitor function to process each node in the TreeGrid.

        Args:
            node (V3TreeNode): The current node being visited.
            accumulator (Tuple[Dict[str, Any], List[Dict[str, Any]]]):
                The accumulator containing the accumulated results.

        Returns:
            Tuple[Dict[str, Any], List[Dict[str, Any]]]: The updated
                accumulator.
        """
        acc_map = accumulator[0]
        final_tree = accumulator[1]
        node_dict: dict[str, Any] = {"__children": []}

        for column_index, column in enumerate(grid.columns):
            renderer = self._type_renderers.get(
                column.type,
                self._type_renderers["default"]
            )
            data = renderer(
                list(node.values)[column_index],
            )
            if isinstance(data, V3BaseAbsentValue):
                data = None
            node_dict[column.name] = data

        if node.parent:
            acc_map[node.parent.path]["__children"].append(node_dict)
        else:
            final_tree.append(node_dict)
        acc_map[node.path] = node_dict
        return acc_map, final_tree

    if not grid.populated:
        grid.populate(visitor, final_output)
    else:
        grid.visit(
            node=None,
            function=visitor,
            initial_accumulator=final_output,
        )
    return {"data": final_output[1]}