Customizing Deck Content with Renderers
Customizing Deck Content with Renderers provides a flexible mechanism for transforming diverse data types and content into HTML for display within dynamic reports or "decks." This capability allows developers to embed rich, interactive, and context-specific information directly into their output, enhancing readability and utility.
The core of this system is the Renderable protocol, which defines a standard contract for any object capable of converting its content into an HTML string. By adhering to this protocol, various data structures and content formats can be seamlessly integrated and rendered.
Available Renderers
Several specialized renderers are available, each designed to handle a specific content type and convert it into a suitable HTML representation.
TopFrameRenderer
The TopFrameRenderer converts Pandas DataFrames into HTML tables. It offers control over the maximum number of rows and columns displayed, which is useful for presenting large datasets concisely.
import pandas as pd
# Assuming TopFrameRenderer is imported from the core classes
# from core_classes import TopFrameRenderer
df = pd.DataFrame({'col1': [1, 2, 3, 4, 5], 'col2': ['A', 'B', 'C', 'D', 'E']})
renderer = TopFrameRenderer(max_rows=3, max_cols=2)
html_output = renderer.to_html(df)
print(html_output)
MarkdownRenderer
The MarkdownRenderer transforms Markdown formatted text into its corresponding HTML representation. This enables developers to include richly formatted text, headings, lists, and links in their deck content without directly writing HTML.
# Assuming MarkdownRenderer is imported from the core classes
# from core_classes import MarkdownRenderer
markdown_text = """
# Report Summary
This section provides a **brief overview** of the results.
- Key finding 1
- Key finding 2
Visit our [website](https://example.com) for more details.
"""
renderer = MarkdownRenderer()
html_output = renderer.to_html(markdown_text)
print(html_output)
SourceCodeRenderer
The SourceCodeRenderer converts Python source code into syntax-highlighted HTML. It leverages the Pygments library to apply a "colorful" style, making code snippets highly readable. This is particularly useful for documenting algorithms, functions, or entire script sections.
# Assuming SourceCodeRenderer is imported from the core classes
# from core_classes import SourceCodeRenderer
python_code = """
def factorial(n):
\"\"\"Calculate the factorial of a non-negative integer.\"\"\"
if n == 0:
return 1
else:
return n * factorial(n-1)
result = factorial(5)
print(f"Factorial of 5 is: {result}")
"""
renderer = SourceCodeRenderer(title="Factorial Function")
html_output = renderer.to_html(python_code)
print(html_output)
ArrowRenderer
The ArrowRenderer renders Apache Arrow Tables as HTML strings. This provides a way to display columnar data efficiently stored in the Arrow format.
import pyarrow as pa
# Assuming ArrowRenderer is imported from the core classes
# from core_classes import ArrowRenderer
table = pa.table([
pa.array([101, 102, 103], type=pa.int64()),
pa.array(['apple', 'banana', 'cherry'], type=pa.string())
], names=['product_id', 'item_name'])
renderer = ArrowRenderer()
html_output = renderer.to_html(table)
print(html_output)
PythonDependencyRenderer
The PythonDependencyRenderer generates a comprehensive HTML report of the Python packages installed in the current environment. This renderer is unique as it does not take an input argument but dynamically fetches dependency information using pip. It includes a convenient button to copy the dependencies as a requirements.txt file, which is crucial for ensuring reproducibility and managing environments.
# Assuming PythonDependencyRenderer is imported from the core classes
# from core_classes import PythonDependencyRenderer
renderer = PythonDependencyRenderer(title="Project Dependencies")
html_output = renderer.to_html()
print(html_output)
Implementing Custom Renderers and Common Use Cases
Developers can extend the system by creating their own custom renderers. Any class that implements the Renderable protocol by providing a to_html(self, python_value: Any) -> str method can be used to transform custom data types or generate specialized HTML content. This allows for highly tailored content generation, such as embedding interactive charts, custom visualizations, or domain-specific data representations.
from typing import Any, Protocol
# The Renderable protocol defines the contract for custom renderers
class Renderable(Protocol):
def to_html(self, python_value: Any) -> str:
"""Convert an object to HTML and return HTML as a unicode string."""
raise NotImplementedError
# Example of a custom renderer for a simple list of strings
class ListRenderer:
def to_html(self, items: list[str]) -> str:
html = "<ul>"
for item in items:
html += f"<li>{item}</li>"
html += "</ul>"
return html
my_list_data = ["First item", "Second item", "Third item"]
custom_renderer = ListRenderer()
html_output = custom_renderer.to_html(my_list_data)
print(html_output)
Common Use Cases
- Data Reporting: Displaying statistical summaries, data samples, or intermediate results from data processing pipelines using
TopFrameRendererorArrowRenderer. - Documentation and Explanations: Embedding rich text descriptions, methodology explanations, or user guides directly within reports using
MarkdownRenderer. - Code Auditing and Sharing: Including relevant source code snippets with syntax highlighting to explain logic or share reproducible examples using
SourceCodeRenderer. - Environment Reproducibility: Automatically documenting the exact Python package versions used for a specific execution, ensuring that others can replicate the environment using
PythonDependencyRenderer. - Custom Visualizations: Developing custom renderers to embed interactive plots (e.g., from Plotly, Bokeh), custom tables, or domain-specific graphical representations that are not covered by the built-in renderers.