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: ABC

Interface for module analysis algorithms.

Implementations analyze QR code matrices to extract information about module patterns, relationships, and properties.

abstractmethod analyze(matrix, detector)[source]

Analyze the QR code matrix and return analysis results.

Parameters:
  • matrix (List[List[bool]]) – 2D boolean matrix representing QR code modules

  • detector (Any) – Module detector for determining module types

Return type:

Any

Returns:

Analysis results specific to the analyzer implementation

class segnomms.core.interfaces.ShapeRenderer[source]

Bases: ABC

Interface for shape rendering implementations.

All shape renderers must implement this interface to ensure compatibility with the rendering pipeline.

Implementations should:

  1. Create SVG elements for individual modules

  2. Support configuration through kwargs

  3. Declare which shape types they handle

abstractmethod render(x, y, size, **kwargs)[source]

Render a shape at the specified position.

Parameters:
  • x (float) – X coordinate

  • y (float) – Y coordinate

  • size (float) – Size of the shape

  • **kwargs (Any) – Additional rendering parameters

Return type:

Element

Returns:

SVG element representing the rendered shape

abstractmethod supports_type(shape_type)[source]

Check if this renderer supports the given shape type.

Parameters:

shape_type (str) – Name of the shape type

Return type:

bool

Returns:

True if this renderer can handle the shape type

class segnomms.core.interfaces.AlgorithmProcessor[source]

Bases: ABC

Interface for algorithm-based processors.

Processors implement algorithms like clustering, contour detection, or other matrix transformations.

abstractmethod process(matrix, detector, **kwargs)[source]

Process the QR matrix using the specific algorithm.

Parameters:
  • matrix (List[List[bool]]) – 2D boolean matrix representing QR code modules

  • detector (Any) – Module detector for determining module types

  • **kwargs (Any) – Algorithm-specific parameters

Return type:

List[Dict[str, Any]]

Returns:

List of processing results (clusters, contours, etc.)

class segnomms.core.interfaces.ConfigurationProvider[source]

Bases: ABC

Interface for configuration providers.

Components that require configuration should implement this interface to provide default values and validation.

abstractmethod get_default_config()[source]

Get default configuration for this component.

Returns:

Default configuration values

Return type:

Dict[str, Any]

abstractmethod validate_config(config)[source]

Validate a configuration dictionary.

Parameters:

config (Dict[str, Any]) – Configuration to validate

Returns:

True if configuration is valid

Return type:

bool

Raises:

ValueError – If configuration is invalid with details

class segnomms.core.interfaces.RendererFactory[source]

Bases: ABC

Interface for renderer factories.

Factories manage the creation and registration of shape renderers.

abstractmethod create_renderer(shape_type, config)[source]

Create a renderer for the specified shape type.

Parameters:
  • shape_type (str) – Type of shape to render

  • config (Dict[str, Any]) – Configuration parameters

Return type:

ShapeRenderer

Returns:

Appropriate shape renderer

abstractmethod list_supported_types()[source]

List all shape types supported by this factory.

Returns:

Supported shape type names

Return type:

List[str]

class segnomms.core.interfaces.SVGBuilder[source]

Bases: ABC

Interface for SVG document builders.

Builders handle the construction of complete SVG documents with proper structure, styles, and metadata.

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

Create the root SVG element.

Parameters:
  • width (int) – SVG width in pixels

  • height (int) – SVG height in pixels

  • **kwargs (Any) – Additional SVG attributes

Returns:

Root SVG element

Return type:

ET.Element

abstractmethod add_styles(svg, interactive=False)[source]

Add CSS styles to the SVG.

Parameters:
  • svg (Element) – SVG root element

  • interactive (bool) – Whether to include interactive styles

Return type:

None

abstractmethod add_background(svg, width, height, color)[source]

Add background to the SVG.

Parameters:
  • svg (Element) – SVG root element

  • width (int) – Background width

  • height (int) – Background height

  • color (str) – Background color (CSS color string)

Return type:

None

class segnomms.core.interfaces.QRCodeAnalyzer[source]

Bases: ABC

Interface for QR code analyzers.

Analyzers determine module types (finder, timing, data, etc.) and extract QR code properties.

abstractmethod get_module_type(row, col)[source]

Get the type of module at the specified position.

Parameters:
  • row (int) – Row index

  • col (int) – Column index

Returns:

Module type identifier

Return type:

str

abstractmethod get_version()[source]

Get the QR code version.

Returns:

QR code version (1-40)

Return type:

int

abstractmethod get_size()[source]

Get the size of the QR code matrix.

Returns:

Number of modules per side

Return type:

int

segnomms.core.interfaces.Matrix

Type alias for QR code matrix (2D list of booleans)

alias of List[List[bool]]

segnomms.core.interfaces.Position

Type alias for module position (row, col)

alias of Tuple[int, int]

segnomms.core.interfaces.BoundingBox

Type alias for bounding box (min_row, min_col, max_row, max_col)

alias of Tuple[int, int, int, int]

segnomms.core.interfaces.RGBColor

Type alias for RGB color (red, green, blue)

alias of Tuple[int, int, int]

segnomms.core.interfaces.Point2D

Type alias for 2D point (x, y)

alias of Tuple[float, float]

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: QRCodeAnalyzer

Detects 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.

Parameters:
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:
  • matrix (List[List[bool]]) – The QR code matrix as a 2D boolean list

  • version (Union[str, int, None]) – QR code version (1-40, ‘M1’-‘M4’, or None for auto-detection)

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:
  • row (int) – Row index (0-based)

  • col (int) – Column index (0-based)

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:

str

Raises:

IndexError – If row or col is out of bounds

get_version()[source]

Get the QR code version.

Returns:

QR code version (1-40)

Return type:

int

get_size()[source]

Get the size of the QR code matrix.

Returns:

Number of modules per side

Return type:

int

is_module_active(row, col)[source]

Check if the module at given position is active (dark).

Parameters:
  • row (int) – Row index

  • col (int) – Column index

Returns:

True if module is dark, False otherwise

Return type:

bool

get_neighbors(row, col, neighborhood='von_neumann')[source]

Get neighboring positions for a module.

Parameters:
  • row (int) – Row position

  • col (int) – Column position

  • neighborhood (str) – ‘von_neumann’ (4-connected) or ‘moore’ (8-connected)

Return type:

List[Tuple[int, int]]

Returns:

List of valid neighbor positions

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:
  • row (int) – Row position

  • col (int) – Column position

  • module_type (str) – Type of module for weighting

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: object

Handles 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:
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 list

  • detector (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.

Parameters:
  • version (int) – QR code version (1-40)

  • error_level (str) – Error correction level (‘L’, ‘M’, ‘Q’, ‘H’)

Return type:

float

Returns:

Maximum safe reserve size as a fraction of QR code area

calculate_placement_offsets(config)[source]

Calculate offset_x and offset_y based on placement mode.

Parameters:

config (CenterpieceConfig) – CenterpieceConfig instance

Return type:

Tuple[float, float]

Returns:

Tuple of (offset_x, offset_y) values

get_module_bounds()[source]

Get bounds of all active modules in the matrix.

Return type:

Dict[str, int]

Returns:

Dict with ‘left’, ‘top’, ‘right’, ‘bottom’ keys representing the bounding box of all active (True) modules in the matrix

get_centerpiece_bounds(config)[source]

Calculate centerpiece bounds in module coordinates.

Parameters:

config (CenterpieceConfig) – CenterpieceConfig instance

Return type:

Dict[str, int]

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 position

  • col (int) – Module column position

  • config (CenterpieceConfig) – CenterpieceConfig instance

Return type:

bool

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:

List[List[bool]]

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:

List[List[bool]]

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:

List[List[bool]]

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 instance

  • error_level (str) – QR error correction level (“L”, “M”, “Q”, “H”)

Return type:

Dict[str, Any]

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:

Tuple[bool, List[str]]

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:
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:

Dict[str, Any]

Returns:

Dictionary with centerpiece bounds and properties

get_imprint_metadata()[source]

Get stored imprint metadata from the last imprint operation.

Return type:

Dict[str, Any]

Returns:

Imprint metadata dictionary, or empty dict if no imprint operation performed

get_performance_warnings(config)[source]

Get performance warnings for centerpiece configuration.

Parameters:

config (CenterpieceConfig) – CenterpieceConfig instance

Return type:

List[str]

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:

List[str]

Returns:

List of all performance warning messages

get_performance_summary()[source]

Get comprehensive performance summary.

Return type:

Dict[str, Any]

Returns:

Dictionary with performance summary

get_geometry_component()[source]

Get the geometry calculation component.

Return type:

CenterpieceGeometry

get_knockout_processor()[source]

Get the knockout processor component.

Return type:

KnockoutProcessor

get_imprint_processor()[source]

Get the imprint processor component.

Return type:

ImprintProcessor

get_validator()[source]

Get the matrix validator component.

Return type:

MatrixValidator

get_performance_monitor()[source]

Get the performance monitor component.

Return type:

CenterpiecePerformanceMonitor

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:

  1. Traverses the QR matrix to find active modules

  2. Groups adjacent modules of the same type into clusters

  3. Analyzes cluster properties (size, density, shape)

  4. Filters clusters based on configurable thresholds

  5. 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: AlgorithmProcessor

Analyzes 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 (int)

  • density_threshold (float)

  • connectivity_mode (Literal['4-way', '8-way'])

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:
  • min_cluster_size (int) – Minimum number of modules to form a cluster

  • density_threshold (float) – Minimum density ratio (0.0-1.0) for valid clusters

  • connectivity_mode (Literal['4-way', '8-way']) – ‘4-way’ or ‘8-way’ connectivity

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]]

cluster_modules(modules, **kwargs)[source]

Alias for process() method for backward compatibility.

Parameters:
  • modules (Any) – Either a 2D matrix or list of (row, col, active) tuples

  • **kwargs (Any) – Additional parameters passed to process()

Return type:

List[Dict[str, Any]]

Returns:

List of cluster dictionaries

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:
  • cluster (Dict[str, Any]) – Cluster data with positions and rendering hints

  • scale (int) – Module size in pixels

  • border (int) – Border size in modules

  • path_clipper (Optional[Any]) – Optional PathClipper instance for frame-aware clipping

Returns:

SVG path data string for the cluster shape

Return type:

str

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: TypedDict

Type definition for segno.make() parameters.

error: Optional[str]
version: Optional[int]
encoding: Optional[str]
eci: bool
mask: Optional[int]
class segnomms.core.advanced_qr.SegnoSequenceParams[source]

Bases: TypedDict

Type definition for segno.make_sequence() parameters.

error: Optional[str]
boost_error: bool
encoding: Optional[str]
mask: Optional[int]
symbol_count: Optional[int]
version: Optional[int]
class segnomms.core.advanced_qr.AnalysisDict[source]

Bases: TypedDict

Type definition for encoding analysis results.

ascii_compatible: bool
latin1_compatible: bool
requires_unicode: bool
total_chars: int
ascii_chars: int
extended_chars: int
has_cjk: bool
class segnomms.core.advanced_qr.RecommendationsDict[source]

Bases: TypedDict

Type definition for encoding recommendations.

recommended_encoding: Optional[str]
needs_eci: bool
analysis: AnalysisDict
alternatives: List[str]
class segnomms.core.advanced_qr.QRGenerationResult(qr_codes, is_sequence, metadata, warnings, fallback_used)[source]

Bases: object

Result 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

qr_codes: List[QRCode]
is_sequence: bool
metadata: Dict[str, Any]
warnings: List[str]
fallback_used: bool
__init__(qr_codes, is_sequence, metadata, warnings, fallback_used)
Parameters:
Return type:

None

class segnomms.core.advanced_qr.AdvancedQRGenerator[source]

Bases: object

Advanced 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.

__init__()[source]

Initialize the advanced QR generator.

Return type:

None

generate_qr(content, config, error='M', version=None)[source]

Generate QR code(s) with advanced features.

Parameters:
  • content (str) – Data to encode in the QR code(s)

  • config (AdvancedQRConfig) – Advanced QR configuration

  • error (str) – Error correction level (‘L’, ‘M’, ‘Q’, ‘H’)

  • version (Optional[int]) – QR code version (None for automatic)

Return type:

QRGenerationResult

Returns:

QRGenerationResult with generated QR code(s) and metadata

validate_config(config)[source]

Validate advanced QR configuration and return warnings.

Parameters:

config (AdvancedQRConfig) – Configuration to validate

Return type:

List[str]

Returns:

List of validation warning messages

get_encoding_recommendations(content)[source]

Get encoding recommendations for the given content.

Parameters:

content (str) – Content to analyze

Return type:

RecommendationsDict

Returns:

Dictionary with encoding recommendations and analysis

segnomms.core.advanced_qr.create_advanced_qr_generator()[source]

Create an AdvancedQRGenerator instance.

Return type:

AdvancedQRGenerator

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 modules

  • ModuleType.SEPARATOR - Separator modules around finders

  • ModuleType.TIMING - Timing pattern modules

  • ModuleType.ALIGNMENT - Alignment pattern modules

  • ModuleType.FORMAT - Format information modules

  • ModuleType.VERSION - Version information modules

  • ModuleType.DATA - Data and error correction modules

  • ModuleType.DARK - Fixed dark module

Architecture Overview

The plugin follows a modular architecture:

  1. Configuration Layer - Validates and manages all settings

  2. Detection Layer - Identifies module types and relationships

  3. Algorithm Layer - Processes modules (clustering, optimization)

  4. Rendering Layer - Generates SVG elements for each module

  5. 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.