SVG Generation

This module handles SVG document generation and manipulation for QR codes.

SVG Builder System

SVG generation and manipulation subsystem.

This package provides comprehensive SVG document creation, styling, and manipulation capabilities for QR code generation.

Key Components:

InteractiveSVGBuilder: Main builder for creating SVG documents

with support for CSS styling, backgrounds, and interactive features.

PathClipper: Utilities for clipping SVG paths to frame boundaries.

The SVG subsystem handles:

  • SVG document structure and namespaces

  • CSS style injection and management

  • Background and foreground layering

  • Interactive hover effects and tooltips

  • Proper XML formatting and encoding

  • Path manipulation and clipping

  • Frame boundary enforcement

Example

Basic usage of the SVG builder:

from segnomms.svg import InteractiveSVGBuilder

builder = InteractiveSVGBuilder()
svg_root = builder.create_svg_root(200, 200)
builder.add_styles(svg_root, interactive=True)
builder.add_background(svg_root, 200, 200, 'white')

See also

segnomms.svg.core: Core SVG building implementation segnomms.svg.interactivity: Interactive features segnomms.svg.path_clipper: Path clipping utilities

class segnomms.svg.InteractiveSVGBuilder(accessibility_config=None)[source]

Bases: SVGBuilder

Main SVG builder that composes all specialized builders.

This class maintains the same interface as the original monolithic SVGBuilder while delegating to specialized builders internally.

Parameters:

accessibility_config (AccessibilityConfig | None)

__init__(accessibility_config=None)[source]

Initialize the composite SVG builder.

Parameters:

accessibility_config (Optional[AccessibilityConfig]) – Configuration for accessibility features

add_background(svg, width, height, color, **kwargs)[source]

Add a background rectangle to the SVG.

Return type:

None

Parameters:
add_centerpiece_metadata(svg, config, bounds, scale, border)[source]

Add metadata about centerpiece location for overlay applications.

Return type:

None

Parameters:
add_definitions(svg, definitions_or_gradients=None, patterns=None, filters=None)[source]

Add definitions section to SVG.

Parameters:
  • svg (Element) – SVG element to add definitions to

  • definitions_or_gradients (Union[Dict[str, Any], List[GradientConfig], None]) – Either a dictionary containing definitions structure or a list of GradientConfig objects (backward compatibility)

  • patterns (Optional[List[Dict[str, Any]]]) – List of pattern definitions (when not using dictionary format)

  • filters (Optional[List[Dict[str, Any]]]) – List of filter definitions (when not using dictionary format)

Return type:

Element

add_frame_definitions(svg, frame_config, width, height, border_pixels)[source]

Add frame shape definitions to SVG defs section.

Return type:

Optional[str]

Parameters:
add_interaction_handlers(svg)[source]

Add default interaction handlers to the SVG.

Return type:

None

Parameters:

svg (Element)

add_javascript(svg, script_content)[source]

Add JavaScript code to the SVG document.

Return type:

None

Parameters:
add_quiet_zone_with_style(svg, config, width, height)[source]

Add styled quiet zone to the SVG.

Return type:

None

Parameters:
add_styles(svg, interactive=False, animation_config=None)[source]

Add CSS styles to the SVG.

Return type:

None

Parameters:
add_svg_accessibility_elements(svg, title=None, description=None)[source]

Add native SVG accessibility elements (<title> and <desc>).

These elements are part of the SVG specification and provide accessibility information that works in all contexts.

Return type:

None

Parameters:
add_title_and_description(svg, title=None, description=None)[source]

Add title and description elements for accessibility.

DEPRECATED: Use add_svg_accessibility_elements() for clarity. Kept for backward compatibility.

Return type:

None

Parameters:
create_layered_structure(svg)[source]

Create a semantic layered structure for the SVG.

Return type:

Dict[str, Element]

Parameters:

svg (Element)

create_svg_root(width, height, **kwargs)[source]

Create the root SVG element with accessibility features.

Handles both web accessibility (ARIA attributes) and SVG accessibility (title/desc elements) for complete coverage.

Return type:

Element

Parameters:
enhance_module_accessibility(element, row, col, module_type='data')[source]

Enhance accessibility for individual QR modules.

Return type:

None

Parameters:
enhance_pattern_group_accessibility(group_element, pattern_type, module_count)[source]

Enhance accessibility for pattern groups.

Return type:

None

Parameters:
get_accessibility_report()[source]

Get a report of accessibility features applied.

Return type:

Dict[str, Any]

validate_accessibility()[source]

Validate accessibility compliance.

Return type:

List[str]

class segnomms.svg.CoreSVGBuilder[source]

Bases: SVGBuilder

Core SVG document builder for basic operations.

Handles fundamental SVG operations like creating root elements, adding CSS styles, and managing background elements.

add_background(svg, width, height, color, **kwargs)[source]

Add a background rectangle to the SVG.

Parameters:
  • svg (Element) – SVG element to add background to

  • width (int) – Width of the background

  • height (int) – Height of the background

  • color (str) – Background color

  • **kwargs (Any) – Additional background configuration options

Return type:

None

add_styles(svg, interactive=False, animation_config=None)[source]

Add CSS styles to the SVG.

Parameters:
  • svg (Element) – SVG element to add styles to

  • interactive (bool) – Whether to include interactive hover styles

  • animation_config (Optional[Dict[str, Any]]) – Optional animation configuration dict

Return type:

None

create_svg_root(width, height, **kwargs)[source]

Create the root SVG element with proper attributes and namespaces.

Parameters:
  • width (int) – Width of the SVG in pixels

  • height (int) – Height of the SVG in pixels

  • **kwargs (Any) – Additional attributes for the SVG element

Return type:

Element

Returns:

Root SVG Element with configured attributes

class segnomms.svg.DefinitionsBuilder[source]

Bases: object

Builder for SVG definition elements.

Manages gradients, patterns, filters, and other reusable SVG elements that belong in the <defs> section.

add_definitions(svg, gradients=None, patterns=None, filters=None)[source]

Add definitions section to SVG with gradients, patterns, and filters.

Parameters:
Return type:

Element

Returns:

The defs element

class segnomms.svg.InteractivityBuilder[source]

Bases: object

Builder for SVG interactive features.

Manages JavaScript injection, event handlers, and interactive behaviors for SVG elements.

add_animation_controls(svg, animations)[source]

Add animation control handlers.

Parameters:
  • svg (Element) – SVG element to add animation controls to

  • animations (List[Dict[str, str]]) – List of animation configurations

Return type:

None

add_custom_interaction(svg, element_selector, event_type, handler_code)[source]

Add a custom interaction handler to specific elements.

Parameters:
  • svg (Element) – SVG element to add handler to

  • element_selector (str) – CSS selector for target elements

  • event_type (str) – Event type (e.g., ‘click’, ‘hover’, ‘focus’)

  • handler_code (str) – JavaScript handler code

Return type:

None

add_interaction_handlers(svg)[source]

Add default interaction handlers to the SVG.

Adds standard interaction handlers for tooltips, click events, and hover effects.

Parameters:

svg (Element) – SVG element to add handlers to

Return type:

None

add_javascript(svg, script_content)[source]

Add JavaScript code to the SVG document.

Parameters:
  • svg (Element) – SVG element to add JavaScript to

  • script_content (str) – JavaScript code to embed

Return type:

None

configure_interaction(element, config)[source]

Configure interaction settings for a specific element.

Parameters:
Return type:

None

class segnomms.svg.FrameVisualBuilder[source]

Bases: object

Builder for frame shapes and visual effects.

Manages frame definitions, quiet zone styling, centerpiece metadata, and other visual enhancements for QR codes.

add_centerpiece_metadata(svg, config, qr_bounds, scale)[source]

Add metadata for centerpiece/reserve area.

Parameters:
  • svg (Element) – SVG element to add metadata to

  • config (Union[RenderingConfig, CenterpieceConfig]) – Rendering configuration with centerpiece settings

  • qr_bounds (Tuple[int, int, int, int]) – Tuple of (x, y, width, height) for QR code bounds

  • scale (int) – Scale factor for module size calculations

Return type:

None

add_frame_definitions(svg, frame_config, qr_size, module_count)[source]

Add frame shape definitions to the SVG.

Parameters:
  • svg (Element) – SVG element to add frame definitions to

  • frame_config (FrameConfig) – Frame configuration object

  • qr_size (int) – Size of the QR code in pixels

  • module_count (int) – Number of modules in the QR code

Return type:

Optional[str]

Returns:

ID of the frame clip path if created

add_quiet_zone_with_style(svg, config, qr_bounds)[source]

Add styled quiet zone to the SVG.

Parameters:
  • svg (Element) – SVG element to add quiet zone to

  • config (QuietZoneConfig) – Rendering configuration with quiet_zone settings

  • qr_bounds (Tuple[int, int, int, int]) – Tuple of (x, y, width, height) for QR code bounds

Return type:

None

class segnomms.svg.AccessibilityBuilder(accessibility_config=None)[source]

Bases: object

Builder for SVG accessibility features.

Manages ARIA attributes, semantic structure, titles, descriptions, and other accessibility enhancements.

Parameters:

accessibility_config (AccessibilityConfig | None)

__init__(accessibility_config=None)[source]

Initialize the accessibility builder.

Parameters:

accessibility_config (Optional[AccessibilityConfig]) – Configuration for accessibility features

add_title_and_description(svg, title=None, description=None)[source]

Add title and description elements for accessibility.

Parameters:
  • svg (Element) – SVG element to add title and description to

  • title (Optional[str]) – Title text for the SVG

  • description (Optional[str]) – Description text for the SVG

Return type:

None

apply_final_enhancements(svg)[source]

Apply final accessibility enhancements to the complete SVG.

Parameters:

svg (Element) – Complete SVG element

Return type:

None

create_layered_structure(svg)[source]

Create a semantic layered structure for the SVG.

Creates groups for different layers (background, modules, overlays) with proper semantic markup.

Parameters:

svg (Element) – SVG element to structure

Return type:

Dict[str, Element]

Returns:

Dictionary mapping layer names to group elements

enhance_module_accessibility(element, row, col, module_type='data')[source]

Enhance accessibility for individual QR modules.

Parameters:
  • element (Element) – Module element to enhance

  • row (int) – Row position of the module

  • col (int) – Column position of the module

  • module_type (str) – Type of QR module

Return type:

None

enhance_pattern_group_accessibility(group_element, pattern_type, module_count)[source]

Enhance accessibility for pattern groups.

Parameters:
  • group_element (Element) – Group element containing pattern modules

  • pattern_type (str) – Type of pattern (finder, timing, etc.)

  • module_count (int) – Number of modules in the pattern

Return type:

None

get_accessibility_report()[source]

Get a report of accessibility features applied.

Return type:

Dict[str, Any]

Returns:

Dictionary containing accessibility metrics and features

validate_accessibility()[source]

Validate accessibility compliance.

Return type:

List[str]

Returns:

List of validation warnings or errors

class segnomms.svg.PathClipper(frame_shape, width, height, border, corner_radius=0.0)[source]

Bases: object

Clips SVG paths to frame boundaries.

This class provides methods to ensure that generated paths (from clustering or other phases) don’t extend beyond the configured frame shape boundaries.

Parameters:
__init__(frame_shape, width, height, border, corner_radius=0.0)[source]

Initialize the path clipper.

Parameters:
  • frame_shape (str) – Frame shape type (‘square’, ‘circle’, ‘rounded-rect’, ‘squircle’)

  • width (int) – Total SVG width in pixels

  • height (int) – Total SVG height in pixels

  • border (int) – Border size in pixels

  • corner_radius (float) – Corner radius for rounded-rect (0.0-1.0)

adjust_cluster_path(path, scale)[source]

Adjust a cluster path to respect frame boundaries.

Parameters:
  • path (str) – SVG path string

  • scale (int) – Module scale in pixels

Return type:

str

Returns:

Adjusted SVG path string

clip_path(path_data)[source]

Clip an SVG path to frame boundaries.

Parameters:

path_data (str) – SVG path string to clip

Return type:

str

Returns:

Clipped SVG path string

Note

This is a basic implementation that returns the original path for most cases. Full path parsing and clipping is a complex operation that would require substantial geometry libraries.

clip_rectangle_to_frame(x, y, width, height)[source]

Clip a rectangle to frame boundaries.

Parameters:
  • x (float) – Rectangle X position

  • y (float) – Rectangle Y position

  • width (float) – Rectangle width

  • height (float) – Rectangle height

Return type:

Optional[str]

Returns:

SVG path string for clipped shape, or None if entirely outside

get_distance_from_edge(x, y)[source]

Calculate distance from point to frame edge.

Parameters:
  • x (float) – X coordinate

  • y (float) – Y coordinate

Return type:

float

Returns:

Distance in pixels from the nearest frame edge (0 = on edge, positive = inside)

get_frame_aware_bounds(positions, scale)[source]

Get bounding box for positions, constrained by frame.

Parameters:
  • positions (List[Tuple[int, int]]) – List of (row, col) positions

  • scale (int) – Module scale in pixels

Return type:

Tuple[int, int, int, int]

Returns:

Tuple of (x, y, width, height) in pixels

get_scale_factor(x, y, scale_distance)[source]

Calculate scale factor for a point based on distance from frame edge.

Parameters:
  • x (float) – X coordinate

  • y (float) – Y coordinate

  • scale_distance (float) – Distance in pixels where scaling begins

Return type:

float

Returns:

Scale factor (1.0 = full size, 0.0 = invisible)

is_point_in_frame(x, y)[source]

Check if a point is within the frame boundaries.

Parameters:
  • x (float) – X coordinate

  • y (float) – Y coordinate

Return type:

bool

Returns:

True if point is within frame boundaries

class segnomms.svg.SVGElementConfig(**data)[source]

Bases: BaseModel

Configuration for SVG root element creation.

This model validates parameters for creating SVG root elements with proper dimensions, viewBox, and attributes.

Example

>>> config = SVGElementConfig(
...     width=200,
...     height=200,
...     id="my-qr-code",
...     css_class="qr-svg"
... )
>>> svg = builder.create_svg_root(**config.model_dump())
Parameters:
  • width (int)

  • height (int)

  • id (str | None)

  • css_class (str | None)

classmethod handle_css_class_aliases(values)[source]

Handle both ‘css_class’ and ‘class’ parameter names.

Return type:

Any

Parameters:

values (Any)

model_config: ClassVar[ConfigDict] = {'str_strip_whitespace': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

classmethod validate_dimensions(v)[source]

Validate reasonable SVG dimensions.

Return type:

int

Parameters:

v (int)

width: int
height: int
id: Optional[str]
css_class: Optional[str]
class segnomms.svg.BackgroundConfig(**data)[source]

Bases: BaseModel

Configuration for SVG background elements.

This model validates parameters for adding background rectangles to SVG documents.

Parameters:
model_config: ClassVar[ConfigDict] = {'str_strip_whitespace': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

classmethod validate_color(v)[source]

Basic validation for CSS color values.

Return type:

str

Parameters:

v (str)

width: int
height: int
color: str
class segnomms.svg.GradientConfig(**data)[source]

Bases: BaseModel

Configuration for SVG gradient definitions.

This model validates gradient parameters for creating linear and radial gradients in SVG definitions.

Parameters:
model_config: ClassVar[ConfigDict] = {'str_strip_whitespace': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

classmethod validate_stops(v, info)[source]

Validate gradient stops match color count.

Return type:

Optional[List[float]]

Parameters:
  • v (List[float] | None)

  • info (ValidationInfo)

gradient_id: str
gradient_type: Literal['linear', 'radial']
colors: List[str]
stops: Optional[List[float]]
x1: Optional[float]
y1: Optional[float]
x2: Optional[float]
y2: Optional[float]
cx: Optional[float]
cy: Optional[float]
r: Optional[float]
class segnomms.svg.TitleDescriptionConfig(**data)[source]

Bases: BaseModel

Configuration for SVG title and description elements.

This model validates accessibility metadata for SVG documents.

Parameters:
  • title (str)

  • description (str | None)

model_config: ClassVar[ConfigDict] = {'str_strip_whitespace': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

title: str
description: Optional[str]
class segnomms.svg.InteractionConfig(**data)[source]

Bases: BaseModel

Configuration for SVG interactivity features.

This model validates parameters for enabling interactive features like hover effects and tooltips.

Parameters:
model_config: ClassVar[ConfigDict] = {'validate_default': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

interactive: bool
tooltips: bool
hover_effects: bool
click_handlers: bool
class segnomms.svg.FrameDefinitionConfig(**data)[source]

Bases: BaseModel

Configuration for SVG frame shape definitions.

This model validates parameters for creating frame shapes in SVG definition sections.

Parameters:
  • frame_shape (Literal['square', 'circle', 'rounded-rect', 'squircle', 'custom'])

  • width (int)

  • height (int)

  • border_pixels (int)

  • corner_radius (float | None)

  • custom_path (str | None)

model_config: ClassVar[ConfigDict] = {'str_strip_whitespace': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

frame_shape: Literal['square', 'circle', 'rounded-rect', 'squircle', 'custom']
width: int
height: int
border_pixels: int
corner_radius: Optional[float]
custom_path: Optional[str]
class segnomms.svg.LayerStructureConfig(**data)[source]

Bases: BaseModel

Configuration for SVG layer organization.

This model defines the structure of layered SVG elements for proper rendering order and organization.

Parameters:
  • background_layer (bool)

  • quiet_zone_layer (bool)

  • frame_layer (bool)

  • modules_layer (bool)

  • centerpiece_layer (bool)

  • overlay_layer (bool)

property layer_names: List[str]

Get ordered list of enabled layer names.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

background_layer: bool
quiet_zone_layer: bool
frame_layer: bool
modules_layer: bool
centerpiece_layer: bool
overlay_layer: bool
class segnomms.svg.CenterpieceMetadataConfig(**data)[source]

Bases: BaseModel

Configuration for centerpiece metadata in SVG.

This model validates parameters for adding centerpiece positioning metadata to SVG documents.

Parameters:
property bounds_dict: Dict[str, float]

Get bounds as dictionary.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

x: float
y: float
width: float
height: float
scale: int
border: int

Main SVG Builder

class segnomms.svg.InteractiveSVGBuilder(accessibility_config=None)[source]

Bases: SVGBuilder

Main SVG builder that composes all specialized builders.

This class maintains the same interface as the original monolithic SVGBuilder while delegating to specialized builders internally.

Parameters:

accessibility_config (AccessibilityConfig | None)

__init__(accessibility_config=None)[source]

Initialize the composite SVG builder.

Parameters:

accessibility_config (Optional[AccessibilityConfig]) – Configuration for accessibility features

create_svg_root(width, height, **kwargs)[source]

Create the root SVG element with accessibility features.

Handles both web accessibility (ARIA attributes) and SVG accessibility (title/desc elements) for complete coverage.

Return type:

Element

Parameters:
add_styles(svg, interactive=False, animation_config=None)[source]

Add CSS styles to the SVG.

Return type:

None

Parameters:
add_background(svg, width, height, color, **kwargs)[source]

Add a background rectangle to the SVG.

Return type:

None

Parameters:
add_definitions(svg, definitions_or_gradients=None, patterns=None, filters=None)[source]

Add definitions section to SVG.

Parameters:
  • svg (Element) – SVG element to add definitions to

  • definitions_or_gradients (Union[Dict[str, Any], List[GradientConfig], None]) – Either a dictionary containing definitions structure or a list of GradientConfig objects (backward compatibility)

  • patterns (Optional[List[Dict[str, Any]]]) – List of pattern definitions (when not using dictionary format)

  • filters (Optional[List[Dict[str, Any]]]) – List of filter definitions (when not using dictionary format)

Return type:

Element

add_svg_accessibility_elements(svg, title=None, description=None)[source]

Add native SVG accessibility elements (<title> and <desc>).

These elements are part of the SVG specification and provide accessibility information that works in all contexts.

Return type:

None

Parameters:
add_title_and_description(svg, title=None, description=None)[source]

Add title and description elements for accessibility.

DEPRECATED: Use add_svg_accessibility_elements() for clarity. Kept for backward compatibility.

Return type:

None

Parameters:
add_javascript(svg, script_content)[source]

Add JavaScript code to the SVG document.

Return type:

None

Parameters:
add_interaction_handlers(svg)[source]

Add default interaction handlers to the SVG.

Return type:

None

Parameters:

svg (Element)

add_frame_definitions(svg, frame_config, width, height, border_pixels)[source]

Add frame shape definitions to SVG defs section.

Return type:

Optional[str]

Parameters:
add_quiet_zone_with_style(svg, config, width, height)[source]

Add styled quiet zone to the SVG.

Return type:

None

Parameters:
add_centerpiece_metadata(svg, config, bounds, scale, border)[source]

Add metadata about centerpiece location for overlay applications.

Return type:

None

Parameters:
create_layered_structure(svg)[source]

Create a semantic layered structure for the SVG.

Return type:

Dict[str, Element]

Parameters:

svg (Element)

enhance_module_accessibility(element, row, col, module_type='data')[source]

Enhance accessibility for individual QR modules.

Return type:

None

Parameters:
enhance_pattern_group_accessibility(group_element, pattern_type, module_count)[source]

Enhance accessibility for pattern groups.

Return type:

None

Parameters:
get_accessibility_report()[source]

Get a report of accessibility features applied.

Return type:

Dict[str, Any]

validate_accessibility()[source]

Validate accessibility compliance.

Return type:

List[str]

The InteractiveSVGBuilder is the main composite builder that orchestrates all specialized builders to create complete interactive SVG documents.

Core SVG Builder

class segnomms.svg.CoreSVGBuilder[source]

Bases: SVGBuilder

Core SVG document builder for basic operations.

Handles fundamental SVG operations like creating root elements, adding CSS styles, and managing background elements.

create_svg_root(width, height, **kwargs)[source]

Create the root SVG element with proper attributes and namespaces.

Parameters:
  • width (int) – Width of the SVG in pixels

  • height (int) – Height of the SVG in pixels

  • **kwargs (Any) – Additional attributes for the SVG element

Return type:

Element

Returns:

Root SVG Element with configured attributes

add_styles(svg, interactive=False, animation_config=None)[source]

Add CSS styles to the SVG.

Parameters:
  • svg (Element) – SVG element to add styles to

  • interactive (bool) – Whether to include interactive hover styles

  • animation_config (Optional[Dict[str, Any]]) – Optional animation configuration dict

Return type:

None

add_background(svg, width, height, color, **kwargs)[source]

Add a background rectangle to the SVG.

Parameters:
  • svg (Element) – SVG element to add background to

  • width (int) – Width of the background

  • height (int) – Height of the background

  • color (str) – Background color

  • **kwargs (Any) – Additional background configuration options

Return type:

None

Path Clipping

class segnomms.svg.PathClipper(frame_shape, width, height, border, corner_radius=0.0)[source]

Bases: object

Clips SVG paths to frame boundaries.

This class provides methods to ensure that generated paths (from clustering or other phases) don’t extend beyond the configured frame shape boundaries.

Parameters:
__init__(frame_shape, width, height, border, corner_radius=0.0)[source]

Initialize the path clipper.

Parameters:
  • frame_shape (str) – Frame shape type (‘square’, ‘circle’, ‘rounded-rect’, ‘squircle’)

  • width (int) – Total SVG width in pixels

  • height (int) – Total SVG height in pixels

  • border (int) – Border size in pixels

  • corner_radius (float) – Corner radius for rounded-rect (0.0-1.0)

is_point_in_frame(x, y)[source]

Check if a point is within the frame boundaries.

Parameters:
  • x (float) – X coordinate

  • y (float) – Y coordinate

Return type:

bool

Returns:

True if point is within frame boundaries

get_distance_from_edge(x, y)[source]

Calculate distance from point to frame edge.

Parameters:
  • x (float) – X coordinate

  • y (float) – Y coordinate

Return type:

float

Returns:

Distance in pixels from the nearest frame edge (0 = on edge, positive = inside)

get_scale_factor(x, y, scale_distance)[source]

Calculate scale factor for a point based on distance from frame edge.

Parameters:
  • x (float) – X coordinate

  • y (float) – Y coordinate

  • scale_distance (float) – Distance in pixels where scaling begins

Return type:

float

Returns:

Scale factor (1.0 = full size, 0.0 = invisible)

clip_rectangle_to_frame(x, y, width, height)[source]

Clip a rectangle to frame boundaries.

Parameters:
  • x (float) – Rectangle X position

  • y (float) – Rectangle Y position

  • width (float) – Rectangle width

  • height (float) – Rectangle height

Return type:

Optional[str]

Returns:

SVG path string for clipped shape, or None if entirely outside

adjust_cluster_path(path, scale)[source]

Adjust a cluster path to respect frame boundaries.

Parameters:
  • path (str) – SVG path string

  • scale (int) – Module scale in pixels

Return type:

str

Returns:

Adjusted SVG path string

clip_path(path_data)[source]

Clip an SVG path to frame boundaries.

Parameters:

path_data (str) – SVG path string to clip

Return type:

str

Returns:

Clipped SVG path string

Note

This is a basic implementation that returns the original path for most cases. Full path parsing and clipping is a complex operation that would require substantial geometry libraries.

get_frame_aware_bounds(positions, scale)[source]

Get bounding box for positions, constrained by frame.

Parameters:
  • positions (List[Tuple[int, int]]) – List of (row, col) positions

  • scale (int) – Module scale in pixels

Return type:

Tuple[int, int, int, int]

Returns:

Tuple of (x, y, width, height) in pixels

SVG Models

Pydantic models for utility components.

This module provides data models for utility classes using Pydantic for automatic validation and type safety.

class segnomms.svg.models.SVGElementConfig(**data)[source]

Bases: BaseModel

Configuration for SVG root element creation.

This model validates parameters for creating SVG root elements with proper dimensions, viewBox, and attributes.

Example

>>> config = SVGElementConfig(
...     width=200,
...     height=200,
...     id="my-qr-code",
...     css_class="qr-svg"
... )
>>> svg = builder.create_svg_root(**config.model_dump())
Parameters:
  • width (Annotated[int, Gt(gt=0), Le(le=10000)])

  • height (Annotated[int, Gt(gt=0), Le(le=10000)])

  • id (Annotated[str | None, MinLen(min_length=1), MaxLen(max_length=100), _PydanticGeneralMetadata(pattern='^[a-zA-Z][a-zA-Z0-9\\-_]*$')])

  • css_class (Annotated[str | None, MinLen(min_length=1), MaxLen(max_length=200)])

model_config: ClassVar[ConfigDict] = {'str_strip_whitespace': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

width: int
height: int
id: Optional[str]
css_class: Optional[str]
classmethod handle_css_class_aliases(values)[source]

Handle both ‘css_class’ and ‘class’ parameter names.

Return type:

Any

Parameters:

values (Any)

classmethod validate_dimensions(v)[source]

Validate reasonable SVG dimensions.

Return type:

int

Parameters:

v (int)

class segnomms.svg.models.BackgroundConfig(**data)[source]

Bases: BaseModel

Configuration for SVG background elements.

This model validates parameters for adding background rectangles to SVG documents.

Parameters:
model_config: ClassVar[ConfigDict] = {'str_strip_whitespace': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

width: int
height: int
color: str
classmethod validate_color(v)[source]

Basic validation for CSS color values.

Return type:

str

Parameters:

v (str)

class segnomms.svg.models.GradientConfig(**data)[source]

Bases: BaseModel

Configuration for SVG gradient definitions.

This model validates gradient parameters for creating linear and radial gradients in SVG definitions.

Parameters:
model_config: ClassVar[ConfigDict] = {'str_strip_whitespace': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

gradient_id: str
gradient_type: Literal['linear', 'radial']
colors: List[str]
stops: Optional[List[float]]
x1: Optional[float]
y1: Optional[float]
x2: Optional[float]
y2: Optional[float]
cx: Optional[float]
cy: Optional[float]
r: Optional[float]
classmethod validate_stops(v, info)[source]

Validate gradient stops match color count.

Return type:

Optional[List[float]]

Parameters:
  • v (List[float] | None)

  • info (ValidationInfo)

class segnomms.svg.models.TitleDescriptionConfig(**data)[source]

Bases: BaseModel

Configuration for SVG title and description elements.

This model validates accessibility metadata for SVG documents.

Parameters:
  • title (Annotated[str, MinLen(min_length=1), MaxLen(max_length=100)])

  • description (Annotated[str | None, MaxLen(max_length=500)])

model_config: ClassVar[ConfigDict] = {'str_strip_whitespace': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

title: str
description: Optional[str]
class segnomms.svg.models.InteractionConfig(**data)[source]

Bases: BaseModel

Configuration for SVG interactivity features.

This model validates parameters for enabling interactive features like hover effects and tooltips.

Parameters:
model_config: ClassVar[ConfigDict] = {'validate_default': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

interactive: bool
tooltips: bool
hover_effects: bool
click_handlers: bool
class segnomms.svg.models.FrameDefinitionConfig(**data)[source]

Bases: BaseModel

Configuration for SVG frame shape definitions.

This model validates parameters for creating frame shapes in SVG definition sections.

Parameters:
model_config: ClassVar[ConfigDict] = {'str_strip_whitespace': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

frame_shape: Literal['square', 'circle', 'rounded-rect', 'squircle', 'custom']
width: int
height: int
border_pixels: int
corner_radius: Optional[float]
custom_path: Optional[str]
class segnomms.svg.models.LayerStructureConfig(**data)[source]

Bases: BaseModel

Configuration for SVG layer organization.

This model defines the structure of layered SVG elements for proper rendering order and organization.

Parameters:
  • background_layer (bool)

  • quiet_zone_layer (bool)

  • frame_layer (bool)

  • modules_layer (bool)

  • centerpiece_layer (bool)

  • overlay_layer (bool)

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

background_layer: bool
quiet_zone_layer: bool
frame_layer: bool
modules_layer: bool
centerpiece_layer: bool
overlay_layer: bool
property layer_names: List[str]

Get ordered list of enabled layer names.

class segnomms.svg.models.CenterpieceMetadataConfig(**data)[source]

Bases: BaseModel

Configuration for centerpiece metadata in SVG.

This model validates parameters for adding centerpiece positioning metadata to SVG documents.

Parameters:
model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

x: float
y: float
width: float
height: float
scale: int
border: int
property bounds_dict: Dict[str, float]

Get bounds as dictionary.

These models provide type-safe configuration for SVG generation parameters.

Example Usage

Basic SVG generation:

from segnomms.svg import InteractiveSVGBuilder

builder = InteractiveSVGBuilder()
svg_root = builder.create_svg_root(200, 200)
builder.add_styles(svg_root, interactive=True)
builder.add_background(svg_root, 200, 200, 'white')

Path clipping for frames:

from segnomms.svg import PathClipper

clipper = PathClipper(
    frame_shape='circle',
    width=200,
    height=200,
    border=20
)
clipped_path = clipper.clip_path_to_frame(original_path)