Add Pattern Templates for Key Colors targets with visual canvas editor
Introduce Pattern Template entity as a reusable rectangle layout that Key Colors targets reference via pattern_template_id. This replaces inline rectangle storage with a shared template system. Backend: - New PatternTemplate data model, store (JSON persistence), CRUD API - KC targets now reference pattern_template_id instead of inline rectangles - ProcessorManager resolves pattern template at KC processing start - Picture source test endpoint supports capture_duration=0 for single frame - Delete protection: 409 when template is referenced by a KC target Frontend: - Pattern Templates section in Key Colors sub-tab with card UI - Visual canvas editor with drag-to-move, 8-point resize handles - Background capture from any picture source for visual alignment - Precise coordinate list synced bidirectionally with canvas - Resizable editor container, viewport-constrained modal - KC target editor uses pattern template dropdown instead of inline rects - Localization (en/ru) for all new UI elements Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -7,6 +7,7 @@ from .routes.devices import router as devices_router
|
||||
from .routes.templates import router as templates_router
|
||||
from .routes.postprocessing import router as postprocessing_router
|
||||
from .routes.picture_sources import router as picture_sources_router
|
||||
from .routes.pattern_templates import router as pattern_templates_router
|
||||
from .routes.picture_targets import router as picture_targets_router
|
||||
|
||||
router = APIRouter()
|
||||
@@ -14,6 +15,7 @@ router.include_router(system_router)
|
||||
router.include_router(devices_router)
|
||||
router.include_router(templates_router)
|
||||
router.include_router(postprocessing_router)
|
||||
router.include_router(pattern_templates_router)
|
||||
router.include_router(picture_sources_router)
|
||||
router.include_router(picture_targets_router)
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ from wled_controller.core.processor_manager import ProcessorManager
|
||||
from wled_controller.storage import DeviceStore
|
||||
from wled_controller.storage.template_store import TemplateStore
|
||||
from wled_controller.storage.postprocessing_template_store import PostprocessingTemplateStore
|
||||
from wled_controller.storage.pattern_template_store import PatternTemplateStore
|
||||
from wled_controller.storage.picture_source_store import PictureSourceStore
|
||||
from wled_controller.storage.picture_target_store import PictureTargetStore
|
||||
|
||||
@@ -11,6 +12,7 @@ from wled_controller.storage.picture_target_store import PictureTargetStore
|
||||
_device_store: DeviceStore | None = None
|
||||
_template_store: TemplateStore | None = None
|
||||
_pp_template_store: PostprocessingTemplateStore | None = None
|
||||
_pattern_template_store: PatternTemplateStore | None = None
|
||||
_picture_source_store: PictureSourceStore | None = None
|
||||
_picture_target_store: PictureTargetStore | None = None
|
||||
_processor_manager: ProcessorManager | None = None
|
||||
@@ -37,6 +39,13 @@ def get_pp_template_store() -> PostprocessingTemplateStore:
|
||||
return _pp_template_store
|
||||
|
||||
|
||||
def get_pattern_template_store() -> PatternTemplateStore:
|
||||
"""Get pattern template store dependency."""
|
||||
if _pattern_template_store is None:
|
||||
raise RuntimeError("Pattern template store not initialized")
|
||||
return _pattern_template_store
|
||||
|
||||
|
||||
def get_picture_source_store() -> PictureSourceStore:
|
||||
"""Get picture source store dependency."""
|
||||
if _picture_source_store is None:
|
||||
@@ -63,15 +72,17 @@ def init_dependencies(
|
||||
template_store: TemplateStore,
|
||||
processor_manager: ProcessorManager,
|
||||
pp_template_store: PostprocessingTemplateStore | None = None,
|
||||
pattern_template_store: PatternTemplateStore | None = None,
|
||||
picture_source_store: PictureSourceStore | None = None,
|
||||
picture_target_store: PictureTargetStore | None = None,
|
||||
):
|
||||
"""Initialize global dependencies."""
|
||||
global _device_store, _template_store, _processor_manager
|
||||
global _pp_template_store, _picture_source_store, _picture_target_store
|
||||
global _pp_template_store, _pattern_template_store, _picture_source_store, _picture_target_store
|
||||
_device_store = device_store
|
||||
_template_store = template_store
|
||||
_processor_manager = processor_manager
|
||||
_pp_template_store = pp_template_store
|
||||
_pattern_template_store = pattern_template_store
|
||||
_picture_source_store = picture_source_store
|
||||
_picture_target_store = picture_target_store
|
||||
|
||||
147
server/src/wled_controller/api/routes/pattern_templates.py
Normal file
147
server/src/wled_controller/api/routes/pattern_templates.py
Normal file
@@ -0,0 +1,147 @@
|
||||
"""Pattern template routes: CRUD for rectangle layout templates."""
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Depends
|
||||
|
||||
from wled_controller.api.auth import AuthRequired
|
||||
from wled_controller.api.dependencies import (
|
||||
get_pattern_template_store,
|
||||
get_picture_target_store,
|
||||
)
|
||||
from wled_controller.api.schemas.pattern_templates import (
|
||||
PatternTemplateCreate,
|
||||
PatternTemplateListResponse,
|
||||
PatternTemplateResponse,
|
||||
PatternTemplateUpdate,
|
||||
)
|
||||
from wled_controller.api.schemas.picture_targets import KeyColorRectangleSchema
|
||||
from wled_controller.storage.key_colors_picture_target import KeyColorRectangle
|
||||
from wled_controller.storage.pattern_template_store import PatternTemplateStore
|
||||
from wled_controller.storage.picture_target_store import PictureTargetStore
|
||||
from wled_controller.utils import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _pat_template_to_response(t) -> PatternTemplateResponse:
|
||||
"""Convert a PatternTemplate to its API response."""
|
||||
return PatternTemplateResponse(
|
||||
id=t.id,
|
||||
name=t.name,
|
||||
rectangles=[
|
||||
KeyColorRectangleSchema(name=r.name, x=r.x, y=r.y, width=r.width, height=r.height)
|
||||
for r in t.rectangles
|
||||
],
|
||||
created_at=t.created_at,
|
||||
updated_at=t.updated_at,
|
||||
description=t.description,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/v1/pattern-templates", response_model=PatternTemplateListResponse, tags=["Pattern Templates"])
|
||||
async def list_pattern_templates(
|
||||
_auth: AuthRequired,
|
||||
store: PatternTemplateStore = Depends(get_pattern_template_store),
|
||||
):
|
||||
"""List all pattern templates."""
|
||||
try:
|
||||
templates = store.get_all_templates()
|
||||
responses = [_pat_template_to_response(t) for t in templates]
|
||||
return PatternTemplateListResponse(templates=responses, count=len(responses))
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to list pattern templates: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/api/v1/pattern-templates", response_model=PatternTemplateResponse, tags=["Pattern Templates"], status_code=201)
|
||||
async def create_pattern_template(
|
||||
data: PatternTemplateCreate,
|
||||
_auth: AuthRequired,
|
||||
store: PatternTemplateStore = Depends(get_pattern_template_store),
|
||||
):
|
||||
"""Create a new pattern template."""
|
||||
try:
|
||||
rectangles = [
|
||||
KeyColorRectangle(name=r.name, x=r.x, y=r.y, width=r.width, height=r.height)
|
||||
for r in data.rectangles
|
||||
]
|
||||
template = store.create_template(
|
||||
name=data.name,
|
||||
rectangles=rectangles,
|
||||
description=data.description,
|
||||
)
|
||||
return _pat_template_to_response(template)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to create pattern template: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/api/v1/pattern-templates/{template_id}", response_model=PatternTemplateResponse, tags=["Pattern Templates"])
|
||||
async def get_pattern_template(
|
||||
template_id: str,
|
||||
_auth: AuthRequired,
|
||||
store: PatternTemplateStore = Depends(get_pattern_template_store),
|
||||
):
|
||||
"""Get pattern template by ID."""
|
||||
try:
|
||||
template = store.get_template(template_id)
|
||||
return _pat_template_to_response(template)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=404, detail=f"Pattern template {template_id} not found")
|
||||
|
||||
|
||||
@router.put("/api/v1/pattern-templates/{template_id}", response_model=PatternTemplateResponse, tags=["Pattern Templates"])
|
||||
async def update_pattern_template(
|
||||
template_id: str,
|
||||
data: PatternTemplateUpdate,
|
||||
_auth: AuthRequired,
|
||||
store: PatternTemplateStore = Depends(get_pattern_template_store),
|
||||
):
|
||||
"""Update a pattern template."""
|
||||
try:
|
||||
rectangles = None
|
||||
if data.rectangles is not None:
|
||||
rectangles = [
|
||||
KeyColorRectangle(name=r.name, x=r.x, y=r.y, width=r.width, height=r.height)
|
||||
for r in data.rectangles
|
||||
]
|
||||
template = store.update_template(
|
||||
template_id=template_id,
|
||||
name=data.name,
|
||||
rectangles=rectangles,
|
||||
description=data.description,
|
||||
)
|
||||
return _pat_template_to_response(template)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to update pattern template: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.delete("/api/v1/pattern-templates/{template_id}", status_code=204, tags=["Pattern Templates"])
|
||||
async def delete_pattern_template(
|
||||
template_id: str,
|
||||
_auth: AuthRequired,
|
||||
store: PatternTemplateStore = Depends(get_pattern_template_store),
|
||||
target_store: PictureTargetStore = Depends(get_picture_target_store),
|
||||
):
|
||||
"""Delete a pattern template."""
|
||||
try:
|
||||
if store.is_referenced_by(template_id, target_store):
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="Cannot delete pattern template: it is referenced by one or more key colors targets. "
|
||||
"Please reassign those targets before deleting.",
|
||||
)
|
||||
store.delete_template(template_id)
|
||||
except HTTPException:
|
||||
raise
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to delete pattern template: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
@@ -365,26 +365,33 @@ async def test_picture_source(
|
||||
)
|
||||
stream.initialize()
|
||||
|
||||
logger.info(f"Starting {test_request.capture_duration}s stream test for {stream_id}")
|
||||
|
||||
frame_count = 0
|
||||
total_capture_time = 0.0
|
||||
last_frame = None
|
||||
|
||||
start_time = time.perf_counter()
|
||||
end_time = start_time + test_request.capture_duration
|
||||
|
||||
while time.perf_counter() < end_time:
|
||||
if test_request.capture_duration == 0:
|
||||
# Single frame capture
|
||||
logger.info(f"Capturing single frame for {stream_id}")
|
||||
capture_start = time.perf_counter()
|
||||
screen_capture = stream.capture_frame()
|
||||
capture_elapsed = time.perf_counter() - capture_start
|
||||
|
||||
if screen_capture is None:
|
||||
continue
|
||||
|
||||
total_capture_time += capture_elapsed
|
||||
frame_count += 1
|
||||
last_frame = screen_capture
|
||||
if screen_capture is not None:
|
||||
total_capture_time = capture_elapsed
|
||||
frame_count = 1
|
||||
last_frame = screen_capture
|
||||
else:
|
||||
logger.info(f"Starting {test_request.capture_duration}s stream test for {stream_id}")
|
||||
end_time = start_time + test_request.capture_duration
|
||||
while time.perf_counter() < end_time:
|
||||
capture_start = time.perf_counter()
|
||||
screen_capture = stream.capture_frame()
|
||||
capture_elapsed = time.perf_counter() - capture_start
|
||||
if screen_capture is None:
|
||||
continue
|
||||
total_capture_time += capture_elapsed
|
||||
frame_count += 1
|
||||
last_frame = screen_capture
|
||||
|
||||
actual_duration = time.perf_counter() - start_time
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ from wled_controller.api.dependencies import (
|
||||
)
|
||||
from wled_controller.api.schemas.picture_targets import (
|
||||
ExtractedColorResponse,
|
||||
KeyColorRectangleSchema,
|
||||
KeyColorsResponse,
|
||||
KeyColorsSettingsSchema,
|
||||
PictureTargetCreate,
|
||||
@@ -28,7 +27,6 @@ from wled_controller.core.processor_manager import ProcessorManager, ProcessingS
|
||||
from wled_controller.storage import DeviceStore
|
||||
from wled_controller.storage.wled_picture_target import WledPictureTarget
|
||||
from wled_controller.storage.key_colors_picture_target import (
|
||||
KeyColorRectangle,
|
||||
KeyColorsSettings,
|
||||
KeyColorsPictureTarget,
|
||||
)
|
||||
@@ -84,10 +82,7 @@ def _kc_settings_to_schema(settings: KeyColorsSettings) -> KeyColorsSettingsSche
|
||||
fps=settings.fps,
|
||||
interpolation_mode=settings.interpolation_mode,
|
||||
smoothing=settings.smoothing,
|
||||
rectangles=[
|
||||
KeyColorRectangleSchema(name=r.name, x=r.x, y=r.y, width=r.width, height=r.height)
|
||||
for r in settings.rectangles
|
||||
],
|
||||
pattern_template_id=settings.pattern_template_id,
|
||||
)
|
||||
|
||||
|
||||
@@ -97,10 +92,7 @@ def _kc_schema_to_settings(schema: KeyColorsSettingsSchema) -> KeyColorsSettings
|
||||
fps=schema.fps,
|
||||
interpolation_mode=schema.interpolation_mode,
|
||||
smoothing=schema.smoothing,
|
||||
rectangles=[
|
||||
KeyColorRectangle(name=r.name, x=r.x, y=r.y, width=r.width, height=r.height)
|
||||
for r in schema.rectangles
|
||||
],
|
||||
pattern_template_id=schema.pattern_template_id,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -56,6 +56,12 @@ from .postprocessing import (
|
||||
PostprocessingTemplateUpdate,
|
||||
PPTemplateTestRequest,
|
||||
)
|
||||
from .pattern_templates import (
|
||||
PatternTemplateCreate,
|
||||
PatternTemplateListResponse,
|
||||
PatternTemplateResponse,
|
||||
PatternTemplateUpdate,
|
||||
)
|
||||
from .picture_sources import (
|
||||
ImageValidateRequest,
|
||||
ImageValidateResponse,
|
||||
@@ -109,6 +115,10 @@ __all__ = [
|
||||
"PostprocessingTemplateResponse",
|
||||
"PostprocessingTemplateUpdate",
|
||||
"PPTemplateTestRequest",
|
||||
"PatternTemplateCreate",
|
||||
"PatternTemplateListResponse",
|
||||
"PatternTemplateResponse",
|
||||
"PatternTemplateUpdate",
|
||||
"ImageValidateRequest",
|
||||
"ImageValidateResponse",
|
||||
"PictureSourceCreate",
|
||||
|
||||
42
server/src/wled_controller/api/schemas/pattern_templates.py
Normal file
42
server/src/wled_controller/api/schemas/pattern_templates.py
Normal file
@@ -0,0 +1,42 @@
|
||||
"""Pydantic schemas for pattern template API."""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from .picture_targets import KeyColorRectangleSchema
|
||||
|
||||
|
||||
class PatternTemplateCreate(BaseModel):
|
||||
"""Request to create a pattern template."""
|
||||
|
||||
name: str = Field(description="Template name", min_length=1, max_length=100)
|
||||
rectangles: List[KeyColorRectangleSchema] = Field(default_factory=list, description="List of named rectangles")
|
||||
description: Optional[str] = Field(None, description="Template description", max_length=500)
|
||||
|
||||
|
||||
class PatternTemplateUpdate(BaseModel):
|
||||
"""Request to update a pattern template."""
|
||||
|
||||
name: Optional[str] = Field(None, description="Template name", min_length=1, max_length=100)
|
||||
rectangles: Optional[List[KeyColorRectangleSchema]] = Field(None, description="List of named rectangles")
|
||||
description: Optional[str] = Field(None, description="Template description", max_length=500)
|
||||
|
||||
|
||||
class PatternTemplateResponse(BaseModel):
|
||||
"""Pattern template response."""
|
||||
|
||||
id: str = Field(description="Template ID")
|
||||
name: str = Field(description="Template name")
|
||||
rectangles: List[KeyColorRectangleSchema] = Field(description="List of named rectangles")
|
||||
created_at: datetime = Field(description="Creation timestamp")
|
||||
updated_at: datetime = Field(description="Last update timestamp")
|
||||
description: Optional[str] = Field(None, description="Template description")
|
||||
|
||||
|
||||
class PatternTemplateListResponse(BaseModel):
|
||||
"""List of pattern templates."""
|
||||
|
||||
templates: List[PatternTemplateResponse] = Field(description="List of pattern templates")
|
||||
count: int = Field(description="Number of templates")
|
||||
@@ -60,7 +60,7 @@ class PictureSourceListResponse(BaseModel):
|
||||
class PictureSourceTestRequest(BaseModel):
|
||||
"""Request to test a picture source."""
|
||||
|
||||
capture_duration: float = Field(default=5.0, ge=1.0, le=30.0, description="Duration to capture in seconds")
|
||||
capture_duration: float = Field(default=5.0, ge=0.0, le=30.0, description="Duration to capture in seconds (0 = single frame)")
|
||||
border_width: int = Field(default=10, ge=1, le=100, description="Border width in pixels for preview")
|
||||
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ class KeyColorsSettingsSchema(BaseModel):
|
||||
fps: int = Field(default=10, description="Extraction rate (1-60)", ge=1, le=60)
|
||||
interpolation_mode: str = Field(default="average", description="Color mode (average, median, dominant)")
|
||||
smoothing: float = Field(default=0.3, description="Temporal smoothing (0.0-1.0)", ge=0.0, le=1.0)
|
||||
rectangles: List[KeyColorRectangleSchema] = Field(default_factory=list, description="Rectangles to extract colors from")
|
||||
pattern_template_id: str = Field(default="", description="Pattern template ID for rectangle layout")
|
||||
|
||||
|
||||
class ExtractedColorResponse(BaseModel):
|
||||
|
||||
Reference in New Issue
Block a user