Core Components
This section documents the core components and interfaces of the plugin.
Interfaces
Core interfaces for the segno interactive SVG plugin.
This module defines the abstract base classes and interfaces that all components must implement to ensure consistency and extensibility.
The interfaces provide contracts for:
Shape rendering (ShapeRenderer)
Module analysis (ModuleAnalyzer)
Algorithm processing (AlgorithmProcessor)
Configuration management (ConfigurationProvider)
Factory patterns (RendererFactory)
SVG building (SVGBuilder)
QR code analysis (QRCodeAnalyzer)
All custom implementations should inherit from these base classes.
- class segnomms.core.interfaces.ModuleAnalyzer[source]
Bases:
ABCInterface for module analysis algorithms.
Implementations analyze QR code matrices to extract information about module patterns, relationships, and properties.
- class segnomms.core.interfaces.ShapeRenderer[source]
Bases:
ABCInterface for shape rendering implementations.
All shape renderers must implement this interface to ensure compatibility with the rendering pipeline.
Implementations should:
Create SVG elements for individual modules
Support configuration through kwargs
Declare which shape types they handle
- class segnomms.core.interfaces.AlgorithmProcessor[source]
Bases:
ABCInterface for algorithm-based processors.
Processors implement algorithms like clustering, contour detection, or other matrix transformations.
- class segnomms.core.interfaces.ConfigurationProvider[source]
Bases:
ABCInterface for configuration providers.
Components that require configuration should implement this interface to provide default values and validation.
- class segnomms.core.interfaces.RendererFactory[source]
Bases:
ABCInterface for renderer factories.
Factories manage the creation and registration of shape renderers.
- class segnomms.core.interfaces.SVGBuilder[source]
Bases:
ABCInterface for SVG document builders.
Builders handle the construction of complete SVG documents with proper structure, styles, and metadata.
- class segnomms.core.interfaces.QRCodeAnalyzer[source]
Bases:
ABCInterface for QR code analyzers.
Analyzers determine module types (finder, timing, data, etc.) and extract QR code properties.
- segnomms.core.interfaces.Matrix
Type alias for QR code matrix (2D list of booleans)
- segnomms.core.interfaces.Position
Type alias for module position (row, col)
- segnomms.core.interfaces.BoundingBox
Type alias for bounding box (min_row, min_col, max_row, max_col)
- segnomms.core.interfaces.RGBColor
Type alias for RGB color (red, green, blue)
Module Detector
Core module detection functionality for QR codes.
This module contains the ModuleDetector class which identifies different types of modules in a QR code (finder patterns, timing patterns, etc.).
The detector analyzes QR code matrices to classify each module as:
Finder patterns (including inner regions)
Separator modules
Timing patterns
Alignment patterns
Format information
Version information
Data modules
- segnomms.core.detector.FINDER_PATTERN_POSITIONS = [(0, 0), (0, -7), (-7, 0)]
Positions of finder patterns (top-left, top-right, bottom-left)
- segnomms.core.detector.FINDER_SIZE = 7
Size of finder patterns in modules
- segnomms.core.detector.ALIGNMENT_PATTERN_SIZE = 5
Size of alignment patterns in modules
- class segnomms.core.detector.ModuleDetector(matrix, version=None)[source]
Bases:
QRCodeAnalyzerDetects QR code module types and properties.
This class analyzes a QR code matrix to identify different module types such as finder patterns, timing patterns, alignment patterns, and data modules.
- matrix
The QR code matrix as a 2D boolean list
- size
Size of the QR code (modules per side)
- version
QR code version (1-40)
- alignment_positions
Calculated alignment pattern positions
Example
>>> # Create a minimal valid matrix (21x21 for version 1) >>> matrix = [[True] * 21 for _ in range(21)] >>> detector = ModuleDetector(matrix, version=1) >>> module_type = detector.get_module_type(10, 10) >>> print(module_type) # 'data'
- __init__(matrix, version=None)[source]
Initialize the detector with QR code matrix and optional version.
- Parameters:
Example
>>> # Create a valid matrix for version 1 QR code (21x21) >>> matrix = [[True] * 21 for _ in range(21)] >>> detector = ModuleDetector(matrix, version=1) >>> # Or using Pydantic model >>> config = ModuleDetectorConfig(matrix=matrix, version=1) >>> detector = ModuleDetector(**config.model_dump())
- get_module_type(row, col)[source]
Determine the type of module at given position.
- Parameters:
- Returns:
- Module type identifier:
’finder’: Finder pattern module
’finder_inner’: Inner finder pattern module
’separator’: Separator module
’timing’: Timing pattern module
’alignment’: Alignment pattern module
’format’: Format information module
’version’: Version information module
’data’: Data or error correction module
- Return type:
- Raises:
IndexError – If row or col is out of bounds
- get_size()[source]
Get the size of the QR code matrix.
- Returns:
Number of modules per side
- Return type:
- get_neighbors(row, col, neighborhood='von_neumann')[source]
Get neighboring positions for a module.
- get_weighted_neighbor_analysis(row, col, module_type='data')[source]
Enhanced neighbor analysis using Moore neighborhood (8-connected) with weighted connectivity.
Returns comprehensive neighbor analysis including connectivity strength, flow direction, and shape hints for advanced rendering.
- Parameters:
- Return type:
NeighborAnalysis- Returns:
NeighborAnalysis model with comprehensive neighbor data
- Raises:
IndexError – If row or col is out of bounds
The ModuleDetector class is responsible for identifying different types of QR code modules
(finder patterns, timing patterns, data modules, etc.) and providing context information
for shape renderers.
Example Usage
from segnomms.core.detector import ModuleDetector
# Create detector with QR matrix
detector = ModuleDetector(matrix, version=1)
# Check module type
module_type = detector.get_module_type(5, 5)
# Get neighbor information
def get_neighbor(dx, dy):
return detector.is_module_active(x + dx, y + dy)
Matrix Manipulation
Matrix manipulation orchestrator using composition pattern.
This module provides the new MatrixManipulator class that orchestrates specialized components for centerpiece reserve functionality while maintaining backward compatibility with the existing API.
- class segnomms.core.matrix.manipulator.MatrixManipulator(matrix, detector)[source]
Bases:
objectHandles matrix modifications for centerpiece reserve using composition.
This class orchestrates specialized components to provide comprehensive centerpiece functionality while maintaining the original API for backward compatibility.
- Components:
CenterpieceGeometry: Pure geometric calculations
KnockoutProcessor: Handles knockout mode clearing
ImprintProcessor: Handles imprint mode processing
MatrixValidator: Validates matrix modifications
CenterpiecePerformanceMonitor: Performance tracking
- Parameters:
detector (ModuleDetector)
- ERROR_CORRECTION_CAPACITY
Maximum data loss capacity by error level
- ERROR_CORRECTION_CAPACITY = {'H': 0.3, 'L': 0.07, 'M': 0.15, 'Q': 0.25}
- __init__(matrix, detector)[source]
Initialize the matrix manipulator with specialized components.
- Parameters:
matrix (
List[List[bool]]) – QR code matrix as 2D boolean listdetector (
ModuleDetector) – Module detector instance for pattern identification
- Raises:
ValueError – If matrix is invalid (empty, non-square, or malformed)
- calculate_safe_reserve_size(version, error_level)[source]
Calculate maximum safe reserve size based on error correction.
- calculate_placement_offsets(config)[source]
Calculate offset_x and offset_y based on placement mode.
- Parameters:
config (
CenterpieceConfig) – CenterpieceConfig instance- Return type:
- Returns:
Tuple of (offset_x, offset_y) values
- get_centerpiece_bounds(config)[source]
Calculate centerpiece bounds in module coordinates.
- Parameters:
config (
CenterpieceConfig) – CenterpieceConfig instance- Return type:
- Returns:
Dict with ‘left’, ‘top’, ‘right’, ‘bottom’ keys
- is_in_centerpiece(row, col, config)[source]
Check if a module is within the centerpiece area.
- Parameters:
row (
int) – Module row positioncol (
int) – Module column positionconfig (
CenterpieceConfig) – CenterpieceConfig instance
- Return type:
- Returns:
True if module is within centerpiece area
- clear_centerpiece_area(config)[source]
Clear modules in centerpiece area, preserving function patterns.
This method orchestrates the appropriate processor based on the reserve mode configuration.
- Parameters:
config (
CenterpieceConfig) – CenterpieceConfig instance- Return type:
- Returns:
Modified matrix with centerpiece area processed
- apply_knockout_mode(config)[source]
Apply knockout mode - clear modules completely from reserve area.
- Parameters:
config (
CenterpieceConfig) – CenterpieceConfig instance- Return type:
- Returns:
Modified matrix with centerpiece area cleared
- apply_imprint_mode(config)[source]
Apply imprint mode - preserve modules underneath centerpiece for scanability.
- Parameters:
config (
CenterpieceConfig) – CenterpieceConfig instance- Return type:
- Returns:
Original matrix (modules preserved for scanability)
- validate_reserve_impact(config, error_level)[source]
Validate the impact of a centerpiece configuration.
- Parameters:
config (
CenterpieceConfig) – CenterpieceConfig instanceerror_level (
str) – QR error correction level (“L”, “M”, “Q”, “H”)
- Return type:
- Returns:
Dictionary with validation results including ‘safe’, ‘estimated_modules’, ‘warnings’
- validate_centerpiece_configuration(config)[source]
Validate centerpiece configuration for potential issues.
- Parameters:
config (
CenterpieceConfig) – CenterpieceConfig instance- Return type:
- Returns:
Tuple of (is_valid, warnings_list)
- analyze_pattern_preservation(config)[source]
Analyze how well critical QR patterns are preserved.
- Parameters:
config (
CenterpieceConfig) – CenterpieceConfig instance- Return type:
PatternAnalysis- Returns:
Dictionary with pattern preservation analysis
- get_scanability_assessment(config, modified_matrix)[source]
Provide comprehensive scanability assessment for the modified matrix.
- Parameters:
config (
CenterpieceConfig) – CenterpieceConfig instancemodified_matrix (
List[List[bool]]) – Matrix with centerpiece modifications
- Return type:
ScanabilityAssessment- Returns:
Dictionary with scanability assessment
- get_centerpiece_metadata(config)[source]
Get metadata about the centerpiece area for SVG generation.
- Parameters:
config (
CenterpieceConfig) – CenterpieceConfig instance- Return type:
- Returns:
Dictionary with centerpiece bounds and properties
- get_performance_warnings(config)[source]
Get performance warnings for centerpiece configuration.
- Parameters:
config (
CenterpieceConfig) – CenterpieceConfig instance- Return type:
- Returns:
List of performance warning messages
- get_comprehensive_performance_warnings(config)[source]
Get comprehensive performance warnings including configuration and runtime metrics.
- Parameters:
config (
CenterpieceConfig) – CenterpieceConfig instance- Return type:
- Returns:
List of all performance warning messages
- get_geometry_component()[source]
Get the geometry calculation component.
- Return type:
CenterpieceGeometry
The MatrixManipulator provides utilities for QR matrix operations
including centerpiece area clearing and module manipulation.
Algorithms
Connected Component Analyzer
Connected component clustering algorithm for QR code modules.
This module implements Phase 2 of the multi-phase rendering pipeline, which identifies and groups adjacent modules into connected components for optimized rendering.
The clustering algorithm:
Traverses the QR matrix to find active modules
Groups adjacent modules of the same type into clusters
Analyzes cluster properties (size, density, shape)
Filters clusters based on configurable thresholds
Optimizes rendering by treating clusters as single shapes
This approach significantly reduces the number of SVG elements needed for complex QR codes, improving both file size and rendering performance.
- class segnomms.algorithms.clustering.ConnectedComponentAnalyzer(min_cluster_size=3, density_threshold=0.5, connectivity_mode='4-way')[source]
Bases:
AlgorithmProcessorAnalyzes connected components in QR code matrices.
This analyzer implements a depth-first search algorithm to identify clusters of connected modules. It’s used in Phase 2 processing to group adjacent modules for optimized rendering.
- Parameters:
- min_cluster_size
Minimum modules required to form a valid cluster
- density_threshold
Minimum density (filled ratio) for valid clusters
- visited
Set tracking already-processed module positions
Example
>>> analyzer = ConnectedComponentAnalyzer(min_cluster_size=5) >>> clusters = analyzer.process(matrix, detector) >>> print(f"Found {len(clusters)} clusters")
- __init__(min_cluster_size=3, density_threshold=0.5, connectivity_mode='4-way')[source]
Initialize the connected component analyzer.
- Parameters:
Example
>>> analyzer = ConnectedComponentAnalyzer(min_cluster_size=5) >>> # Or using Pydantic model >>> config = ClusteringConfig(min_cluster_size=5, density_threshold=0.7) >>> analyzer = ConnectedComponentAnalyzer(**config.model_dump())
- process(matrix, detector, **kwargs)[source]
Process the QR matrix to find connected components.
Traverses the matrix to identify groups of connected modules, analyzes their properties, and returns clusters that meet the size and density requirements.
- Parameters:
matrix (
List[List[bool]]) – 2D boolean matrix representing QR code modules.detector (
ModuleDetector) – Module detector for determining module types.**kwargs (
Any) – Additional parameters.
- Keyword Arguments:
cluster_module_types (List[str]) – List of module types to cluster. Defaults to
['data'].- Returns:
List of cluster dictionaries, each containing: - positions: List of (row, col) tuples - bounds: (min_row, min_col, max_row, max_col) - module_count: Number of modules in cluster - density: Ratio of filled modules in bounding box - aspect_ratio: Width/height ratio - is_rectangular: Whether cluster forms a rectangle
- Return type:
List[Dict[str, Any]]
- get_cluster_svg_path(cluster, scale=8, border=0, path_clipper=None)[source]
Generate SVG path for rendering cluster as a single shape.
Creates an SVG path string that represents the entire cluster as a merged shape, reducing the number of individual elements.
- Parameters:
- Returns:
SVG path data string for the cluster shape
- Return type:
Note
Currently uses a simple bounding box approach. Future versions could implement more sophisticated contour tracing.
The clustering algorithm groups connected modules together for more efficient rendering and better visual effects with connected shapes.
Phase 4 Core Components
Advanced QR Generation
Advanced QR code generation with ECI, mask patterns, and structured append.
This module provides enhanced QR code generation capabilities including: - ECI (Extended Channel Interpretation) mode for international character encoding - Manual mask pattern selection for visual optimization - Structured append for multi-symbol QR code sequences
The module integrates with Segno’s advanced features while providing proper error handling, validation, and fallback mechanisms.
- class segnomms.core.advanced_qr.SegnoMakeParams[source]
Bases:
TypedDictType definition for segno.make() parameters.
- class segnomms.core.advanced_qr.SegnoSequenceParams[source]
Bases:
TypedDictType definition for segno.make_sequence() parameters.
- class segnomms.core.advanced_qr.AnalysisDict[source]
Bases:
TypedDictType definition for encoding analysis results.
- class segnomms.core.advanced_qr.RecommendationsDict[source]
Bases:
TypedDictType definition for encoding recommendations.
-
analysis:
AnalysisDict
-
analysis:
- class segnomms.core.advanced_qr.QRGenerationResult(qr_codes, is_sequence, metadata, warnings, fallback_used)[source]
Bases:
objectResult of advanced QR code generation.
- Parameters:
- qr_codes
List of generated QR codes (single code or sequence)
- is_sequence
Whether result is a structured append sequence
- metadata
Additional metadata about generation process
- warnings
Any warnings generated during creation
- fallback_used
Whether fallback generation was used
- class segnomms.core.advanced_qr.AdvancedQRGenerator[source]
Bases:
objectAdvanced QR code generator with ECI, mask patterns, and structured append.
This class provides enhanced QR code generation capabilities while maintaining compatibility with standard QR codes. It includes proper error handling and fallback mechanisms for maximum reliability.
- generate_qr(content, config, error='M', version=None)[source]
Generate QR code(s) with advanced features.
- Parameters:
- Return type:
- Returns:
QRGenerationResult with generated QR code(s) and metadata
- segnomms.core.advanced_qr.create_advanced_qr_generator()[source]
Create an AdvancedQRGenerator instance.
- Return type:
- Returns:
Configured AdvancedQRGenerator instance
The advanced QR generation system provides enhanced features including ECI character encoding, manual mask patterns, and structured append sequences.
Extending the Plugin
Creating a Custom Shape Renderer
from segnomms.core.interfaces import ShapeRenderer
import xml.etree.ElementTree as ET
class CustomRenderer(ShapeRenderer):
"""My custom shape renderer."""
def render(self, x: float, y: float, size: float, **kwargs) -> ET.Element:
"""Render the shape."""
# Create your custom SVG element
element = ET.Element('polygon', {
'points': self._calculate_points(x, y, size),
'class': kwargs.get('css_class', 'qr-module')
})
return element
def supports_type(self, shape_type: str) -> bool:
"""Check if this renderer handles the shape type."""
return shape_type == 'custom'
def _calculate_points(self, x, y, size):
# Custom logic here
pass
Creating a Custom Algorithm
from segnomms.core.interfaces import AlgorithmProcessor
class CustomProcessor(AlgorithmProcessor):
"""Custom algorithm processor."""
def process(self, matrix, config):
"""Process the QR matrix."""
# Your algorithm logic
results = self._analyze(matrix)
return results
def get_config_schema(self):
"""Return configuration schema."""
return {
'type': 'object',
'properties': {
'threshold': {'type': 'number'}
}
}
Module Types
The plugin recognizes these QR code module types:
ModuleType.FINDER- Finder pattern modulesModuleType.SEPARATOR- Separator modules around findersModuleType.TIMING- Timing pattern modulesModuleType.ALIGNMENT- Alignment pattern modulesModuleType.FORMAT- Format information modulesModuleType.VERSION- Version information modulesModuleType.DATA- Data and error correction modulesModuleType.DARK- Fixed dark module
Architecture Overview
The plugin follows a modular architecture:
Configuration Layer - Validates and manages all settings
Detection Layer - Identifies module types and relationships
Algorithm Layer - Processes modules (clustering, optimization)
Rendering Layer - Generates SVG elements for each module
Assembly Layer - Combines elements into final SVG
This separation allows for easy extension and modification of individual components without affecting the rest of the system.