A library to generate HTML + JS pages, spun off from folium and based on Jinja2
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Comprehensive collection of helper functions for color processing, image conversion, legend scaling, and data manipulation. These utilities support visualization workflows with ColorBrewer integration, PNG generation, and data transformation capabilities.
Core color parsing functions for converting between different color formats.
def _parse_color(x):
"""
Parse color input to RGBA float tuple.
Parameters:
- x: color input (tuple, list, hex string, or color name)
Returns:
tuple: (r, g, b, a) with float values between 0.0 and 1.0
Raises:
ValueError: if color format is unrecognized
"""
def _color_int_to_float(x: int) -> float:
"""
Convert integer color value (0-255) to float (0.0-1.0).
Parameters:
- x: integer color value between 0 and 255
Returns:
float: converted value between 0.0 and 1.0
"""
def _color_float_to_int(x: float) -> int:
"""
Convert float color value (0.0-1.0) to integer (0-255).
Parameters:
- x: float color value between 0.0 and 1.0
Returns:
int: converted value between 0 and 255
"""
def _is_hex(x: str) -> bool:
"""
Check if string is a valid hex color code.
Parameters:
- x: string to check
Returns:
bool: True if valid hex color (#RRGGBB format)
"""
def _parse_hex(color_code: str):
"""
Parse hex color string to RGBA float tuple.
Parameters:
- color_code: hex color string (#RRGGBB)
Returns:
tuple: (r, g, b, a) with float values between 0.0 and 1.0
"""Generate ColorBrewer color schemes with automatic interpolation for data visualization.
def color_brewer(color_code: str, n: int = 6) -> list:
"""
Generate ColorBrewer color scheme with specified number of colors.
Parameters:
- color_code: ColorBrewer scheme name (e.g., 'YlGnBu', 'Set1', 'RdYlBu_r')
- n: number of colors to generate (3-253)
Returns:
list: hex color strings for the scheme
Raises:
ValueError: if color_code is invalid or n is out of range
TypeError: if n is not an integer
"""
def linear_gradient(hexList: list, nColors: int) -> list:
"""
Create linear color gradient between hex colors.
Parameters:
- hexList: list of hex color strings to interpolate between
- nColors: number of output colors
Returns:
list: hex color strings with smooth gradient
"""
def _base(x: float) -> float:
"""
Calculate base value for logarithmic scaling (used in round_method='log10').
Parameters:
- x: input value
Returns:
float: base value for logarithmic rounding
"""Functions for managing legend displays and scaling data values.
def legend_scaler(legend_values: list, max_labels: int = 10) -> list:
"""
Downsample legend values to prevent text collision on colorbar.
Parameters:
- legend_values: sequence of float values for legend
- max_labels: maximum number of labels to display
Returns:
list: downsampled legend values with empty strings as spacers
"""Convert image data to web-compatible formats with colormap support.
def image_to_url(
image,
colormap = None,
origin: str = "upper"
) -> str:
"""
Convert image data to base64 data URL for web embedding.
Parameters:
- image: string URL, file object, or array-like image data
- colormap: ColorMap instance or callable for mono images
- origin: image origin placement ('upper' or 'lower')
Returns:
str: base64 data URL string for HTML embedding
"""
def write_png(
data,
origin: str = "upper",
colormap = None
) -> bytes:
"""
Convert array data to PNG byte string.
Parameters:
- data: numpy array (NxM mono, NxMx3 RGB, or NxMx4 RGBA)
- origin: image origin placement ('upper' or 'lower')
- colormap: ColorMap instance or callable for mono images
Returns:
bytes: PNG formatted byte string
Raises:
ImportError: if NumPy is not available
ValueError: if data dimensions are invalid
"""Access to Jinja2 template environment for custom template rendering.
def get_templates():
"""
Get Jinja2 environment with branca template loader.
Returns:
Environment: configured Jinja2 environment for branca templates
"""Helper functions for processing coordinate data and handling optional values.
def none_min(x: float | None, y: float | None) -> float | None:
"""
Return minimum of two optional float values.
Parameters:
- x: optional float value
- y: optional float value
Returns:
Optional float: minimum value, or None if both are None
"""
def none_max(x: float | None, y: float | None) -> float | None:
"""
Return maximum of two optional float values.
Parameters:
- x: optional float value
- y: optional float value
Returns:
Optional float: maximum value, or None if both are None
"""
def iter_points(x: list | tuple) -> list:
"""
Flatten nested coordinate structures to simple point list.
Parameters:
- x: nested list/tuple structure of coordinates
Returns:
list: flattened list of coordinate points
Raises:
ValueError: if input is not list or tuple type
"""from branca.utilities import color_brewer
# Generate standard ColorBrewer schemes
blues = color_brewer('Blues', 9)
# Returns: ['#f7fbff', '#deebf7', '#c6dbef', '#9ecae1',
# '#6baed6', '#4292c6', '#2171b5', '#08519c', '#08306b']
# Generate reversed scheme
reds_reversed = color_brewer('Reds_r', 5)
# Generate diverging scheme
rd_yl_bu = color_brewer('RdYlBu', 11)import numpy as np
from branca.utilities import image_to_url, write_png
from branca.colormap import LinearColormap
# Create sample data
data = np.random.rand(100, 100)
# Convert with custom colormap
colormap = LinearColormap(['blue', 'red'])
data_url = image_to_url(data, colormap=colormap, origin='upper')
# Generate PNG bytes for file saving
png_bytes = write_png(data, colormap=colormap)
with open('output.png', 'wb') as f:
f.write(png_bytes)
# Convert existing image file
with open('input.jpg', 'rb') as f:
image_url = image_to_url(f)from branca.utilities import legend_scaler
# Scale down large number of legend values
values = list(range(0, 101, 5)) # [0, 5, 10, ..., 100]
scaled = legend_scaler(values, max_labels=6)
# Returns: [0, '', '', '', 20, '', '', '', 40, '', '', '', 60, '', '', '', 80, '', '', '', 100]from branca.utilities import linear_gradient
# Create gradient between colors
colors = ['#ff0000', '#00ff00', '#0000ff'] # Red, green, blue
gradient = linear_gradient(colors, 20) # 20 interpolated colorsfrom branca.utilities import iter_points, none_min, none_max
# Flatten nested coordinate structures
nested_coords = [[[1, 2], [3, 4]], [[5, 6]], [7, 8]]
flat_points = iter_points(nested_coords)
# Returns: [[1, 2], [3, 4], [5, 6], [7, 8]]
# Handle optional values
bounds = [
[none_min(1.0, None), none_min(2.0, 1.5)], # [1.0, 1.5]
[none_max(None, 3.0), none_max(4.0, 3.5)] # [3.0, 4.0]
]from branca.utilities import get_templates
# Access branca template environment
env = get_templates()
template = env.get_template('color_scale.js')
rendered = template.render(colormap_data={'vmin': 0, 'vmax': 100})# Size parsing type for CSS dimensions
TypeParseSize = int | float | str | tuple[float, str]These functions are used internally by branca but may be useful for advanced customization:
def _camelify(out: str) -> str:
"""Convert string to camelCase with underscores."""
def _parse_size(value) -> tuple[float, str]:
"""Parse size values to (number, unit) tuples."""
def _locations_mirror(x):
"""Mirror coordinate order in nested structures."""
def _locations_tolist(x):
"""Convert nested iterables to lists recursively."""The utilities module has the following optional dependencies:
image_to_url() and write_png() functionsWhen numpy is not available, image processing functions will raise ImportError with helpful messages.
Install with Tessl CLI
npx tessl i tessl/pypi-branca